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

    <info-model
      ref="detailModel"
      v-model="visible"
      :config="modelConfig"
      :validateFun="validateExtract"
      :ibValidates="[
        'vaildateItemInbound',
        'vaildateItemCategory',
        'vaildateItemLicense',
        'vaildateItemVol',
        'vaildateSuppilerAndCustomer',
        'vaildateLicense',
        'vaildateCargoOwnerScop',
      ]"
      @change="setinfo"
    />

    <!-- history -->
    <info-model ref="historyModel" v-model="showHistoryModal" :config="historyConfig" @change="getHistory" />
    <!-- 异常单 -->
    <info-model ref="exceptionModel" v-model="showExceptionModal" :config="exceptionConfig" @change="setinfo" />
    <!-- 采集监管码 -->
    <scanCode v-model="scanVisible" :scanTable="scanTableList" @detail="onDetail" @successScanCode="successScanCode" />

    <imgsUpload v-model="isUpload" :isView="lookats" @completed="handleUploadImgs" :uploadIdlist="uploadIdlist" />

    <view-supplier v-model="showViewSupplier" :item="viewSupplierItem" />

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

    <p-modal
      title="商品维护"
      :visible="maintainVisible"
      :dialogStyle="{ top: '20px' }"
      :width="'90%'"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div class="box-p20-bg">
        <c-cditor
          v-if="maintainVisible"
          ref="itemsEditor"
          :detailItem="detailItem"
          :isSingle="true"
          @changeStep="handleItemsComplete"
        />
      </div>
    </p-modal>

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

    <!-- <a-affix :offsetBottom="0" class="footer">
      <div class="footer_bat">
        <span v-for="item of items" :key="item.name" class="footer_bat-item">
          {{ item.label }}:<span class="numClass">{{ item.value }}</span></span
        >
      </div>
    </a-affix> -->

    <hosting v-model="showHost" :hostData="hostData" :refList="hostList"></hosting>

    <login-modal v-model="loginVisible" title="双人收货登录" @onLogined="onLogined" />

    <exceptionModal
      v-model="showException"
      :exceptionData="exceptionData"
      :refException="refException"
      :mainException="mainException"
    />
  </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 scanCode from "../rcvEditor/components/scanCode.vue";
import ViewSupplier from "../../components/viewSupplier";
import ViewCommodity from "../../components/viewCommodity";
import ImgsUpload from "@/views/kzyWMS/components/ImgsUpload";
import Editor from "../../../basedata/goodsManager/editor";
import hosting from "../../components/hosting";
import LoginModal from "../../components/login-modal";
import exceptionModal from "../../components/exceptionModal";

import modelConfig from "./config/model/index";
import { detailConfig } from "./config/detail";
import { footerItem } from "./config/detail/footer";
import historyConfig from "./config/history";
import exceptionConfig from "./config/exception";

import { splitColumns } from "./config/split/columns";
import { splitFormItems } from "./config/split/formitems";

import { extendInfoModule } from "./mixins/extendInfo";
import { historyModule } from "./mixins/history";
import { validateModule } from "./mixins/validate";
import { itemsColChangeModule } from "./mixins/itemsColChange";
import { showStockCountModual } from "../../mixins/showStockCount";
import { splitModule } from "./mixins/split";
import { getExpiredDaysModual } from "../../mixins/getExpiredDays";
import { extractAfterModule } from "../../mixins/extractAfter";
import { daiGuanModule } from "./mixins/daiGuan";
import { businessRuleModule } from "../../mixins/rule";
import { doubleRcvModule } from "../../mixins/doubleRcv";
import { getBusiness } from "@/views/kzyWMS/api/business"; // 系统参数接口
import { addItem, getItem, postAsnClear, getStockStatusOptions, IS_AGV, strategyExecute, expiredDays, deleteCodesByBill } from "./api";

import { createValidator } from "../../../utils/validator";
import { upcloud_base_common } from "@/config/serviceSettings";
import { aa } from "./mock";
import { reject } from "../../../bound/erpCheckOverflow/api";

export default {
  components: {
    "bill-editor": BillEditor,
    "info-model": InfoModel,
    "split-bill": SplitBill,
    "c-cditor": Editor,
    imgsUpload: ImgsUpload,
    "view-supplier": ViewSupplier,
    "view-commodity": ViewCommodity,
    hosting: hosting,
    "login-modal": LoginModal,
    exceptionModal: exceptionModal,
    scanCode,
  },

  mixins: [
    extendInfoModule,
    splitModule,
    historyModule,
    validateModule,
    itemsColChangeModule,
    showStockCountModual,
    getExpiredDaysModual,
    extractAfterModule,
    daiGuanModule,
    businessRuleModule,
    doubleRcvModule,
  ],
  //   showStockCountModual

  data() {
    return {
      superviseList:[],      // 监管码数据
      isScanCodeOk:false, // 是否扫描监管码全部完成
      scanVisible: false, // 监管码弹框
      scanTableList:[],   // 传入监管码弹框数据
      businessData: null,
      mainlist: null,
      sublist: null,
      modelConfig: modelConfig(this),
      detailtList: null,
      detailData: null,
      visible: false,
      items: footerItem,
      show: true,
      maintainVisible: false,
      detailItem: null,
      //   expiredDays: { intercept: 90, alert: 180 },
      expiredDays: {},
      isUpload: false,
      lookats: false,
      uploadItemIndex: null,
      showViewSupplier: false,
      viewSupplierItem: null,
      showCommodity: false,
      viewCommodity: null,
      historyConfig: historyConfig(this),
      exceptionConfig: exceptionConfig(this),
      showHistoryModal: false,
      showExceptionModal: false,
      splitColumns: splitColumns,
      splitFormItems: splitFormItems,
      uploadIdlist: [],
      hostData: null,
      showHost: false,
      hostList: [],
      selectedRows: [],
      showException: false,
      exceptionData: [],
      refException: {},
      mainException: {},
      stockStatusOptions: [],
      createValidator: createValidator([
        this.validateNotEmpty,
        this.validateStockStatusContainer,
        this.validateCaseOrPiece,
        this.validateStockStatus,
        this.validateExpiredDays,
        this.validateStoreTemperature,
        this.validateBatchExpiredDate,
        this.validateStockStatusTemperature,
        this.container,
      ]),
    };
  },

  created() {
    getBusiness().then((res) => {
      this.businessData = res; // 系统参数
      this.execute(detailConfig(this)).then((list) => {
        this.detailtList = list;
      });
    });
    this.getexpiredDays();
    // setTimeout(() => {
    //   this.setinfo(null,aa)
    // }, 3000);
  },
  mounted() {},
  methods: {
    deleteCodesByBill(par) {
      if(par.length==0) return
      deleteCodesByBill(par).then(res => {
        if (res.success) {
          self.$message.success('操作成功')
        } else {
          self.$message.error(res.message)
        }
      })
    },
    onDetail(data) {
      console.log(data,'data');
      this.superviseList = data
    },
    successScanCode(val) {
      this.isScanCodeOk = val;
    },
    async getexpiredDays() {
      let res = await expiredDays();
      console.log(res);
      res.data.forEach((i) => {
        this.expiredDays[i.dictCode] = +i.dictName;
      });
      console.log(this.expiredDays);
    },
    //查询库别接口
    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),
        categoryId: String(record.categoryId),
        dataSource: "0",
        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") {
            return value.split(",").includes(matchObj[fieldName]);
            // 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;
    },
    queryRefFromName(name) {
      return this.$refs.detail.$refs[name][0];
    },

    // setinfo(a, data) {
    //   if (data) {
    //     this.$refs.detail.resetData();
    //     this.mainlist = data.mainlist;
    //     this.sublist = data.sublist;
    //     let info = {
    //       main: {
    //         ...data.mainlist[0],
    //         rcvDate: moment().format("YYYY-MM-DD HH:mm:ss"),
    //         executorUser: this.$store.state.user.name,
    //       },
    //       extend: {
    //         ...data.mainlist[0],
    //       },
    //       operate: {},
    //       list: data.sublist.map((tt) => {
    //         // conversionRate可能存在没有的情况，英特是选择的不是上游下发的，不存在就用总数量
    //         let pieceQty =
    //           tt.conversionRate > 0 ? tt.conversionRate * (+tt.oddCaseQty || 0) + (+tt.oddPieceQty || 0) : tt.pieceQty;
    //         let batchProductionDate = tt.batchProductionDate ? tt.batchProductionDate.substring(0, 10) : "";
    //         let batchExpiredDate = tt.batchExpiredDate ? tt.batchExpiredDate.substring(0, 10) : "";
    //         let showProductionDate = batchProductionDate.replace(/-/g, "");
    //         let showExpiredDate = batchExpiredDate.replace(/-/g, "");
    //         return {
    //           ...tt,
    //           asnLineId: tt.asnLineId /* + '_cus_' + Math.floor(Math.random() * 1000) */, //暂存后 拆分可能重复
    //           tempAsnLineId: tt.asnLineId,
    //           stockStatus: tt.stockStatus ? tt.stockStatus : "0", // 默认收货
    //           mtlOwnerId: data.mainlist[0].mtlOwnerId,
    //           showProductionDate: showProductionDate,
    //           showExpiredDate: showExpiredDate,
    //           batchProductionDate: batchProductionDate,
    //           batchExpiredDate: batchExpiredDate,
    //           itemHealthIsDouble: tt.itemHealthIsDouble || "0",
    //           qty: (pieceQty / tt.conversionRate).toFixed(2),
    //           pieceQty: pieceQty,
    //           oldPieceQty: pieceQty,
    //           // 冷藏 2~8   冷冻 -10~-1
    //           tempControlScope: tt.tempControlScope
    //             ? tt.tempControlScope
    //             : tt.storeTemperature == "冷藏"
    //             ? "2~8"
    //             : tt.storeTemperature == "冷冻"
    //             ? "-100~-1"
    //             : null,
    //           rcvType: data.mainlist[0].rcvType,
    //         };
    //       }),
    //     };
    //     info.list.forEach((t) => {
    //       let expiredDate = new Date(t.batchExpiredDate);
    //       expiredDate.setHours(0);
    //       //有效期小于当前日期|| 有效期至为null，结论默认null
    //       if (expiredDate < new Date() || !t.batchExpiredDate) {
    //         t.stockStatus = "";
    //       } else {
    //         t.stockStatus = "0";
    //       }
    //     });
    //     //直调(7)与越库(6)需要库别默认赋值
    //     info.list.forEach((t) => {
    //       if (info.main.rcvType == "6") {
    //         t.whAreaCategory = "YKQ";
    //       } else if (info.main.rcvType == "7") {
    //         t.whAreaCategory = "ZDK";
    //       } else if (info.main.rcvType == "8" || info.main.rcvType == "9") {
    //         // 13.代管库 只能订单类型是代管的才可以入到代管库，即订单类型是代管的默认并且只能入代管库
    //         t.whAreaCategory = "DGK";
    //       }
    //     });

    //     //是否异常驳回单据
    //     if (info.main.errorResult) {
    //       if (info.main.errorResult === "0") {
    //         info.list.forEach((t) => {
    //           t.errorResult = "0";
    //         });
    //       } else {
    //         info.list.forEach((t) => {
    //           t.errorResult = "1";
    //         });
    //       }
    //     }
    //     //判断库别逻辑

    //     this.detailData = JSON.parse(JSON.stringify(info));

    //     this.showDaiGuan(info.main);
    //     this.getExpiredDays(data.mainlist[0].warehouseId);
    //     this.showStockCount(info.list[0].itemId);
    //     this.receiveSetValueAfter(info.list);
    //     var p1 = null;
    //     this.checkDG(p1);
    //   }
    // },
    // async setinfo(flag, data) {
    //   //    remoteUrl: { url: upcloud_base_common + "/dict/listbytype?dicttypeCodes=IS_AGV", method: "post" },

    //   let res = await IS_AGV();
    //   //   console.log(res);
    //   let isAgvType = res.data.map((i) => {
    //     return {
    //       dictName: i.dictName,
    //       dictCode: i.dictCode,
    //     };
    //   });
    //   console.log(isAgvType);
    //   if (!data) return;
    //   console.log("setinfo", data);
    //   this.$refs.detail.resetData();
    //   const { mainlist = [], sublist = [] } = data;
    //   const user = this.$store.state.user.name;
    //   // 主单数据
    //   this.mainlist = mainlist;
    //   const mainForm = {
    //     ...mainlist[0],
    //     rcvDate: moment().format("YYYY-MM-DD HH:mm:ss"),
    //     executorUser: user,
    //   };
    //   let { mtlOwnerId, rcvType, warehouseId, errorResult } = mainForm;
    //   // 入库结论策略
    //   this.getStockStatusOptions();

    //   //是否异常驳回单据
    //   errorResult = errorResult === "0" ? "0" : "1";

    //   // 次要信息
    //   const extend = { ...mainForm };
    //   // 明细数据
    //   this.sublist = sublist;
    //   const list = sublist.map((item) => {
    //     let {
    //       length,
    //       width,
    //       height,
    //       asnLineId,
    //       stockStatus,
    //       itemHealthIsDouble,
    //       conversionRate,
    //       oddCaseQty,
    //       oddPieceQty,
    //       pieceQty,
    //       batchProductionDate,
    //       batchExpiredDate,
    //       whAreaCategory,
    //     } = item;
    //     // conversionRate可能存在没有的情况，英特是选择的不是上游下发的，不存在就用总数量
    //     pieceQty = conversionRate > 0 ? conversionRate * (+oddCaseQty || 0) + (+oddPieceQty || 0) : pieceQty;
    //     batchProductionDate = batchProductionDate?.substring(0, 10) || "";
    //     batchExpiredDate = batchExpiredDate?.substring(0, 10) || "";
    //     let tempControlScope = item.tempControlScope;
    //     if (!tempControlScope) {
    //       const storeTemperature = item.storeTemperature;
    //       if (storeTemperature === "冷藏") {
    //         tempControlScope = "2~8";
    //       } else if (storeTemperature === "冷冻") {
    //         tempControlScope = "-100~-1";
    //       } else {
    //         tempControlScope = null;
    //       }
    //     }
    //     // 批号，当未带出且批号管理为true则可编辑 '1'-是 '0'-否
    //     const { itemIsBatch, expiryDateTrackLevel, manufacturerLotNum } = item;
    //     const manufacturerLotNumEdit = !!itemIsBatch && itemIsBatch === 1;
    //     // 效期
    //     // expiryDateTrackLevel 效期跟踪级别 '1'-生产日期 '2'-有效期至 '3'-两者
    //     const batchProductionDateEdit =
    //       !batchProductionDate &&
    //       !!expiryDateTrackLevel &&
    //       (expiryDateTrackLevel === "1" || expiryDateTrackLevel === "3");
    //     const batchExpiredDateEdit =
    //       !batchExpiredDate && !!expiryDateTrackLevel && (expiryDateTrackLevel === "2" || expiryDateTrackLevel === "3");

    //     // 收货结论
    //     let expiredDate = new Date(batchExpiredDate);
    //     expiredDate.setHours(0);
    //     //有效期小于当前日期|| 有效期至为null，结论默认null
    //     stockStatus = expiredDate < new Date() || !batchExpiredDate ? "" : "0";

    //     // 直调(7)与越库(6)需要库别默认赋值
    //     if (rcvType === "6") {
    //       whAreaCategory = "YKQ";
    //     } else if (rcvType === "7") {
    //       whAreaCategory = "ZDK";
    //     } else if (["8", "9"].includes(rcvType)) {
    //       // 13.代管库 只能订单类型是代管的才可以入到代管库，即订单类型是代管的默认并且只能入代管库
    //       whAreaCategory = "DGK";
    //     }
    //     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);
    //     return {
    //       isAgv,
    //       ...item,
    //       tempAsnLineId: asnLineId,
    //       // 收货结论
    //       stockStatus,
    //       rcvType,
    //       mtlOwnerId,
    //       batchProductionDate,
    //       batchExpiredDate,
    //       itemHealthIsDouble: itemHealthIsDouble || "0",
    //       qty: Number(conversionRate) === 0 ? 0 : (pieceQty / conversionRate).toFixed(2),
    //       pieceQty: pieceQty,
    //       oldPieceQty: pieceQty,
    //       // 冷藏 2~8   冷冻 -10~-1
    //       tempControlScope,
    //       // 是否异常驳回单据
    //       errorResult,
    //       // 批号、效期跟踪
    //       manufacturerLotNumEdit,
    //       batchProductionDateEdit,
    //       batchExpiredDateEdit,
    //       // 库别
    //       whAreaCategory,
    //     };
    //   });
    //   const info = {
    //     main: mainForm,
    //     extend,
    //     operate: {},
    //     list,
    //   };
    //   this.detailData = JSON.parse(JSON.stringify(info));

    //   // this.showDaiGuan(mainForm)
    //   // this.getExpiredDays(warehouseId)
    //   // this.receiveSetValueAfter(list)

    //   // this.checkDG(null)
    // },

    async setinfo(flag, data) {
      //    remoteUrl: { url: upcloud_base_common + "/dict/listbytype?dicttypeCodes=IS_AGV", method: "post" },

      let res = await IS_AGV();
      //   console.log(res);
      let isAgvType = res.data.map((i) => {
        return {
          dictName: i.dictName,
          dictCode: i.dictCode,
        };
      });
      console.log(isAgvType);
      if (!data) return;
      console.log("setinfo", data);
      this.$refs.detail.resetData();
      const { mainlist = [], sublist = [] } = data;
      let info1 = {
        main: {
          ...data.mainlist[0],
          rcvDate: moment().format("YYYY-MM-DD HH:mm:ss"),
          executorUser: this.$store.state.user.name,
        },
        extend: {
          ...data.mainlist[0],
        },
        operate: {},
        list: data.sublist.map((tt) => {
          // conversionRate可能存在没有的情况，英特是选择的不是上游下发的，不存在就用总数量
          let pieceQty =
            tt.conversionRate > 0 ? tt.conversionRate * (+tt.oddCaseQty || 0) + (+tt.oddPieceQty || 0) : tt.pieceQty;
          let batchProductionDate = tt.batchProductionDate ? tt.batchProductionDate.substring(0, 10) : "";
          let batchExpiredDate = tt.batchExpiredDate ? tt.batchExpiredDate.substring(0, 10) : "";
          let showProductionDate = batchProductionDate.replace(/-/g, "");
          let showExpiredDate = batchExpiredDate.replace(/-/g, "");
          return {
            ...tt,
            asnLineId: tt.asnLineId /* + '_cus_' + Math.floor(Math.random() * 1000) */, //暂存后 拆分可能重复
            tempAsnLineId: tt.asnLineId,
            stockStatus: tt.stockStatus ? tt.stockStatus : "0", // 默认收货
            mtlOwnerId: data.mainlist[0].mtlOwnerId,
            showProductionDate: showProductionDate,
            showExpiredDate: showExpiredDate,
            batchProductionDate: batchProductionDate,
            batchExpiredDate: batchExpiredDate,
            itemHealthIsDouble: tt.itemHealthIsDouble || "0",
            qty: (pieceQty / tt.conversionRate).toFixed(2),
            pieceQty: pieceQty,
            oldPieceQty: pieceQty,
            // 冷藏 2~8   冷冻 -10~-1
            tempControlScope: tt.tempControlScope
              ? tt.tempControlScope
              : tt.storeTemperature == "冷藏"
              ? "2~8"
              : tt.storeTemperature == "冷冻"
              ? "-100~-1"
              : null,
            rcvType: data.mainlist[0].rcvType,
          };
        }),
      };

      // this.receiveSetValueAfter(info1.list);
      const user = this.$store.state.user.name;
      // 主单数据
      this.mainlist = mainlist;
      const mainForm = {
        ...mainlist[0],
        rcvDate: moment().format("YYYY-MM-DD HH:mm:ss"),
        executorUser: user,
      };
      let { mtlOwnerId, rcvType, warehouseId, errorResult } = mainForm;
      // 入库结论策略
      this.getStockStatusOptions();

      //是否异常驳回单据
      errorResult = errorResult === "0" ? "0" : "1";

      // 次要信息
      const extend = { ...mainForm };
      // 明细数据
      this.sublist = sublist;
      const list = sublist.map((item) => {
        let {
          length,
          width,
          height,
          asnLineId,
          stockStatus,
          itemHealthIsDouble,
          conversionRate,
          oddCaseQty,
          oddPieceQty,
          pieceQty,
          batchProductionDate,
          batchExpiredDate,
          whAreaCategory,
        } = item;
        // conversionRate可能存在没有的情况，英特是选择的不是上游下发的，不存在就用总数量
        pieceQty = conversionRate > 0 ? conversionRate * (+oddCaseQty || 0) + (+oddPieceQty || 0) : pieceQty;
        batchProductionDate = batchProductionDate?.substring(0, 10) || "";
        batchExpiredDate = batchExpiredDate?.substring(0, 10) || "";
        let tempControlScope = item.tempControlScope;
        if (!tempControlScope) {
          const storeTemperature = item.storeTemperature;
          if (storeTemperature === "冷藏") {
            tempControlScope = "2~8";
          } else if (storeTemperature === "冷冻") {
            tempControlScope = "-100~-1";
          } else {
            tempControlScope = null;
          }
        }
        // 批号，当未带出且批号管理为true则可编辑 '1'-是 '0'-否
        const { itemIsBatch, expiryDateTrackLevel, manufacturerLotNum } = item;
        const manufacturerLotNumEdit = !!itemIsBatch && itemIsBatch === 1;
        // 效期
        // expiryDateTrackLevel 效期跟踪级别 '1'-生产日期 '2'-有效期至 '3'-两者
        const batchProductionDateEdit =
          !batchProductionDate &&
          !!expiryDateTrackLevel &&
          (expiryDateTrackLevel === "1" || expiryDateTrackLevel === "3");
        const batchExpiredDateEdit =
          !batchExpiredDate && !!expiryDateTrackLevel && (expiryDateTrackLevel === "2" || expiryDateTrackLevel === "3");

        // 收货结论
        let expiredDate = new Date(batchExpiredDate);
        expiredDate.setHours(0);
        //有效期小于当前日期|| 有效期至为null，结论默认null
        stockStatus = expiredDate < new Date() || !batchExpiredDate ? "" : "0";

        // 直调(7)与越库(6)需要库别默认赋值
        if (rcvType === "6") {
          whAreaCategory = "YKQ";
        } else if (rcvType === "7") {
          whAreaCategory = "ZDK";
        } else if (["8", "9"].includes(rcvType)) {
          // 13.代管库 只能订单类型是代管的才可以入到代管库，即订单类型是代管的默认并且只能入代管库
          whAreaCategory = "DGK";
        }
        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);
        return {
          isAgv,
          ...item,
          tempAsnLineId: asnLineId,
          // 收货结论
          stockStatus,
          rcvType,
          mtlOwnerId,
          batchProductionDate,
          batchExpiredDate,
          itemHealthIsDouble: itemHealthIsDouble || "0",
          qty: Number(conversionRate) === 0 ? 0 : (pieceQty / conversionRate).toFixed(2),
          pieceQty: pieceQty,
          oldPieceQty: pieceQty,
          // 冷藏 2~8   冷冻 -10~-1
          tempControlScope,
          // 是否异常驳回单据
          errorResult,
          // 批号、效期跟踪
          manufacturerLotNumEdit,
          batchProductionDateEdit,
          batchExpiredDateEdit,
          // 库别
          whAreaCategory,
        };
      });
      const info = {
        main: mainForm,
        extend,
        operate: {},
        list,
      };
      this.detailData = JSON.parse(JSON.stringify(info));

      // this.showDaiGuan(mainForm)
      // this.getExpiredDays(warehouseId)
      // this.receiveSetValueAfter(list)

      // this.checkDG(null)
    },
    // 获取入库结论字典-策略
    getStockStatusOptions() {
      const mainForm = this.mainlist[0] || {};
      const { rcvType } = mainForm;
      // if (!rcvType) return
      const params = {
        enterpriseId: this.$store.state.user.info.enterpriseId,
        category: "RcvStatusChoose",
        dataSource: "0",
      };
      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("0"));
        if (!curFactors) {
          console.error("入库结论匹配失败");
          return;
        }
        const curRuleId = curFactors.ruleId;
        const curRule = res.data.rules.find((_) => _.id === curRuleId);
        const dictionary = {
          0: "收货",
          3: "拒收",
        };
        // 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);
      });
    },

    submitData() {
      this.getDetailData().then((params) => {
        var aa = 0;
        if (!params) {
          return;
        }
        //判断单据是否代管
        params.rcvLinesDTOList.forEach((t) => {
          if (params.rcvHeadersDTO.inventoryOpType == "1") {
            t.inventoryOpType = 0;
            if (t.locatorCode == null || t.locatorCode == "") {
              this.$message.warning(" 代管转正常单 商品代管库位为必填项，请检查");
              aa = 1;
            }
          }
        });
        if (aa == 1) {
          return;
        }
        if (!params) {
          return;
        }
        let toSave = () => {
          this.$confirm({
            content: this.$lang("是否确定保存?"),
            onOk: () => {
              return this.handleAdd(params);
            },
          });
        };

        this.validateShipFromDate(params, () => {
          // 双人收货
          this.handleDoubleRcv(params, () => {
            this.validateManufacturerLotNum(params, toSave);
          });
        });
      });
    },

    getDetailData(isValidate = true, isSelected = true) {
      return this.$refs.detail.getDetailData(isValidate, isSelected).then((vals) => {
        console.log(vals);
        return this.createValidator.execute(vals, { notValid: !isValidate }).then((res) => {
          if (res)
            return {
              rcvHeadersDTO: {
                ...vals.main,
                caseQty: "1",
                pieceQty: "1",
                autoBillNum: +new Date() + "",
                shipArriveTime: moment(vals.main.shipArriveTime).format("YYYY-MM-DD HH:mm:ss"),
                rcvDate: moment(vals.main.rcvDate).format("YYYY-MM-DD HH:mm:ss"),
              },
              rcvHeadersProfilesDTO: { ...this.mainlist[0], ...vals.extend },
              rcvHeadersSrcBillsDTOList: [
                {
                  ...this.mainlist[0],
                  srcHeaderType: vals.main.srcBillType,
                  srcAutoBillNum: vals.main.srcAutoBillNum,
                  rcvDate: vals.main.rcvDate,
                },
              ],
              rcvLinesDTOList: vals.list.map((tt, ii) => {
                let list = this.superviseList.filter(item => item.refBillLineId == tt.asnLineId)

                // 拆单
                let asnLineId = tt.asnLineId.replace(/_cus_\d*/g, "");
                let rcvLinesProfilesDTO = this.sublist.find((ttt) => ttt.asnLineId == asnLineId);
                rcvLinesProfilesDTO.lineNum = ii + 1;
                var _batchId = null;
                var _batchNum = null;
                if (vals.main.inventoryOpType === "1") {
                  _batchId = tt.batchId;
                  _batchNum = tt.batchNum;
                } else {
                  if (tt.manufacturerLotNum == tt.manufacturerLotNumOld) {
                    _batchId = tt.batchId;
                    _batchNum = tt.batchNum;
                  }
                }
                return {
                  ...tt,
                  superviseCodesModal:list,
                  asnLineId: asnLineId,
                  lineNum: ii + 1,
                  mtlOwnerName: vals.main.mtlOwnerName,
                  warehouseName: vals.main.warehouseName,
                  srcBillType: vals.main.srcBillType,
                  rcvLinesProfilesDTO: rcvLinesProfilesDTO,
                  rcvType: this.mainlist[0].rcvType,
                  // showProductionDate: tt.showProductionDate,
                  // showExpiredDate: tt.showExpiredDate,
                  batchProductionDate: tt.batchProductionDate ? tt.batchProductionDate + " 00:00:00" : "",
                  batchExpiredDate: tt.batchExpiredDate ? tt.batchExpiredDate + " 00:00:00" : "",
                  rcvLinesPicDTOList: tt.rcvLinesPicDTOList
                    ? tt.rcvLinesPicDTOList.split(",").map((t) => ({ picFileurl: t }))
                    : null,

                  batchId: _batchId,
                  batchNum: _batchNum,
                  // batchNum:  vals.maininventoryOpType ==='0' && tt.manufacturerLotNum == tt.manufacturerLotNumOld ? tt.batchNum : null,
                  // batchId: tt.manufacturerLotNum == tt.manufacturerLotNumOld ? tt.batchId : null,
                };
              }),
            };
          return res;
        });
      });
    },

    validateNotEmpty(params) {
      console.log(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);
      });
    },

    validateSubmit(params) {
      if (!params) {
        this.$message.warning("请输入必填项2");
        return false;
      }
      if (!Array.isArray(params.list) || params.list.length === 0) {
        this.$message.warning("请选择要提交的明细");
        return false;
      }
      setTimeout(() => {
        let ref = this.queryRefFromName("main");
        let item = ref.$refs.list.items;
        var val = 0;
        item.forEach((t) => {
          if (t.name === "inventoryOpType") {
            val = t.value;
          }
        });
      }, 2000);
      //特殊单据收货类型必须为收货
      let rcvType = this.mainlist[0].rcvType;

      return true;
    },

    handleAdd(params) {
      return addItem(params).then((res) => {
        if (!res.success) {
          this.$exception(res);
          return;
        }
        this.items.forEach((tt, i) => {
          tt.value = null;
        });
        this.$message.success(this.$lang("新增成功"));
        this.handleReset();
        this.items.forEach((tt) => {
          tt.value = "";
        });
      });
    },

    handleReset() {
      let data = this.queryRefFromName("list");
      data.resetFields();
      this.detailData = null;
      this.splitOriginItem = null;
      this.detailItem = null;
      // this.rcvItemLotNumList.clear();
      this.viewSupplierItem = null;
      this.viewCommodity = null;
      this.mainlist = null;
      this.sublist = null;
    },

    /* 商品维护 */
    handleOk(e) {
      this.$refs.itemsEditor.getDetailData();
    },
    handleCancel(e) {
      this.maintainVisible = false;
    },
    handleItemsComplete() {
      this.maintainVisible = false;
    },
    showMaintain() {
      let ref = this.queryRefFromName("list");
      ref.getDataSource(true, false).then((list) => {
        if (!Array.isArray(list) || list.length == 0) {
          this.$message.warning("请勾选需要维护的商品项");
          return;
        }
        this.detailItem = { itemId: list[0].itemId };
        this.maintainVisible = true;
      });
    },

    // 上传逻辑
    showUploadImgs(record, index, dataSource) {
      if (record.rcvLinesPicDTOList) {
        this.uploadIdlist = record.rcvLinesPicDTOList.split(",");
      }
      this.uploadItemIndex = { record, index, dataSource };
      this.isUpload = true;
    },
    handleUploadImgs(list) {
      // 拆分后的同一类明细，上传图片数据要一致
      let rcvLinesPicDTOList = list.map((t) => t.id).join(",");
      let asnLineId = this.uploadItemIndex.record.asnLineId;
      asnLineId = asnLineId.replace(/_cus_\d*/g, "");
      this.uploadItemIndex.dataSource.forEach((tt) => {
        if (tt.asnLineId.indexOf(asnLineId) >= 0) {
          tt.rcvLinesPicDTOList = rcvLinesPicDTOList;
        }
      });
    },

    // 清理过期
    handleAsnClear(items) {
      this.$confirm({
        content: this.$lang("是否确定清理此过期订单?"),
        onOk: () => {
          let ids = items.map((tt) => tt.asnHeaderId);
          return postAsnClear(ids).then((res) => {
            if (!res.success) {
              this.$exception(res);
              return;
            }
            this.$refs.detailModel.reloadMain();
            this.$message.success("清理过期订单成功");
          });
        },
      });
    },
    // 异常处理
    exceptionModal() {
      if (this.selectedRows.length < 1) {
        this.$message.warning("请勾选需要处理的商品明细");
        return;
      }
      let ref = this.queryRefFromName("list");
      this.showException = true;
      this.exceptionData = this.selectedRows;
      this.refException = ref;
      this.mainException = this.detailData.main;
    },
  },
};
</script>

<style lang="less" scoped>
.footer {
  margin-top: 50px;
  bottom: 0px;
}
.footer_bat {
  background-color: #feffe0; // #f0f8ff;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
  padding: 20px;
}
.footer_bat-item {
  display: inline-block;
  width: 25%;
  min-width: 180px;
  font-size: 14px;
  // color: #2b80ff;
  font-weight: bold;
  .numClass {
    font-size: 20px;
    color: #2b80ff;
    padding-left: 8px;
  }
}
</style>
