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

    <info-model ref="infoModel" v-model="visible" :config="config" @change="setinfo" :ibValidates="['vaildateItemInbound', 'vaildateItemCategory', 'vaildateItemLicense', 'vaildateItemVol']" />

    <split-bill
      v-model="splitVisible"
      :formItems="splitFormItems"
      :columns="splitColumns"
      :data="splitOriginItem"
      :splitedCallback="splitedCallback"
      :confirmLoading="confirmLoading"
      :rcvType="detailData ? detailData.main.rcvType : null"
      @ok="handleSpliteOk"
    />

    <spot-check v-model="spotVisible" ref="data" :dataList="spotData" v-on:isSpotCheck="isSpotCheckNum"></spot-check>

    <scan-code @successScanCode="successScanCode" v-model="scanVisible" ref="scan" :scanTable="scanTableList"></scan-code>

    <IsSeque-code @successScanCode="successScanCode" v-model="IsSequeVisible" ref="IsSeque" :scanTable="scanTableList"></IsSeque-code>

    <!-- IsSeque-code -->
    <view-commodity v-model="showCommodity" :item="viewCommodity" />

    <view-supplier v-model="showViewSupplier" :item="viewSupplierItem" />
    <view-update v-model="showUpdate" :item="viewUpdate" />
  </div>
</template>

<script>
import moment from "moment";
import BillEditor from "../../../components/bill-editor/index";
import InfoModel from "../../components/infomodel/index";
import SplitBill from "../../components/splitBill";
import config from "./config/model";
import { detailConfig } from "./config/detail";
import { rcvTypeOptions } from "../../config/options";
import { splitColumns } from "./config/split/columns";
import { splitFormItems } from "./config/split/formitems";
import spotCheck from "./components/spotCheck.vue";
import scanCode from "./components/scanCode";
import IsSequeCode from "./components/IsSequeCode";
// IsSequeCode
import { getPrintInfo, addItem, taskSplit, doException, getPreList, getDicts, isSupervised, extractSelectedRqcTask, getStockStatusOptions, IS_AGV, strategyExecute, isSupervisedReject } from "./api";
import ViewSupplier from "../../components/viewSupplier";
import ViewCommodity from "../../components/viewCommodity";
import viewUpdata from "../../components/viewUpdata";
import { toPrintServer, tempType, handlePrint } from "../../../utils/printServer";
import { businessRuleModule } from "../../mixins/rule";
import { createValidator } from "../../../utils/validator";
import { getBusiness } from "@/views/kzyWMS/api/business"; // 系统参数接口
import { itemsColChangeModule } from "../../receive/rcvEditor/mixins/itemsColChange";

import { a } from "./mock";

export default {
  components: {
    "bill-editor": BillEditor,
    "info-model": InfoModel,
    "spot-check": spotCheck,
    "split-bill": SplitBill,
    "scan-code": scanCode,
    "view-supplier": ViewSupplier,
    "view-commodity": ViewCommodity,
    "view-update": viewUpdata,
    "IsSeque-code": IsSequeCode,
  },
  mixins: [businessRuleModule, itemsColChangeModule],
  props: {
    isView: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      splitTaskRqcId: "", //拆分原id
      expiredDays: {},
      IsSequeVisible: false,
      businessData: null,
      mainlist: [],
      sublist: [],
      config: config(this),
      isScanCodeOk: false, //是否扫描监管码全部完成
      detailtList: null,
      detailData: null,
      visible: false,
      splitVisible: false,
      splitColumns: splitColumns,
      splitFormItems: splitFormItems,
      splitOriginItem: null,
      spotVisible: false,
      confirmLoading: false,
      spotData: [],
      scanVisible: false,
      scanTableList: [],
      showViewSupplier: false,
      viewSupplierItem: null,
      showCommodity: false,
      viewCommodity: null,
      showUpdate: false,
      viewUpdate: null,
      isSpotCheck: false,
      selectedRows: [],
      isSplit: false,
      stockStatusOptions: [],
      createValidator: createValidator([this.validateNotEmpty]),
    };
  },

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

  methods: {
    //查询库别接口
    async strategyExecuteFun(data) {
      let res = await strategyExecute(data);
      return res;
    },
    getwhAreaCategoryCode(res, record) {
      const matchObj = {
        oddPieceQty: String(record.oddPieceQty),
        oddCaseQty: String(record.oddCaseQty),
        stockStatus: String(record.stockStatus),
        categoryName: String(record.categoryName),
        dataSource: "1",
        isAgv: String(record.isAgv),
      };
      let hitRule = res.data.rules.find((rule) => {
        const { matchFactors } = rule;
        if (matchFactors.length === 0) return false;
        return rule.matchFactors.every((matchFactor) => {
          const { fieldName, matchType, value } = matchFactor;
          if (matchType === "equal") {
            return matchObj[fieldName] === value;
          }
          if (matchType === "in") {
            if (fieldName == "categoryName") {
              value.split(",").some((i) => matchObj.categoryName.indexOf(i) > -1);
            } else {
              return value.split(",").includes(matchObj[fieldName]);
            }
          }
          if (matchType === "gt") {
            return matchObj[fieldName] > value;
          }
          if (matchType === "lt") {
            return matchObj[fieldName] < value;
          }
        });
      });
      console.log("hitRule", hitRule);

      //   let options = hitRule.searchFactors.map((_) => {
      //     const label = whAreaCategoryCodeList.find((item) => item.value === _.value)?.label || _.value;
      //     return { label, value: _.value };
      //   });

      let value = hitRule.searchFactors.map((_) => _.value)[0].split(",");
      console.log(value);
      return value;
    },
    successScanCode(val) {
      this.isScanCodeOk = val;
    },
    queryRefFromName(name) {
      return this.$refs.detail.$refs[name][0];
    },
    getStockStatusOptions() {
      const mainForm = this.mainlist[0] || {};
      const { rcvType } = mainForm;
      // if (!rcvType) return
      const params = {
        enterpriseId: this.$store.state.user.info.enterpriseId,
        category: "RcvStatusChoose",
        dataSource: "1",
      };
      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("1"));
        if (!curFactors) {
          console.error("入库结论匹配失败");
          return;
        }
        const curRuleId = curFactors.ruleId;
        const curRule = res.data.rules.find((_) => _.id === curRuleId);
        const dictionary = {
          0: "合格",
          1: "不合格",
          2: "待处理",
          3: "拒收",

          // { label: "合格", value: "0" },
          //   { label: "不合格", value: "1" },
          //   { label: "待处理", value: "2" },
        };
        // let options = curRule.searchFactors.map((_) => {
        //   const label = dictionary[_.value] || _.value;
        //   return { label, value: _.value };
        // });

        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);
      });
    },
    async setinfo(a, data) {
      if (!data) return;

      let qingniu = {
        manufacturerLotNum: "",
        showProductionDate: "",
        showExpiredDate: "",
        batchProductionDate: "",
        batchExpiredDate: "",
      };

      let res = await IS_AGV();
      //   console.log(res);
      let isAgvType = res.data.map((i) => {
        return {
          dictName: i.dictName,
          dictCode: i.dictCode,
        };
      });
      console.log(isAgvType);
      this.mainlist = data.mainlist;
      this.sublist = data.sublist;
      //   let { length, width, height } = data.sublist;
      let ab = new Date();
      // let cc = new moment(ab)
      let cc = moment(ab).format("YYYY-MM-DD HH:mm:ss");
      let info = {
        main: {
          ...data.mainlist[0],
          qcOperator: this.$store.state.user.name,
          rcvTypet: rcvTypeOptions.find((t) => t.value == data.mainlist[0].rcvType).title,
          billDate: cc,
          // rcvDate: data.mainlist[0].rcvDate.substring(0, 10),
        },
        extend: { ...data.mainlist[0] },
        operate: {},
        list: data.sublist.map((t) => {
          let { length, width, height } = t;
          let pieceQty = t.conversionRate * (+t.oddCaseQty || 0) + (+t.oddPieceQty || 0);
          let batchProductionDate = t.batchProductionDate ? t.batchProductionDate.substring(0, 10) : "";
          let batchExpiredDate = t.batchExpiredDate ? t.batchExpiredDate.substring(0, 10) : "";
          // let showProductionDate = batchProductionDate.replace(/-/g, '')
          // let showExpiredDate = batchExpiredDate.replace(/-/g, '')
          let whAreaCategoryCode = "";
          // 3.直调库 只能订单类型是直调的选，即订单类型是直调的默认并且只能入直调库
          if (data.mainlist[0].rcvType == "7") {
            whAreaCategoryCode = "ZDK";
          }
          // 10.整散合一库 只能入整散合一的商品，即整散合一的商品默认并且只能入整散合一库
          else if (t.itemHealthStoreCategory.indexOf("合一") >= 0) {
            whAreaCategoryCode = "HYK";
          } else {
            whAreaCategoryCode = "";
          }

          this.getStockStatusOptions();

          let isAgv = "0";
          let b = 0;
          isAgvType.forEach((i) => {
            if (i.dictCode == "length") {
              let a = i.dictName.split("-");
              a[0] < length && a[1] > length && b++;
            }
            if (i.dictCode == "width") {
              let a = i.dictName.split("-");
              a[0] < width && a[1] > width && b++;
            }
            if (i.dictCode == "height") {
              let a = i.dictName.split("-");
              a[0] < height && a[1] > height && b++;
            }
          });
          if (b === 3) {
            isAgv = "1";
          }
          console.log(isAgv);
          this.isSplit = false;
          return {
            isAgv,
            ...t,
            qcOpcode1: this.$store.state.user.name,
            qcOddCaseActQty: t.caseQty,
            qcOddPieceActQty: t.oddPieceQty,
            // showExpiredDate: showExpiredDate,
            // showProductionDate: showProductionDate,
            batchProductionDate: batchProductionDate,
            batchExpiredDate: batchExpiredDate,
            srcAutoBillNum: data.mainlist[0].srcAutoBillNum,
            qty: (pieceQty / t.conversionRate).toFixed(2),
            pieceQty: pieceQty,
            oldPieceQty: pieceQty,
            // 收货的时候 结论为收货 到质检那里都是合格 结论为待处理 到质检那里是待处理
            qcResult1: typeof t.result === "string" ? t.result.trim() : null, //默认值参考收货结论
            whAreaCategoryCode: t.whAreaCategoryCode || whAreaCategoryCode,
            rqcReportNoNew: t.rqcReportNo, //用来判断报告单号是否可编辑
            rcvType: data.mainlist[0].rcvType, //入库类型
            ...qingniu,
          };
        }),
      };
      let rqcUser = this.$store.state.user.name;
      info.main.rqcUser = rqcUser;
      let ref = this.queryRefFromName("main");
      console.log(info, "info");
      //直调库不需要打印
      if (info.main.rcvType == "7") {
        info.main.isInstockPrint = "0";
        ref.form.hiddenItem("isInstockPrint");
      } else {
        info.main.isInstockPrint = "1";
        ref.form.unhiddenItem("isInstockPrint");
      }
      // 销售退回有效期至超过当前日期，库别默认退货库
      if (info.main.rcvType == "2") {
        info.list.forEach((t) => {
          let tempData = new Date(t.batchExpiredDate);
          tempData.setHours(0, 0, 0);
          if (Number(tempData) < Number(new Date())) {
            t.whAreaCategory = "THK";
          } else {
            t.whAreaCategory = "";
          }
        });
      }
      info.list.forEach((t) => {
        console.log(t);
        if (t.stockStatus == 1) {
          t.whAreaCategoryCode = "NHK";
        }
        // 越库(6)需要库别默认赋值
        if (info.main.rcvType == "6") {
          t.whAreaCategory = "YKQ";
        } else if (info.main.rcvType == "8" || info.main.rcvType == "9") {
          // 13.代管库 只能订单类型是代管的才可以入到代管库，即订单类型是代管的默认并且只能入代管库
          t.whAreaCategory = "DGK";
        }
      });
      console.log(info, "111111111111");
      this.detailData = info;
      this.isSpotCheck = false;
      this.selectedRows = [];
    },

    showSplitBill(record) {
      this.splitOriginItem = record;
      this.splitVisible = true;
    },

    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);
      });
    },
    async isScanCode() {
      let type = await this.getDetailData().then((params) => {
        console.log(params.rqcLinesDTOList);
        if (!params.rqcLinesDTOList) return;
        let list = params.rqcLinesDTOList.filter((i) => i.isSupervise != 0).map((i) => i.isSupervise);
        console.log(list);
        list = [...new Set(list)];
        console.log(list);
        if (list.length > 1) {
          this.$message.warning("选中行扫描类型不一致 不能同时选中!");
          return false;
        } else {
          return true;
        }
      });
      console.log(type);
      return type;
    },
    async submitData() {
      //   let isScanCode = await this.isScanCode();
      //   if (!isScanCode) {
      //     return;
      //   }
      let ref = this.queryRefFromName("list");
      let that = this;
      ref.getDataSource(true, false).then((list) => {
        if (list.length < 1) {
          // that.$message.warning(this.$lang("请先勾选"));
          return;
        }
        let info = list.filter((item) => item.isSupervise == 1 && item.stockStatus == 3);

        if (info.length != 0) {
          info.forEach((item) => {
            item.rcvHeaderId = item.rcvHeaderId;
            item.refBillId = item.rcvHeaderId;
            item.rcvLineId = item.rcvLineId;
            item.refBillLineId = item.rcvLineId;
            item.srcCode = item.asnAutoBillNum;
            item.cargoOwnerId = item.mtlOwnerId;
            item.cargoOwnerCode = item.mtlOwnerCode;
            item.taskRqcId = item.asnLineId;
            item.uploadFlag = "0";
            item.rejectQty = item.pieceQty;
            item.pieceQty = item.receiveQty;
          });

          const result = Object.values(
            info.reduce((acc, cur) => {
              const key = `${cur.rcvHeaderId}-${cur.rcvLineId}`;
              if (!acc[key]) {
                acc[key] = { ...cur };
              } else {
                acc[key].oddCaseQty += cur.oddCaseQty;
                acc[key].rejectQty += cur.rejectQty;
                acc[key].oddPieceQty += cur.oddPieceQty;
              }
              return acc;
            }, {})
          );

          console.log(result);
          isSupervisedReject(list).then((res) => {
            if (res.success) {
              if (!res.data) {
                this.scanTableList = result;
                this.scanVisible = true;
              } else {
                this.getDetailData().then((params) => {
                  if (!params) {
                    return;
                  }
                  if (!this.isSpotCheck) {
                    this.getList();
                    return;
                  }

                  this.$confirm({
                    content: this.$lang("是否确定提交?"),
                    onOk: () => {
                      return this.handleAdd(params);
                    },
                  });
                });
              }
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          this.getDetailData().then((params) => {
            if (!params) {
              return;
            }
            if (!this.isSpotCheck) {
              this.getList();
              return;
            }

            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 {
              rqcHeadersDTO: {
                ...vals.main,
                rcvDate: moment(vals.main.rcvDate).format("YYYY-MM-DD HH:mm:ss"),
              },
              rqcLinesDTOList: vals.list.map((t) => ({
                ...t,
                oddCaseQty: t.caseQty,
                rcvType: this.mainlist[0].rcvType,
                // stockStatus: t.qcResult1,
              })),
            };
          return res;
        });
      });
    },

    isSpotCheckNum(data) {
      this.isSpotCheck = data;
    },
    // 是否完成扫描监管码
    isCode(list, callback) {
      // refBillId\refBillLineId
      let ref = [];
      list.forEach((t) => {
        if (t.isSupervise >= 1) {
          ref.push({
            refBillId: t.rcvHeaderId,
            refBillLineId: t.rcvLineId,
            warehouseId: t.warehouseId,
          });
        }
        return;
      });
      if (ref.length > 0) {
        isSupervised(ref).then(async (res) => {
          if (!res.data) {
            // this.scanCode();

            // let isScanCode = await this.isScanCode();
            // if (!isScanCode) {
            //   return;
            // }

            this.scanCodeSplit(list);

            return;
          }
          callback(true);
        });
      } else {
        callback(true);
      }
    },

    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.execute(arr, "inBound_quality").then((list) => {
        this.detailtList = list;
        console.log(this.detailtList, "this.detailtList");
      });
    },

    splitedCallback(item) {
      item.pieceQty = item.conversionRate * item.caseQty + item.oddPieceQty;
      item.qty = (item.pieceQty / item.conversionRate).toFixed(2);
    },

    handleSpliteOk(list) {
      let nList = list.map((t, i) => ({
        ...this.splitOriginItem,
        ...t,
        taskRqcId: i == 0 ? this.splitOriginItem.taskRqcId : null,
      }));
      this.isSplit = true;
      this.handleSplitBill(nList);
    },

    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(); //默认删除勾选数据
            });
          },
        });
      });
    },
    //批量不合格
    batchFailure() {
      let ref = this.queryRefFromName("list");
      //勾选、校验
      ref.getDataSource(false, false).then((list) => {
        list.forEach((t) => {
          t.qcResult1 = "1";
        });
      });
    },

    handleAdd(params) {
      const isPrint = +params.rqcHeadersDTO.isInstockPrint;
      console.log(params);
      //   return;
      return addItem(params).then(async (res) => {
        if (!res.success) {
          this.$exception(res);
          return;
        }
        this.handleReset();
        //itemHealthIsDouble 双人业务类型(0:正常 1：双人验收，默认正常)
        params.rqcLinesDTOList.forEach((tt, i) => {
          if (tt.itemHealthIsDouble === 1) {
            // 商品需要双人验收时，第一次验收需要进行提示
            if (tt.times === 0) {
              this.$message.warning(this.$lang(`第${i + 1}行商品需双人验收`));
            }
          }
        });
        if (isPrint === 0) {
          this.$message.success(this.$lang("新增成功"));
          return;
        }
        // if (!res.data || !res.data.data) {
        //   this.$message.warning(this.$lang("当前没有需要进行打印的任务"));
        // } else {
        //   const printParms = {
        //     consignorId: params.rqcHeadersDTO.mtlOwnerId,
        //   };
        //   const warehouseId = params.rqcHeadersDTO.warehouseId;
        //   var temp = tempType.SJ_BQ;
        //   if (res.data.tempType) {
        //     temp = res.data.tempType;
        //   }
        //   //调用打印方法()
        //   handlePrint(res.data.data.printData, res.data.data.printAddress).then((res) => {
        //     if (!res.success) {
        //       this.$exception(res);
        //       return;
        //     }
        //     this.$message.success(res.message);
        //   });
        // }
        if (!res.data) {
          return;
        }
        let printData = await getPrintInfo(res.data);
        console.log(printData, "====");
        handlePrint(printData.data.printData, printData.data.printAddress).then((res) => {
          if (!res.success) {
            this.$exception(res);
            return;
          }
          this.$message.success(res.message);
        });

        return false;
      });
    },

    handleReset() {
      this.detailData = null;
      this.viewCommodity = null;
      this.viewSupplierItem = null;
      this.viewUpdate = null;
      this.isSpotCheck = false;
      this.selectedRows = [];
      this.isSplit = false;
    },

    handleSplitBill(params) {
      this.confirmLoading = true;

      return taskSplit(params)
        .then((res) => {
          if (!res.success) {
            this.$exception(res);
            return;
          }
          this.$message.success(this.$lang("拆单成功"));
          this.splitVisible = false;
          this.confirmLoading = false;
          let newBills = params.map((t, i) => ({
            ...t,
            qcOpcode1: this.$store.state.user.name,
            qcOddCaseActQty: t.caseQty,
            qcOddPieceActQty: t.oddPieceQty,
            srcAutoBillNum: this.mainlist[0].srcAutoBillNum,
            taskRqcId: res.data[i],
          }));
          let id = this.splitOriginItem.taskRqcId;
          let ref = this.queryRefFromName("list");
          let rowIndex = this.splitOriginItem._row_count;
          let first = newBills.shift();
          ref.setDataSource(first, [id]);
          newBills.forEach((tt, ii) => {
            tt.containerCode = "";
            ref.addRow(1, null, rowIndex + ii, tt);
          });
        })
        .catch((err) => {
          this.$exception(err);
          this.confirmLoading = false;
        });
    },

    handleErrorBill(params) {
      return doException(params).then((res) => {
        if (!res.success) {
          this.$exception(res);
          return false;
        }
        this.$message.success(this.$lang("操作成功"));
        return true;
      });
    },
    //抽检
    getList() {
      this.spotData = [];
      this.queryRefFromName("list")
        .getDataSource(this.selectedRows.length == 0 ? false : true, false)
        .then((vals) => {
          if (!vals.length) {
            this.$message.error("请先选择单据再进行抽检操作");
            return;
          }
          this.getCheck(vals);
        });
    },
    getCheck(data) {
      let result = [];
      data.forEach((t) => {
        if (t.qcResult1 === "3") {
          return;
        }
        result.push(t);
      });
      console.log(result, "resultresultresultresult");
      if (result.length === 0) {
        this.$message.warn("该拒收单据不需要进行抽检操作!");
        this.isSpotCheck = true;
        this.submitData();
        return;
      }
      this.spotVisible = true;
      getPreList(
        result.map((t) => ({
          ...t,
          oddCaseQty: t.caseQty,
        }))
      ).then((res) => {
        if (!res.success) {
          this.$exception(res);
          return;
        }
        this.spotData = res.data;
      });
    },
    //扫描监管码
    async scanCode() {
      let isScanCode = await this.isScanCode();
      if (!isScanCode) {
        return;
      }

      this.queryRefFromName("list")
        .getDataSource(this.selectedRows.length == 0 ? false : true, false)
        .then(async (vals) => {
          if (!vals.length) {
            this.$message.error("请先选择单据再操作扫描药品追溯码");
            return;
          }
          //   if (this.isSplit) {
          //     this.$message.error("商品已拆分，无法进行药品追溯码扫描");
          //     return;
          //   }

          let list = vals.filter((tt) => tt.isSupervise >= 1);
          let data = {};
          if (list && list.length < 1) {
            data = {};
          } else {
            data = await extractSelectedRqcTask(this.changeData([...list]));
          }
          this.scanTableList = this.updateTable(data ? (data.data ? data.data.list : []) : [], list);
          if (!list[0]) {
            this.$message.error("当前数据无需扫描监管码!");
            return;
          }
          //   console.log(list);
          if (list[0] && list[0].isSupervise == 1) {
            this.scanVisible = true;
          }

          if (list[0] && list[0].isSupervise == 2) {
            this.IsSequeVisible = true;
          }

          //   this.$refs.scan.modelVal = true;
        });
    },

    async scanCodeSplit(data1) {
      //   let isScanCode = await this.isScanCode();
      //   if (!isScanCode) {
      //     return;
      //   }

      //   this.queryRefFromName("list")
      //     .getDataSource(this.selectedRows.length == 0 ? false : true, false)
      //     .then(async (vals) => {
      //       if (!vals.length) {
      //         this.$message.error("请先选择单据再操作扫描药品追溯码");
      //         return;
      //       }
      //   if (this.isSplit) {
      //     this.$message.error("商品已拆分，无法进行药品追溯码扫描");
      //     return;
      //   }

      let list = data1.filter((tt) => tt.isSupervise >= 1);
      let data = {};
      if (list && list.length < 1) {
        data = {};
      } else {
        data = await extractSelectedRqcTask(this.changeData([...list]));
      }
      this.scanTableList = this.updateTable(data ? (data.data ? data.data.list : []) : [], list);
      if (!list[0]) {
        this.$message.error("当前数据无需扫描监管码!");
        return;
      }
      //   console.log(list);
      if (list[0] && list[0].isSupervise == 1) {
        this.scanVisible = true;
      }

      if (list[0] && list[0].isSupervise == 2) {
        this.IsSequeVisible = true;
      }

      //   this.$refs.scan.modelVal = true;
      // });
    },
    changeData(arr) {
      if (!arr) return;
      arr.forEach((item) => {
        item.refBillId = item.rcvHeaderId;
        item.refBillLineId = item.rcvLineId;
      });
      return arr;
    },
    updateTable(arr1, arr2) {
      //更新监管码最新数据
      let newArr = [];
      arr1.forEach((item) => {
        arr2.forEach((itm) => {
          if (itm.refBillLineId == item.refBillLineId) {
            itm.pieceQty = item.pieceQty;
            itm.packLevel = item.packLevel ? item.packLevel : "0";
            newArr.push(itm);
          }
        });
      });
      return newArr;
    },

    //点击明细弹扫描监管码
    async codeModal(data, callBack) {
      this.isCode([data], callBack);
      return;
      let datas = {};
      if (data && data.length < 1) {
        datas = {};
      } else {
        datas = await extractSelectedRqcTask(this.changeData([data]));
      }
      this.scanTableList = this.updateTable(datas ? (datas.data ? datas.data.list : []) : [], [data]);
      if (this.scanTableList.length < 1) {
        this.isScanCodeOk = true;
        return callBack(true);
      }
      // this.scanTableList = [data]

      if (data[0] && data[0].isSupervise == 1) {
        this.scanVisible = true;
      }

      if (data[0] && data[0].isSupervise == 2) {
        this.IsSequeVisible = true;
      }
      //   this.scanVisible = true;
      //   this.$refs.scan.modelVal = true;
      callBack(false);
    },
  },
};
</script>

<style></style>
