<template>
  <div>
    <bill-editor ref="detail" :list="detailtList" :isView="isView" :defData="detailData" />

    <info-model v-model="visible" :config="modelConfig" @change="setinfo" />
    <view-supplier v-model="showViewSupplier" :item="viewSupplierItem" />
    <view-commodity v-model="showCommodity" :item="viewCommodity" />
  </div>
</template>

<script>
import BillEditor from "../../../components/bill-editor/index";
import InfoModel from "../../components/infomodel/index";
import modelConfig from "./config/model";
import ViewSupplier from "../../components/viewSupplier";
import ViewCommodity from "../../components/viewCommodity";
import { detailConfig } from "./config/detail";
import { rcvTypeOptions } from "../../config/options";
import { addItem, doException, getDicts, getStockStatusOptions, IS_AGV, strategyExecute } from "./api";
import { getBusiness } from "@/views/kzyWMS/api/business"; // 系统参数接口
import { createValidator } from "../../../utils/validator";

export default {
  components: {
    "bill-editor": BillEditor,
    "info-model": InfoModel,
    "view-supplier": ViewSupplier,
    "view-commodity": ViewCommodity,
  },
  props: {
    isView: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      mainlist: [],
      sublist: [],
      stockStatusOptions: [],
      modelConfig: modelConfig(this),
      detailtList: null,
      detailData: null,
      visible: false,
      confirmLoading: false,
      showViewSupplier: false,
      businessData: "",
      viewSupplierItem: null,
      showCommodity: false,
      viewCommodity: null,
      createValidator: createValidator([this.validateNotEmpty]),
    };
  },

  created() {
    getBusiness().then((res) => {
      this.businessData = res; // 系统参数
      this.handleView();
    });
  },

  methods: {
    getStockStatusOptions() {
      const mainForm = this.mainlist[0] || {};
      const { rcvType } = mainForm;
      // if (!rcvType) return
      const params = {
        enterpriseId: this.$store.state.user.info.enterpriseId,
        category: "RcvStatusChoose",
        dataSource: "2",
      };
      getStockStatusOptions(params).then((res) => {
        if (!res.success) return;
        const matchFactors = res.data.rules.map((rule) => rule.matchFactors).flat();
        const curFactors = matchFactors.find((_) => _.value.split(",").includes("2"));
        if (!curFactors) {
          console.error("入库结论匹配失败");
          return;
        }
        const curRuleId = curFactors.ruleId;
        const curRule = res.data.rules.find((_) => _.id === curRuleId);
        const dictionary = {
          0: "合格",
          1: "不合格",
        };

        let value = curRule.searchFactors.map((_) => _.value)[0].split(",");
        console.log(value);
        let options = value.map((i) => {
          const label = dictionary[i] || i;
          return { label, value: i };
        });

        this.stockStatusOptions = options;
        console.log(this.stockStatusOptions);
      });
    },
    queryRefFromName(name) {
      return this.$refs.detail.$refs[name][0];
    },
    setinfo(a, data) {
      if (!data) return;
      this.mainlist = data.mainlist;
      this.sublist = data.sublist;
      let info = {
        main: {
          ...data.mainlist[0],
          qcOperator: this.$store.state.user.name,
          rcvTypet: rcvTypeOptions.find((t) => t.value == data.mainlist[0].rcvType).title,
        },
        extend: { ...data.mainlist[0] },
        operate: {},
        list: data.sublist.map((t) => ({
          ...t,
          qcOpcode1: this.$store.state.user.name,
          qcOddCaseActQty: t.caseQty,
          qcOddPieceActQty: t.oddPieceQty,
          srcAutoBillNum: data.mainlist[0].srcAutoBillNum,
          result: t.qcResult1,
        })),
      };

      this.getStockStatusOptions();
      this.detailData = info;
      console.log(this.detailData, "this.detailData");
      // this.getBilldRcvreason1()
      // this.getDefReason()
      // this.getHandlingMeasure()
    },

    validateNotEmpty(params) {
      return new Promise((resolve) => {
        if (!params) {
          this.$message.warning("请输入必填项");
          resolve(false);
          return false;
        }
        if (!Array.isArray(params.list) || params.list.length === 0) {
          this.$message.warning("请选择要提交的明细");
          resolve(false);
          return false;
        }
        resolve(true);
      });
    },

    submitData() {
      this.getDetailData().then((params) => {
        if (!params) {
          return;
        }
        console.log(params, "paramsparams");
        this.$confirm({
          content: this.$lang("是否确定提交?"),
          onOk: () => {
            return this.handleAdd(params);
          },
        });
      });
    },

    getDetailData(isValidate = true, isSelected = true) {
      return this.$refs.detail.getDetailData(isValidate, isSelected).then((vals) => {
        return this.createValidator.execute(vals, { notValid: !isValidate }).then((res) => {
          if (res)
            return {
              rqcReHeadersDTO: vals.main,
              rqcReLinesDTOList: vals.list.map((t) => ({
                ...t,
                oddCaseQty: t.caseQty,
                rcvType: this.mainlist[0].rcvType,
                taskReRqcId: t.taskRecheckId,
                stockStatus: t.qcReResult,
              })),
            };
          return res;
        });
      });
    },

    handleView() {
      let arr = detailConfig(this);
      if (this.isView) {
        arr.forEach((t) => {
          t.list.forEach((tt) => {
            if (tt.item.type === "p-grid-form") {
              tt.item.config = tt.item.config.map((t) => ({ ...t, disabled: true, placeholder: "" }));
            } else if (tt.item.type === "p-table-edit") {
            }
          });
        });
      }
      this.detailtList = arr;
    },

    toErrorBill() {
      let ref = this.queryRefFromName("list");
      let that = this;
      ref.getDataSource(true, false).then((list) => {
        if (list.length < 1) {
          that.$message.warning(this.$lang("请先勾选"));
          return;
        }
        this.$confirm({
          content: this.$lang("是否确定提交?"),
          onOk: () => {
            // let params = list.filter((t) => ref.selectedRowKeys.some((k) => k == t[ref.rowKey]))
            return this.handleErrorBill(list).then((res) => {
              if (!res) return;
              ref.removeSelectedRow(); //默认删除勾选数据
            });
          },
        });
      });
    },

    handleAdd(params) {
      return addItem(params).then((res) => {
        if (!res.success) {
          this.$exception(res);
          return;
        }
        //itemHealthIsDouble 双人业务类型(0:正常 1：双人验收，默认正常)
        params.rqcReLinesDTOList.forEach((tt, i) => {
          //
          if (tt.itemHealthIsDouble === 1) {
            // 商品需要双人验收时，第一次验收需要进行提示
            if (tt.times === 0) {
              this.$message.warning(this.$lang(i + 1 + "行商品需双人验收"));
            }
          }
        });
        this.$message.success(this.$lang("新增成功"));
        this.handleReset();
      });
    },

    handleReset() {
      this.detailData = null;
      this.viewSupplierItem = null;
      this.viewCommodity = null;
    },

    handleErrorBill(params) {
      return doException(params).then((res) => {
        if (!res.success) {
          this.$exception(res);
          return false;
        }
        this.$message.success(this.$lang("操作成功"));
        return true;
      });
    },
  },
};
</script>

<style></style>
