<template>
  <div>
    <div>
      <p-card title="主要信息">
        <p-grid-form
          ref="formTarget"
          :items="gridItems"
          @submit="
            ($event, form) => {
              handleSubmit($event, form, 'formTarget');
            }
          "
        />
        <p-table
          ref="logTable"
          style="margin-top: 10px"
          :columns="tableColumnsConfig"
          rowKey="rcvHeaderId"
          :expandRowByClick="false"
          @clickRow="customRowThing"
          :rowSelectFixed="true"
          :rowSelectType="false"
          :dataSource.sync="dataSource"
          :loading="tabLoding"
          dragle
          auto-width
          bordered
        >
        </p-table>
      </p-card>
      <p-card title="商品明细" style="margin-top: 5px">
        <p-table
          ref="detailTable"
          :columns="extendFormItems"
          :scroll="{ x: true }"
          rowKey="taskExceptionId"
          :rowSelectType="false"
          :dataSource.sync="detailData"
          :rowSelectFixed="true"
          :loading="detailLoding"
          dragle
          auto-width
          bordered
        >
          <div slot="action" href="javascript:;" slot-scope="text">
            <a slot="action" @click.stop="edit(text)">差异处理</a>
            <a-divider type="vertical" />
            <a slot="action" @click.stop="lotNo(text)">批号驳回</a>
          </div>
        </p-table>
      </p-card>
    </div>
    <div>
      <p-modal
        :title="Title"
        :visible="visible"
        :enlargeable="false"
        :draggable="true"
        width="65%"
        :maskClosable="false"
        @cancel="handleCancel"
        :footer="null"
      >
        <div>
          <p-grid-form
            ref="formdetail"
            :items="detailFormItems"
            :span="10"
            :labelCol="{ span: 8 }"
            @submit="
              ($event, form) => {
                formSubmit($event, form, 'formdetail');
              }
            "
          />
          <div style="text-align: right">
            <p-button type="primary" @click="addForm">保存</p-button>
          </div>
        </div>
      </p-modal>
    </div>
  </div>
</template>
<script>
import { setFormItems, tableColumnsConfig, detailFormItems, extendFormItems } from "./js/config";
import { querySubList, taskSplit, addItems, rejectLotNo, getRcvItemLotNum } from "./api/index";
import { diffOption } from "@/views/kzyWMS/utils/index.js";
import { sorter } from "../../utils/sort";

export default {
  data() {
    return {
      dataSource: [],
      detailData: [],
      tabLoding: false,
      detailLoding: false,
      gridItems: setFormItems(this),
      rowSelectType: 2,
      tableColumnsConfig: null,
      extendFormItems: extendFormItems,
      detailFormItems: detailFormItems(this, {
        on: {
          ok: this.ok,
        },
      }),
      Title: "",
      visible: false,
      mainData: {},
      itemData: {},
      headerId: "",
      rcvType: "",
    };
  },
  created() {
    // this.getList()
    let warehouse = this.$store.state.user.warehouse;
    this.$nextTick(() => {
      this.$refs.formTarget.form.setFieldsValue(warehouse);
    });

    diffOption(tableColumnsConfig).then((res) => {
      this.tableColumnsConfig = sorter(res);
    });
  },
  methods: {
    //弹框关闭
    handleCancel(e) {
      this.visible = false;
      this.$refs.formdetail.form.resetFields();
    },

    //初始化list
    getList(params) {
      this.tabLoding = true;
      params = { ...params, taskStatus: "1" };
      querySubList(params).then((res) => {
        this.tabLoding = false;
        if (res.success) {
          this.dataSource = res.data.list;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //获取明细数据
    getDetail(params) {
      this.detailLoding = true;
      taskSplit(params).then((res) => {
        this.detailLoding = false;
        if (res.success) {
          this.detailData = res.data.list.map((t) => ({
            ...t,
            expiredDateNew: t.expiredDateNew.substring(0, 10),
            expiredDateOld: t.expiredDateOld.substring(0, 10),
            productionDateNew: t.productionDateNew.substring(0, 10),
            productionDateOld: t.productionDateOld.substring(0, 10),
          }));
          console.log(this.detailData);
        } else {
          this.$message.error(res.message);
        }
      });
    },

    //查询事件
    handleSubmit(event, form) {
      event.preventDefault();
      this.detailData = [];
      form.validateFields((error, values) => {
        if (!error) {
          this.getList(values);
        }
      });
    },

    //点击主表
    customRowThing(event, activeID, record) {
      if (this.detailLoding) return;
      this.rcvType = record.rcvType;
      this.detailLoding = true;
      this.mainData = record;
      this.headerId = record.rcvHeaderId;
      let params = { taskStatus: "1", rcvHeaderId: record.rcvHeaderId, pageNum: 1, pageSize: 10 };
      this.getDetail(params);
    },

    async edit(text) {
      this.Title = "差异处理";
      console.log(this.rcvType);
      // if (this.rcvType == "2") {
      //   this.$nextTick(() => {
      //     this.$refs.formdetail.form.disableItem([
      //       "showProductionDateNew",
      //       "showExpiredDateNew",
      //       "productionDateNew",
      //       "expiredDateNew",
      //       "manufacturerLotNum",
      //     ]);
      //   });
      // } else {
      //   this.$nextTick(() => {
      //     this.$refs.formdetail.form.enableItem([
      //       "showProductionDateNew",
      //       "showExpiredDateNew",
      //       "productionDateNew",
      //       "expiredDateNew",
      //       "manufacturerLotNum",
      //     ]);
      //   });
      // }
      this.visible = true;
      // try {
      //   let res = await getRcvItemLotNum({ ...text, pageNum: 1, pageSize: 999, manufacturerLotNum: "" });
      //   if (res.success) {
      //     console.log(res.data.list);
      //     let list = res.data.list;
      //     let key;
      //     if (list) {
      //       key = list.some((i) => i.manufacturerLotNum == text.manufacturerLotNum);
      //     }

      //     console.log(key);
      //     if (!key&&this.rcvType!=2) {
      //       this.$nextTick(() => {
      //         this.$refs.formdetail.form.enableItem(["productionDateNew", "expiredDateNew", "manufacturerLotNum"]);
      //       });
      //     } else {
      //       this.$nextTick(() => {
      //         this.$refs.formdetail.form.disableItem(["productionDateNew", "expiredDateNew", "manufacturerLotNum"]);
      //       });
      //     }
      //   } else {
      //     this.$exception(res);
      //   }
      // } catch (error) {
      //   this.$exception(error);
      // }

      console.log(text);
      this.itemData = text;
      this.$nextTick(() => {
        this.$refs.formdetail.form.setFieldsValue(text);
      });
    },
    // 批号驳回
    lotNo(text) {
      this.$confirm({
        content: this.$lang("是否确定驳回?"),
        onOk: () => {
          return this.addLot(text);
        },
      });
    },
    addLot(text) {
      return rejectLotNo([text]).then((res) => {
        if (!res.success) {
          this.$exception(res);
          return false;
        }
        let params = { taskStatus: "1", rcvHeaderId: this.headerId };
        let params1 = { taskStatus: "1" };
        this.getDetail(params);
        this.getList(params1);
        this.$message.success(this.$lang("操作成功"));
        return true;
      });
    },
    // 保存
    addForm() {
      const { form } = this.$refs.formdetail;
      form.validateFields((error, values) => {
        if (!error) {
          if (values.manufacturerLotNum != "*") {
            if (
              values.productionDateNew == "" ||
              values.productionDateNew == null ||
              values.expiredDateNew == "" ||
              values.expiredDateNew == null
            ) {
              this.$message.error("请输入生产日期或有效期");
            } else {
              this.save();
            }
          } else {
            this.save();
          }
        }
      });
    },
    save() {
      const test = this.$refs.formdetail.form.getFieldsValue();
      console.log(test);
      //   return
      test.manufacturerLotNumNew = test.manufacturerLotNum;
      this.mainData.lineNum = 1;
      test.lineNum = 1;
      this.mainData.nodeType = test.nodeType;
      // let aa = {...this.itemData,...test}
      // Object.keys(test).forEach((k) => {
      //   this.itemData[k + 'Old'] = this.itemData[k]
      //   test[k + 'New'] = test[k]
      // })
      let newObj = { ...this.itemData, ...test };
      if (newObj.pieceQtyNew > newObj.pieceQtyOld) {
        this.$message.error("新修改的数量不能大于旧数量，请重新输入");
        return;
      }
      addItems({ exceptionHeader: this.mainData, exceptionLineList: [newObj] }).then((res) => {
        if (res.success) {
          this.visible = false;
          let params = { taskStatus: "1", rcvHeaderId: this.headerId };
          let params1 = { taskStatus: "1" };
          this.getDetail(params);
          this.getList(params1);
          // this.$refs.detailTable.reload(params)
          this.$message.success(this.$lang("差异修改成功"));
        } else {
          this.$exception(res);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.ant-card-body {
  padding: 12px 18px 18px 18px;
}
</style>
