<!--
@name: 已派车
@author: 张泽贤
@time: 2022-04-28
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_调度管理_1.2.2.doc
-->
<template>
  <div class="pages">
    <p-spin :spinning="spinning" v-show="!editType">
      <p-card style="margin-bottom: 10px">
        <p-form-model ref="formTarget" @submit="onSearch" :model="form" :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.loadingBillNo" @blur="(event) => (form.loadingBillNo = event.target.value)" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="派车单状态">
                <p-select v-model="form.status" :options="options.LOADING_BILL_STATUS" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="创建时间">
                <p-range-picker v-model="date1" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" style="width: 100%" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <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="onUndoAudit" :disabled="!selectedRowKeys.length">反审核</p-button>
          <p-button type="primary" @click="onAudit" :disabled="!selectedRowKeys.length">审核</p-button>
          <p-button type="danger" @click="onRevoke" :disabled="!selectedRowKeys.length">撤销</p-button>
          <p-button type="primary" @click="onMap" :disabled="!selectedRowKeys.length">地图</p-button>
          <!-- <p-button type="primary" @click="onCalculateMileage" :disabled="!selectedRowKeys.length">计算里程</p-button> -->
          <a-dropdown>
            <template #overlay>
              <a-menu>
                <a-menu-item key="2">
                  <export-button
                    type="link"
                    :ids="selectedRowKeys"
                    :pages="mainPages"
                    :getSearchValue="() => listParams"
                    downloadFileName="已派车"
                    :allUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/sendcar/sendcar_export_all'"
                    :currentUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/sendcar/sendcar_export_page'"
                    :selectUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/sendcar/sendcar_export_choose'"
                    >导出</export-button
                  >
                </a-menu-item>
                <a-menu-item type="link" key="3">
                  <p-button type="link" :disabled="!selectedRowKeys.length" @click="printAsnFun">打印</p-button>
                </a-menu-item>
                <a-menu-item type="link" key="4">
                  <p-button type="link" :disabled="!selectedRowKeys.length" @click="printAsnFunManifest">打印-按收货方合并</p-button>
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>更多</a-button>
          </a-dropdown>
        </a-space>
        <t-table
          ref="masterTable"
          dragle
          bordered
          rowSelectFixed
          :extendedObjectCode="'15'"
          row-key="loadingBillId"
          :id="$route.meta.menuId + '_dispatched'"
          :scroll="{ x: true}"
         :vScrollX="{enabled:true}"
         :vScrollY="{enabled:true,rows:10}"
          :columns="loading_columns"
          :data-source="dataSource"
          :remote-url="listRemoteUrl"
          :remoteData="listParams"
          :rowSelectType="2"
          @selectChange="(selectKey, selectData)=>selectedRowKeys=selectKey"
          @clickRow="masterClickRow"
          :sign="true"
          :doneBefore="doneBefore"
        >
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a @click.stop="toView(record)">查看</a>
              <a @click.stop="toEdit(record)">修改</a>
              <a @click.stop="toAudit(record)" :disabled="record.status > 10">审核</a>
              <a @click.stop="toRevoke(record)" :disabled="record.status > 10">撤销</a>
            </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">
            <waybillList ref="waybillList" :editData="waybillData" :options="options"></waybillList>
          </p-tab-pane>
          <p-tab-pane key="2" tab="配载商品" :forceRender="true">
            <t-table
              ref="goodsTable"
              dragle
              bordered
              row-key="id"
              :id="$route.meta.menuId + '_goodsTable'"
              :scroll="{ x: true }"
              :vScrollX="{enabled:false}"
              :vScrollY="{enabled:true,rows:4}"
              :columns="goods_columns"
              :data-source="goodsDataSource"
              :remote-url="goodsListRemoteUrl"
              :remoteData="goodsListParams"
              :rowSelectType="false"
              :autoLoad="false"
            >
            </t-table>
          </p-tab-pane>
          <p-tab-pane key="3" tab="配载包裹" :forceRender="true">
            <t-table
              ref="packTable"
              dragle
              bordered
              row-key="id"
              :id="$route.meta.menuId + '_packTable'"
              :scroll="{ x: true }"
              :vScrollX="{enabled:false}"
              :vScrollY="{enabled:true,rows:4}"
              :columns="pack_columns"
              :data-source="packDataSource"
              :remote-url="packListRemoteUrl"
              :remoteData="packListParams"
              :rowSelectType="false"
              :autoLoad="false"
            >
            </t-table>
          </p-tab-pane>
        </p-tabs>
      </p-card>
    </p-spin>

    <!-- 线路地图 -->
    <lineMap v-if="editType === 'map'" :type="'list'" :selectLineIdList="selectLineIdList" @mapBack="editType = ''"></lineMap>
    <!-- <Map v-if="editType === 'map'" :selectedRowKeys="selectedRowKeys" @back="editType = ''"></Map> -->

    <!-- 编辑 -->
    <Tabs v-if="editType === 'edit' || editType === 'view'" :editType="editType" :editData="editData" :options="options" :mextendedField_list="mextendedField_list" @back="editType = ''"></Tabs>
  </div>
</template>

<script>
import { initDictionary, resultExtendedField } from '@/blocks/utils';
import { UPCLOUD_RDC_TMS_BUSINESS_SERVICE } from '@/config/serviceSettings.js';
import exportButton from '@/blocks/components/export-modal/modal.index.vue';
import { setLoadingColumns, setGoodsColums, setPackColums } from '@/blocks/components/scheduling/js/table/tableConfig.js';
import { toPrintServer } from '@/utils/printServe.js';

import lineMap from './modules/lineMap.vue';
import Tabs from './modules/tabs.vue';
import waybillList from './modules/waybillList.vue';
import { listRemoteUrl, goodsListRemoteUrl, packListRemoteUrl, Audit, undoAudit, Revoke, printAsn } from './js/api.js';

export default {
  components: { lineMap, Tabs, waybillList, exportButton },
  computed: {
    date1: {
      get() {
        return [this.form.createStartTime, this.form.createEndTime];
      },
      set(value) {
        this.$set(this.form, 'createStartTime', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'createEndTime', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
  },
  data() {
    return {
      UPCLOUD_RDC_TMS_BUSINESS_SERVICE,
      spinning: false,
      editType: '', // 空-列表页 map-地图 view-查看 edit-编辑
      activeKey: '1',

      form: {
        loadingBillNo: '',
        status: '',
        createStartTime: '',
        createEndTime: '',
      },
      options: {
        LOADING_BILL_STATUS: [],
        ORDER_BUSINESS_TYPE: [],
      },

      mainId: '',

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      listRemoteUrl,
      listParams: {},
      editData: {},
      waybillData: {},
      loading_columns: setLoadingColumns(this, this.tableExtendedField),
      mextendedField_list: [],
      tableExtendedField: [],
      mainPages: { pageNum: 1, pageSize: 15 },

      // 商品表格
      goodsDataSource: [],
      goodsListRemoteUrl,
      goodsListParams: {},
      goods_columns: setGoodsColums(this),

      // 包裹表格
      packDataSource: [],
      packListRemoteUrl,
      packListParams: {},
      pack_columns: setPackColums(this),

      waypoint_dataSource: [],
      selectLineIdList: [],
    };
  },
  watch: {
    activeKey(value) {
      switch (value) {
        case '1':
          this.mainId && this.$refs.waybillList.reload();
          break;
        case '2':
          this.mainId && this.$refs.goodsTable.reload({ data: { loadingBillId: this.mainId } });
          break;
        case '3':
          this.mainId && this.$refs.packTable.reload({ data: { loadingBillId: this.mainId } });
          break;
      }
    },
  },
  mounted() {
    initDictionary([{ objectcode: 'LOADING_BILL_STATUS' }, { objectcode: 'ORDER_BUSINESS_TYPE' }]).then((res) => {
      this.options.LOADING_BILL_STATUS = res.LOADING_BILL_STATUS.map((item) => {
        item.value = +item.value;
        return item;
      });
      this.options.ORDER_BUSINESS_TYPE = res.ORDER_BUSINESS_TYPE.map((item) => {
        item.value = +item.value;
        return item;
      });
    });
    resultExtendedField({ extendedObjectCode: '15' }).then((res) => {
      if (res) {
        this.mextendedField_list = res.list;
        this.tableExtendedField = res.table;
        this.loading_columns = setLoadingColumns(this, this.tableExtendedField);
      }
    });
  },
  methods: {
    // 查询
    onSearch(event) {
      if (event) {
        event.preventDefault();
        event.submitter.focus();
      }
      this.mainId = '';
      this.dataSource = [];
      this.selectedRowKeys = [];
      this.$refs.waybillList.waybillDataSource = [];
      this.goodsDataSource = [];
      this.packDataSource = [];
      this.listParams = { ...this.form };
    },
    // 重置
    onReset() {
      this.form = {
        loadingBillNo: '',
        status: '',
        createStartTime: '',
        createEndTime: '',
      };
    },
    doneBefore(res) {
      const { pageNum, pageSize } = res.data;
      this.mainPages = { pageNum, pageSize };
    },
    masterClickRow(event, activeID, rowRecord) {
      this.mainId = rowRecord.loadingBillId;
      switch (this.activeKey) {
        case '1':
          this.waybillData = { ...rowRecord };
          break;
        case '2':
          this.goodsListParams = { loadingBillId: rowRecord.loadingBillId };
          break;
        case '3':
          this.packListParams = { loadingBillId: rowRecord.loadingBillId };
          break;
      }
    },

    // 审核
    onAudit() {
      this.Methods(this.selectedRowKeys, Audit, '审核');
    },
    toAudit(record) {
      this.Methods([record.loadingBillId], Audit, '审核');
    },
    // 反审核
    onUndoAudit() {
      let fdata = this.dataSource.find((t) => t.status < 20 && this.selectedRowKeys.includes(t.loadingBillId));
      if (fdata) {
        this.$message.error('派车单' + fdata.loadingBillNo + '不为已审核及之后的状态，不可反审核！');
        return false;
      }
      this.Methods(this.selectedRowKeys, undoAudit, '反审核');
    },
    Methods(list, method, title) {
      let self = this;
      this.$confirm({
        title: '是否' + title + '？',
        onOk() {
          return new Promise((resolve, reject) => {
            self.spinning = true;
            method(list)
              .then((res) => {
                self.spinning = false;
                if (res.success) {
                  self.$message.success(res.message);
                  self.onSearch();
                  resolve();
                } else {
                  self.$exception(res);
                  resolve();
                }
              })
              .finally(() => {
                self.spinning = false;
                reject();
              });
          });
        },
      });
    },

    // 撤销
    onRevoke() {
      this.Revoke(this.selectedRowKeys);
    },
    toRevoke(record) {
      this.Revoke([record.loadingBillId]);
    },
    Revoke(list) {
      let self = this;
      this.$confirm({
        title: '是否撤销？',
        onOk() {
          return new Promise((resolve, reject) => {
            self.spinning = true;
            Revoke(list)
              .then((res) => {
                self.spinning = false;
                if (res.success) {
                  self.$message.success(res.message);
                  self.onSearch();
                  resolve();
                } else {
                  self.$exception(res);
                  resolve();
                }
              })
              .finally(() => {
                self.spinning = false;
                reject();
              });
          });
        },
      });
    },

    onMap() {
      this.selectLineIdList = [...this.selectedRowKeys];
      this.editType = 'map';
    },
    onCalculateMileage() {},
    toView(record) {
      this.editData = { ...record };
      this.editType = 'view';
    },
    toEdit(record) {
      this.editData = { ...record };
      this.editType = 'edit';
    },

    async printAsnFun() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.error('请选择需要打印的订单');
        return;
      }
      // 请选择需要打印的订单/
      let data = {
        params: {
          loadingBillNo: this.selectedRowKeys,
        },
        printBillCode: 'TMS_LOADING_BILL_PRINT',
      };
      try {
        let res = await printAsn(data);
        if (!res.success) {
          this.$exception(res);
          return;
        }
        if (!res.data) {
          this.$message.error('打印数据为空');
          return;
        }
        const printRes = await toPrintServer(res.data.printData, { url: res.data.printAddress });
        if (printRes.success) {
          this.$message.success(printRes.message);
        } else {
          this.$exception(printRes);
        }
      } catch (error) {
        this.$exception(error);
      }
    },

    printAsnFunManifest() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.error('请选择需要打印的订单');
        return;
      }
      // 请选择需要打印的订单/
      this.printAsnFunManifest_1('LOADING_NON_MEDICAL');
      this.printAsnFunManifest_1('LOADING_MEDICAL');
    },
    async printAsnFunManifest_1(printBillCode) {
      let data = {
        params: {
          loadingBillIds: this.selectedRowKeys,
        },
        printBillCode,
      };
      try {
        let res = await printAsn(data);
        if (!res.success) {
          this.$exception(res);
          return;
        }
        if (!res.data) {
          this.$message.error('打印数据为空');
          return;
        }

        this.printAsnFunManifest_2(res.data.printData.data, printBillCode);

        const printRes = await toPrintServer(res.data.printData, { url: res.data.printAddress });
        if (printRes.success) {
          this.$message.success(printRes.message);
        } else {
          this.$exception(printRes);
        }
      } catch (error) {
        this.$exception(error);
      }
    },
    async printAsnFunManifest_2(printData, printBillCode) {
      let shipbillIds = new Set(),
        packageCodes = new Set();
      printData.forEach((item) => {
        item.table.forEach((item2) => {
          shipbillIds.add(item2.shipbillId);
          if (item2.packageCode !== '/') {
            packageCodes.add(item2.packageCode);
          }
        });
      });
      let data = {
        params: {
          shipbillIds: [...shipbillIds],
          packageCodes: [...packageCodes],
        },
        printBillCode: printBillCode + '_D',
      };
      try {
        let res = await printAsn(data);
        if (!res.success) {
          this.$exception(res);
          return;
        }
        if (!res.data) {
          this.$message.error('打印数据为空');
          return;
        }
        const printRes = await toPrintServer(res.data.printData, { url: res.data.printAddress });
        if (printRes.success) {
          this.$message.success(printRes.message);
        } else {
          this.$exception(printRes);
        }
      } catch (error) {
        this.$exception(error);
      }
    },
  },
};
</script>