<template>
  <div class="app-container">
    <!-- 操作 -->
    <el-row :gutter="10">
      <el-col :span="6">
        <el-button
          type="primary"
          size="mini"
          plain
          icon="el-icon-check"
          :loading="sureLoading"
          @click="submitForm"
          >提交</el-button
        >
      </el-col>
    </el-row>

    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="form"
      :model="form"
      size="small"
      label-width="98px"
      :rules="rules"
    >
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="收料类别" prop="receiptType">
            <DictSelect
              v-model="form.receiptType"
              placeholder="请选择物料类别"
              dict-type="WMS_MATERIAL_RECEIVING_CATEGORY"
              :disabled="!!materialLots"
              @change="receiptTypeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="otherShow" label="供应商" prop="supplierCode">
            <SupplierListSelect
              ref="supplierListSelect"
              v-model="form.supplierCode"
              clearable
              filterable
              :disabled="form.receiptType == '1' || form.receiptType == '3'"
              @change="supplierChange"
            />
          </el-form-item>
          <el-form-item v-else label="客户" prop="customerCode">
            <CustomerSelect
              ref="customerSelect"
              v-model="form.customerCode"
              clearable
              filterable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="源单编号" prop="purchaseOrderNo">
            <OrderSelect
              ref="purchaseOrder"
              v-model="form.purchaseOrderNo"
              clearable
              :disabled="
                form.receiptType === '4' ||
                form.receiptType === '2' ||
                !!materialLots
              "
              placeholder="请选择源单编号"
              :options="orderOptions"
              @change="OrderNoChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="物料编码" prop="materialNo">
            <MaterialSelect
              ref="materialOrder"
              v-model="form.wmsPurchaseOrderDetailId"
              clearable
              :disabled="materialDisabled || !!materialLots"
              @change="materialNoChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="物料名称" prop="materialName">
            <el-input
              v-model="form.materialName"
              disabled
              placeholder="请输入物料名称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="是否需要检验" prop="checkIncoming" disabled>
            <DictSelect
              v-model="form.checkIncoming"
              disabled
              placeholder="请选择是否免检"
              dict-type="WMS_JUDGE_CHECKING"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单位" prop="unitCode">
            <UnitCodeSelect
              v-model="form.unitCode"
              placeholder="请选择单位"
              filterable
              disabled
              @change="unitChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="到货总数" prop="receiptQty">
            <el-input
              v-model="form.receiptQty"
              placeholder="请输入到货总数"
              oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="送货批次" prop="deliverBatch">
            <el-input
              v-model="form.deliverBatch"
              placeholder="请输入送货批次"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产日期" prop="produceDate">
            <el-date-picker
              v-model="form.produceDate"
              type="date"
              value-format="timestamp"
              placeholder="请选择生产日期"
              clearable
              @change="produceDateChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="有效期至" prop="validTill">
            <el-input
              v-model="form.validTill"
              placeholder="请输入有效期至"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <!-- form.receiptType === '4' 收料类别为其他收料时显示 -->
        <el-col :span="8">
          <el-form-item
            v-if="form.receiptType === '4'"
            label="入库类型"
            prop="inType"
          >
            <DictSelect
              v-model="form.inType"
              placeholder="请选择入库类型"
              dict-type="OTHER_IN_STOCK_TYPE"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            v-if="form.receiptType === '4'"
            label="部门"
            prop="departmentNo"
          >
            <DepartMentSelect
              ref="departMentSelect"
              v-model="form.departmentNo"
              placeholder="请选择部门"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="存储条件" prop="storageEnvironment">
            <el-input
              v-model="form.storageEnvironment"
              disabled
              placeholder="请输入存储条件"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格" prop="size">
            <el-input v-model="form.size" placeholder="请输入规格" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建人" prop="creator">
            <el-input v-model="form.creator" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="修改人" prop="updater">
            <el-input v-model="form.updater" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料批次" prop="materialLots">
            <el-input v-model="form.materialLots" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button
            type="primary"
            plain
            style="width: 60%"
            icon="el-icon-upload2"
            @click="handleUpload"
            >附件上传</el-button
          >
        </el-col>
        <el-col :span="form.receiptType === '4' ? 8 : 16">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-tabs type="border-card">
      <el-tab-pane label="物料列表">
        <!-- 操作工具栏 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
        </el-row>
        <!-- 列表 -->
        <el-table
          ref="table"
          v-loading="loading"
          :data="list"
          max-height="450px"
          border
          size="mini"
        >
          <el-table-column label="到货包数" align="center" prop="bagQty">
            <template slot-scope="scope">
              <el-input
                v-model.trim="scope.row.bagQty"
                oninput="value=value.replace(/^\D*(\d*(?:.\d)?).*$/g, '$1')"
                placeholder="请输入到货包数"
                @change="handleBagQtyChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="每包长度(m)" align="center" prop="length">
            <template slot-scope="scope">
              <el-input
                v-model.trim="scope.row.length"
                oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                placeholder="请输入物料长度"
                @change="lengthChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="每包宽度(mm)" align="center" prop="width">
            <template slot-scope="scope">
              <el-input
                v-model.trim="scope.row.width"
                oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                placeholder="请输入物料宽度"
                @change="widthChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="每包厚度(mm)" align="center" prop="thickness">
            <template slot-scope="scope">
              <el-input
                v-model.trim="scope.row.thickness"
                oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                placeholder="请输入物料厚度"
              />
            </template>
          </el-table-column>
          <el-table-column label="每包数量" align="center" prop="qty">
            <template slot-scope="scope">
              <el-input
                v-model.trim="scope.row.qty"
                oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                placeholder="请输入数量"
                @change="handleQtyChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="120"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                class="text-danger"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="补打列表">
        <!-- 查看 -->
        <LabelRepair ref="labelRepair" />
      </el-tab-pane>
    </el-tabs>
    <!-- 附件上传 -->
    <AttachmentUpload ref="attachmentUpload" @files="getFileList" />
    <PrintTemplate ref="packingLabelPrinitTemplate" :print-data="printData" />
    <!-- 东苏发单据打印 -->
    <IssuePrinit ref="issuePrint" />
  </div>
</template>

<script>
import {
  createIncomingReceipt,
  getLabelPrintData,
  validateIsQuality,
  // getRegisterMaterialLabelPrintData,
  getFilesById,
  getMaterialInfo,
} from "@/api/wms/incoming/register";
import OrderSelect from "./components/OrderSelect.vue";
import MaterialSelect from "./components/MaterialSelect.vue";
import PrintTemplate from "./components/PrintTemplate.vue";
import { printLabel } from "@/api/common";
// 物料下拉
// import { getMaterialDropDownList } from "@/api/wms/base/material";
// 客户下拉选择
import CustomerSelect from "./components/CustomerSelect.vue";
// 东苏发单据打印
import IssuePrinit from "../../output/productionIssue/issueDetails/IssuePrinit.vue";
const AccessTokenKey = "ACCESS_TOKEN";
// 供应商下拉列表
import SupplierListSelect from "./components/SupplierListSelect.vue";
import { getDropDownList, getDropDownList2 } from "@/api/wms/orders/purchase";
// 部门
import DepartMentSelect from "./components/DepartMentSelect.vue";
import AttachmentUpload from "./components/AttachmentUpload.vue";
// 单位
import UnitCodeSelect from "./components/UnitCodeSelect.vue";
import { getAppendixTableData } from "@/api/system/appendix.js";
import LabelRepair from "@/views/wms/incoming/register/components/LabelRepair.vue";

export default {
  name: "MaterialRegistration",
  components: {
    OrderSelect,
    MaterialSelect,
    PrintTemplate,
    CustomerSelect,
    IssuePrinit,
    SupplierListSelect,
    DepartMentSelect,
    AttachmentUpload,
    UnitCodeSelect,
    LabelRepair,
  },
  data() {
    return {
      // 物料批次
      materialLots: null,
      // 供应商置灰状态
      supplierDisabled: false,
      // 生产日期
      produceDate: "",
      printData: [],
      // 遮罩层
      loading: false,
      sureLoading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 其他入库
      otherShow: true,
      // 物料过期遮罩
      dialogVisible: false,
      // 总条数
      total: 0,
      // WMS 入库业务-来料登记主列表
      list: [],
      // 弹出层标题
      title: "",
      currentData: [],
      // 是否显示弹出层
      open: false,
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        // pageNo: 1,
        // pageSize: 10,
        areaTest: null,
        materialLots: null,
        purchaseOrderNo: null,
        materialNo: null,
        receiptQty: null,
        testStatus: null,
        createTime: [],
        materialName: null,
      },
      // 显示客户
      receiptShow: true,
      // 物料编码
      materialDisabled: false,
      // 物料编码列表
      materialList: [],
      // 采购单列表
      orderOptions: [],
      // 上传的文件
      uploadFiles: [],
      //  过保质期提示
      warningText: null,
      // 单据打印参数
      tokens: "",
      baseUrl: "",
      reportId: "",
      // 登记的参数
      registerParams: {
        areaTest: null,
        materialLots: null,
        purchaseOrderNo: null,
        materialNo: null,
        receiptQty: null,
        testStatus: null,
      },
      // 表单参数
      form: {
        printer: "",
        BtReportId: "",
        BtReportUrl: "",
        BtReportName: "",
        HicoreReportName: "",
        reportType: "0",
        deliverBatch: null,
        materialNo: null,
        produceDate: null,
        purchaseOrderNo: null,
        pieceQty: null,
        unitCode: null,
        receiptType: null,
        validTill: null,
        receiptQty: null,
        size: null,
        remark: null,
      },
      nextIndex: 0,
      nextPrintState: false,
      // bartender模板列表
      btTemplateList: [],
      registerForm: {},
      printers: [],
      // 表单校验
      rules: {
        purchaseOrderNo: [
          {
            required: true,
            message: "请输入关键字选择采购订单",
            trigger: "change",
          },
        ],
        materialNo: [
          {
            required: true,
            message: "请输入关键字选择物料编码",
            trigger: "change",
          },
        ],
        bagQty: [
          { required: true, message: "到货包数不能为空", trigger: "change" },
        ],
        receiptQty: [
          { required: true, message: "到货包数不能为空", trigger: "blur" },
        ],
        mantissaQty: [
          { required: true, message: "到货尾数不能为空", trigger: "change" },
        ],
        pieceQty: [
          { required: true, message: "到货件数不能为空", trigger: "change" },
        ],
        deliverBatch: [
          { required: true, message: "送货批次不能为空", trigger: "change" },
        ],
        customerCode: [
          { required: true, message: "请选择客户", trigger: "change" },
        ],
        receiptType: [
          { required: true, message: "请选择物料类别", trigger: "change" },
        ],
        produceDate: [
          { required: true, message: "生产日期不能为空", trigger: "change" },
        ],
        supplierCode: [
          { required: false, message: "供应商不能为空", trigger: "change" },
        ],

        departmentNo: [
          {
            required: true,
            message: "部门不能为空",
            trigger: "change",
          },
        ],
        inType: [
          {
            required: true,
            message: "入库类型不能为空",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.reportId = this.$route.meta.reportId;
    this.baseUrl = process.env.VUE_APP_REPORT_API;
    this.getTemplateList();

    const { materialLots } = this.$route.query;
    if (materialLots) {
      this.materialLots = materialLots;
      // 物料列表
      this.handleGetMaterialInfo({ materialLots });
    }
  },
  methods: {
    // 获取来料登记详情
    handleGetMaterialInfo({ materialLots }) {
      getMaterialInfo({ materialLots }).then(async ({ code, data, msg }) => {
        this.form = {
          ...this.form,
          ...data,
          validTill: data.validTill
            ? new Date(data.validTill).toLocaleString().replace(/\//g, "-")
            : "",
        };
        if (data.receiptType == 2) {
          this.otherShow = false;
        }
        if (data.receiptType !== 1) {
          // 设置源单编号为非必填项
          this.$refs.form.rules.purchaseOrderNo[0].required = false;
        }
        // 补打列表
        this.$nextTick(() => {
          this.$refs.labelRepair.queryParams.materialLots = materialLots;
          this.$refs.labelRepair.loading = false;
          this.$refs.labelRepair.list = data.qrCodes;
        });
        // 物料列表
        this.list = data.materials;
        // 附件列表
        this.uploadFiles = data.filesListVos;
        await this.supplierChange({ code: this.form.supplierCode });
        await this.fetchOrderNoList(this.form.supplierCode);
        await this.OrderNoChange({
          erpOrderNo: this.form.purchaseOrderNo,
          id: this.orderOptions.find(
            (ret) => ret.erpOrderNo === this.form.purchaseOrderNo
          ),
        });
        await this.materialNoChange({ ...this.form });
      });
    },
    // 模板选择
    reportChange(e) {
      const fdIndex = this.btTemplateList.findIndex((ret) => ret.id === e);
      this.form.HicoreReportName = this.btTemplateList[fdIndex].sysName;
      this.form.BtReportName = this.btTemplateList[fdIndex].originName;
      this.form.BtReportUrl = this.btTemplateList[fdIndex].url;
    },
    // 获取BT打印模板
    getTemplateList() {
      getAppendixTableData({
        pageNum: 1,
        pageSize: 999,
        printFlag: "1",
        filesMenuId: "1000000000000000001",
      }).then(({ data }) => {
        this.btTemplateList = data?.list ?? [];
      });
    },
    handleAdd() {
      this.list.push({
        qty: "",
        length: "",
        width: "",
        thickness: "",
        id: this.list.length,
      });
      // 新增行后重新计算到货总数
      this.calculateTotalReceiptQty();
    },
    // 计算到货总数（所有行的 到货包数 x 每包数量 总和）
    calculateTotalReceiptQty() {
      if (this.list.length === 0) {
        this.form.receiptQty = null;
        return;
      }
      const total = this.list.reduce((sum, item) => {
        const bagQty = parseFloat(item.bagQty) || 0;
        const qty = parseFloat(item.qty) || 0;
        return this.getHandleNumber(sum + bagQty * qty);
      }, 0);
      this.form.receiptQty = total || null;
    },
    /** 删除按钮操作 */
    /** 删除按钮操作 */
    handleDelete(row, $index) {
      const { id } = row;
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
      // 删除行后重新计算到货总数
      this.calculateTotalReceiptQty();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        areaTest: undefined,
        materialLots: undefined,
        purchaseOrderNo: undefined,
        materialNo: undefined,
        receiptQty: undefined,
        testStatus: undefined,
        produceDate: undefined,
        width: undefined,
        length: undefined,
        thickness: undefined,
        pieceQty: undefined,
      };
      this.resetForm("form");
    },
    // 小数点问题处理
    getHandleNumber(val) {
      return Math.round(parseFloat(val) * 100000000) / 100000000;
    },
    // 根据每批尾数计算到货数量
    mantissaQtyChange(v) {
      const { bagQty, pieceQty } = this.form;
      if (v * 1 > pieceQty * 1) {
        this.$modal.msgWarning("到货尾数不能大于到货件数~");
        this.form.receiptQty = "";
        return;
      }
      if (bagQty === undefined || pieceQty === undefined) {
        this.$modal.msgWarning("请先输入到货包数或每包件数!");
        return;
      }
      this.form.receiptQty = this.getHandleNumber(
        bagQty * pieceQty + parseFloat(v)
      );
    },
    // 根据到货包数计算到货数量
    mantissaQtyChangeOfPack(v) {
      const { mantissaQty, pieceQty } = this.form;
      if (mantissaQty === undefined || pieceQty === undefined) {
        this.form.receiptQty = "";
        return;
      }
      this.form.receiptQty = this.getHandleNumber(
        v * pieceQty + parseFloat(mantissaQty)
      );
    },
    // 根据每包数量计算到货数量
    mantissaQtyChangeOfPice(v) {
      const { mantissaQty, bagQty } = this.form;
      if (mantissaQty === undefined || bagQty === undefined) {
        this.form.receiptQty = "";
        return;
      }
      this.form.receiptQty = this.getHandleNumber(
        v * bagQty + parseFloat(mantissaQty)
      );
    },
    reLoading(timeout) {
      const loading = this.$loading({
        lock: true,
        text: "标签打印中，请勿重复操作",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
      }, timeout * 1000);
    },
    /** 提交按钮 */
    async submitForm() {
      // if (!this.form.id) {
      //   if (!this.form.BtReportUrl || !this.form.BtReportName) {
      //     this.$message.warning("请选择打印模板");
      //     return;
      //   }
      // }
      try {
        await this.$refs.form.validate();
        this.sureLoading = true;

        // 取出上传的文件id
        const files = this.uploadFiles
          .map((item) => {
            return item.id || item.name?.fileId;
          })
          .filter((id) => id && id !== "");

        const isAll = this.list.some(
          (item) => item.qty && item.length && item.width
        );
        if (this.form.unitName === "平方米" && this.list.length === 0) {
          this.$modal.msgWarning("请填写物料的长度、宽度、数量等信息!");
          return;
        }
        if (this.form.unitName === "平方米" && !isAll && this.list.length > 0) {
          this.$modal.msgWarning("长度/宽度/数量不能为空!");
          return;
        }
        this.form.files = files;
        this.form.unitCode = undefined;
        const subitParams = {
          ...this.form,
          materials: this.list || [],
        };
        if (this.form.checkIncoming === 0) {
          this.$modal.confirm("此物料为免检物料，可直接入库").then(() => {
            this.commonSubmit(subitParams);
          });
        } else {
          this.commonSubmit(subitParams);
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.sureLoading = false;
      }
    },

    // 打印
    async commonSubmit(subitParams) {
      const result = await createIncomingReceipt(subitParams);
      const { data: materialLots } = result;

      if (
        (process.env.VUE_APP_TITLE === "麦禾田WMS管理系统" ||
          process.env.VUE_APP_TITLE === "WMS开发环境") &&
        !this.form.id &&
        false
      ) {
        this.$modal.msgSuccess("登记成功，正在打印");
        const params = {
          materialLots,
        };

        const printDetailData = await getLabelPrintData(params); // 获取打印数据
        const { data: productsDetails } = printDetailData;
        this.printData.push(...productsDetails);
        // 打印参数
        const printParams = {
          printJson: JSON.stringify(this.printData),
          fileUrl: this.form.BtReportUrl,
        };
        try {
          const data = await printLabel(printParams); // 打印
          console.log(data, "???");
        } catch (error) {
          console.log(error);
        } finally {
          this.printData = [];
          this.$router.replace({
            path:
              "/entry-exit/purchase-out-in/material-regist-enter?materialLots?materialLots=" +
              materialLots,
          });
        }
      } else {
        if (this.form.id) {
          this.$modal.msgSuccess("修改成功");
        } else {
          this.$modal.msgSuccess("登记成功");
          this.$router.replace({
            path:
              "/entry-exit/purchase-out-in/material-regist-enter?materialLots?materialLots=" +
              materialLots,
          });
          console.log(this.reportId);
          const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&materialLots=${materialLots}`;
          this.$refs.issuePrint.dialogVisible = true;
          this.$refs.issuePrint.src = src;
        }
      }
    },
    // 根据到货包数 到货包数*每包数量计算到货总数
    handleBagQtyChange(row) {
      const { bagQty, qty } = row;
      // 当前行计算每包数量（如果是平方米单位）
      if (this.form.unitName === "平方米" && row.length && row.width) {
        row.qty = this.getHandleNumber((row.width / 1000) * row.length);
      }
      // 重新计算所有行的到货总数
      this.calculateTotalReceiptQty();
    },
    // 根据每包数量 每包数量 * 到货包数
    handleQtyChange(row) {
      // 重新计算所有行的到货总数
      this.calculateTotalReceiptQty();
    },
    // 原单单号change事件
    OrderNoChange(item) {
      if (item) {
        const { erpOrderNo, id, supplierCode } = item;
        this.form.purchaseOrderNo = erpOrderNo;
        if (supplierCode) {
          this.form.supplierCode = supplierCode;
        }
        if (this.form.receiptType == "3") {
          this.$refs.materialOrder.outSourceId = id;
        } else {
          this.$refs.materialOrder.inStockId = id;
        }
        // this.fetchMaterialNoList(id);
        this.materialDisabled = false;
      }
    },
    // 物料编码change事件
    materialNoChange(item) {
      if (item) {
        const {
          materialNo,
          checkIncoming,
          materialName,
          storageEnvironment,
          // needProduceDate,
          size,
          unitCode,
          unitName,
        } = item;
        this.form.size = size;
        this.form.materialNo = materialNo;
        this.form.materialName = materialName;
        this.form.checkIncoming = checkIncoming;
        this.form.storageEnvironment = storageEnvironment;
        this.form.unitCode = unitCode;
        this.form.unitName = unitName;
        // 根据后端返回的needProduceDate字段来决定是否必填
        // if (needProduceDate === 1) {
        //   this.rules.produceDate[0].required = true
        // } else {
        //   this.rules.produceDate[0].required = false
        // }
      }
    },
    // 收料类别变化事件处理函数
    // 参数v: 选择的收料类型值
    receiptTypeChange(v) {
      console.log(v);
      // 收料类型为'1'（采购入库）时的处理逻辑
      if (v === "1") {
        // 显示收料单相关字段
        this.receiptShow = true;
        // 显示其他相关字段
        this.otherShow = true;
        // 如果源单编号未定义
        if (this.purchaseOrderNo === undefined) {
          // 禁用物料选择
          this.materialDisabled = true;
          // 清空客户代码
          this.form.customerCode = undefined;
          // 设置源单编号为必填项
          this.$refs.form.rules.purchaseOrderNo[0].required = true;
          // 获取订单号列表
          this.fetchOrderNoList();
        }
      } else if (v === "3") {
        // 显示收料单相关字段
        this.receiptShow = true;
        // 显示其他相关字段
        this.otherShow = true;
        // 如果源单编号未定义
        if (this.purchaseOrderNo === undefined) {
          // 禁用物料选择
          this.materialDisabled = true;
          // 清空客户代码
          this.form.customerCode = undefined;
          // 设置源单编号为必填项
          this.$refs.form.rules.purchaseOrderNo[0].required = true;
          // 获取订单号列表
          this.fetchOrderNoList2();
        }
      }
      // 收料类型为'4'（其他入库）时的处理逻辑
      else if (v === "4") {
        // 显示其他相关字段
        this.otherShow = true;
        // 禁用物料选择
        this.materialDisabled = false;
        // 隐藏收料单相关字段
        this.receiptShow = false;
        // 设置源单编号为非必填项
        this.$refs.form.rules.purchaseOrderNo[0].required = false;
        // 清空客户代码
        this.form.customerCode = undefined;
        // 清空源单编号
        this.form.purchaseOrderNo = undefined;
        // 清空物料订单的入库ID
        this.$refs.materialOrder.inStockId = undefined;
      }
      // 其他收料类型的处理逻辑
      else {
        // 设置源单编号为非必填项
        this.$refs.form.rules.purchaseOrderNo[0].required = false;
        // 隐藏收料单相关字段
        this.receiptShow = false;
        // 隐藏其他相关字段
        this.otherShow = false;
        // 启用物料选择
        this.materialDisabled = false;
        // 清空源单编号
        this.form.purchaseOrderNo = undefined;
        // 清空供应商代码
        this.form.supplierCode = undefined;
        // 清空物料订单的入库ID和委外ID
        this.$refs.materialOrder.inStockId = undefined;
        this.$refs.materialOrder.outSourceId = undefined;
      }
    },
    // 根据宽度计算每包数量
    widthChange(row) {
      const { length } = row;
      if (length === null || length === undefined || length === 0) {
        row.qty = undefined;
        this.calculateTotalReceiptQty(); // 重新计算总数
        return;
      }
      row.qty = this.getHandleNumber((row.width / 1000) * length);
      this.calculateTotalReceiptQty(); // 重新计算总数
    },
    // 根据长度计算每包数量
    lengthChange(row) {
      const { width } = row;
      if (width === null || width === undefined || width === 0) {
        row.qty = undefined;
        this.calculateTotalReceiptQty(); // 重新计算总数
        return;
      }
      row.qty = this.getHandleNumber((width / 1000) * row.length);
      this.calculateTotalReceiptQty(); // 重新计算总数
    },
    // 生产日期change事件
    produceDateChange(v) {
      const currentDate = new Date();
      const selectedDate = new Date(v);

      if (selectedDate > currentDate) {
        this.$modal.msgWarning("生产日期不能超过当前日期，请重新选择!");
        this.form.produceDate = undefined;
      } else if (v) {
        const params = {
          produceDate: v,
          materialNo: this.form.materialNo,
        };

        validateIsQuality(params)
          .then((res) => {
            if (Object.keys(res.data).length > 0) {
              this.warningText = res.data["1005000162"];
              this.form.validTill = res.data.validTillW;
              if (this.warningText) {
                this.dialogVisible = true;
              }
            }
            // if (res.data === '1005000162') {
            //   this.dialogVisible = true
            // }
          })
          .catch((error) => {
            // 处理错误
            console.log(error);
          });
      }
    },
    // 查询子组件物料编码列表
    fetchMaterialNoList(inStockId) {
      this.$refs.materialOrder.inStockId = inStockId;
    },
    supplierChange(item) {
      if (item) {
        const { code } = item;
        this.fetchOrderNoList(code);
      }
    },
    // 查询子组件源单单号列表
    fetchOrderNoList(supplierCode) {
      const params = {
        pageNo: 1,
        pageSize: 100,
        supplierCode,
      };
      getDropDownList(params)
        .then((res) => {
          this.orderOptions = res.data || [];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    fetchOrderNoList2(supplierCode) {
      const params = {
        supplierCode,
      };
      getDropDownList2(params)
        .then((res) => {
          this.orderOptions = res.data || [];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 附件上传
    handleUpload() {
      this.$refs.attachmentUpload.isUploadShow = -1;
      this.$refs.attachmentUpload.title = "上传附件";

      // 直接使用当前组件维护的 uploadFiles，而不是重新获取
      this.$refs.attachmentUpload.fileList = this.uploadFiles || [];

      this.$refs.attachmentUpload.visible = true;
    },
    // 获取上传的附件
    getFileList(data) {
      this.uploadFiles = data;
    },
    // 查看附件
    handleUploaded(data) {
      this.$refs.attachmentUpload.fileList = data;
      this.$refs.attachmentUpload.title = "查看附件";
      this.$refs.attachmentUpload.isUploadShow = 0;
      this.$refs.attachmentUpload.visible = true;
    },
    // 单位
    unitChange(v) {
      const { name } = v;
      this.form.unitCode = name;
    },
  },
};
</script>
<style scoped>
.validateDate {
  font-size: 16px;
}
</style>
