<!--
@name: 司机物流价格
@author: 张泽贤
@time: 2022-08-26
@doc:
-->
<template>
  <div class="pages">
    <p-spin :spinning="spinning" v-if="!editType">
      <p-card style="margin-bottom: 10px">
        <p-form-model ref="formTarget" :model="form" @submit="handelSubmit" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" class="plg-grid-from">
          <a-row>
            <a-col :span="6">
              <p-form-model-item label="报价编号">
                <p-input :value="form.contractNo" @blur="(event) => (form.contractNo = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="报价名称">
                <p-input :value="form.contractName" @blur="(event) => (form.contractName = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="12">
              <p-form-model-item :wrapper-col="{ span: 24 }" style="text-align: right">
                <a-space>
                  <p-button type="primary" html-type="submit" icon="search">查询</p-button>
                  <p-button @click="onReset">重置</p-button>
                  <!-- <p-button type="primary" @click="onSeniorSearch">高级查询</p-button> -->
                </a-space>
              </p-form-model-item>
            </a-col>
          </a-row>
        </p-form-model>
      </p-card>
      <p-card title="合同信息" style="margin-bottom: 10px">
        <a-space slot="extra">
          <p-button type="primary" @click="onEdit({}, 'add')">新增</p-button>
          <p-button type="primary" @click="onEnOrDis(1)" :disabled="!selectedRowKeys.length">启用</p-button>
          <p-button type="danger" @click="onEnOrDis(0)" :disabled="!selectedRowKeys.length">停用</p-button>
          <p-button type="primary" @click="onExperiment">试算实验</p-button>
        </a-space>
        <t-table
          ref="masterTable"
          dragle
          bordered
          row-key="id"
          :id="$route.meta.menuId + '_freightLogisticsPrice'"
          :scroll="{ x: true }"
          :vScrollX="{enabled:true}"
          :vScrollY="{enabled:true,rows:10}"
          :columns="mx_columns"
          :data-source.sync="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="2"
          @selectChange="(selectKey, selectData)=>selectedRowKeys=selectKey"
          @clickRow="masterClickRow"
          :autoLoad="false"
        >
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a @click.stop="onEdit(record, 'view')">查看</a>
              <a @click.stop="onEdit(record, 'copy')">复制</a>
              <a @click.stop="onEdit(record, 'edit')">修改</a>
              <p-switch @change="toEnOrDis(record)" :checked="record.status === 1 ? true : false" size="small" />
            </a-space>
          </template>
        </t-table>
      </p-card>

      <p-card>
        <p-tabs :animated="false" :activeKey="activeKey" @tabClick="activeKey = $event">
          <p-tab-pane key="1" tab="运费价格" :forceRender="true">
            <priceList ref="childrenTable_1" priceType="freight" :contractNo="selectContractNo" @priceOperation="priceOperation" :isShow="activeKey === '1'"></priceList>
          </p-tab-pane>
          <p-tab-pane key="2" tab="附加费价格" :forceRender="true">
            <priceList ref="childrenTable_2" priceType="surcharge" :contractNo="selectContractNo" @priceOperation="priceOperation" :isShow="activeKey === '2'"></priceList>
          </p-tab-pane>
          <p-tab-pane key="3" tab="审批信息" :forceRender="true">
            <auditList ref="childrenTable_3" :isShow="activeKey === '3'"></auditList>
          </p-tab-pane>
          <p-tab-pane key="4" tab="操作日志" :forceRender="true">
            <operationLog ref="childrenTable_4" :contractNo="selectContractNo" :isShow="activeKey === '4'"></operationLog>
          </p-tab-pane>
        </p-tabs>
      </p-card>
    </p-spin>

    <!-- 物流合同编辑 -->
    <edit ref="edit" v-if="editList.includes(editType)" :type="editType" :editId="editId" :options="options" :mextendedField_list="mextendedField_list" @back="back"></edit>

    <!-- 运费/附加费价格编辑 -->
    <priceEdit v-if="priceList.includes(editType)" :type="editType" :editId="editId" :priceId="priceId" :options="options" :mextendedField_list="mextendedField_list" @back="back"></priceEdit>

    <!-- 试算实验 -->
    <p-search-modal v-bind="setQueryFormItmes.waybillAttr" @ok="(...args) => onFormBlur('waybill', ...args)" @cancel="waybillDialog = false" v-show="false" :modalConfig="{ visible: waybillDialog }" />

    <orderView
      v-show="editType === 'orderView'"
      :st="1"
      :formExtendedField="formExtendedField"
      :goodsExtendedField="childrenTableExtendedField"
      :record="currentMainDataView"
      :mode="mode"
      :mainId="mainId"
      :options="options"
      :formName="formName"
      @back="back"
    />
  </div>
</template>

<script>
import { initDictionary, initDictionaryAll, resultExtendedField } from '@/blocks/utils';

import { listRemoteUrl, updateStatus, trialTest } from './js/api.js';
import { setMainColumns } from './js/tableConfig.js';
import edit from './modules/edit.vue';
import priceList from './modules/priceList.vue';
import priceEdit from './modules/priceEdit.vue';
import auditList from './modules/auditList.vue';
import operationLog from './modules/operationLog.vue';
import { setQueryFormItmes } from './js/form.js';

import orderView from '@/views/BMS/$common/model/orderView/index.orderView.vue'; /**内容查看 */

export default {
  components: { edit, priceList, priceEdit, auditList, operationLog, orderView },
  data() {
    return {
      spinning: false,
      editType: '', // 空-列表页 view-查看 add-新增 edit-修改 copy-复制 orderView-订单查看
      editList: ['view', 'add', 'edit', 'copy'],
      priceList: ['freightView', 'freightAdd', 'freightEdit', 'freightCopy', 'surchargeView', 'surchargeAdd', 'surchargeEdit', 'surchargeCopy'],
      editId: '',
      activeKey: '1',

      form: {
        contractNo: '',
        contractName: '',
        firstPartyName: '',
        secondPartyName: '',
        contractMode: 3,
      },
      options: {
        SECTION_SYMBOL: [],
        LESS_THAN: [],
        CONTRACT_TYPE: [],
        SETTLEMENT_WAY: [],
        RECONCILIATION_DATE: [],
        TAX_POINT: [],
        SETTLEMENT_TYPE_KG: [],
        SETTLEMENT_TYPE_MILEAGE: [],
        SETTLEMENT_TYPE_TIME: [],
        SETTLEMENT_TYPE_HOUR: [],
        SETTLEMENT_MODEL: [],
        LADDER_TYPE: [],
        APPROVAL_STATUS: [],
        APPROVAL_FLOW_TYPE: [],
        NODE_APPROVER_TYPE: [],
        NODE_APPROVAL_TYPE: [],
        BMS_APPROVAL_CONDITION_TYPE: [],
        FLOW_CONDITION_TYPE: [],
        DELIVERY_METHOD_TYPE: [],
        SHIPPER_TYPE: [],
        CONSIGNEE_TYPE: [],
        ORDER_TYPE: [],
        ORDER_BUSINESS_TYPE: [],
        TRANSPORT_TYPE: [],
        TEMPERATURE_REQUIREMENT: [],
        SETTLEMENT_ORDER_TYPE: [],
        SETTLEMENT_MODEL_yundan: [],
        SETTLEMENT_MODEL_paichedan: [],
        BMS_APPROVAL_CONDITION_TYPE_yundan: [],
        BMS_APPROVAL_CONDITION_TYPE_paichedan: [],
        STATION_AREAS: [],
      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      selectContractNo: '',
      listRemoteUrl,
      listParams: {
        contractMode: 3,
      },
      mx_columns: setMainColumns(this, this.tableExtendedField),
      mextendedField_list: [],
      tableExtendedField: [],

      priceId: '',

      setQueryFormItmes: setQueryFormItmes(this),
      waybillDialog: false,

      formExtendedField: [],
      childrenTableExtendedField: [],
      currentMainDataView: null,
      mode: 1,
      mainId: '',
      formName: 'main',
    };
  },
  mounted() {
    initDictionary(
      [
        { objectcode: 'SECTION_SYMBOL' },
        { objectcode: 'LESS_THAN' },
        { objectcode: 'CONTRACT_TYPE' },
        { objectcode: 'SETTLEMENT_WAY' },
        { objectcode: 'RECONCILIATION_DATE' },
        { objectcode: 'TAX_POINT' },
        { objectcode: 'SETTLEMENT_MODEL' },
        { objectcode: 'LADDER_TYPE', groupcode1: 'driver' },
        { objectcode: 'APPROVAL_STATUS' },
        { objectcode: 'APPROVAL_FLOW_TYPE' },
        { objectcode: 'NODE_APPROVER_TYPE' },
        { objectcode: 'NODE_APPROVAL_TYPE' },
        { objectcode: 'BMS_APPROVAL_CONDITION_TYPE' },
        { objectcode: 'FLOW_CONDITION_TYPE' },
        { objectcode: 'DELIVERY_METHOD_TYPE' },
        { objectcode: 'SHIPPER_TYPE' },
        { objectcode: 'CONSIGNEE_TYPE' },
        { objectcode: 'ORDER_TYPE' },
        { objectcode: 'ORDER_BUSINESS_TYPE' },
        { objectcode: 'TRANSPORT_TYPE' },
        { objectcode: 'TEMPERATURE_REQUIREMENT' },
        { objectcode: 'SETTLEMENT_ORDER_TYPE', groupcode1: 'driver' },
        { objectcode: 'STATION_AREAS' },
      ],
      true
    ).then((res) => {
      for (const key in res) {
        this.options[key] = res[key];
      }
    });
    initDictionaryAll({ objectcode: 'SETTLEMENT_TYPE' }).then((res) => {
      res.forEach((item) => {
        item.value = +item.value;
        if (item.groupcode2 == '1') {
          this.options['SETTLEMENT_TYPE_' + item.groupcode1].push(item);
        }
      });
    });
    initDictionaryAll({ objectcode: 'SETTLEMENT_MODEL' }).then((res) => {
      res.forEach((item) => {
        item.value = +item.value;
        if (item.groupcode2 == '1') {
          this.options['SETTLEMENT_MODEL_yundan'].push(item);
        }
        if (item.groupcode3 == '1') {
          this.options['SETTLEMENT_MODEL_paichedan'].push(item);
        }
      });
    });
    initDictionaryAll({ objectcode: 'BMS_APPROVAL_CONDITION_TYPE' }).then((res) => {
      res.forEach((item) => {
        item.value = +item.value;
        if (item.groupcode2 == '1') {
          this.options['BMS_APPROVAL_CONDITION_TYPE_yundan'].push(item);
        }
        if (item.groupcode4 == '1') {
          this.options['BMS_APPROVAL_CONDITION_TYPE_paichedan'].push(item);
        }
      });
    });
    resultExtendedField({ extendedObjectCode: '15' }).then((res) => {
      if (res) {
        this.formExtendedField = res.form;
      }
    });
    resultExtendedField({ extendedObjectCode: '17' }).then((res) => {
      if (res) {
        this.childrenTableExtendedField = res.table;
      }
    });
    this.onSearch();
  },
  watch: {
    activeKey(v) {
      this.childrenTableReload();
    },
  },
  methods: {
    handelSubmit(event) {
      event.preventDefault();
      event.submitter.focus();
      this.onSearch();
    },
    // 查询
    onSearch() {
      this.listParams = { ...this.form };
      this.editId = '';
      this.selectContractNo = '';
    },
    // 重置
    onReset() {
      this.form = {
        contractMode: 3,
      };
    },

    // 新增、修改、复制、查看
    onEdit(record = { id: '' }, type) {
      this.editId = record.id;
      this.editType = type;
    },

    // 启用、停用
    onEnOrDis(status) {
      let list = this.selectedRowKeys.map((item) => {
        return {
          id: item,
          status,
        };
      });
      this.WhetherToEnable(updateStatus, list, status === 1 ? '启用' : '停用');
    },
    toEnOrDis(record) {
      let reuest = [
        {
          id: record.id,
          status: record.status === 1 ? 0 : 1,
        },
      ];
      this.WhetherToEnable(updateStatus, reuest, record.status === 1 ? '停用' : '启用');
    },
    WhetherToEnable(method, idList, text) {
      let self = this;
      this.$confirm({
        title: '是否' + text + '?',
        onOk() {
          return new Promise((resolve, reject) => {
            method(idList)
              .then((res) => {
                if (res.success) {
                  self.$message.success(res.message);
                  self.onSearch();
                } else {
                  self.$exception(res);
                }
                resolve();
              })
              .catch((res) => {
                self.$exception(res);
                resolve();
              });
          });
        },
      });
    },

    // 试算实验
    onExperiment() {
      this.waybillDialog = true;
    },

    // 行点击
    masterClickRow(event, activeID, rowRecord) {
      this.selectContractNo = rowRecord.contractNo;
      this.editId = rowRecord.id;
    },

    // 费用操作
    priceOperation({ priceId, editType }) {
      this.priceId = priceId;
      this.editType = editType;
    },

    back() {
      this.editType = '';
      this.$nextTick(() => {
        this.onSearch();
      });
    },

    onFormBlur(name, ...args) {
      if (name === 'waybill') {
        trialTest({ id: args[1] }).then((res) => {
          if (res.success) {
            let lineData = { ...args[2][0] };
            lineData.dataSource = 1;
            this.waybillDialog = false;
            this.mainId = args[1];
            this.currentMainDataView = lineData;
            this.editType = 'orderView';
          } else {
            this.$exception(res);
          }
        });
      }
    },

    // 明细表查询
    childrenTableReload() {
      this.$nextTick(() => {
        let table = this.$refs['childrenTable_' + this.activeKey];
        if (table) {
          table.dataSource = [];
          this.selectContractNo && table.reload();
        }
      });
    },
  },
};
</script>