/*
 *@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"> {{ $route.meta.title }}:先扫运单再扫商品</a-space>
        <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-tabs type="card" v-model="tabKey">
          <a-tab-pane key="1" tab="直接派车"></a-tab-pane>
          <a-tab-pane key="2" tab="委托承运商"></a-tab-pane>
        </a-tabs>
        <p-grid-form ref="form" layout="inline" style="display: inline-block" :items="formItems" @submit.prevent="handleOk">
          <div style="margin: 20px auto 0 auto; text-align: center">
            <a-space>
              <p-button size="large" style="width: 200px" @click="reset">清空重扫</p-button>
              <p-button html-type="submit" style="width: 200px" type="primary" size="large">直接派车</p-button>
            </a-space>
          </div>
        </p-grid-form>
      </a-page-header>
      <a-page-header style="background-color: #fff" :bordered="false" title="扫描结果">
        <p-button slot="extra" icon="delete" type="primary" :disabled="!selectedRowKeys.length" @clickSync="removeItem(selectedRowKeys)">删除</p-button>
        <p-table
          ref="shipbill"
          dragle
          bordered
          row-key="shipbillId"
          hasRowSelectCheck
          autoColWidth
          :data-source.sync="billDataSource"
          :scroll="{ x: true,y: 300,minHeight:300 }"
          :rowSelectType="2"
          :pagination="false"
          :columns="shipbillColumns"
          :selectedRowKeys.sync="selectedRowKeys"
          @selectChange="masterClickRow"
        >
        </p-table>
      </a-page-header>
      <a-page-header style="background-color: #fff" :bordered="false" title="商品信息">
        <p-button slot="extra" icon="delete" type="primary" :disabled="!goodsSelectedRowKeys.length" @clickSync="removeGoods(goodsSelectedRowKeys)">删除</p-button>

        <p-table-edit-pro
          bordered
          ref="tableGoods"
          :id="$route.meta.menuId + '-goods'"
          rowKey="_row_count"
          :rowSelectType="2"
          hasRowSelectCheck
          :selectedRowKeys.sync="goodsSelectedRowKeys"
          :scroll="{ x: 2200, y: 300,minHeight:300  }"
          :pagination="false"
          dragle
          :columns="columns"
          :activeKey="goodsKey"
          :dataSource.sync="goodsList"
        />
      </a-page-header>
    </a-spin>
  </div>
</template>
<script>
import { queryShipbillByLoadingBill, loadingScan, scanDispatch_dispatch } from '../js/api';
import setGoodsTable from './goodsTableConfig';
import { shipbillColumns } from './tableConfig.js';
import getFormItems from './getformItems.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: {
    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() {
    this.shipbillColumns = shipbillColumns(this);
    this.columns = setGoodsTable(this);
    this.shipbillNoCaches = new Set();
    this.goodsCaches = new Map();

    return {
      carrierId: '',
      tabKey: '1',
      formItems: getFormItems(this),
      message,
      goodsKey: '',
      sysConfig: null,
      loading: false,
      magType: 'info',
      flag: 1,
      billDataSource: [],
      selectedRowKeys: [],
      goodsSelectedRowKeys: [],
      goodsList: [],
      confirmLoading: false,
    };
  },
  watch: {
    tabKey() {
      this.carrierId = '';
      this.$refs.form.form.resetFields();
      this.formItems = getFormItems(this);
    },
  },
  mounted() {
    //getSysConfig(this);
  },
  methods: {
    reset() {
      this.carrierId = '';
      this.$refs.form.form.resetFields();
      this.shipbillNoCaches = new Set();
      this.goodsCaches = new Map();
      this.billDataSource = [];
      this.selectedRowKeys = [];
      this.goodsList = [];
      this.flag = 1;
      this.$refs.scanInput.focus();
    },
    removeGoods(arr) {
      arr.forEach((_row_count) => {
        let itme = this.goodsList.find(item => item._row_count == _row_count);
        console.log(itme)
        if (itme) {

          let map=this.goodsCaches.get(itme.itemCode)
           map?.delete(itme.shipbillId)
           console.log('map',map)
        }
      })
      this.$refs.tableGoods.removeRows(arr);
      console.log(this.shipbillNoCaches)
      console.log(this.goodsCaches)


    },
    removeItem(arr) {
      this.$refs.shipbill.removeRows(arr);

        arr.forEach((sid) => {
          this.shipbillNoCaches.delete(sid);
          this.goodsCaches.forEach(item => {
            item.delete(sid)
          });
          if (this.goodsList.length > 0) {
            this.goodsList = this.goodsList.filter((data) => {
            return sid !== data.shipbillId;
          });
          }
        });
      this.$nextTick(() => {
          this.selectedRowKeys=[]
        this.$refs.scanInput.focus();
        console.log(this.shipbillNoCaches)
        console.log(this.goodsCaches)

        });

    },
    form() {
      return this.$refs.grid.form;
    },
    async handleOk() {
      this.$refs.form.form.validateFields((err, vals) => {
        if (err) return;
        let loadingBillHeaderVO = vals;
        let loadingBillDetailVO = this.billDataSource.map(({ shipbillId }) => {
          return { shipbillId };
        });
        let shipbillDetailVO = this.goodsList.map(({ shipbillId, applyPcs, pcs, id }) => {
          return { shipbillId, applyPcs, pcs, id };
        });

        //@ApiModelProperty(value = "装车单汇总")
        // private LoadingBillHeaderVO loadingBillHeaderVO;

        // @ApiModelProperty(value = "装车单明细")
        // private List<LoadingBillDetailVO> loadingBillDetailVO;

        // @ApiModelProperty(value = "运单明细")
        // private List<ShipbillDetailVO> shipbillDetailVO;

        return scanDispatch_dispatch(this, {
          loadingBillHeaderVO,
          shipbillDetailVO,
          loadingBillDetailVO,
        }).then((res) => {
          if (res.success) {
            this.reset();
          }
        });
      });
    },
    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) {
        //扫描商品
        let shipbillNo = Array.from(this.shipbillNoCaches);

        return this.loadingScan({ billCode: scanId, shipbillNo: shipbillNo.join(',') });
      }
    },
    //扫描没有扫过的派车单  { billCode: scanId, loadingBillNo: scanId }
    loadingScan(params) {
      return loadingScan(this, params)
        .then((res) => {
          if (res.success) {
            let { shipbillNo, billCode } = params;
            this.magType = 'success';
            this.message = res.message;
            let { codeType, scannedShipbillList, scannedShipbillDetailList } = res.data;
            if (codeType == 1) {
              if (this.shipbillNoCaches.has(billCode)) {
                this.magType = 'warning';
                this.message = '该运单号已存在！';
                return;
              }
              this.shipbillNoCaches.add(billCode);
              let same = this.billDataSource.find((item) => item == billCode);
              if (!same) {
                this.billDataSource = this.billDataSource.concat(scannedShipbillList);
              }
              this.flag = 2;
            } else if (codeType == 3) {
              let arr = new Set()
              console.log(this.shipbillNoCaches)
              console.log(this.goodsCaches)
              if (this.goodsCaches.has(billCode)) {
                arr = this.goodsCaches.get(billCode);
                if (arr.size > 0) {
                  scannedShipbillDetailList = scannedShipbillDetailList.filter(item => {
                    return !(arr.has(item.shipbillNo)&&item.itemCode==billCode)
                  });

                if (!scannedShipbillDetailList.length) {
                  this.magType = 'warning';
                  this.message = '该商品条码已存在！';
                  return;
                }
                }

              }
              console.log(this.goodsCaches);

              shipbillNo = shipbillNo.split(',');
              shipbillNo.forEach(NO => {
                arr.add(NO)
              })

              this.goodsCaches.set(billCode, arr);
              this.goodsList = this.goodsList.concat(scannedShipbillDetailList);
            }
          } else {
            this.magType = 'warning';
            this.message = res.message;
          }
        })
        .finally(() => {
          this.$refs.scanInput.focus();
        });
    },

    //通过已扫过的派车查询商品
    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;

          } 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);
      }
    },
  },
};
</script>

