<template>
  <ele-modal
    :visible.sync="visible"
    title="取样"
    width="80%"
    append-to-body
    :maxable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="el-form-box"
    >
      <header-title title="基本信息"></header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="质检工单编码：" prop="code">
            <el-input disabled v-model="form.code" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质检工单名称：" prop="name">
            <el-input disabled v-model="form.name" placeholder=" " />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="来源单号：" prop="sourceCode">
            <el-input disabled v-model="form.sourceCode" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="类型：" prop="qualityType">
            <DictSelection
              dictName="质检计划类型"
              v-model="form.qualityType"
              disabled
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="编码：" prop="productCode">
            <el-input disabled v-model="form.productCode" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="名称：" prop="productName">
            <el-input disabled v-model="form.productName" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批次号：" prop="batchNo">
            <el-input disabled v-model="form.batchNo" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格：" prop="specification">
            <el-input disabled v-model="form.specification" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="型号：" prop="modelType">
            <el-input disabled v-model="form.modelType" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="牌号：" prop="brandNo">
            <el-input disabled v-model="form.brandNo" placeholder=" " />
          </el-form-item>
        </el-col>
      </el-row>
      <header-title title="来源清单"></header-title>
      <ele-pro-table
        ref="sourceTable"
        :columns="tableColumns"
        :datasource="datasource"
        :initLoad="false"
        :needPage="false"
        height="400px"
        full-height="calc(100vh - 120px)"
        :selection.sync="selection"
      ></ele-pro-table>
      <header-title title="取样信息"> </header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="质检方式：" prop="qualityMode">
            <DictSelection
              dictName="取样类型"
              v-model="form.qualityMode"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验方法：" prop="sampleQuantity">
            <el-select
              style="width: 100%"
              v-model="form.sampleQuantity"
              placeholder="请选择"
            >
              <el-option
                v-for="item in sampleQuantityList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.qualityMode == '2'">
        <el-col :span="8">
          <el-form-item label="取样：" prop="sampleNumber">
            <el-select
              style="width: 100%"
              v-model="form.conditionType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in sampleNumberList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row>
            <el-col :span="6" v-if="form.conditionType == 2">
              <el-form-item prop="measureQ">
                <el-input
                  v-model="form.measureQ"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="form.conditionType == 2">
              <el-form-item prop="sampleUnit" label-width="0">
                <DictSelection
                  dictName="计量单位"
                  clearable
                  v-model="form.sampleUnit"
                  filter-placeholder="请输入计量单位搜索"
                  @change="changeSamUnit"
                ></DictSelection>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="form.conditionType == 2">
              <el-form-item prop="portion" label="数量">
                <el-input
                  v-model="form.portion"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10" v-if="form.conditionType == 1">
              <el-form-item prop="portion" label="数量">
                <el-input
                  v-model="form.portion"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10" v-if="form.conditionType == 1">
              <el-form-item prop="packingUnit" label="单位">
                <el-select v-model="form.packingUnit" placeholder="请选择">
                  <el-option
                    v-for="item in packingSpecificationOption"
                    :key="item.id"
                    :label="item.conversionUnit"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :span="4"
              style="text-align: right"
              v-if="form.conditionType == 2"
            >
              <el-button
                type="primary"
                size="mini"
                @click="handleSampleSubmit"
                style="margin-right: 12px"
                >确认</el-button
              >
            </el-col>
            <el-col
              :span="4"
              style="text-align: right"
              v-if="form.conditionType == 1"
            >
              <el-button
                type="primary"
                size="mini"
                @click="handleSampleSubmit"
                style="margin-right: 12px"
                >确认</el-button
              >
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <header-title title="样品信息"></header-title>
      <ele-pro-table
        ref="showSampleListTable"
        :columns="tableColumns1"
        :datasource="sampleList"
        :needPage="false"
        height="400px"
        full-height="calc(100vh - 120px)"
      ></ele-pro-table>
    </el-form>

    <template v-slot:footer>
      <el-button type="primary" @click="save()" v-lodading="loading"
        >确认</el-button
      >

      <el-button @click="cancel">关闭</el-button>
    </template>
  </ele-modal>
</template>

<script>
  const defForm = {
    code: '', //编码
    name: '', //名称
    conditionType: '',
    measureQ: '',
    sampleUnit: '',
    portion: ''
  };
  import {
    queryQualityInventory,
    queryQualityTempleContent
  } from '@/api/inspectionWork';
  import { getCodeList } from '@/api/login';
  export default {
    components: {},
    data() {
      return {
        form: { ...defForm },
        visible: false,
        loading: false,
        rules: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'change' }
          ],
          factoriesId: [
            { required: true, message: '请选择工厂', trigger: 'change' }
          ],
          bomId: [
            { required: true, message: '请选择BOM版本', trigger: 'change' }
          ],
          bomCategory: [
            { required: true, message: '请选择BOM类型', trigger: 'change' }
          ],
          produceRoutingId: [
            { required: true, message: '请选择工艺路线', trigger: 'change' }
          ],
          code: [{ required: true, message: '编码不能为空', trigger: 'change' }]
        },
        sampleQuantityList: [
          { label: '依次检验', value: '1' },
          { label: '分别检验', value: '2' }
        ],
        sampleNumberList: [
          { label: '取整样', value: '1' },
          { label: '取小样', value: '2' }
        ],
        selection: [],
        tableColumns1: [
          {
            label: '样品编码',
            prop: 'sampleCode',
            width: '200',
            align: 'center',
            fixed: 'left'
          },
          {
            label: '编码',
            prop: 'categoryCode',
            align: 'center',
            fixed: 'left'
          },
          {
            label: '名称',
            prop: 'categoryName',
            align: 'center'
          },
          { label: '批次号', prop: 'batchNo', align: 'center' },
          { label: '发货条码', prop: 'barcodes', align: 'center' },
          { label: '包装编码', prop: 'packageNo', align: 'center' },
          { label: '包装数量', prop: 'packingQuantity', align: 'center' },
          { label: '包装单位', prop: 'packingUnit', align: 'center' },
          { label: '计量数量', prop: 'measureQuantity', align: 'center' },
          { label: '计量单位', prop: 'measureUnit', align: 'center' },
          {
            label: '供应商名称',
            prop: 'supplierName',
            align: 'center',
            width: '120'
          },
          {
            label: '供应商代号',
            prop: 'supplierCode',
            align: 'center',
            width: '120'
          },
          {
            label: '物料代号',
            prop: 'materielDesignation',
            align: 'center',
            slot: 'materielDesignation',
            width: '120'
          },
          {
            label: '客户代号',
            prop: 'clientCode',
            align: 'center',
            slot: 'clientCode',
            width: '120'
          },
          {
            label: '刻码',
            prop: 'engrave',
            align: 'center',
            slot: 'engrave',
            width: '120'
          },
          {
            label: '机型',
            prop: 'modelKey',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '颜色',
            prop: 'colorKey',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '重量',
            prop: 'weight',
            align: 'center',
            slot: 'weight',
            width: '120'
          },
          {
            label: '重量单位',
            prop: 'weightUnit',
            align: 'center',
            width: 100
          },
          { label: '仓库', prop: 'warehouseName', align: 'center', width: 100 },
          { label: '货区', prop: 'areaName', align: 'center' },
          { label: '货架', prop: 'goodsShelfName', align: 'center' },
          { label: '货位', prop: 'goodsAllocationName', align: 'center' },
          { label: '生产日期', prop: 'productionDate', align: 'center' },
          { label: '采购日期', prop: 'purchaseDate', align: 'center' }
        ],
        tableColumns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            fixed: 'left'
          },
          {
            label: '编码',
            prop: 'categoryCode',
            width: 150,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '名称',
            prop: 'categoryName',
            width: '150',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          },
          {
            label: '批次号',
            prop: 'batchNo',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          },
          {
            label: '发货条码',
            prop: 'barcodes',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '包装编码',
            prop: 'packageNo',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          },
          { label: '包装数量', prop: 'packingQuantity', align: 'center' },
          { label: '包装单位', prop: 'packingUnit', align: 'center' },

          { label: '计量数量', prop: 'measureQuantity', align: 'center' },
          { label: '计量单位', prop: 'measureUnit', align: 'center' },
          { label: '物料代号', prop: 'materielDesignation', align: 'center' },
          { label: '客户代号', prop: 'clientCode', align: 'center' },
          {
            label: '供应商名称',
            prop: 'supplierName',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          },
          {
            label: '供应商代号',
            prop: 'supplierCode',
            align: 'center',
            width: '120',
            showOverflowTooltip: true
          },
          { label: '刻码', prop: 'engrave', align: 'center' },
          {
            label: '机型',
            prop: 'modelKey',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '颜色',
            prop: 'colorKey',
            align: 'center',
            showOverflowTooltip: true
          },
          { label: '重量', prop: 'weight', align: 'center' },
          { label: '重量单位', prop: 'weightUnit', align: 'center' },
          {
            label: '仓库',
            prop: 'warehouseName',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          },
          { label: '货区', prop: 'areaName', align: 'center' },
          { label: '货架', prop: 'goodsShelfName', align: 'center' },
          { label: '货位', prop: 'goodsAllocationName', align: 'center' },
          {
            label: '生产日期',
            prop: 'productionDate',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          },
          {
            label: '采购日期',
            prop: 'purchaseDate',
            align: 'center',
            width: 120,
            showOverflowTooltip: true
          }
        ],
        packingSpecificationOption: [],
        sampleList: [],
        schemeList: []
      };
    },

    computed: {},
    created() {},
    methods: {
      async open(row) {
        this.visible = true;
        row.sourceCode = row.qualityPlanCode || row.workOrderCode;
        this.form = row;
        this.queryQualityTempleContent();
        this.$nextTick(() => {
          this.$refs.sourceTable.reload({
            page: 1,
            where: { qualityWorkerId: row.id }
          });
        });
      },
      async queryQualityTempleContent() {
        const res = await queryQualityTempleContent({
          qualityWorkerId: this.form.id,
          page: 1,
          size: 10000
        });
        this.schemeList = res.list;
      },
      cancel() {
        this.form = {
          ...defForm
        };
        this.schemeList = [];
        this.visible = false;
      },
      async datasource({ page, limit, where }) {
        const res = await queryQualityInventory({
          ...where,
          pageNum: page,
          size: -1
        });
        if (res.list.length == 0) {
          return res;
        }

        let o = res.list[0];
        let listArr = [];
        if (o.measureUnit) {
          listArr.push({
            packageCellTotal: 1,
            conversionUnit: o.measureUnit,
            id: '111'
          });
        }
        if (o.packingUnit) {
          listArr.push({
            packageCellTotal: o.measureQuantity - 0,
            conversionUnit: o.packingUnit,
            id: '222'
          });
        }

        res.list.map((el) => {
          el.weightProportion = el.weight
            ? (el.weight / el.measureQuantity).toFixed(4)
            : 0;
          el.weightProportion = el.weightProportion - 0;
        });
        this.packingSpecificationOption = listArr;
        return res;
      },

      handleSampleSubmit() {
        // this.$refs.ruleForm.validate((valid) => {
        // if (valid) {
        let params = {
          conditionType: this.form.conditionType,
          measureQ: this.form.measureQ,
          sampleUnit: this.form.sampleUnit,
          portion: this.form.portion
        };
        let specifications = this.packingSpecificationOption.find(
          (el) => el.id == this.form.packingUnit
        );
        this.sampleFn(params, specifications);
        // }
        // });
      },

      async sampleFn(data, specifications) {
        this.sampleList = [];
        if (!this.selection || this.selection.length == 0) {
          this.$message.warning('请先选择样品！');
          return;
        }
        const measureQ = data.measureQ || 1;
        const unit = data.sampleUnit;
        const sampleCount = Number(data.portion);
        try {
          if (
            this.form.inspectionStandards === 1 ||
            ([2, 3, 4, 5].includes(this.form.inspectionStandards) &&
              this.form.conditionType == 2)
          ) {
            // 新增校验 数量  取整样 ***
            if (this.form.conditionType == 1) {
              let isFlag = this.validateSampleQuantity(
                sampleCount,
                specifications
              );
              if (!isFlag) return;
            }
            // ***
            //抽检计量整样小样或者抽检计重小样
            if (!this.validateMeasureQuantity(measureQ, unit, sampleCount))
              return; //取样数量验证
            if (unit === 'KG' && !this.validateWeight(measureQ, sampleCount))
              return; // 若计量单位为重量，还需验证总重量是否足够
            await this.getNewFullSampleList(
              Math.ceil(sampleCount),
              // sampleCount,
              measureQ,
              unit,
              specifications
            );
            // 这里是取整样 非数量
          } else if (
            [2, 3, 4, 5].includes(this.form.inspectionStandards) &&
            this.form.conditionType == 1
          ) {
            console.log('这里是取整样 吗');
            //抽检取计重取整样
            if (!this.validateSampleCount(sampleCount, specifications)) return;
            await this.handleWeightFullSample(sampleCount, specifications);
          }
        } catch (error) {
          console.error('取样处理失败:', error);
          this.$message.error('取样处理失败');
        }
      },
      validateWeight(measureQ, sampleCount) {
        let totalMaxPossible = 0;
        this.selection.forEach((item) => {
          totalMaxPossible += item.measureQuantity / measureQ;
        });

        if (totalMaxPossible < sampleCount) {
          // this.form.portion = totalMaxPossible;
          this.$message.info(`最大取样条数为${totalMaxPossible}`);
          return false;
        }

        let totalWeight = this.selection.reduce(
          (sum, item) => sum + item.weight,
          0
        );
        const weightUnit = this.selection[0].weightUnit;
        if (weightUnit === 'G') totalWeight /= 1000;

        if (measureQ * sampleCount > totalWeight) {
          this.$message.info('取样计量重量不能大于总计量重量');
          return false;
        }

        const invalidItem = this.selection.find((item) => {
          const weight =
            item.weightUnit === 'G' ? item.weight / 1000 : item.weight;
          return weight < measureQ;
        });

        if (invalidItem) {
          this.$message.info('勾选条目重量小于取样重量');
          return false;
        }

        return true;
      },

      validateMeasureQuantity(measureQ, unit, sampleCount) {
        if (this.form.conditionType == 2 && measureQ <= 0) {
          this.$message.info('取样计量数量必须大于0');
          return false;
        }

        const totalQuantity = this.selection.reduce(
          (sum, item) => sum + item.measureQuantity,
          0
        );
        if (
          (this.selection[0].measureUnit === unit ||
            this.form.conditionType == 1) &&
          measureQ * sampleCount > totalQuantity
        ) {
          this.$message.info('取样计量数量不能大于总计量数量');
          return false;
        }

        const invalidItem = this.selection.find(
          (item) => item.measureQuantity < measureQ
        );
        if (invalidItem) {
          this.$message.info('条目计量数量小于取样计量数量');
          return false;
        }

        return true;
      },

      // 抽检取整样 校验
      validateSampleCount(sampleCount, specifications) {
        // 新增校验 ***
        let isFlag = this.validateSampleQuantity(sampleCount, specifications);
        if (!isFlag) {
          return false;
        }
        // ***
        const chooseNumber = this.selection.reduce((acc, pro) => {
          return pro.measureQuantity ? acc + Number(pro.measureQuantity) : acc;
        }, 0);
        const invalidItem = chooseNumber < sampleCount;
        // console.log(this.selection, 'this.selection');
        // const invalidItem = this.selection.find(
        //   (item) => item.measureQuantity < sampleCount
        // );
        if (invalidItem) {
          this.$message.info('所选的条目计量数量小于取样计量数量');
          return false;
        }
        // ***
        return true;
      },

      async handleWeightFullSample(sampleCount, specifications) {
        const dataList = [];
        let currentNum = sampleCount - this.selection.length;
        let currentNum1 = sampleCount;
        for (const item of this.selection) {
          const qualitySampleTemplateList = item.qualitySampleTemplateList
            ?.length
            ? JSON.parse(JSON.stringify(item.qualitySampleTemplateList))
            : JSON.parse(
                JSON.stringify(
                  this.schemeList.map((item) => {
                    item['qualityResults'] = 1;
                    return item;
                  })
                )
              );

          if (sampleCount >= this.selection.length) {
            dataList.push({
              ...item,
              measureQuantity: 1, //作为计量数量
              sampleCode: await this.getSampleCode(),
              qualitySampleTemplateList
            });
          } else {
            if (dataList.length < sampleCount) {
              dataList.push({
                ...item,
                measureQuantity: currentNum1 > 1 ? 1 : currentNum1, //作为计量数量
                sampleCode: await this.getSampleCode(),
                qualitySampleTemplateList
              });
              currentNum1 -= 1;
            }
          }
        }
        if (sampleCount > this.selection.length) {
          dataList.forEach((item) => {
            if (currentNum > 0) {
              let data = this.selection.find((val) => val.id == item.id);
              item['measureQuantity'] =
                data.measureQuantity - 1 - currentNum > 0
                  ? currentNum + 1
                  : data.measureQuantity;
              currentNum = currentNum - (data.measureQuantity - 1);
            }
          });
        }
        // 更改 从新计算 样品清单 取整样 数据
        if (specifications && specifications.id) {
          // let proportion = (obj.weight / obj.measureQuantity).toFixed(2);
          dataList.map((el) => {
            el.measureQuantity =
              el.measureQuantity * specifications.packageCellTotal;
            el.weight = this.formatNumber(
              el.measureQuantity,
              el.weightProportion
            );
          });
        }
        // 更改
        this.sampleList = dataList;
      },
      // 小数点数据判断
      formatNumber(a, b, maxDecimals = 4) {
        if (a == 0 || b == 0 || !a || !b) {
          return 0;
        }
        // 计算乘积
        const product = a * b;
        // 转换为固定小数位数，然后转换为数字以去除末尾零
        const rounded = Number(product.toFixed(maxDecimals));
        // 转换为字符串检查是否需要显示小数部分
        const str = rounded.toString();
        // 如果包含小数点
        if (str.indexOf('.') !== -1) {
          // 移除末尾的零和小数点（如果后面没有数字了）
          return str.replace(/\.?0+$/, '');
        }
        return str;
      },
      //从来源数组取样到目标数组
      async getNewFullSampleList(
        sampleCount,
        sampleQuantity,
        sampleUnit,
        specifications
      ) {
        const sourceArray = this.selection;
        // 检查单位是否匹配
        const isUnitMismatch =
          sourceArray.length > 0 && sourceArray[0].measureUnit !== sampleUnit;

        // 创建副本并计算初始可取样数量
        const items = sourceArray.map((item) => ({
          ...item,
          remainingQuantity: isUnitMismatch
            ? Infinity
            : item['measureQuantity'], // 剩余可取样数量
          maxPossible: item['measureQuantity'] / sampleQuantity // 最大取样次数
        }));

        const result = [];
        let remainingCount = sampleCount;
        let count = Math.ceil(remainingCount);
        const codeList = await this.batchCodes(count);
        let codeIdx = 0;
        // 尽可能均匀地从各条目取样
        while (remainingCount > 0) {
          // 按剩余可取样比例排序
          items.sort(
            (a, b) =>
              b.remainingQuantity / b['measureQuantity'] -
              a.remainingQuantity / a['measureQuantity']
          );

          let distributed = false;

          for (const item of items) {
            // let values = remainingCount > 1 ? 1 : remainingCount;
            if (
              !isUnitMismatch ||
              (item.remainingQuantity >= sampleQuantity && remainingCount > 0)
            ) {
              let qualitySampleTemplateList = [];
              if (
                item.qualitySampleTemplateList == undefined ||
                item.qualitySampleTemplateList == null ||
                item.qualitySampleTemplateList.length == 0
              ) {
                qualitySampleTemplateList = JSON.parse(
                  JSON.stringify(this.schemeList)
                );
              } else {
                qualitySampleTemplateList = item.qualitySampleTemplateList;
              }
              // 添加到结果数组
              // let sampleCode = await this.getSampleCode();
              let sampleCode = codeList[codeIdx];
              if (
                this.form.conditionType == 1 &&
                this.form.inspectionStandards == 1
              ) {
                result.push({
                  ...item,
                  // measureQuantity: values,
                  measureQuantity: 1,
                  sampleCode,
                  qualitySampleTemplateList
                });
              } else if (this.form.conditionType == 2) {
                let weight = (item.weight / item.maxPossible).toFixed(2);
                result.push({
                  ...item,
                  measureQuantity: sampleQuantity,
                  measureUnit: sampleUnit,
                  sampleCode,
                  weight,
                  qualitySampleTemplateList
                });
              }
              // 更新剩余数量
              if (!isUnitMismatch) {
                item.remainingQuantity -= sampleQuantity;
              }
              remainingCount = (remainingCount - 1).toFixed(2);
              codeIdx++;
              distributed = true;
            }
          }

          // 如果没有分配任何取样
          if (!distributed) {
            break;
          }
        }

        // 判断是不是取整样
        if (
          this.form.conditionType == 1 &&
          specifications &&
          specifications.id
        ) {
          result.map((el) => {
            el.measureQuantity =
              el.measureQuantity * specifications.packageCellTotal;
            el.weight = this.formatNumber(
              el.measureQuantity,
              el.weightProportion
            );
          });
        }
        this.sampleList = result;
        if (this.sampleList.length > sampleCount) {
          this.sampleList = this.sampleList.splice(0, sampleCount);
        }
      },
      // 当计量类型 是数量的时候 取整样 校验
      validateSampleQuantity(sampleCount, specifications) {
        let packingUnit = this.selection[0].packingUnit?.trim() || '';
        let totalS = 0;
        let labelKey =
          packingUnit == specifications.conversionUnit.trim()
            ? 'packingQuantity'
            : 'measureQuantity';
        let labelName = labelKey == 'packingQuantity' ? '包装数量' : '计量数量';
        totalS = this.selection.reduce((total, el) => total + el[labelKey], 0);

        if (sampleCount > totalS) {
          this.$message.info(
            `所填的条目数量不能超过所选${labelName}总和${totalS}`
          );
          return false;
        }
        return true;
      },
      async batchCodes(count) {
        if (count <= 0) return;
        let params = { count };
        const res = await getCodeList('sample_code', params);
        return res;
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.loading = true;
            saveOrUpdate(this.form)
              .then((res) => {
                this.$message.success('操作成功');
                this.cancel();
                this.$emit('done');
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  .basic-details-title {
    margin: 10px 0;
  }

  .title {
    font-size: 16px;
    line-height: 45px;
  }

  .add-product {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 30px;
    color: #1890ff;
    margin: 10px 0;
    cursor: pointer;
  }
</style>
