<!--
@name: 待调度-拆分
@author: 张泽贤
@time: 2022-04-26
-->
<template>
  <p-card :bordered="false" class="full-card-panel">
    <a-space slot="title"> <a-icon type="arrow-left" style="color: #1990ff" @click="back" />运单拆分</a-space>
    <a-space slot="extra">
      <p-button type="primary" :disabled="spinning" style="float: right;" @click="onTableAdd">新增拆分行</p-button>
      <p-button type="primary" @click="onSave" :loading="spinning">提交</p-button>
    </a-space>
      <a-row :gutter="10" style="margin-bottom: 10px">
        <a-col :span="12">
          <p-grid-form ref="gridFrom" :span="12" >
            <p-grid-form-item label="运单号" :labelCol="{span:3}" :span="24">{{ selectedRow.shipbillNo }}</p-grid-form-item>
            <p-grid-form-item label="发货单位"  >{{ selectedRow.shipperUnitName }}</p-grid-form-item>
            <p-grid-form-item label="发货地址" >{{ selectedRow.shipperAddress }}</p-grid-form-item>
            <p-grid-form-item label="收货单位" >{{ selectedRow.consigneeUnitName }}</p-grid-form-item>
            <p-grid-form-item label="收货地址" > {{selectedRow.consigneeAddress}}</p-grid-form-item>
            <p-grid-form-item  label="拆单数量">{{splitList.length }}</p-grid-form-item>
          </p-grid-form>
        </a-col>
        <a-col :span="12">
          <t-table
            ref="goodsTable"
            :loading="spinning"
            dragle
            bordered
            row-key="id"
            :id="$route.meta.menuId + '_goodsTable'"
            :scroll="{ x: true }"
            :vScrollY="{enabled:true,rows:5}"
            :data-source.sync="goodsDataSource"
            :remote-url="goodsListRemoteUrl"
            :remoteData="goodsListParams"
            :rowSelectType="false"
            :autoLoad="false"
            :pagination="false"
          >
            <t-table-column data-index="itemCode" title="商品编码" :width="120" />
            <t-table-column data-index="itemName" title="商品名称" :width="120" />
            <t-table-column data-index="itemCategoryName" title="商品品类" :width="120" />
            <t-table-column data-index="pcs" title="件数" :width="120" />
            <t-table-column data-index="pcsDiff" title="件数差值" :width="120" />
            <t-table-column data-index="packTypeName" title="包装类型" :width="120" />
            <t-table-column data-index="cargoThermosphereName" title="货物温层" :width="120" />
            <t-table-column data-index="weight" title="重量" :width="120" />
            <t-table-column data-index="weightDiff" title="重量差值" :width="120" />
            <t-table-column data-index="volume" title="体积" :width="120" />
            <t-table-column data-index="volumeDiff" title="体积差值" :width="120" />
            <t-table-column data-index="memo" title="备注" :width="120" />
          </t-table>
        </a-col>
      </a-row>
        <p-card v-for="(item, index) in splitList" :key="item.id">
          <a-space slot="extra">
            <p-button type="primary" @click="onItemAdd(index)">新增明细行</p-button>
            <p-button type="danger" @click="onTableDel(index)">删除</p-button>
          </a-space>
          <t-table
            class="p-table-edit"
            :ref="'splitTable' + item.id"
            dragle
            bordered
            row-key="tableId"
            :scroll="{ x: true }"
            :vScrollY="{enabled:true,rows:5}"
            :data-source="item.dataSource"
            :rowSelectType="false"
            :autoLoad="false"
            :pagination="false"
          >
            <t-table-column data-index="itemCode" title="商品编码" :width="120" />
            <t-table-column data-index="itemName" title="商品名称" :width="120" />
            <t-table-column data-index="itemCategoryName" title="商品品类" :width="120" />
            <t-table-column data-index="packTypeName" title="包装类型" :width="120" />
            <t-table-column data-index="cargoThermosphereName" title="货物温层" :width="120" />
            <t-table-column data-index="pcs" title="件数" :width="120">
                <p-input-number  slot-scope="text, record"  :min="0" :max="record.pcsDiff" v-model="record.pcs"  style="width: 100%" @blur="pcsBlur(record)" />
            </t-table-column>
            <t-table-column data-index="weight" title="重量" :width="120">
                <p-input-number slot-scope="text, record" v-model="record.weight" style="width: 100%" @blur="numberBlur" />
            </t-table-column>
            <t-table-column data-index="volume" title="体积" :width="120">
                <p-input-number slot-scope="text, record" v-model="record.volume" style="width: 100%" @blur="numberBlur" />
            </t-table-column>
            <t-table-column data-index="height9" title="备注" :width="120" />
            <t-table-column key="action" title="操作" :width="120" fixed="right" align="center" >
                <a-space  slot-scope="text, record">
                  <a @click.stop="toDel(index, record)">删除</a>
                </a-space>
            </t-table-column>
          </t-table>
        </p-card>

    <p-modal title="选择商品" width="50%" :visible="visible" @ok="handleOk" @cancel="visible = false">
      <t-table
        ref="dialogTable"
        dragle
        bordered
        row-key="id"
        :id="$route.meta.menuId + '_dialogTable'"
        :scroll="{ x: true}"
        :vScrollY="{enabled:true,rows:6}"
        :data-source.sync="goodsDataSource"
        :rowSelectType="2"
        hasRowSelectCheck
        :selectedRowKeys="goodsSelectedRowKeys"
        @selectChange="selectChange"
        :autoLoad="false"
        :pagination="false"
        :getCheckboxProps="(record)=>({props:{disabled:!record.pcsDiff}  })"
      >
        <t-table-column data-index="itemCode" title="商品编码" :width="120" />
        <t-table-column data-index="itemName" title="商品名称" :width="120" />
        <t-table-column data-index="pcsDiff" title="件数差值" :width="120" />
        <t-table-column data-index="itemCategoryName" title="商品品类" :width="120" />
        <t-table-column data-index="packTypeName" title="包装类型" :width="120" />
        <t-table-column data-index="cargoThermosphereName" title="货物温层" :width="120" />
        <t-table-column data-index="weight" title="重量" :width="120" />
        <t-table-column data-index="volume" title="体积" :width="120" />
      </t-table>
    </p-modal>
  </p-card>
</template>

<script>
import { split_detail_list, goods_split, getItemListNoPage, getItemVolumeWeight } from '../js/api';

export default {
  props: {
    selectedRow: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      spinning: false,
      visible: false,

      goodsDataSource: [],
      goodsListRemoteUrl: split_detail_list,
      goodsListParams: {},
      goodsSelectedRowKeys: [],

      splitList: [],
      splitTableIndex: -1, // 用于储存选择额度哪个table
      itemDialog: false,
    };
  },
  mounted() {
    this.spinning = true;
   return getItemListNoPage({ shipbillId: this.selectedRow.shipbillId })
      .then((res1) => {
        let idList = res1.data.map((item) => item.itemId);
       return getItemVolumeWeight(idList)
          .then((res2) => {
            res1.data.forEach((item1) => {
              item1.pcsDiff=item1.pcs
              res2.data.forEach((item2) => {
                if (item1.itemId === item2.itemId) {
                  item1.unitVolume = item2.volume;
                  item1.unitWeight = item2.weight;
                }
              });
            });

            this.goodsDataSource = [...res1.data];

          })
          .finally(() => {
            this.spinning = false;
          });
      })
      .finally(() => {
        this.spinning = false;
      });
  },
  methods: {
    selectChange(selectKey, selectData) {
      this.goodsSelectedRowKeys=selectKey
    },
    // 返回
    back() {
      this.$emit('back');
    },

    // 添加表格
    onTableAdd() {
      this.splitList.push({
        id: new Date().getTime(),
        dataSource: [],
      });
      this.splitList = JSON.parse(JSON.stringify(this.splitList));
    },
    // 删除表格
    onTableDel(index) {
      this.splitList.splice(index, 1);
      this.numberBlur();
    },
    // 添加行
    onItemAdd(index) {
      this.goodsSelectedRowKeys = [];
      this.splitTableIndex = index;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs.dialogTable.scrollResize()
      })
      // this.splitList[this.splitTableIndex].dataSource.push({ tableId: new Date().getTime(), itemName: new Date().getTime() })
    },
    // 删除行
    toDel(index, record) {
      let rowIndex = this.splitList[index].dataSource.findIndex((item) => item.id === record.id);
      this.splitList[index].dataSource.splice(rowIndex, 1);
      this.numberBlur();
    },
    // 添加商品
    handleOk() {
      if (!this.goodsSelectedRowKeys.length) {
        this.$message.error('请选择商品');
        return false;
      }
      this.goodsDataSource.forEach((item) => {
        if (this.goodsSelectedRowKeys.includes(item.id)) {
          setTimeout(() => {
            let ele = { ...item };
            ele.tableId = new Date().getTime();
            ele.parentId = item.id;
            ele.pcs = 0;
            ele.weight = 0;
            ele.volume = 0;
            this.splitList[this.splitTableIndex].dataSource.push(ele);
          }, 100);
        }
      });
      this.visible = false;
    },

    onItemSplit() {},
    onPackSpit() {},

    // 保存
    onSave() {
      if(this.spinning) return
      for (let index = 0; index < this.goodsDataSource.length; index++) {
        const element = this.goodsDataSource[index];
        if (element.pcsDiff !== 0) {
          this.$message.error('商品' + element.itemName + '件数差值不为0');
          return false;
        }
        if (element.weight && element.weightDiff !== 0) {
          this.$message.error('商品' + element.itemName + '重量差值不为0');
          return false;
        }
        if (element.volume && element.volumeDiff !== 0) {
          this.$message.error('商品' + element.itemName + '体积差值不为0');
          return false;
        }
      }
      let params = {
        shipbillId: this.selectedRow.shipbillId,
        splitGoodsList: [],
      };
      this.splitList.forEach((item, index) => {
        params.splitGoodsList.push({
          splitGoodsDetailVOList: item.dataSource,
          splitNumber: index + 1,
        });
      });
      this.spinning = true;
      goods_split(params)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.$emit('back');
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    // 计算差值
    pcsBlur(record) {
      record.weight = parseFloat(this.BigJs(record.pcs || 0).times(record.unitWeight || 0));
      record.volume = parseFloat(this.BigJs(record.pcs || 0).times(record.unitVolume || 0));
      this.numberBlur();
    },
    numberBlur() {
      let numberObj = {};
      this.splitList.forEach((item1) => {
        item1.dataSource.forEach((record) => {
          if (!numberObj[record.parentId + '_' + record.itemCode]) {
            numberObj[record.parentId + '_' + record.itemCode] = {
              pcs: 0,
              weight: 0,
              volume: 0,
            };
          }
          numberObj[record.parentId + '_' + record.itemCode].pcs = parseFloat(this.BigJs(numberObj[record.parentId + '_' + record.itemCode].pcs || 0).plus(record.pcs || 0));
          numberObj[record.parentId + '_' + record.itemCode].weight = parseFloat(this.BigJs(numberObj[record.parentId + '_' + record.itemCode].weight || 0).plus(record.weight || 0));
          numberObj[record.parentId + '_' + record.itemCode].volume = parseFloat(this.BigJs(numberObj[record.parentId + '_' + record.itemCode].volume || 0).plus(record.volume || 0));
        });
      });

      this.goodsDataSource.forEach((item) => {
        item.pcsDiff = item.pcs;
        item.weightDiff = item.weight;
        item.volumeDiff = item.volume;
        if (numberObj[item.id + '_' + item.itemCode]) {
          item.pcsDiff = parseFloat(this.BigJs(item.pcsDiff).minus(numberObj[item.id + '_' + item.itemCode].pcs));
          item.weightDiff = parseFloat(this.BigJs(item.weightDiff).minus(numberObj[item.id + '_' + item.itemCode].weight));
          item.volumeDiff = parseFloat(this.BigJs(item.volumeDiff).minus(numberObj[item.id + '_' + item.itemCode].volume));
        } else {
        }
      });
      this.goodsDataSource = [...this.goodsDataSource];
    },
  },
};
</script>