<template>
  <a-spin :spinning="spinning">
    <p-card title="主要信息">
      <div slot="extra">
        <p-button type="primary" @click="reset">重置</p-button>
        <p-button type="primary" class="ml-10" @click="save">保存</p-button>
      </div>
      <p-grid-form ref="formTarget" :span="8" :items="formItems" />
    </p-card>
    <p-card title="移库明细" class="mt-10">
      <div slot="extra">
        <!-- <p-button type="primary" @click="mergeTrayQuery">合托移库查询</p-button> -->
        <p-button type="primary" class="ml-10" @click="addRow">新增</p-button>
        <p-button type="primary" class="ml-10" @click="delRow">删除</p-button>
      </div>
      <p-table-edit
        style="width: 100%"
        :scroll="{ x: 3000 }"
        @colChange="colChange"
        @clickRow="clickRow"
        ref="editorTableRef"
        rowKey="_row_count"
        :editorRowTable="true"
        :selectedRowKeys.sync="selectedRowKeys"
        :dataSource.sync="dataSource"
        :columns="columns"
      />
    </p-card>
  </a-spin>
</template>

<script>
import editorTable from "../components/bill-editor/editor-table";

import { columns, formItems } from "./config/moveDetial";
import { mergeTrayQuery, moveAdd } from "../api/api";
import { getCargoOwner } from "../../utils/index";

export default {
  components: { editorTable },
  data() {
    return {
      formItems: formItems(this),
      columns: columns(this),
      spinning: false,

      selectedRowKeys: [],
      dataSource: [],
      // 当前点击行
      clickRowRecord: -1,
    };
  },
  mounted() {
    this.initData();
    this.getAuthBycargoOwner();
  },
  methods: {
    clickRow(record) {
      this.clickRowRecord = Number(record.index) + 1;
    },
    // 重置
    reset() {
      const refMain = this.$refs.formTarget;
      let ref = this.$refs.editorTableRef;
      refMain.form.enableItem(["warehouseName", "cargoOwnerName", "moveOutBldg", "moveInBldg"]);
      // refMain.form.resetFields()
      refMain.form.setFieldsValue({
        dcId: "",
        warehouseId: "",
        warehouseName: "",
        moveOutBldg: "",
        cargoOwnerId: "",
        cargoOwnerName: "",
        warehouseName2: "",
        moveInBldg: "",
        remark: "",
      });
      ref.delItems(); // 删除附表信息
    },
    // 保存
    save() {
      this.$refs.editorTableRef.validateFields((error, detailValue) => {
        // 头表数据
        const mainValues = this.$refs.formTarget.form.getFieldsValue();
        console.log(mainValues);
        console.log(detailValue);
        let { autoPrint } = mainValues;
        if (autoPrint) {
          this.$message.warning("打印移库单接口未联调");
        }
        if (mainValues.outwarehouseAreaCategory == 'LK' && mainValues.inwarehouseAreaCategoryName == 'LK') {
            this.$message.warn('立库与立库之间不能执行移库操作')
            return
        }
        if (mainValues.outwarehouseAreaCategory == 'LK' && mainValues.yichukucunzhuangtai == '不合格'  && (mainValues.outwarehouseAreaCategory != '不合格库' || mainValues.outwarehouseAreaCategory != '残次品库')) {
            this.$message.warn('不合格的立库商品只能移库至残次品库')
            return
        }

        if (!mainValues.warehouseWorkerName) {
          this.$message.warn("未获取到主表信息中的操作员");
          return;
        }
        // 明细数据
        if (detailValue.length === 0) {
          this.$message.warn("请选择商品");
          return;
        }
        let flag = true;
        const moveDetails = [];
        detailValue.forEach((item) => {
          let { oddPieceQuantity, caseQuantity, numData, destWarehouseCategory, unqualifiedReason, outwarehouseAreaCategory, outGoodsCaseCode } = item;
          oddPieceQuantity = oddPieceQuantity || 0;
          caseQuantity = caseQuantity || 0;
          item.inWarehouseAreaCategory = item.inwarehouseAreaCategory;
          item.outWarehouseAreaCategory = item.outwarehouseAreaCategory;

          if (Number(numData) <= 0) {
            flag = false;
            this.$message.warn("移库数量不能为0！");
            return;
          }
          if (destWarehouseCategory === "NHK" && !unqualifiedReason) {
            flag = false;
            this.$message.warn("移入库别为不合格库时，请选择不合格原因！");
            return;
          }
          if (outwarehouseAreaCategory === "AGVL" && !outGoodsCaseCode) {
            flag = false;
            this.$message.warn("请输入移出货格号！");
            return;
          }
          moveDetails.push({ ...item, oddPieceQuantity, caseQuantity });
        });
        if (!flag) return;
        // 保存调用
        const params = {
          moveDetails,
          ...mainValues,
          dcId: "",
        };
        this.spinning = true;
        moveAdd(params)
          .then((res) => {
            if (res.success) {
              this.$message.success("保存成功");
              //   todo  是否打印移库单
              if (autoPrint) {
                this.$message.warning("打印移库单接口未联调");
              }

              this.dataSource = [];
            } else {
              return this.$exception(res);
            }
          })
          .finally(() => {
            this.spinning = false;
          });
      });
    },
    // 合托移库查询
    mergeTrayQuery() {
      let refMain = this.$refs.formTarget;
      let formsVal = refMain.form.getFieldsValue();
      if (!formsVal.warehouseId) return this.$message.warn("请选择仓库");
      if (!formsVal.cargoOwnerId) return this.$message.warn("请选择货主");
      if (!formsVal.moveOutBldg) return this.$message.warn("请选择移出建筑");
      if (!formsVal.moveInBldg) return this.$message.warn("请选择移入建筑");
      const params = {
        ...formsVal,
      };
      mergeTrayQuery(params).then((res) => {
        if (res.success) {
          this.dataSource.push(...res.data);
          refMain.form.disableItem(["warehouseName", "cargoOwnerName", "moveOutBldg", "moveInBldg"]);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 新增明细行
    addRow() {
      let editorTableRef = this.$refs.editorTableRef;
      let refMain = this.$refs.formTarget;
      let formsVal = refMain.form.getFieldsValue();
      if (!formsVal.warehouseId) return this.$message.warn("请选择仓库");
      if (!formsVal.cargoOwnerId) return this.$message.warn("请选择货主");
      if (!formsVal.moveOutBldg) return this.$message.warn("请选择移出建筑");
      if (!formsVal.moveInBldg) return this.$message.warn("请选择移入建筑");
      editorTableRef.createRow(0, undefined, false);

      refMain.form.disableItem(["warehouseName", "cargoOwnerName", "moveOutBldg", "moveInBldg"]);
    },
    // 删除明细行
    delRow() {
      const selectedRowKeys = this.selectedRowKeys;
      if (selectedRowKeys.length === 0) return this.$message.warn("请选择要删除的明细");
      let editorTableRef = this.$refs.editorTableRef;
      this.$confirm({
        content: "确定删除?",
        onOk: () => {
          editorTableRef.removeRow(selectedRowKeys);
        },
      });
    },
    // 设置初始数据
    initData() {
      let user = this.$store.state.user;
      let warehouse = this.$store.state.user.warehouse;
      let today = new Date();
      let tYear = today.getFullYear();
      let tMonth = today.getMonth() + 1;
      let tDate = today.getDate();
      let day = tYear + "-" + tMonth + "-" + tDate;
      this.$nextTick(() => {
        this.$refs.formTarget.form.setFieldsValue({
          today: day,
          warehouseName: warehouse.warehouseName,
          warehouseId: warehouse.warehouseId,
          enterpriseName: user.info.enterpriseName,
          warehouseWorkerId: user.info.userId,
          warehouseWorkerName: user.info.username,
          departmentId: user.info.organizations
            ? user.info.organizations[0]
              ? user.info.organizations[0].id
              : ""
            : "",
          departmentName: user.info.organizations
            ? user.info.organizations[0]
              ? user.info.organizations[0].name
              : ""
            : "",
        });
      });
    },
    // 编辑表格-修改列
    colChange({ record, name, value, index }) {},
    getAuthBycargoOwner() {
      getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.$refs.formTarget.form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerName: res.data.list[0].companyName,
              cargoOwnerCode: res.data.list[0].companyCode,
            });
          });
        } else {
          this.$exception(res);
        }
      });
    },
  },
};
</script>

<style></style>
