<!--
@name: 待审核
@author: 张泽贤
@time: 2022-04-11
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_调度管理_1.2.2
-->
<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="onSearch" :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.cargoOwnerName"  @blur="event=> form.cargoOwnerName=event.target.value" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="订单号">
                <p-input :value="form.orderNo"  @blur="event=> form.orderNo=event.target.value"/>
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="运单号">
                <p-input  :value="form.shipbillNo"  @blur="event=> form.shipbillNo=event.target.value" />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="业务类型">
                <p-select v-model="form.orderBusinessType" :options="options.ORDER_BUSINESS_TYPE" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="预计提货时间" >
                <p-range-picker v-model="estimatedPickupTime" 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 label="预计送达时间" >
                <p-range-picker v-model="estimatedDeliveryTime" 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 label="收货方位置">
                <p-select v-model="form.consigneeLocation" :options="options.CONSIGNEE_LOCATION" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="6">
              <p-form-model-item label="发货方位置">
                <p-select v-model="form.shipperLocation" :options="options.SHIPPER_LOCATION" allowClear />
              </p-form-model-item>
            </a-col>
            <a-col :span="24">
              <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>
                </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="onReview" :disabled="!selectedRowKeys.length">审核</p-button>
          <p-button type="danger" @click="onBackOff" :disabled="!selectedRowKeys.length">回退</p-button>
          <a-dropdown>
            <template #overlay>
              <a-menu>
                <a-menu-item type="link" key="1" :disabled="!selectedRowKeys.length">
                  <p-button type="link" @click="mapPase" :disabled="selectedRowKeys.length === 0">地址解析</p-button>
                </a-menu-item>
                <a-menu-item key="2">
                  <export-button
                    type="link"
                    :ids="selectedRowKeys"
                    :pages="mainPages"
                    :getSearchValue="() => listParams"
                    downloadFileName="待审核"
                    :allUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_review/export_all_detail'"
                    :currentUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_review/export_current_page_detail'"
                    :selectUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_review/export_select_line_detail'"
                    >导出</export-button
                  >
                </a-menu-item>
                <a-menu-item type="link" key="3" v-action:print>
                  <p-button type="link" :disabled="selectedRowKeys.length === 0">打印</p-button>
                </a-menu-item>
                <a-menu-item type="link" key="4" v-action:location>
                  <p-button type="link" @click="onLocation" :disabled="selectedRowKeys.length === 0">定位</p-button>
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>更多</a-button>
          </a-dropdown>
        </a-space>
        <t-table
          ref="masterTable"
          dragle
          rowSelectFixed
          bordered
          :extendedObjectCode="'15'"
          row-key="shipbillId"
          :id="$route.meta.menuId + '_vehicleManagement'"
          :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="(selectKeys)=>selectedRowKeys=selectKeys"
          @clickRow="masterClickRow"
          :sign="true"
          :doneBefore="doneBefore"

          :attachFooter="[{ key: 'totalPcs' }, { key: 'totalVolume' }, { key: 'totalWeight' }]"
        >
          <template slot="operation" slot-scope="text, record">
            <a-space>
              <a @click.stop="toView(record)">查看</a>
              <a @click.stop="toReview(record)">审核</a>
              <a @click.stop="toBackOff(record)">回退</a>
              <a @click.stop="toPrint(record)" v-action:print>打印</a>
            </a-space>
          </template>
        </t-table>
      </p-card>
      <a-row>
        <a-col :span="12">
          <p-card title="商品信息">
            <t-table
              ref="goodsTable"
              dragle
              bordered
              :extendedObjectCode="'17'"
              row-key="id"
              :id="$route.meta.menuId + '_goodsTable'"
              :scroll="{ x: true}"
             :vScrollX="{enabled:false}"
             :vScrollY="{enabled:true,rows:4}"
              :columns="goods_columns"
              :data-source.sync="goodsDataSource"
              :remote-url="goodsListRemoteUrl"
              :remoteData="goodsListParams"
              :rowSelectType="false"
              @selectChange="(selectKey, selectData)=>goodsSelectedRowKeys=selectKey"
              :autoLoad="false"
              @clickRow="goodsClickRow"
            >
            </t-table>
          </p-card>
        </a-col>
        <a-col :span="12">
          <p-card title="包裹信息">
            <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.sync="packDataSource"
              :remote-url="packListRemoteUrl"
              :remoteData="packListParams"
              :rowSelectType="false"
              @selectChange="(selectKey, selectData)=>selectedRowKeys=selectKey"
              :autoLoad="false"
              @clickRow="packClickRow"
            >
            </t-table>
          </p-card>
        </a-col>
      </a-row>
    </p-spin>

    <p-modal title="回退" width="50%" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="visible = false">
      <p-grid-form ref="model" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <p-grid-form-item label="回退类型" name="backType" type="select" :options="options.BACK_TYPE" :required="true"></p-grid-form-item>
        <p-grid-form-item label="回退原因" name="backReason" type="textarea"></p-grid-form-item>
      </p-grid-form>
    </p-modal>

    <!-- <addressAnalysis v-if="editType === 'address'" :searchParams="addressSearchData" @back="editType = ''"></addressAnalysis> -->
    <addressAnalysis
      :showType="addressAnalysisShow"
      rowKey="shipbillId"
      :remoteUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_review/address_resolution/page'"
      :saveUrl="UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/pending_review/parse_address'"
      :searchParams="addressSearchData"
      @back="addressBack"
    />

    <edit v-show="editType === 'view'" parcelTable :options="options" :record="editId ? { shipbillId: editId } : null" :formExtendedField="formExtendedField" @back="editType = ''"></edit>
    <!-- :goods_tableExtendedField="goods_tableExtendedField" -->
  </div>
</template>

<script>
import { initDictionary, resultExtendedField } from '@/blocks/utils';
import edit from '@/blocks/components/orderView/index.orderView.vue';
import addressAnalysis from '@/views/TMS/order/orderManage/model/addressAnalysis/addressAnalysis.index.vue';
import { UPCLOUD_RDC_TMS_BUSINESS_SERVICE } from '@/config/serviceSettings.js';
import exportButton from '@/blocks/components/export-modal/modal.index.vue';
import { setMainColumns, setGoodsColums, setPackColums } from '@/blocks/components/scheduling/js/table/tableConfig.js';

import { listRemoteUrl, page_detail_item, page_package_item, page_detail_package, page_item_package, Review, Back, Print, viewUrl, Location } from './js/api';

export default {
  components: { addressAnalysis, edit, exportButton },
  computed: {
    estimatedPickupTime: {
      get() {
        return [this.form.estimatedPickupStartTime, this.form.estimatedPickupEndTime];
      },
      set(value) {
        this.$set(this.form, 'estimatedPickupStartTime', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'estimatedPickupEndTime', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
    estimatedDeliveryTime: {
      get() {
        return [this.form.estimatedDeliveryStartTime, this.form.estimatedDeliveryEndTime];
      },
      set(value) {
        this.$set(this.form, 'estimatedDeliveryStartTime', value.length ? value[0] + ' 00:00:00' : '');
        this.$set(this.form, 'estimatedDeliveryEndTime', value.length ? value[1] + ' 23:59:59' : '');
      },
    },
  },
  data() {
    return {
      formExtendedField: {
        form: [],
        formTable: [],
      },
      UPCLOUD_RDC_TMS_BUSINESS_SERVICE,
      spinning: false,
      editType: '', // 空-列表页 view-查看 address-地址解析
      editId: '',
      visible: false,
      confirmLoading: false,
      form: {
        cargoOwnerName: '',
        orderNo: '',
        shipbillNo: '',
        estimatedPickupStartTime: '',
        estimatedPickupEndTime: '',
        estimatedDeliveryStartTime: '',
        estimatedDeliveryEndTime: '',
        consigneeLocation: '',
        shipperLocation: '',
      },
      options: {
        ORDER_BUSINESS_TYPE: [],
        CONSIGNEE_LOCATION: [],
        SHIPPER_LOCATION: [],
        BACK_TYPE: [],
      },

      // 主表格
      dataSource: [],
      selectedRowKeys: [],
      listRemoteUrl,
      listParams: {
        consigneeLocation: '',
        shipperLocation: '',
      },
      mx_columns: setMainColumns(this, this.tableExtendedField),
      mextendedField_list: [],
      tableExtendedField: [],
      mainPages: { pageNum: 1, pageSize: 15 },

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

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

      addressSearchData: {}, // 列表点击地址解析时的查询传参

      idList: [],

      addressAnalysisShow: 0,
    };
  },
  mounted() {
    initDictionary([{ objectcode: 'ORDER_BUSINESS_TYPE' }, { objectcode: 'BACK_TYPE' }, { objectcode: 'CONSIGNEE_LOCATION' }, { objectcode: 'SHIPPER_LOCATION' }]).then((res) => {
      this.options.ORDER_BUSINESS_TYPE = res.ORDER_BUSINESS_TYPE.map((item) => {
        item.value = +item.value;
        return item;
      });
      this.options.CONSIGNEE_LOCATION = res.CONSIGNEE_LOCATION.map((item) => {
        item.value = +item.value;
        return item;
      });
      this.options.SHIPPER_LOCATION = res.SHIPPER_LOCATION.map((item) => {
        item.value = +item.value;
        return item;
      });
      this.options.BACK_TYPE = res.BACK_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.formExtendedField.form = res.form;
        this.mx_columns = setMainColumns(this, this.tableExtendedField);
      }
    });
    resultExtendedField({ extendedObjectCode: '17' }).then((res) => {
      if (res) {
        this.goods_tableExtendedField = res.table;
        this.formExtendedField.formTable = res.table;
        this.goods_columns = setGoodsColums(this, this.goods_tableExtendedField);
      }
    });
  },
  methods: {
    viewUrl,
    // 查询
    onSearch(event) {
      if (event) {
        event.preventDefault()
         event.submitter.focus();
      }
      this.dataSource = [];
      this.selectedRowKeys = [];
      this.goodsDataSource = [];
      this.goodsSelectedRowKeys = [];
      this.packDataSource = [];
      this.packSelectedRowKeys = [];
      this.listParams = { ...this.form };
    },
    // 重置
    onReset() {
      this.form = {
        cargoOwnerName: '',
        orderNo: '',
        shipbillNo: '',
        estimatedPickupStartTime: '',
        estimatedPickupEndTime: '',
        estimatedDeliveryStartTime: '',
        estimatedDeliveryEndTime: '',
        consigneeLocation: '',
        shipperLocation: '',
      };
    },
    doneBefore(res) {
      const { pageNum, pageSize } = res.data;
      this.mainPages = { pageNum, pageSize };
    },
    masterClickRow(event, activeID, rowRecord) {
      this.goodsListRemoteUrl = page_detail_item;
      this.packListRemoteUrl = page_detail_package;
      this.goodsListParams = { shipbillId: rowRecord.shipbillId };
      this.packListParams = { shipbillId: rowRecord.shipbillId };
    },
    goodsClickRow(event, activeID, rowRecord) {
      this.packListRemoteUrl = page_package_item;
      this.packListParams = { shipbillId: rowRecord.shipbillId, itemId: rowRecord.itemId };
    },
    packClickRow(event, activeID, rowRecord) {
      this.goodsListRemoteUrl = page_item_package;
      this.goodsListParams = { shipbillId: rowRecord.shipbillId, packageId: rowRecord.packageId };
    },

    // 查看
    toView(editData = { shipbillId: '' }) {
      this.editId = editData.shipbillId;
      this.editType = 'view';
    },

    // 审核
    onReview() {
      this.Review(this.selectedRowKeys);
    },
    toReview(editData) {
      this.Review([editData.shipbillId]);
    },
    Review(list) {
      this.spinning = true;
      Review(list)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.$refs.masterTable.reload();
            this.goodsDataSource = [];
            this.packDataSource = [];
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    // 回退
    toBackOff(editData) {
      this.BackOff([editData.shipbillId]);
    },
    onBackOff() {
      this.BackOff(this.selectedRowKeys);
    },
    BackOff(idList) {
      this.idList = idList;
      this.visible = true;
      this.$refs.model && this.$refs.model.form.resetFields();
    },
    handleOk() {
      this.$refs.model.form.validateFields(async (err, value) => {
        if (!err) {
          Back({ backReason: value.backReason, backType: value.backType, shipbillIdList: this.idList })
            .then((res) => {
              if (res.success) {
                this.visible = false;
                this.$message.success(res.message);
                this.$refs.masterTable.reload();
                this.goodsDataSource = [];
                this.packDataSource = [];
              } else {
                this.$exception(res);
              }
            })
            .catch((res) => {
              this.$exception(res);
            });
        }
      });
    },

    // 打印
    toPrint(editData) {
      this.Print([editData.shipbillId]);
    },
    Print(list) {
      this.spinning = true;
      Print(list)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    // 地址解析
    mapPase() {
      this.addressSearchData = {
        shipbillIds: this.selectedRowKeys,
      };
      this.addressAnalysisShow = 2;
      this.editType = 'address';
    },
    addressBack() {
      this.addressAnalysisShow = 0;
      this.editType = '';
    },

    // 定位
    onLocation() {
      let list = [];
      this.dataSource.forEach((item) => {
        if (this.selectedRowKeys.includes(item.shipbillId)) {
          list.push({
            shipbillId: item.shipbillId,
            shipperType: item.shipperType,
            shipperId: item.shipperId,
            consigneeType: item.consigneeType,
            consigneeId: item.consigneeId,
          });
        }
      });
      this.spinning = true;
      Location(list)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.$refs.masterTable.reload();
            this.goodsDataSource = [];
            this.packDataSource = [];
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
  },
};
</script>