/*
 *@description:装车扫描
 *@author: hudw
 *@date: 2022-07-07 14:02:01
*/
<template>
  <div class="pages">
    <a-spin :spinning="loading">

    <a-page-header style="background-color: #fff" :bordered="false">
      <a-space slot="title"> <a-icon type="arrow-left" @click="$emit('back')" :style="{ color: '#08c' }" />装车扫描:{{ scanType[system] }}</a-space>
      <p-button slot="extra" size="large" type="primary" style="width: 120px" :disabled="selectedRowKeysLength === 0" @click.stop="completeScan">装车确认</p-button>
      <p-grid-form ref="grid" @submit="scanSubmit" style="margin-bottom: 10px" justify="center" :span="12" selfUpdate class="scan-form" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18 }">
        <!-- value="ZCD0000000022" -->
        <p-grid-form-item :wrapperCol="{ span: 24 }" name="scanId" style="padding-right: 20px">
          <p-input class="scan-input" ref="scanInput" :disabled="loading" :placeholder="flag === 1 ? '请扫描派车单号' : '请扫描运单号'">
            <a-icon slot="prefix" :style="{ fontSize: '30px', color: '#ccc' }" type="scan" />
            <a-icon v-if="loading" slot="suffix" :style="{ fontSize: '30px', color: '#ccc' }" type="loading" />
          </p-input>
        </p-grid-form-item>
        <p-grid-form-item :wrapperCol="{ span: 24 }" :type="null">
          <a-alert class="scan-msg" :message="message" :type="magType" show-icon />
        </p-grid-form-item>
      </p-grid-form>
    </a-page-header>
    <a-page-header style="background-color: #fff; margin-top: 10px" :bordered="false" title="派车单信息">
      <!-- <p-grid-form ref="shipbill" style="margin-bottom: 10px" :items="paiCeItems" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }" :span="4" /> -->
      <p-table
        ref="shipbill"
        dragle
        bordered
        row-key="loadingBillId"
        hasRowSelectCheck
        :customScrollbar="true"
        :data-source="billDataSource"
        :scroll="{ x: true, y: 300 }"
        :rowSelectType="1"
        :pagination="false"
        :columns="paiCeItems"
        :selectedRowKeys="selectedRowKeys"
        @selectChange="masterClickRow"
        >
        <template slot="vehicleDevice" slot-scope="text, record">
          <p-search-modal
            v-model="record.vehicleDeviceName"
            v-bind="$data.$formItems.deviceAttr_scanPage"
            :remoteBefore="
              (vNode, remoteUrl) => {
                remoteUrl.data = { vehicleId: record.vehicleId, ...remoteUrl.data };
              }
            "
            @change="(...args) => onTableChange('vehicleDevice', record, ...args)"
          />
        </template>
      </p-table>
    </a-page-header>

      <a-page-header style="background-color: #fff; margin-top: 10px" :bordered="false" title="运单信息">
        <a-transfer
          class="scan-transfer"
          :show-select-all="false"
          :rowKey="(record) => record.shipbillId"
          :dataSource="transferData"
          :targetKeys="targetKeys"
          :locale="{ itemUnit: '项', itemsUnit: '项', notFoundContent: '列表为空', searchPlaceholder: '请输入名称' }"
          :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
          :titles="talbeTitle"
        >
          <template slot="children" slot-scope="{ props: { direction, filteredItems, selectedKeys }, on: { itemSelectAll, itemSelect } }">
            <p-table
              :ref="'table-transfer-' + direction"
              :id="$route.meta.menuId + '_transfer_1' + direction"
              class="table-body-height"
              rowKey="shipbillId"
              :rowSelectType="false"
              :scroll="{ x: 2200, y: 400 }"
              :pagination="false"
              dragle
              :columns="columns"
              :activeKey="goodsKey"
              :dataSource="filteredItems"
            />
          </template>
        </a-transfer>
      </a-page-header>
<!--
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="未扫描运单">
          <p-table
             :autoLoad="false"
            :customScrollbar="true"
            :ref="'table-transfer-' + 'left'"
            :id="$route.meta.menuId + '_transfer_' + 'left'"
            class="table-body-height"
            rowKey="shipbillId"
            :rowSelectType="false"
            :scroll="{ x: 6000, y: 400 }"
            :pagination="false"
            dragle
            :columns="waitColumns"
            :dataSource="waitPickUpGoodsNotScannedDTOS"
            @view="handleView"
          />
        </a-tab-pane>
        <a-tab-pane key="2" tab="已扫描运单" force-render>
          <p-table
            :customScrollbar="true"
            :ref="'table-transfer-' + 'right'"
            :id="$route.meta.menuId + '_transfer_' + 'right'"
            class="table-body-height"
            rowKey="shipbillId"
            :rowSelectType="false"
            :scroll="{ x: 6000, y: 400 }"
            :pagination="false"
            dragle
            :columns="columns"
            :dataSource="pickUpGoodsNotScannedDTOS"
            @view="handleView"
          />
        </a-tab-pane>
      </a-tabs> -->
    </a-spin>

  </div>
</template>
<script>
import * as $formItems from '@/blocks/components/searchModalConfig/index';
import {getBillScanInfo, queryShipbillByLoadingBill, loadingScan, loading_confirm } from '../../api.js';
// import { setMainColumns } from '@/views/TMS/transportation/$common/mainTable/tableConfig.js';

import { setPaiCeItems } from './config.js';
import { setMainColumns } from './tableConfig.js';
const message = '请扫描派车单号!';
export default {
  props: {
    st: {
      type: Number,
      default: 0,
    },
    system: {
      type: null,


    },
    options: {
      type: null,
    },
    portName: {
      type: String,
      default: 'waitLoadingAndUnloading',
    },
  },
  computed: {
    selectedRowKeysLength() {
      return this.selectedRowKeys.length;
    },


  },
  watch: {
    st(value) {
      this.targetKeys = [];
      this.transferData = [];
      this.selectedRowKeys = [];
      if (value === 5) {
        getBillScanInfo(this);
      }
    },


    selectedRowKeys(value) {
      if (!value.length) {
        this.flag = 1;
      }
    },
    flag(value) {
      let form = this.form();
      setTimeout(() => {
        form.setFieldsValue({ scanId: '' });
        this.magType = 'info';
        if (value == 1) {
          this.message = '请扫派车单号!';
        } else if (value == 2) {
          this.message = '请扫运单号';
        }
      }, 1000);
    },
  },
  data() {
    let waitColumns = setMainColumns(this, false);
    let columns = setMainColumns(this, true);
    waitColumns.pop();
    columns.pop();
    this.scanType = {
      1: '先扫描派车单号再扫描运单号',
      2: '先扫描派车单号再扫描包裹号',
      3: '先扫描派车单号再扫描商品条码',
      4: '只扫描派车单号',
      5: '只扫描运单号',
      6: '只扫描包裹号',
      7: '只扫描商品条码',
    };
    return {
      $formItems,
      message,
      goodsKey: '',
      paiCeItems: setPaiCeItems(this),
      sysConfig: null,
      transferData: [],
      targetKeys: [],
      talbeTitle: ['未扫描运单号信息', '已扫描运单号信息'],
      loading: false,
      waitColumns,
      columns,
      magType: 'info',
      flag: 1,
      billDataSource: [],
      selectedRowKeys: [],
      confirmLoading: false,
    };
  },
  mounted() {
    //getSysConfig(this);
  },
  methods: {
    form() {
      return this.$refs.grid.form;
    },

    completeScan() {
      let record = this.billDataSource.find((item) => item.loadingBillNo === this.selectedRowKeys[0]);
      if (!record) return false;
      let { loadingBillId, vehicleDeviceId, vehicleDeviceCode, vehicleDeviceName, coldShipbillNumber, vehicleTypeCategoryName } = record;
      if (coldShipbillNumber == '0' && vehicleTypeCategoryName === '常温' && !vehicleDeviceId) {
        this.$message.error('请先绑定设备');
        return false;
      }
      this.handleOk()

    },

    async handleOk() {
      let record = this.billDataSource.find((item) => item.loadingBillNo === this.selectedRowKeys[0]);
      let { loadingBillId, vehicleDeviceId, vehicleDeviceCode, vehicleDeviceName, coldShipbillNumber, vehicleTypeCategoryName } = record;
      let noScannedShipbillList = [],
        scannedShipbillList = [];
      //如果有没有扫完的商品
      this.transferData.forEach((item) => {
        if (this.targetKeys.includes(item.shipbillId)) {
          scannedShipbillList.push(item.itemId);
        } else {
          noScannedShipbillList.push(item.itemId);
        }
      }, this);

      let value = {
        containerWithVehicle:1,
        loadingBillId,
        vehicleDeviceId,
        vehicleDeviceCode,
        vehicleDeviceName,
        noScannedShipbillList,
        scannedShipbillList,
        scanLoadingMethod: this.system,
      };

      value.loadingBillId = value.loadingBillId.trim();
      let scanInput = this.$refs.scanInput;
      try {
        const res = await loading_confirm(this, value);
        if (res.success) {
          this.targetKeys = [];
          this.flag = 1;
          this.$nextTick(() => {
            scanInput.focus();
            // 清空当前选中的派车单
            this.billDataSource = this.billDataSource.filter((item) => item.loadingBillId != record.loadingBillId);
            this.selectedRowKeys = [];
            this.targetKeys = [];
            this.transferData = [];
          });
        }
      } finally {
      }
    },
    scanSubmit(event, form) {
      event?.preventDefault();
      if (!form) {
        form = this.form();
      }
      let value = form.getFieldsValue();
      value.scanId = value.scanId ? value.scanId.trim() : '';
      let scanId = value.scanId;
      let master = this.billDataSource.find((item) => item.loadingBillId === value.scanId);
      if (master) {
        this.selectedRowKeys = [master.loadingBillId];
          //通过已扫过的派车查询商品
        return this.queryShipbillByLoadingBill(master.loadingBillId);

      }
      if (this.flag === 1) {
        return this.loadingScan({ billCode: scanId });
      } else if (this.flag === 2) {
        //扫描商品
        return this.loadingScan({ billCode: scanId, loadingBillNo: this.selectedRowKeys[0] });
      }
    },
    //扫描没有扫过的派车单  { billCode: scanId, loadingBillNo: scanId }
     //扫描没有扫过的派车单  { billCode: scanId, loadingBillNo: scanId }
     loadingScan(params) {
      return loadingScan(this, params).then((res) => {
        if (res.success) {
          this.magType = 'success';
          this.message =res.message;
          const { codeType, scannedShipbillList, scannedLoadingBillDTOList, noScannedShipbillList } = res.data;
          if (codeType == 1) {
            this.selectedRowKeys = [params.billCode];

            let same = this.billDataSource.find(item => item == params.billCode)
            if (!same) {
              this.billDataSource = this.billDataSource.concat(scannedLoadingBillDTOList);
            }
            this.targetKeys = [];
            this.transferData = noScannedShipbillList.concat(scannedShipbillList);
            if (this.flag == 1) {
              //this.activeKey = params.billCode;
             // this.selectedRowKeys = [params.billCode];
            }
            this.flag = 2;
          } else if (codeType == 2) {
            //运单
            this.targetKeys = scannedShipbillList.map((item) => {
              return item.shipbillId;
            });
            this.goodsKey = params.billCode


          }
          this.$nextTick(() => {
          let left = this.$refs['table-transfer-left'];
          if (left.tData.length === 0) {
            this.completeScan();
          }
        });

        } else {
          this.magType = 'warning';
          this.message = res.message;
        }
      })
    },

    //通过已扫过的派车查询商品
    queryShipbillByLoadingBill(loadingId) {
      return queryShipbillByLoadingBill(this, { loadingId }).then((res) => {
        if (res.success) {
          this.magType = 'success';
          this.message = '查询成功';
          const { codeType, scannedShipbillList, noScannedShipbillList } = res.data;

          //没扫商品
          this.targetKeys = scannedShipbillList.map((item) => {
            return item.shipbillId;
          });
          //所有商品
          this.transferData = [...scannedShipbillList, ...noScannedShipbillList];
          this.activeKey = loadingId;
          this.selectedRowKeys = [loadingId];
          this.flag = 2;
          this.$nextTick(() => {
          let left = this.$refs['table-transfer-left'];
          if (left.tData.length === 0) {
            this.completeScan();
          }
        });
        } else {
          this.magType = 'warning';
          this.message = res.message;
        }
      }).finally(() => {

      })
    },
    masterClickRow(selectedRowKeys, selectedRows) {
      this.activeKey = selectedRowKeys[0] || '';
      this.targetKeys = [];
      this.transferData = [];
      this.selectedRowKeys = selectedRowKeys;
      this.flag = 1;

      if (this.activeKey) {
        let form = this.form();
        form.setFieldsValue({ scanId: this.activeKey });
        this.queryShipbillByLoadingBill(this.activeKey);
      }
    },
    onTableChange(name, record, ...args) {
      if (name === 'vehicleDevice') {
        this.$set(record, 'vehicleDeviceId', args[1] ? args[2][0].deviceId : '');
        this.$set(record, 'vehicleDeviceCode', args[1] ? args[2][0].deviceCode : '');
        this.$set(record, 'vehicleDeviceName', args[1]);
      }
    },

    handleView(data) {
      this.$emit('view', data);
    },
  },
};
</script>

