<!--
@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" @click="onSave" :loading="spinning">提交</p-button>
    </a-space>
    <p-spin :spinning="spinning">
      <a-row style="margin-bottom: 10px">
        <a-col :span="12">
          <p-form-model ref="formTarget" :model="selectedRow" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" class="plg-grid-from">
            <a-row>
              <p-col :span="12">
                <p-form-model-item label="运单号">{{ selectedRow.shipbillNo }}</p-form-model-item>
              </p-col>
            </a-row>
            <a-row>
              <p-col :span="12">
                <p-form-model-item label="发货单位">{{ selectedRow.shipperUnitName }}</p-form-model-item>
              </p-col>
              <p-col :span="12">
                <p-form-model-item label="发货地址">{{ selectedRow.shipperAddress }}</p-form-model-item>
              </p-col>
            </a-row>
            <a-row>
              <p-col :span="12">
                <p-form-model-item label="收货单位">{{ selectedRow.consigneeUnitName }}</p-form-model-item>
              </p-col>
              <p-col :span="12">
                <p-form-model-item label="收货地址">{{ selectedRow.consigneeAddress }}</p-form-model-item>
              </p-col>
            </a-row>
            <a-row>
              <p-col :span="12">
                <p-form-model-item label="拆单数量">{{ splitList.length }}</p-form-model-item>
              </p-col>
              <a-col :span="12" style="text-align: right; padding-right: 20px">
                <p-button type="primary" @click="onTableAdd">新增拆分行</p-button>
              </a-col>
            </a-row>
          </p-form-model>
        </a-col>
        <a-col :span="12">
          <p-table
            ref="goodsTable"
            dragle
            :customScrollbar="true"
            bordered
            row-key="id"
            :id="$route.meta.menuId + '_goodsTable'"
            :scroll="{ x: true, y: 160 }"
            :data-source.sync="goodsDataSource"
            :remote-url="goodsListRemoteUrl"
            :remoteData="goodsListParams"
            :rowSelectType="false"
            :autoLoad="false"
            :pagination="false"
          >
            <p-table-column data-index="itemCode" title="商品编码" :width="120" />
            <p-table-column data-index="itemName" title="商品名称" :width="120" />
            <p-table-column data-index="itemCategoryName" title="商品品类" :width="120" />
            <p-table-column data-index="packTypeName" title="包装类型" :width="120" />
            <p-table-column data-index="cargoThermosphereName" title="货物温层" :width="120" />
            <p-table-column data-index="pcs" title="件数" :width="120" />
            <p-table-column data-index="pcsDiff" title="件数差值" :width="120" />
            <p-table-column data-index="weight" title="重量" :width="120" />
            <p-table-column data-index="weightDiff" title="重量差值" :width="120" />
            <p-table-column data-index="volume" title="体积" :width="120" />
            <p-table-column data-index="volumeDiff" title="体积差值" :width="120" />
            <p-table-column data-index="memo" title="备注" />
          </p-table>
        </a-col>
      </a-row>
      <div>
        <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>
          <p-table
            :customScrollbar="true"
            :ref="'splitTable' + item.id"
            dragle
            bordered
            row-key="tableId"
            :scroll="{ x: true, y: 160 }"
            :data-source.sync="item.dataSource"
            :rowSelectType="false"
            :autoLoad="false"
            :pagination="false"
          >
            <p-table-column data-index="itemCode" title="商品编码" :width="120" />
            <p-table-column data-index="itemName" title="商品名称" :width="120" />
            <p-table-column data-index="itemCategoryName" title="商品品类" :width="120" />
            <p-table-column data-index="packTypeName" title="包装类型" :width="120" />
            <p-table-column data-index="cargoThermosphereName" title="货物温层" :width="120" />
            <p-table-column data-index="pcs" title="件数" :width="120">
              <template slot-scope="text, record">
                <p-input-number v-model="record.pcs" style="width: 100%" @blur="pcsBlur(record)" />
              </template>
            </p-table-column>
            <p-table-column data-index="weight" title="重量" :width="120">
              <template slot-scope="text, record">
                <p-input-number v-model="record.weight" style="width: 100%" @blur="numberBlur" />
              </template>
            </p-table-column>
            <p-table-column data-index="volume" title="体积" :width="120">
              <template slot-scope="text, record">
                <p-input-number v-model="record.volume" style="width: 100%" @blur="numberBlur" />
              </template>
            </p-table-column>
            <p-table-column data-index="height9" title="备注" />
            <p-table-column key="action" title="操作" :width="120" :align="'center'" fixed="right">
              <template slot-scope="text, record">
                <a-space>
                  <a @click.stop="toDel(index, record)">删除</a>
                </a-space>
              </template>
            </p-table-column>
          </p-table>
        </p-card>
      </div>
    </p-spin>

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

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

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() {
    getItemListNoPage({ shipbillId: this.selectedRow.shipbillId })
      .then((res1) => {
        let idList = res1.data.map((item) => item.itemId);
        getItemVolumeWeight(idList)
          .then((res2) => {
            res1.data.forEach((item1) => {
              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: {
    // 返回
    back(...args) {
      this.$parent.mainCurrent = null;
      this.$emit('back', ...args);
    },

    // 添加表格
    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.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() {
      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;

      let confirmLoading = true;
      let _this = this;
      this.$confirm({
        title: '是否确认拆分?',
        confirmLoading,
        onOk(clear) {
          confirmLoading = true;
          return goods_split(params)
            .then((res) => {
              if (res.success) {
                _this.$message.success(res.message);
                _this.$emit('back', 'main', null, true);
              } else {
                _this.$exception(res);
              }
            })
            .finally(() => {
              clear();
              _this.spinning = false;
              confirmLoading = 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>