<template>
  <p-modal
    :title="'商品货位限定-' + (pkId ? '编辑' : '新增')"
    :visible="value"
    :dialogStyle="{ top: '20px' }"
    :width="'90%'"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <p-grid-form v-if="value" ref="form" :span="8" :items="formItems" />
    <a-divider />
    <a-row v-if="value" style="margin-top: 20px">
      <a-col :span="12" style="padding-right: 10px">
        <div style="font-size: 14px; padding-bottom: 10px; text-indent: 10px">
          逻辑区
          <a-button type="primary" style="float: right" size="small" @click="addLogic">新增</a-button>
        </div>

        <p-table-edit
          ref="easyTable"
          :rowSelectType="false"
          size="small"
          :bordered="true"
          :pagination="false"
          :colorTransformRow="false"
          rowKey="stItemLocatorLId"
          :columns="logicColumns"
          :data-source.sync="logicData"
          @colChange="colChange"
        >
          <template v-slot:operation="text, record">
            <span class="btn" @click="delLogic(record)">删除</span>
          </template>
        </p-table-edit>
      </a-col>
      <a-col :span="12">
        <div style="font-size: 14px; padding-bottom: 10px; text-indent: 10px">算法</div>
        <p-table-edit
          ref="easyTable1"
          :rowSelectType="2"
          size="small"
          :bordered="true"
          :pagination="false"
          :hasRowCount="false"
          :colorTransformRow="false"
          rowKey="algorithmCode"
          :columns="alColumns"
          :data-source.sync="alData"
          :selectedRowKeys.sync="selectedRowKeys"
          :autoLoad="true"
          :remoteUrl="{
            url: upcloud_base_common + '/dict/listbytype?dicttypeCodes=wms_instock_algorithm',
            method: 'post',
          }"
          :doneBefore="alTransform"
        >
        </p-table-edit>
      </a-col>
    </a-row>
  </p-modal>
</template>

<script>
import { formItems } from "../config/modal-form";
import { logicColumns, alColumns } from "../config/modal-table";
import { addItem, queryItem, uploadItem, queryItemInfos } from "../api";
import { upcloud_base_common } from "@/config/serviceSettings";

export default {
  props: {
    value: {
      type: Boolean,
      default: true,
    },
    pkId: {
      type: String,
    },
  },

  watch: {
    value(bool) {
      if (bool) {
        // let warehouse = this.$store.state.user.warehouse
        // if (Object.keys(warehouse).length > 0) {
        //   this.$nextTick(() => {
        //     this.$refs.form.form.setFieldsValue(warehouse)
        //   });
        // }
        if (this.pkId) this.handleQueryItem({ pkId: this.pkId });
      }
    },
  },

  data() {
    return {
      upcloud_base_common,
      formItems: formItems(this),
      logicColumns: logicColumns(this),
      logicData: [],
      alColumns: [...alColumns],
      alData: [],
      selectedRowKeys: [],
      detail: null,
    };
  },

  methods: {
    addLogic() {
      let p = {
        stItemLocatorLId: "aaa" + Math.random(),
        warehouseLogicId: "",
        warehouseLogicName: "",
        warehouseLogicCode: "",
        bldgName: "",
      };
      this.logicData.push(p);
    },

    colChange({ modalRowData, index, value, record }) {
      this.logicChange(modalRowData[0], index);
    },

    delLogic(item) {
      this.logicData.splice(
        this.logicData.findIndex((t) => t.stItemLocatorLId == item.stItemLocatorLId),
        1
      );
    },

    logicChange(data, index) {
      this.logicData[index].warehouseLogicId = data.warehouseLogicId;
      this.logicData[index].warehouseLogicName = data.warehouseLogicName;
      this.logicData[index].bldgName = data.bldgName;
    },

    alTransform(res) {
      res.data.forEach((t, i) => {
        // t.algorithmId = 'aaa' + i + 1;
        t.algorithmSortIdx = i + 1;
        t.algorithmName = t.dictName;
        t.algorithmCode = t.dictCode;
        t.algorithmDesc = t.dictDesc || "";
      });
      return res;
    },

    handleOk() {
      return new Promise((resolve, reject) => {
        this.$refs.form.form.validateFields((errs, vals) => {
          if (errs) {
            reject();
            return;
          }
          this.$refs.easyTable.validateFields((error, values, selectData) => {
            if (error) {
              reject();
              return;
            }
            if (vals.billtype) {
              vals.billtype = vals.billtype.join();
            }

            console.log(vals);
            let p = {
              stItemLocatorHDTO: vals,
              stItemLocatorDDTOList: this.logicData.map((t) => ({
                ...t,
                locatorHigherLimit: vals.locatorHigherLimit,
                locatorLowerLimit: vals.locatorLowerLimit,
              })),
              stItemLocatorADTOList: this.alData.filter((t) =>
                this.selectedRowKeys.some((tt) => tt == t.algorithmCode)
              ),
            };
            if (this.detail) {
              let stItemLocatorHId = this.detail.stItemLocatorHDTO.stItemLocatorHId;
              p.stItemLocatorHDTO.stItemLocatorHId = stItemLocatorHId;
              p.stItemLocatorDDTOList.forEach((t) => (t.stItemLocatorHId = stItemLocatorHId));
              p.stItemLocatorADTOList.forEach((t) => (t.stItemLocatorHId = stItemLocatorHId));
              this.handleUpload(p).then((res) => {
                resolve();
              });
            } else {
              this.handleAdd(p).then((res) => {
                resolve();
              });
            }
          });
        });
      });
    },

    handleCancel() {
      this.logicData = [];
      this.alData = [];
      this.selectedRowKeys = [];
      this.detail = null;
      this.$emit("input", false);
    },

    handleAdd(params) {
      return addItem(params).then((res) => {
        if (!res.success) {
          this.$exception(res.message);
          return;
        }
        this.$message.success("新增成功");
        this.$emit("ok");
        this.handleCancel();
      });
    },

    handleUpload(params) {
      return uploadItem(params).then((res) => {
        if (!res.success) {
          this.$exception(res.message);
          return;
        }
        this.$message.success("编辑成功");
        this.$emit("ok");
        this.handleCancel();
      });
    },

    handleQueryItem(p) {
      return queryItem(p).then((res) => {
        if (!res.success) {
          this.$exception(res.message);
          return;
        }
        queryItemInfos({ itemIds: [res.data.stItemLocatorHDTO.itemId] }).then((res) => {
          if (!res.success) {
            this.$exception(res);
            return;
          }
          if (res.data && res.data.list && res.data.list[0]) {
            this.$refs.form.form.setFieldsValue({
              caseUom: res.data.list[0].caseUom,
              caseConversionRate: res.data.list[0].caseConversionRate,
              itemHealthType: res.data.list[0].itemHealthType,
              pieceConversionRate: res.data.list[0].pieceConversionRate,
              storeTemperature: res.data.list[0].storeTemperature,
            });
          }
        });
        this.$nextTick(() => {
          this.detail = res.data;
        //   res.data.stItemLocatorHDTO.billtype = "1,7";
          res.data.stItemLocatorHDTO?.billtype &&
            (res.data.stItemLocatorHDTO.billtype = res.data.stItemLocatorHDTO.billtype.split(","));
          this.$refs.form.form.setFieldsValue(res.data.stItemLocatorHDTO);
          res.data.stItemLocatorDDTOList.forEach((tt) => this.$refs.easyTable.createRow(tt));

          // this.logicData = res.data.stItemLocatorDDTOList;
          this.selectedRowKeys = res.data.stItemLocatorADTOList.map((t) => t.algorithmCode);
        });
      });
    },
  },
};
</script>

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