<script>
import {
  editColumns,
  editTabColumns,
  forbidden,
  SelectColumns,
} from "./initColumn";
import orderApi from "@/api/business/purchase/purchase-order";
import { initDicts, initRules, initParams } from "@/utils/init/index.js";
import { tax, currency } from "@/components/popover-select-v2/fetch";
import VirtualScroll from "el-table-virtual-scroll";
import { VirtualColumn } from "el-table-virtual-scroll";

export default {
  name: "EditPurchaseOrderDrawer",
  dicts: initDicts(SelectColumns),
  components: {
    "virtual-scroll": VirtualScroll,
    VirtualColumn,
    FileUploadCenter: () => import("../components/FileUploadCenter/index.vue"),
    BatchImport: () => import("@/components/BatchImport/index.vue"),
    ButtonHide: () => import("../components/hide/index.vue"),
    CgxjButton: () => import("../cai-gou-xun-jia/index.vue"),
  },
  data() {
    return {
      size: "mini",
      visible: false,
      loading: false,
      tabLoading: false,
      columns: editColumns,
      rules: initRules(editColumns),
      params: {
        ...initParams(editColumns),
        puOrderItemList: [],
        // puOrderExecuteList: [],
      },

      tabColumns: editTabColumns,
      tabName: "puOrderItemList",
      count: 1,
      tableData: [], //虚拟滚动加载显示的数据
    };
  },
  computed: {
    role: {
      get() {
        let { roles } = this.$store.state.user;
        return (
          roles.find((item) => item === "syfz-purchaseorder") ||
          "procurementManager"
        );
      },
      set() {},
    },
    tabHeight: {
      get() {
        let length = this.params["puOrderItemList"].filter(
          (item) => item.delFlag === "0"
        ).length;
        return `${length ? (length > 8 ? 500 : length * 36 + 120) : 120}px`;
      },
      set() {},
    },
    innerColumns: {
      get() {
        let { tabName, tabColumns } = this;
        let obj = tabColumns.find(({ key }) => key === tabName).tableColumns;

        return obj;
      },
      set(value) {
        let { tabName, tabColumns } = this;
        this.tabColumns = tabColumns.map((item) => {
          if (item.key === tabName) {
            item.tableColumns = value;
          }
          return { ...item };
        });
        this.$nextTick(() => {
          this.$refs.puOrderItemList &&
            this.$refs.puOrderItemList[0].doLayout();
        });
      },
    },
    // 手动询价
    isManualInquiry: {
      get() {
        let { handleIsRevise, role, params } = this;
        if (
          !handleIsRevise() &&
          role === "procurementManager" &&
          params.source != "3"
        ) {
          return true;
        }
        return false;
      },
      set() {},
    },
  },
  watch: {
    "params.contractType": function (newProp) {
      this.tabColumns = editTabColumns.filter((element) =>
        newProp === "1" ? element.key !== "puOrderItemList" : element
      );
      this.tabName = this.tabColumns[0].key;
    },
    tabName: function (newProp) {
      const { id } = this.params;
      // this.fetchTable(id, newProp);
    },
    // "params.puOrderItemList": {
    //   handler(nVal, oVal) {
    //     this.params.source == 3 &&
    //       this.handleSynchronousMaterial(
    //         "puOrderItemList",
    //         "puOrderExecuteList"
    //       );
    //   },
    //   deep: true,
    //   immediate: true,
    // },
    // "params.puOrderExecuteList": {
    //   handler(nVal, oVal) {
    //     this.params.source == 3 &&
    //       this.handleSynchronousMaterial(
    //         "puOrderExecuteList",
    //         "puOrderItemList"
    //       );
    //   },
    //   deep: true,
    //   immediate: true,
    // },
    "params.billType": {
      handler(nVal, oVal) {
        let billList = ["21-Cxx-02", "21-Cxx-04", "21-Cxx-10", "21-Cxx-14"];

        if (billList.find((item) => item === nVal)) {
          this.rules.warehouseName = [
            {
              required: true,
              message: "WMS入库仓库不能为空",
              trigger: "change",
            },
          ];
        } else {
          this.rules.warehouseName = null;
        }

        this.count++;
      },
    },
    "params.isBack": {
      handler(nVal, oVal) {
        if (nVal === "Y") {
          this.rules.retReasonName = [
            { required: true, message: "退换原因不能为空", trigger: "change" },
          ];
          this.rules.processTypeName = [
            { required: true, message: "处理方式不能为空", trigger: "change" },
          ];
        } else {
          this.rules.retReasonName = null;
          this.rules.processTypeName = null;
        }
        this.count++;
      },
    },
  },
  methods: {
    setVisible(prop) {
      this.visible = prop;

      if (!this.visible) {
        this.$refs["orderEditForm"].clearValidate();
      }
    },
    // 同步子表物料
    handleSynchronousMaterial(tableOne, tableTwo) {
      let _this = this;
      // this.params[tableOne]-- -> this.params[tableTwo]
      this.params[tableOne] &&
        this.params[tableOne].length &&
        this.params[tableOne].forEach((item, index) => {
          for (const key in item) {
            if (
              _this.params[tableTwo][index] &&
              key in _this.params[tableTwo][index]
            ) {
              _this.params[tableTwo][index].material = item.material;

              key !== "id" && (_this.params[tableTwo][index][key] = item[key]);
            }
          }
        });
    },
    // 判断属性是否禁用
    async handleIsForbidden(status, source) {
      let { updateColumns, updateTabColumns } = await forbidden(
        status != "2",
        source
      );
      this.columns = updateColumns;
      this.tabColumns = updateTabColumns;
      try {
        const { code, rows } = await orderApi.REFER(
          {
            type: "WAREHOUSE_PARAM",
            // search:  this.params.warehouseName,
            search: "",
            id: this.params.warehouse,
            isPage: true,
          },
          { pageNum: 1, pageSize: 10 }
        );

        if (code == 200) {
          this.judgeGoodsAllocation(rows[0].csFlag);
        }
      } catch (error) {}
      this.count++;
    },
    // 查询详细
    async fetchItem(prop) {
      try {
        this.loading = true;
        const { code, msg, data } = await orderApi.details(prop);
        if (code === 200) {
          this.params = { ...this.params, ...data };
          this.handleIsForbidden(this.params.status, this.params.source);
        }
      } catch (err) {
        //
      } finally {
        this.loading = false;
      }
    },
    // 新增行
    addTableRow(prop) {
      for (const key in this.params) {
        // if (key === "puOrderItemList" || key === "puOrderExecuteList") {
        if (key === "puOrderItemList") {
          const arr = this.tabColumns.find(
            (element) => element["key"] === key
          ).tableColumns;

          let rowData = initParams(arr, "key", "value");

          "rowno" in rowData &&
            (rowData["rowno"] = this.params[key].length
              ? this.params[key][this.params[key].length - 1]["rowno"] + 1
              : this.params[key].length + 1);
          // 物料
          if ("rowNo" in rowData) {
            rowData["rowNo"] = this.params[key].length
              ? this.params[key][this.params[key].length - 1]["rowNo"] + 1
              : this.params[key].length + 1;
            // 扣税类别
            rowData["taxDeductClassify"] = "1";
            // 折本汇率
            rowData["exchangeRate"] = "1";
            // 价格类型
            rowData["priceType"] = "order";
            // 币种
            rowData["currency"] = "1002Z0100000000001K1";
            rowData["currencyName"] = "人民币";
          }
          // 是否完成询价，新增明细行需默认明细为false
          // rowData['whetherCompleteInquiry'] = false;
          rowData["delFlag"] = "0";
          rowData["insertId"] = new Date().getTime();

          this.params[key].push(rowData);
        }
      }

      // const arr = this.tabColumns.find(
      //   (element) => element.key === this.tabName
      // ).tableColumns;
      // prop.push(initParams(arr, "key", "value"));
    },
    // 删除行
    async delTableRow(prop, row, name) {
      let delNo = name === "puOrderItemList" ? "rowNo" : "rowno";

      if (prop.length === 1) {
        this.$alert("订单行不允许为空", "提示", {
          confirmButtonText: "确定",
          callback: (action) => {
            // this.$message({
            //   type: 'info',
            //   message: `action: ${ action }`
            // });
          },
        });
      } else {
        for (const key in this.params) {
          // if (key === "puOrderItemList" || key === "puOrderExecuteList") {
          if (key === "puOrderItemList") {
            this.params[key].forEach((item, index) => {
              let flag = key === "puOrderItemList" ? "rowNo" : "rowno";

              if (item[flag] && item[flag] === row[delNo]) {
                item.id
                  ? (item["delFlag"] = "2")
                  : this.params[key].splice(index, 1);
              }
            });

            // this.params[key][index].id ?
            //   (this.params[key][index]['delFlag'] = '2') :
            //   this.params[key].splice(index, 1);
          }
        }

        await this.handleGetPrice();
      }
    },
    // 取消
    handleCancel() {
      this.params = {
        ...initParams(this.columns),
        puOrderItemList: [],
        // puOrderExecuteList: [],
      };
      this.setVisible(false);
    },
    // 判断保存条件
    judgeSaveCondition(cb) {
      const _this = this;
      this.$refs["orderEditForm"].validate(async (valid) => {
        if (valid) {
          // 执行结果在审批之后出现
          let validList = _this.params["puOrderItemList"].filter(
            (item) => item.delFlag === "0"
          );
          if (!validList.length) {
            _this.$notify.error({
              title: "错误",
              message: "请填写订单行！",
            });

            return false;
          }

          //   let isPrice =  _this.params.puOrderItemList.filter(item => !item.whetherCompleteInquiry);

          //  if(isPrice.length && this.role === 'procurementManager'){

          //   _this.$notify.error({
          //       title: '错误',
          //       message: '询价失败！'
          //     });
          //     return false

          //  }
          cb();
        } else {
          _this.$notify.error({
            title: "错误",
            message: "存在必填项未填写",
          });
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 保存
    handleSava() {
      console.log(this.params, "this.params---------");
      this.judgeSaveCondition(async () => {
        try {
          this.loading = true;
          const { code, msg } = await (this.handleIsRevise()
            ? orderApi.revision(this.params)
            : orderApi.edit(this.params));
          if (code === 200) {
            this.handleCancel();
          }
        } catch (err) {
          //
        } finally {
          this.loading = false;
        }
      });
    },
    beforeOpen() {},

    judgeGoodsAllocation(porp) {
      if (porp === "Y") {
        this.rules.goodsAllocationName = [
          { required: true, message: "货位不能为空", trigger: "change" },
        ];
      } else {
        this.rules.goodsAllocationName = null;
      }
      this.count++;
    },

    // 主表参照改变之后
    async handleReferChange(val, type, source) {
      // 供应商选择
      if (type === "SUPPLIER_PARAM") {
        let page = { pageNum: 1, pageSize: 10 };

        let relevanceRefer = [
          {
            // 供应商联系人
            key: "supplierContacts",
            params: {
              type: "SUPPLIERCONTACTS_PARAM",
              supplierId: val.id,
            },
          },
          {
            // 供应商业务员
            key: "supplierPersonal",
            params: {
              type: "PSNLICENSE_PARAM",
              supplierId: val.id,
              pkOrg: source.puOrg,
            },
          },
        ];

        try {
          let promiseArr = relevanceRefer.map((refer) => {
            return new Promise((resolve, reject) => {
              orderApi
                .REFER(
                  {
                    ...refer.params,
                    search: "",
                    isPage: true,
                  },
                  page
                )
                .then((res) => {
                  let { code, rows } = res;
                  if (code === 200) {
                    source[refer.key] = rows[0] ? rows[0].id : "";

                    source[`${refer.key}Name`] = rows[0] ? rows[0].name : "";

                    resolve();
                  }
                });
            });
          });

          Promise.all(promiseArr).then(async () => {
            // 需要手动询价
            if (this.isManualInquiry) {
              // 清空含税单价
              this.params["puOrderItemList"] = this.params[
                "puOrderItemList"
              ].map((item) => ({
                ...item,
                taxPrice: 0,
                money: 0,
              }));
              return;
            }

            // 明细不为空的情况下进行询价
            let detailList = this.params["puOrderItemList"].filter(
              (item) => item.material && item.material != ""
            );

            if (detailList.length) {
              await this.handleGetPrice();
            }
          });
        } catch (error) {}
      }

      // 组织
      if (type === "ORG_PARAM") {
        for (const key in this.params) {
          // if (key === "puOrderItemList" || key === "puOrderExecuteList") {
          if (key === "puOrderItemList") {
            this.params[key] = [];
          } else if (key === "sysFileRecordList") {
            this.params[key] = [];
          } else if (
            key != "puOrg" &&
            key != "puOrgName" &&
            // key != "buyer" &&
            // key != "buyerName" &&
            // key != "puDept" &&
            // key != "puDeptName" &&
            key != "status" &&
            key != "billDate" &&
            key != "createTime" &&
            key != "source"
          ) {
            this.params[key] = "";
          } else {
          }
        }
      }

      // WMS仓库
      if (type === "WAREHOUSE_PARAM") {
        // this.judgeGoodsAllocation(val.csFlag);
        // source.goodsAllocation = "";
        // source.goodsAllocationName = "";
        this.params.puOrderItemList = this.params.puOrderItemList.map(
          (item) => ({
            ...item,
            goodsAllocation: "",
            goodsAllocationName: "",
          })
        );
        // this.count++
      }
    },
    // 子表参照改变之后
    async handleTabReferChange(val, type, source) {
      // 物料触发税率
      if (type == "MATERIAL_PARAM") {
        let { rateCode } = source;
        try {
          // try
          this.loading = true;
          const { ntaxrate } = await tax(rateCode);
          source.tax = ntaxrate === "0E-8" ? 0 : ntaxrate;
        } catch (err) {
          // catch
          console.error(err);
        } finally {
          // finally
          this.loading = false;
        }

        if (source.qty && source.qty != "") {
          source["qty"] = 0;

          // source['whetherCompleteInquiry'] = false;

          source["taxPrice"] = 0;

          source["money"] = 0;

          source["taxDeductMoneya"] = 0;

          source["price"] = 0;

          source["notaxMoney"] = 0;

          source["tax"] = 0;

          this.params["qty"] = 0;
          this.params["originalQty"] = 0;
          this.params["money"] = 0;
          this.params["originalMoney"] = 0;
          this.params["notaxMoney"] = 0;

          source.isDrug = val.materialMedcine.isDrug == "0" ? "Y" : "N";

          // await this.handleGetPrice();
        }
      }
    },

    // Select改变之后
    handleSelectChange(val, typeName) {
      if (val === "billType") {
        this.params["billTypeName"] = this.dict.type[typeName].find(
          (item) => item.value == this.params[val]
        ).label;
        this.params.warehouse = "";
        this.params.warehouseName = "";
        this.params.goodsAllocation = "";
        this.params.goodsAllocationName = "";
        this.rules.goodsAllocationName = null;
        this.params["puOrderItemList"] = this.params["puOrderItemList"].map(
          (item) => ({
            ...item,
            goodsAllocation: "",
            goodsAllocationName: "",
          })
        );
      }
    },

    // 子表下拉框改变
    handleTabSelectChange(type, row) {
      if (type == "priceType") {
        // 需要手动询价
        if (this.isManualInquiry) {
          // 清空含税单价
          row["taxPrice"] = 0;
          row["money"] = 0;
          this.params.money = this.params["puOrderItemList"].reduce(
            (total, item) => {
              return (total += item.money);
            },
            0
          );
          return;
        }

        if (row.material && row.qty != "") {
          // row['whetherCompleteInquiry'] = false;
          this.handleGetPrice();
        }
      }
    },
    // 子表inputNumber
    handleInputChange(row, type) {
      if (this.isManualInquiry) {
        if (type == "qty" || type === "taxPrice") {
          // 不进行询价
          row.money = Number(row.taxPrice) * Number(row.qty);

          // 主表价税合计
          this.params.money = this.params["puOrderItemList"].reduce(
            (total, item) => {
              return (total += item.money);
            },
            0
          );
          this.params.qty = this.params["puOrderItemList"].reduce(
            (total, item) => {
              return (total += item.qty);
            },
            0
          );
          return;
        }
      }

      // 物料数量变化----询价
      if (
        (type == "qty" || type == "taxPrice" || type == "taxDeductMoneya") &&
        row.material
      ) {
        if (this.params.status === "2") {
          // 修订
          this.handleCalculateOrderAmount();
        } else {
          // row['whetherCompleteInquiry'] = false;

          this.handleGetPrice();
        }

        this.$refs.puOrderItemList[0].updateFooter();
        // this.$refs.puOrderExecuteList[0].updateFooter();
      }
    },
    // 子表多选框改变
    handleTabCheckbox(type, row) {
      if (type == "isGift" && this.isManualInquiry) {
        if (row.isGift === "Y") {
          row.money = 0;
        } else {
          row.money = Number(row.taxPrice) * Number(row.qty);
        }
        // 不进行询价

        // 主表价税合计
        this.params.money = this.params["puOrderItemList"].reduce(
          (total, item) => {
            return (total += item.money);
          },
          0
        );
        return;
      }

      // 勾选赠品，价税合计更新为0，含税单价、无税单价更新为0
      if (type === "isGift" && row.material && row.qty && row.qty != "") {
        // row['whetherCompleteInquiry'] = false;

        this.handleGetPrice();
      }
    },
    // 询价 getPrice
    async handleGetPrice() {
      // if(this.role === 'procurementManager'){

      try {
        // action:insert(新增)、revise(修订)、update(编辑)
        let { code, data } = await orderApi.getPrice({
          ...this.params,
          action: this.handleIsRevise() ? "revise" : "update",
        });
        if (code == 200) {
          this.params = data;
        }
      } catch (error) {
      } finally {
      }
      // }
    },
    // 修订——计算金额
    async handleCalculateOrderAmount() {
      try {
        let { code, data } = await orderApi.calculateOrderAmount({
          ...this.params,
          action: this.handleIsRevise() ? "revise" : "update",
        });

        code == 200 && (this.params = data);
      } catch (error) {
      } finally {
      }
    },

    // 判断修订还是编辑
    handleIsRevise() {
      return this.params.status == "2";
    },

    // /handleIsRevise() ? scope.row[cColumn.key] : Infinity
    getInputNumberMax(key, row) {
      if (key === "qty") {
        return this.handleIsRevise()
          ? Math.sign(row["originalQty"]) == -1
            ? 0
            : row["originalQty"]
          : this.params.source == "3"
          ? Infinity
          : row["originalQty"];
      }

      return Infinity;
    },

    async handelImport(fileList) {
      try {
        let formData = new FormData();

        formData.append("file", fileList[0].raw);

        let tabList = {
          puOrderItemList: [...this.params.puOrderItemList],
          warehouse: this.params.warehouse,
          // puOrderExecuteList: [...this.params.puOrderExecuteList],
        };

        const blob = new Blob([JSON.stringify(tabList)], {
          type: "application/json",
        });

        formData.append("tabList", blob);

        this.$modal.loading("正在上传文件，请稍候...");

        let {
          code,
          data: { puOrderItemList, puOrderExecuteList },
        } = await orderApi.orderImport(formData);

        if (code == 200) {
          // for (const key in data) {
          //   this.params[key].push(...data[key]);
          // }
          this.params["puOrderItemList"] = [...puOrderItemList];
          this.params["puOrderExecuteList"] = [...puOrderExecuteList];
          let { setVisible } = this.$refs.batchImport;

          setVisible(false);

          // if(num > total)
          this.handleGetPrice();
        }
      } catch (error) {
      } finally {
        this.$modal.closeLoading();
      }
    },

    async handleTemDownload() {
      this.download(
        "/pu/order/downloadFailData",
        {},
        `物料信息模板${new Date().getTime()}.xlsx`
      );
    },
    getSummaries({ columns, data }) {
      const means = []; // 合计
      let { tabColumns, tabName } = this;
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          means.push("合计");
        } else {
          const values = data.map((item) => Number(item[column.property]));

          let sumColumn = tabColumns
            .find((tab) => tab.key === tabName)
            .tableColumns.filter((item) => item.hidden)
            .filter(
              ({ key, isSummary }) => isSummary && key === column.property
            );

          // 合计
          // if (!values.every(value => isNaN(value))) {
          if (sumColumn.length) {
            means[columnIndex] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            means[columnIndex] = means[columnIndex].toFixed(2);
          } else {
            means[columnIndex] = "";
          }
        }
      });
      // sums[index] = sums[index] && sums[index].toFixed(2); // 保留2位小数，解决小数合计列
      return [means];
    },
    // 子表-批量复制
    async tabCopyChange(prop, { column, source }) {
      let { key, referName, dataMapping } = column;
      try {
        this.tabLoading = true;
        if (key === "materialCode") {
          let {
            code,
            data: { puOrderItemList },
          } = await orderApi.materialCopy({
            materialCode: prop,
            puOrderItemList: this.params.puOrderItemList.filter(
              (item) => item.rowNo != source.rowNo
            ),
            // puOrderExecuteList
          });
          if (code == 200) {
            this.params.puOrderItemList = [...puOrderItemList];
            // this.params.puOrderExecuteList = [...puOrderExecuteList];
          }
        } else {
          let params = {
            searchList: prop,
            type: referName,
          };

          key === "goodsAllocationName" &&
            (params["stordocId"] = this.params.warehouse);
          let { code, rows } = await orderApi.REFER(params);
          if (code == 200) {
            // !rows.length &&
            //   this.$notify.warning({
            //     message: "粘贴数据检索为空,请检查是否符合要求！",
            //   });
            if (!rows.length) {
              this.$notify.warning({
                message: "粘贴数据检索为空,请检查是否符合要求！",
              });
              for (const key in dataMapping) {
                source[key] = "";
              }
            }
            rows = rows.map((item) => {
              let obj = {};
              for (const key in dataMapping) {
                obj[key] = item[dataMapping[key]];
              }
              return obj;
            });

            let invariant = this.params.puOrderItemList.filter(
              (item) => item.rowNo < source.rowNo || item.delFlag !== "0"
            );
            let change = this.params.puOrderItemList
              .filter(
                (item) => !(item.rowNo < source.rowNo) && item.delFlag === "0"
              )
              .map((item, index) => {
                return {
                  ...item,
                  ...rows[index],
                };
              });
            this.params.puOrderItemList = [...invariant, ...change];
          }
        }
      } catch (error) {
      } finally {
        this.tabLoading = false;
      }
    },

    inputTabChange(prop, { column, source }) {
      let { key, copy } = column;
      // 数量-批量复制
      if (copy) {
        if (key === "qty") {
          let munList = prop.split(/,|，|\s+/);

          let invariant = this.params.puOrderItemList.filter(
            (item) => item.rowNo < source.rowNo || item.delFlag !== "0"
          );

          let change = this.params.puOrderItemList
            .filter(
              (item) => !(item.rowNo < source.rowNo) && item.delFlag === "0"
            )
            .map((item, index) => {
              return {
                ...item,
                qty: munList[index] || item.qty,
                money: this.isManualInquiry
                  ? Number(item.taxPrice) * Number(item.qty)
                  : item.money,
              };
            });
          this.params.puOrderItemList = [...invariant, ...change];

          if (this.isManualInquiry) {
            // 不进行询价

            // 主表价税合计
            this.params.money = this.params["puOrderItemList"].reduce(
              (total, item) => {
                return (total += Number(item.money));
              },
              0
            );
            // 原始总数量
            this.params.qty = this.params["puOrderItemList"].reduce(
              (total, item) => {
                return (total += Number(item.qty));
              },
              0
            );
            return;
          }
          if (this.params.status === "2") {
            // 修订
            this.handleCalculateOrderAmount();
          } else {
            this.handleGetPrice();
          }
        }
      }
    },
    onHide(prop) {
      this.innerColumns = prop;
    },
  },
  created() {},
  mounted() {},
  updated() {
    this.$nextTick(() => {
      // this.$refs.puOrderExecuteList &&
      //   this.$refs.puOrderExecuteList[0].doLayout();
      this.$refs.puOrderItemList && this.$refs.puOrderItemList[0].doLayout();
    });
  },
  destroyed() {},
};
</script>
<template>
  <el-drawer
    direction="btt"
    size="100%"
    :with-header="false"
    :visible.sync="visible"
    @open="beforeOpen"
    @close="$emit('close')"
  >
    <el-form
      :key="count"
      v-loading="loading"
      :size="size"
      ref="orderEditForm"
      class="orderEditForm"
      label-position="right"
      label-width="140px"
      :model="params"
      :rules="rules"
    >
      <el-card
        :body-style="{
          padding: '20px',
          display: 'flex',
          'flex-wrap': 'wrap',
        }"
        style="margin: 10px"
      >
        <div
          slot="header"
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h3>{{ handleIsRevise() ? "修订" : "编辑" }}</h3>
          <div style="text-align: right">
            <!-- 编辑 非自制 采购角色 -->
            <cgxj-button
              v-if="
                !handleIsRevise() &&
                role === 'procurementManager' &&
                params.source != '3'
              "
              v-model="params"
              :size="size"
              :source.sync="params"
            ></cgxj-button>
            <el-button :size="size" type="primary" @click="handleSava"
              >更 新</el-button
            >
            <el-button :size="size" @click="handleCancel">取 消</el-button>
          </div>
        </div>
        <el-row style="display: flex; flex-wrap: wrap">
          <el-col
            v-for="(column, index) in columns"
            :key="index"
            :span="column.span || 6"
          >
            <el-form-item
              :prop="column.key"
              :label="column.title"
              v-if="column.isShow"
            >
              <el-input
                v-if="column.inputType === 'Input'"
                v-model="params[column.key]"
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                :disabled="column.disabled"
                style="width: 100%"
              ></el-input>
              <dr-popover-select
                v-if="column.inputType === 'PopoverSelect'"
                v-model="params[column.key]"
                :size="size"
                :value-key="column.valueKey"
                :source.sync="params"
                :title="column.title"
                :type="column.referName"
                :multiple="column.multiple"
                :placeholder="column.placeholder"
                :data-mapping="column.dataMapping"
                :disabled="column.disabled"
                :clearable="column.clearable"
                :query-params="column.queryParams"
                @change="handleReferChange"
              ></dr-popover-select>
              <el-input
                v-if="column.inputType === 'Textarea'"
                v-model="params[column.key]"
                type="textarea"
                :rows="column.rows"
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                :disabled="column.disabled"
                :maxlength="column.maxlength"
                show-word-limit
                style="width: 100%"
              ></el-input>
              <el-input-number
                v-if="column.inputType === 'InputNumber'"
                v-model="params[column.key]"
                :precision="column.precision"
                :controls-position="column.controlsPosition"
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                :disabled="column.disabled"
                style="width: 100%"
              ></el-input-number>
              <el-select
                v-if="column.inputType === 'Select'"
                v-model="params[column.key]"
                :disabled="column.disabled"
                :clearable="column.clearable"
                :placeholder="column.placeholder"
                style="width: 100%"
                @change="handleSelectChange(column.key, column.referName)"
              >
                <el-option
                  v-for="item in dict.type[column.referName]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-select
                v-if="column.inputType === 'TagSelect'"
                v-model="params[column.key]"
                multiple
                clearable
                collapse-tags
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                :disabled="column.disabled"
                style="width: 100%"
              >
                <template #prefix>
                  <el-icon
                    class="el-icon-view"
                    style="cursor: pointer"
                    @click.stop="$message.info(234)"
                  ></el-icon>
                </template>
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <el-date-picker
                v-if="column.inputType === 'DatePicker'"
                v-model="params[column.key]"
                :type="column.type"
                :placeholder="column.placeholder"
                :clearable="column.clearable"
                :disabled="column.disabled"
                :picker-options="column.pickerOptions"
                style="width: 100%"
              ></el-date-picker>
              <el-checkbox
                v-if="column.inputType === 'Checkbox'"
                v-model="params[column.key]"
                :disabled="column.disabled"
                true-label="Y"
                false-label="N"
              >
              </el-checkbox>
              <file-upload-center
                v-if="column.inputType === 'Upload'"
                v-model="params[column.key]"
                :file-type="column.fileType"
                :disabled="handleIsRevise()"
              ></file-upload-center>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card
        :body-style="{
          padding: '20px',
          display: 'flex',
          'flex-wrap': 'wrap',
          position: 'relative',
        }"
        style="margin: 10px"
      >
        <el-tabs v-model="tabName" style="width: 100%" v-loading="tabLoading">
          <el-tab-pane
            v-for="(column, index) in tabColumns"
            :key="index"
            :label="column.title"
            :name="column.key"
          >
            <ux-grid
              border
              use-virtual
              keep-source
              show-summary
              show-overflow
              beautify-table
              :ref="column.key"
              :size="size"
              :height="tabHeight"
              style="width: 100%"
              :data="params[column.key].filter((item) => item.delFlag === '0')"
              :summary-method="getSummaries"
              :header-row-style="{
                color: '#515a6e',
              }"
            >
              <ux-table-column
                title="序号"
                type="index"
                width="60"
              ></ux-table-column>
              <ux-table-column
                v-for="(cColumn, cIndex) in column.tableColumns.filter(
                  (item) => item.hidden
                )"
                :key="cColumn.key + cColumn.hidden"
                :field="cColumn.key"
                :title="cColumn.title"
                :width="cColumn.width || 80"
                resizable
              >
                <template slot="header" slot-scope="scope">
                  <span v-if="cColumn.require" style="color: #ff4949">*</span>
                  <span>
                    {{ cColumn.title }}
                  </span>
                </template>
                <template slot-scope="scope">
                  <el-form-item label-width="0">
                    <span v-if="!cColumn.inputType">
                      {{ scope.row[cColumn.key] }}
                    </span>

                    <el-input
                      v-if="cColumn.inputType === 'Input'"
                      v-model="scope.row[cColumn.key]"
                      :placeholder="cColumn.placeholder"
                      :clearable="cColumn.clearable"
                      :disabled="cColumn.disabled"
                      :size="size"
                      style="width: 100%"
                      @change="
                        (prop) =>
                          inputTabChange(prop, {
                            column: cColumn,
                            source: scope.row,
                          })
                      "
                    ></el-input>

                    <dr-popover-select
                      v-if="cColumn.inputType === 'PopoverSelect'"
                      v-model="scope.row[cColumn.key]"
                      :source.sync="scope.row"
                      :title="cColumn.title"
                      :value-key="cColumn.valueKey"
                      :disabled="cColumn.disabled"
                      :clearable="cColumn.clearable"
                      :copy="cColumn.copy"
                      :type="cColumn.referName"
                      :multiple="cColumn.multiple"
                      :placeholder="cColumn.placeholder"
                      :data-mapping="cColumn.dataMapping"
                      :query-params="
                        cColumn.key !== 'goodsAllocationName'
                          ? cColumn.queryParams
                          : () => ({
                              stordocId: params.warehouse,
                              pkOrg: params.puOrg,
                            })
                      "
                      :size="size"
                      @change="handleTabReferChange"
                      @copyChange="
                        (prop) =>
                          tabCopyChange(prop, {
                            column: cColumn,
                            source: scope.row,
                          })
                      "
                    ></dr-popover-select>

                    <el-select
                      v-if="cColumn.inputType === 'Select'"
                      v-model="scope.row[cColumn.key]"
                      :size="size"
                      :disabled="cColumn.disabled"
                      :clearable="cColumn.clearable"
                      :placeholder="cColumn.placeholder"
                      style="width: 100%"
                      @change="handleTabSelectChange(cColumn.key, scope.row)"
                    >
                      <el-option
                        v-for="item in dict.type[cColumn.referName]"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>

                    <el-checkbox
                      v-if="cColumn.inputType === 'Checkbox'"
                      v-model="scope.row[cColumn.key]"
                      :disabled="cColumn.disabled"
                      true-label="Y"
                      false-label="N"
                      @change="handleTabCheckbox(cColumn.key, scope.row)"
                    ></el-checkbox>
                    <el-input-number
                      v-if="cColumn.inputType === 'InputNumber'"
                      v-model="scope.row[cColumn.key]"
                      :precision="cColumn.precision"
                      :controls-position="cColumn.controlsPosition"
                      :max="getInputNumberMax(cColumn.key, scope.row)"
                      :min="cColumn.key === 'reservedQty' ? 0 : -Infinity"
                      @change="handleInputChange(scope.row, cColumn.key)"
                      :placeholder="cColumn.placeholder"
                      :clearable="cColumn.clearable"
                      :disabled="cColumn.disabled"
                      :size="size"
                      style="width: 100%"
                    ></el-input-number>
                    <el-date-picker
                      v-if="cColumn.inputType === 'DatePicker'"
                      v-model="scope.row[cColumn.key]"
                      :size="size"
                      :type="cColumn.type"
                      :placeholder="cColumn.placeholder"
                      :clearable="cColumn.clearable"
                      :disabled="cColumn.disabled"
                      :picker-options="cColumn.pickerOptions"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-form-item>
                </template>
              </ux-table-column>

              <!-- 修订：不可删除、增行
                  编辑：自制：可删可增 -->
              <!-- v-if="!handleIsRevise()" -->
              <ux-table-column
                v-if="!handleIsRevise()"
                fixed="right"
                label="操作"
                width="120"
              >
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="
                      delTableRow(params[tabName], scope.row, tabName)
                    "
                    type="text"
                    :size="size"
                  >
                    删行
                  </el-button>
                </template>
              </ux-table-column>
            </ux-grid>
            <!-- </template>
          </virtual-scroll> -->
          </el-tab-pane>
        </el-tabs>
        <el-row style="position: absolute; top: 20px; right: 20px">
          <el-button
            v-if="params.source == '3' && !handleIsRevise()"
            :size="size"
            @click="addTableRow(params[tabName])"
            >增行</el-button
          >
          <BatchImport
            v-if="params.source == '3' && !handleIsRevise()"
            ref="batchImport"
            @import="handelImport"
            @temDownload="handleTemDownload"
            :fileSize="2"
          ></BatchImport>
        </el-row>
        <el-row style="margin-top: 10px">
          <el-col>
            <button-hide v-model="innerColumns" @change="onHide"></button-hide>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </el-drawer>
</template>

<style scoped>
.orderEditForm >>> .el-form-item {
  margin-bottom: 5px;
}
::v-deep .singleTable .el-form-item {
  margin-bottom: 0px;
}
::v-deep.uxbeautifyTableClass
  .elx-header--column
  .elx-resizable.is--line:before {
  height: 100%;
  background-color: #dfe6ec;
}
</style>
