<template>
  <p-modal
    title="拆分"
    :visible="visible"
    :dialogStyle="{ top: '40px' }"
    :draggable="true"
    :width="'80%'"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div v-if="visible" class="box-wrapper" @click="errText = ''">
      <div style="padding-bottom: 20px">
        <span v-for="(item, index) in nFormItems" :key="item.name" style="margin-right: 20px">
          {{ item.label }}:
          <a-input-number v-model="item.num" :min="0" :precision="index == 1 ? precision : 0" />
        </span>
        <p-button type="primary" @click="toSplit">拆分</p-button>
        <p-button type="primary" style="margin-left: 10px" @click="toEqualSplit">平均拆分</p-button>
        <div style="float: right; line-height: 40px; font-size: 14px">
          <span style="margin: 20px">原最小单位数量: {{ data.pieceQty }}</span>
          <span>最小单位数量: {{ calcPieceQty() }}</span>
        </div>
      </div>
      <p-table-edit-pro
        ref="mainlist"
        size="small"
        :rowKey="nColumns[0].key"
        :columns="nColumns"
        :data-source.sync="dataList"
        :hasRowSelectCheck="true"
        :selectedRowKeys.sync="selectedRowKeys"
        :pagination="false"
        :rowSelectType="1"
        :has-row-count="false"
        dragle
        auto-width
        :scroll="{ y: 400 }"
        @colChange="colChange"
      >
        <template v-slot:operation="text, record">
          <span class="btn" @click="delItem(record)"> 删除 </span>
        </template>
      </p-table-edit-pro>
      <div v-show="!!errText" style="margin-top: 20px; color: red" v-html="errText"></div>
    </div>
  </p-modal>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    formItems: {
      type: Array,
      default: null,
    },
    columns: {
      type: Array,
      default: null,
    },
    rcvType: {
      type: String,
      default: null,
    },
    data: {
      type: Object,
      default: null,
    },
    splitedCallback: {
      type: Function,
    },
    confirmLoading: {
      type: Boolean,
      default: false,
    },
    error: {
      type: String,
      default: "",
    },
  },

  model: {
    prop: "visible",
    event: "change",
  },

  watch: {
    visible: {
      handler(visible) {
        if (!visible) return;
        this.dataList = [];
        this.nFormItems = this.formItems.map((t) => ({
          ...t,
          num: 0,
        }));
        this.nColumns = [
          { hidden: true, title: "_cusId", dataIndex: "_cusId", key: "_cusId" },
          ...this.columns,
          // { title: '操作', key: 'operation', fixed: 'right', width: 100, scopedSlots: { customRender: 'operation' } },
        ];
        this.initLineData();
      },
    },
    error(val) {
      this.errText = val;
    },
  },

  data() {
    return {
      nFormItems: null,
      nColumns: null,
      dataList: [],
      errText: "",
      precision: 0,
      selectedRowKeys: [],
    };
  },

  methods: {
    initLineData() {
      let item = { _cusId: Math.random() };
      this.columns.forEach((tt) => {
        let val = this.data[tt.key];
        // null
        if (!val && typeof val === "object") {
          val = "";
        }
        if (typeof val === "undefined") {
          val = "";
        }
        item[tt.key] = val;
      });
      // 采购入库+allowDecimal(=Y)才可为整数，其它都可小数
      if (this.rcvType == "1" && this.data.allowDecimal != "Y") {
        this.precision = 0;
      } else {
        this.precision = 4;
      }
      // if (this.data.allowDecimal == 'Y') {
      //   this.precision = 4
      // } else {
      //   this.precision = 0
      // }
      this.dataList.push(item);
    },

    toSplit() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning("请选择需要拆分的项");
        return;
      }
      if (this.nFormItems.every((tt) => !tt.num)) {
        // this.$message.warning('')
        return;
      }
      // let firstItem = this.dataList[0];
      let firstItem = this.dataList.find((t) => t[this.nColumns[0].key] == this.selectedRowKeys[0]);
      let conversionRate = +firstItem.conversionRate;
      // 整件
      let k1 = this.nFormItems[0].name;
      let n1 = +this.nFormItems[0].num; //输入数量
      let m1 = +firstItem[k1]; //第一行数量
      // 零散
      let k2 = this.nFormItems[1].name;
      let n2 = +this.nFormItems[1].num; //输入数量
      let m2 = +firstItem[k2]; //第一行数量
      // 输入整件>存在整件
      if (n1 > m1) {
        this.$message.warning("拆分整件数大于的整件数!");
        return;
      }
      // 0整件  1零散  整散分离isCaseOrPiece
      // 算零散，零散不够从整件中借一
      while (n2 > m2) {
        if (m1 <= 0) {
          this.$message.warning("零散拆分数量过大，件数不够拆分!");
          return;
        }
        m1--;
        m2 += conversionRate;
      }
      let items = [
        {
          ...firstItem,
          _cusId: "_cusId" + Math.random() * 10000,
          [k1]: m1 - n1,
          [k2]: m2 - n2,
        },
        {
          ...firstItem,
          _cusId: "_cusId" + Math.random() * 10000,
          [k1]: n1,
          [k2]: n2,
        },
      ];
      if (this.precision == 4)
        items.forEach((tt) => {
          tt[k2] = Math.floor(tt[k2] * 10000) / 10000;
        });
      /*  */
      let i = this.dataList.findIndex((t) => t[this.nColumns[0].key] == this.selectedRowKeys[0]);
      this.selectedRowKeys = [];
      items = items.filter((tt) => !(!tt[k1] && !tt[k2]));
      items.forEach((tt) => this.splitedCallback && this.splitedCallback(tt));
      this.dataList.splice(i, 1, ...items);
      this.nFormItems.forEach((tt) => (tt.num = 0));
      this.sortList();
    },

    toEqualSplit() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning("请选择需要拆分的项");
        return;
      }
      if (this.nFormItems.every((tt) => !tt.num)) {
        // this.$message.warning('')
        return;
      }
      // let firstItem = this.dataList[0];
      let firstItem = this.dataList.find((t) => t[this.nColumns[0].key] == this.selectedRowKeys[0]);
      let conversionRate = +firstItem.conversionRate;
      // 整件
      let k1 = this.nFormItems[0].name;
      let n1 = +this.nFormItems[0].num; //输入数量
      let m1 = +firstItem[k1]; //第一行数量
      // 零散
      let k2 = this.nFormItems[1].name;
      let n2 = +this.nFormItems[1].num; //输入数量
      let m2 = +firstItem[k2]; //第一行数量
      // 输入整件>存在整件
      if (n1 > m1) {
        this.$message.warning("拆分整件数大于的整件数!");
        return;
      }
      // 0整件  1零散  整散分离isCaseOrPiece
      // 算零散，零散不够从整件中借一
      while (n2 > m2) {
        if (m1 <= 0) {
          this.$message.warning("零散拆分数量过大，件数不够拆分!");
          return;
        }
        m1--;
        m2 += conversionRate;
      }
      // 拆整件
      let arr1 = [];
      if (n1 === 0) {
        arr1.push(m1);
      } else {
        while (m1 > 0) {
          if (m1 >= n1) {
            arr1.push(n1);
          } else if (m1 > 0) {
            arr1.push(m1);
          }
          m1 -= n1;
        }
      }
      // 拆零散
      let arr2 = [];
      if (n2 === 0) {
        arr2.push(m2);
      } else if (m2 === n2) {
        arr2.push(n2);
      } else {
        let f = m2 - n2;
        arr2.push(f);
        if (f > 0) arr2.push(n2);
      }
      let items = [];
      arr1.forEach((t) => {
        if (t == 0) return;
        items.push({ ...firstItem, [k1]: t, [k2]: 0, _cusId: "_cusId" + Math.random() * 10000 });
      });
      arr2.forEach((t) => {
        if (t == 0) return;
        items.push({ ...firstItem, [k1]: 0, [k2]: t, _cusId: "_cusId" + Math.random() * 10000 });
      });
      // if(this.precision == 4) items.forEach(tt => { tt[k2] = Math.floor(tt[k2]*10000)/10000 });
      /*  */
      let i = this.dataList.findIndex((t) => t[this.nColumns[0].key] == this.selectedRowKeys[0]);
      this.selectedRowKeys = [];
      items = items.filter((tt) => tt[k1] || tt[k2]);
      items.forEach((tt) => this.splitedCallback && this.splitedCallback(tt));
      this.dataList.splice(i, 1, ...items);
      this.nFormItems.forEach((tt) => (tt.num = 0));
      this.sortList();
    },

    sortList() {
      setTimeout(() => {
        this.dataList.sort((a, b) => {
          // if (a[k1] > 0 && b[k1] == 0) {
          let n = b[this.nFormItems[0].name] - a[this.nFormItems[0].name];
          if (n == 0) {
            return b[this.nFormItems[1].name] - a[this.nFormItems[1].name];
          } else {
            return n;
          }
        });
      }, 50);
    },

    delItem(item) {
      let i = this.dataList.findIndex((t) => t == item);
      if (i == 0) {
        return;
      }
      this.nFormItems.forEach((tt) => {
        this.dataList[0][tt.name] = +this.dataList[0][tt.name] + this.dataList[i][tt.name];
      });
      this.dataList.splice(i, 1);
    },

    handleOk(e) {
      if (
        this.data.itemHealthStoreCategory &&
        this.data.itemHealthStoreCategory.indexOf("分开") >= 0 &&
        !this.dataList.every((tt) => tt[this.nFormItems[0].name] == 0 || tt[this.nFormItems[1].name] == 0)
      ) {
        this.$message.warning("请注意该明细为整散分开");
        return;
      }
      let pieceQty = 0;
    //   console.log(this.dataList);
    //   console.log(this.data);
      this.dataList.forEach((t) => (pieceQty += t.pieceQty));
      if (+this.data.pieceQty != pieceQty) {
        this.$message.warning("请注意拆分后的数量与拆分前数量不一致，请检查");
        return;
      }
   
      let a = this.$emit("ok", this.dataList);
    },

    calcPieceQty() {
      let pieceQty = 0;
      this.dataList.forEach((t) => (pieceQty += t.pieceQty));
      return pieceQty;
    },

    handleCancel(e) {
      this.reset();
      this.$emit("change", false);
    },

    colChange() {
      this.dataList.forEach((tt) => this.splitedCallback && this.splitedCallback(tt));
    },

    reset() {
      this.dataList = [];
    },
  },
};
</script>

<style scoped>
.box-wrapper {
  margin-bottom: 20px;
  background: #fff;
}
.btn {
  color: #2b80ff;
  margin-right: 10px;
  cursor: pointer;
}
.btn:hover {
  text-decoration: underline;
}
</style>
