<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :title="title"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="80%"
    :maxable="true"
  >
    <header-title title="基本信息"></header-title>
    <base-info
      ref="baseInfoRefs"
      v-if="baseForm"
      :form="baseForm"
      :btnType="btnType"
      :isChangeNumber="isChangeNumber"
      :isChangeType="isChangeType"
      @resetTable="resetTable"
      @changeModel="changeModel"
      @getList="getList"
      @table2="table2"
      @changeType="changeType"
      @changeSource="changeSource"
      @getInspectionStandards="getInspectionStandards"
      :packingLists="packingList"
      @getCategoryInfo="getCategoryInfo"
      @changeProductNumberModel="changeProductNumberModel"
      @changesStokledgerNumberModal="changesStokledgerNumberModal"
      @getQualityTemplate="getQualityTemplate"
    ></base-info>
    <el-row>
      <header-title title="质检内容"></header-title>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="来源清单" name="1">
          <!-- <ele-pro-table
            ref="table12"
            :columns="tableColumns"
            :datasource="datasource"
            :needPage="
              btnType == 'add' ||
              (btnType == 'edit' && !isFormNumber && !isOrder)
                ? false
                : true
            "
            @selection-change="handleSelectionChange"
          > -->
          <!-- :datasource="sourceList" -->

          <!-- :datasource="
              btnType == 'add' ||
              (btnType == 'edit' && (!isPackingList || !isSampleList))
                ? sourceList
                : datasource
            " -->
          <!-- 来料列表表格 -->
          <ele-pro-table
            ref="table12"
            :columns="tableColumns"
            :datasource="sourceList"
            @selection-change="handleSelectionChange"
          >
            <template
              v-slot:toolbar
              v-if="this.baseForm.qualityMode == 2 && btnType != 'detail'"
            >
              <el-dropdown trigger="click" @command="handleSampleNumber">
                <el-link type="primary" icon="el-icon-plus">取样</el-link>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="1">取整样</el-dropdown-item>
                  <el-dropdown-item command="2">取小样</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <template v-slot:toolkit v-if="this.baseForm.qualityMode == 2">
              <el-row>
                <el-form
                  ref="ruleForm"
                  :model="formData"
                  label-width="60px"
                  size="mini"
                  :rules="rules"
                  class="flex"
                  :show-message="false"
                >
                  <el-col :span="6" v-if="conditionType == 2">
                    <el-form-item
                      prop="number"
                      label-width="0"
                      style="margin-bottom: 0"
                    >
                      <el-input
                        v-model="formData.number"
                        placeholder="请输入"
                        size="mini"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="conditionType == 2">
                    <el-form-item
                      prop="sampleUnit"
                      label-width="0"
                      style="margin: 0"
                    >
                      <DictSelection
                        dictName="计量单位"
                        clearable
                        v-model="formData.sampleUnit"
                        size="mini"
                        @change="changeSamUnit"
                      ></DictSelection>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" v-if="conditionType == 2">
                    <el-form-item prop="portion" label="数量" style="margin: 0">
                      <el-input
                        v-model="formData.portion"
                        placeholder="请输入"
                        size="mini"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24" v-if="conditionType == 1">
                    <el-form-item prop="portion" label="数量" style="margin: 0">
                      <el-input
                        v-model="formData.portion"
                        placeholder="请输入"
                        size="mini"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col
                    :span="4"
                    style="text-align: right"
                    v-if="conditionType == 1"
                  >
                    <el-button
                      type="primary"
                      size="mini"
                      @click="handleExtractFull"
                      style="margin-right: 12px"
                      >确认</el-button
                    >
                  </el-col>
                  <el-col
                    :span="4"
                    style="text-align: right"
                    v-if="conditionType == 2"
                  >
                    <el-button
                      type="primary"
                      size="mini"
                      @click="handleExtractFull"
                      style="margin-right: 12px"
                      >确认</el-button
                    >
                  </el-col>
                </el-form>
              </el-row>
            </template>
          </ele-pro-table>
        </el-tab-pane>
        <el-tab-pane label="样品清单" name="2">
          <el-table
            v-show="activeName === '2'"
            v-if="sampleList.length > 0"
            ref="showSampleListTable"
            :data="paginatedSampleList"
            tooltip-effect="dark"
            :max-height="300"
            border
            row-key="sampleCode"
          >
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center"
            ></el-table-column>
            <template v-for="column in tableColumns2">
              <el-table-column
                :key="column.prop"
                :label="column.label"
                :prop="column.prop"
                :show-overflow-tooltip="true"
                :width="column.width"
                :align="column.align"
              ></el-table-column>
            </template>
          </el-table>
          <el-pagination
            v-show="activeName === '2' && sampleList.length > 0"
            @size-change="handleSampleSizeChange"
            @current-change="handleSampleCurrentChange"
            :current-page="samplePagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="samplePagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="samplePagination.total"
            style="margin-top: 10px"
          ></el-pagination>
        </el-tab-pane>
        <el-tab-pane label="质检方案" name="3">
          <el-button
            @click="addInspectionTemplate(baseForm.type)"
            type="primary"
            style="margin-top: 5px"
            >选择质检方案</el-button
          >
          <el-table
            v-show="activeName === '3'"
            v-if="schemeList.length > 0"
            ref="showSchemeListTable"
            :data="paginatedSchemeList"
            tooltip-effect="dark"
            :max-height="300"
            border
            row-key="id"
          >
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center"
            ></el-table-column>
            <el-table-column
              label="质检方案编码"
              prop="qualitySchemeTemplateCode"
              align="center"
              width="170"
            ></el-table-column>
            <el-table-column
              label="质检方案名称"
              prop="qualitySchemeTemplateName"
              align="center"
              width="170"
            ></el-table-column>
            <el-table-column
              label="质检类型"
              prop="categoryLevelClassName"
              align="center"
              width="170"
            ></el-table-column>
            <el-table-column
              label="质检项编码"
              prop="inspectionCode"
              align="center"
              width="170"
            ></el-table-column>
            <el-table-column
              label="质检项名称"
              prop="inspectionName"
              align="center"
              width="150"
            ></el-table-column>
            <el-table-column
              label="工艺参数"
              prop="defaultValue"
              align="center"
            >
              <template slot-scope="scope">
                <div style="display: flex; flex-direction: row">
                  <DictSelection
                    v-if="btnType != 'detail'"
                    style="width: 85px"
                    clearable
                    dictName="数学字符"
                    v-model="scope.row.symbol"
                  ></DictSelection>
                  <el-input
                    :disabled="btnType == 'detail'"
                    v-model="scope.row.defaultValue"
                    placeholder="请输入内容"
                    style="width: 120px"
                  ></el-input>
                  <DictSelection
                    v-if="btnType != 'detail'"
                    dictName="工艺参数单位"
                    clearable
                    filterable
                    v-model="scope.row.unitName"
                    style="width: 100px"
                  >
                  </DictSelection>
                </div>
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="80">
              <template slot-scope="scope">
                <el-popconfirm
                  class="ele-action"
                  title="确定要删除当前方案吗？"
                  @confirm="handDel(scope.$index)"
                >
                  <template v-slot:reference>
                    <el-link
                      type="danger"
                      :underline="false"
                      icon="el-icon-delete"
                    >
                      删除
                    </el-link>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-show="activeName === '3' && schemeList.length > 0"
            @size-change="handleSchemeSizeChange"
            @current-change="handleSchemeCurrentChange"
            :current-page="schemePagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="schemePagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="schemePagination.total"
            style="margin-top: 10px"
          ></el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-row>

    <template v-slot:footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button
        v-if="btnType != 'detail' && btnType != 'issued'"
        type="primary"
        :loading="loading"
        @click="handleSave"
        >保存</el-button
      >
      <el-button
        v-if="btnType != 'detail'"
        type="primary"
        :loading="loading"
        @click="handleIssued"
        >下发</el-button
      >
      <!-- 选择质检方案 -->
      <inspectionTemplateDialog
        v-if="baseForm"
        :type="baseForm.type"
        ref="inspectionTemplateRef"
        @choose="inspectionTemplateSuccess"
      ></inspectionTemplateDialog>
    </template>
  </ele-modal>
</template>

<script>
  // import baseInfo from './baseInfo.vue';
  import baseInfo from './new-baseInfo.vue';
  // 质检方案的弹窗
  import inspectionTemplateDialog from '@/views/inspectionTemplate/components/inspectionTemplateDialog.vue';
  import { getCode } from '@/api/login';
  import { save, update, planIssued } from '@/api/inspectionPlan';
  import {
    getQualityTemplateList,
    getTemplateListByPlanId,
    getSampleListByPlanId,
    getInventoryListByPlanId,
    outInRecordsPage,
    getBatchInfoData,
    getProductOrder,
    getProductSteup
  } from '@/api/inspectionPlan/index.js';
  import { getQualityTemplateByIds } from '@/api/inspectionTemplate';

  export default {
    components: {
      baseInfo,
      inspectionTemplateDialog
    },
    data() {
      const defaultForm = function () {
        return {
          id: '',
          code: '',
          name: '',
          type: '',
          qualityMode: '',
          inspectionStandards: '',
          autoOrder: '',
          groupId: '',
          groupName: '',
          executeId: '',
          executeName: '',
          planStartTime: '',
          planEndTime: '',
          standard: '',
          planSource: '',
          planSourceCode: '',
          productName: '',
          productCode: '',
          batchNo: '',
          specification: '',
          modelType: '',
          brandNo: '',
          productNumber: '',
          qualifiedNumber: '',
          unqualifiedNumber: '',
          qualificationRate: '',
          totalWeight: '',
          sampleNumber: null,
          sampleMeasureUnit: '',
          sampleProportion: '',
          supplierMark: '',
          remark: '',
          accessory: [],
          conditionType: 1
        };
      };
      return {
        defaultForm,
        // 表单数据
        baseForm: { ...defaultForm() },

        tableColumns2: [
          {
            label: '样品编码',
            prop: 'sampleCode',
            width: '150',
            align: 'center'
          },
          {
            label: '编码',
            prop: 'categoryCode',
            width: '150',
            align: 'center'
          },
          {
            label: '名称',
            prop: 'categoryName',
            width: '150',
            align: 'center'
          },
          { label: '批次号', prop: 'batchNo', align: 'center', width: 120 },
          { label: '发货条码', prop: 'barcodes', align: 'center' },
          { label: '包装编码', prop: 'packageNo', align: 'center' },
          { label: '计量数量', prop: 'measureQuantity', align: 'center' },
          { label: '计量单位', prop: 'measureUnit', align: 'center' },
          { label: '物料代号', prop: 'materielDesignation', align: 'center' },
          { label: '客户代号', prop: 'clientCode', align: 'center' },
          { label: '刻码', prop: 'engrave', align: 'center' },
          // { prop: 'specification', label: '规格', align: 'center', width: 100, showOverflowTooltip: true },
          // { prop: 'brandNum', label: '牌号', align: 'center', width: 100, showOverflowTooltip: true },
          // { prop: 'modelType', label: '型号', align: 'center', width: 100, showOverflowTooltip: true },
          { label: '重量', prop: 'weight', align: 'center' },
          { label: '重量单位', prop: 'weightUnit', align: 'center' },
          { label: '仓库', prop: 'warehouseName', align: 'center' },
          { 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' }
        ],

        packingList: [],

        sourceList: [],
        sourcePagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },

        sampleList: [],
        samplePagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },

        schemeList: [],
        schemePagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },

        // 表单验证规则
        visible: false,
        btnType: null,
        title: null,
        loading: false,
        listPage: [],

        activeName: '1',
        selectedList: [],
        isCheck: false, // 是否拆包  false 不拆包 true 拆包

        rowIds: '',
        formData: {
          number: 1,
          sampleUnit: '',
          portion: null
        },
        rules: {
          number: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            }
          ],
          sampleUnit: [
            {
              required: true,
              message: '请选择样品单位',
              trigger: 'change'
            }
          ],
          portion: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            }
          ]
        },
        isScheme: true,
        isOrder: true,
        isConsumable: '', //0 单件 1批量
        netWeight: '', // 净重
        conditionType: null,
        isFormNumber: true,

        sampleListCode: '',
        productItem: {}, //产品信息
        isUpdateData: true,
        isChangeNumber: true,
        isChangeType: true,
        isOnce: true,
        dimensionType: '',
        isSampleList: true,
        isPackingList: true,
        isSchemeList: true,
        newSampleList: [],
        kkconditionType: ''
      };
    },
    computed: {
      tableColumns() {
        let arr = [
          // (this.btnType !== 'issued' || this.baseForm.qualityMode === 2)
          //   ? {
          //     columnKey: 'selection',
          //     type: 'selection',
          //     width: 45,
          //     align: 'center'
          //   }
          //   : null,
          {
            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 },
          { label: '发货条码', prop: 'barcodes', align: 'center' },
          {
            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'
          },
          { label: '刻码', prop: 'engrave', align: 'center' },
          { 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
          }
        ];
        return arr;
      },

      //分页后的来源列表
      paginatedSourceList() {
        console.log('分页', this.sourceList);
        const { currentPage, pageSize } = this.sourcePagination;
        const start = (currentPage - 1) * pageSize;
        const end = start + pageSize;
        return this.sourceList.slice(start, end);
      },

      // 分页后的样品列表
      paginatedSampleList() {
        if (this.rowIds && this.isSampleList) {
          console.log(this.sampleList, 'sampleList');
          return this.sampleList;
        }
        const { currentPage, pageSize } = this.samplePagination;
        const start = (currentPage - 1) * pageSize;
        const end = start + pageSize;
        return this.sampleList.slice(start, end);
      },
      // 分页后的质检方案列表
      paginatedSchemeList() {
        if (this.rowIds && this.isScheme) {
          console.log(this.schemeList, 'test');
          return this.schemeList;
        }
        const { currentPage, pageSize } = this.schemePagination;
        const start = (currentPage - 1) * pageSize;
        const end = start + pageSize;
        return this.schemeList.slice(start, end);
      }
    },

    created() {},
    methods: {
      //成品检验类型，计划来源主数据，修改数量生成来源清单
      changeProductNumberModel(num) {
        // if (
        //   this.btnType == 'add' ||
        //   (this.btnType == 'edit' && !this.isUpdateData)
        // ) {
        //   this.$refs.table12.setData([]);
        //   this.isOrder = false;
        //   let nums = Number(num);
        //   let p = this.productItem;
        //   let list = [];
        //   if (this.isConsumable == 0) {
        //     for (let i = 0; i < nums; i++) {
        //       let obj = {
        //         id: p.id,
        //         batchNo: p.batchNo,
        //         categoryCode: p.code, //编码
        //         categoryName: p.name, //名称
        //         measureQuantity: 1,
        //         measureUnit: p.measuringUnit, //计量单位
        //         weightUnit: p.weightUnit, //重量单位
        //         weight: p.netWeight //重量
        //       };
        //       list.push(obj);
        //     }
        //   } else if (this.isConsumable == 1) {
        //     let obj = {
        //       id: p.id,
        //       batchNo: p.batchNo,
        //       categoryCode: p.code, //编码
        //       categoryName: p.name, //名称
        //       measureQuantity: nums, //计量数量
        //       measureUnit: p.measuringUnit, //计量单位
        //       weightUnit: p.weightUnit, //重量单位
        //       weight: p.netWeight * nums //重量
        //     };
        //     list.push(obj);
        //   }
        //   this.$refs.table12.setData(list);

        //   // *** 如果检验方式是全量的话 还需要同步样品清单数据
        //   if (
        //     this.baseForm.qualityMode == 1 &&
        //     this.baseForm.inspectionStandards
        //   ) {
        //     this.isFormNumber = false;
        //     this.handleSampleList();
        //   }
        //   console.log(this.baseForm, 'form --');
        // }
        console.log('数据33333');
        // this.$refs.table12.setData([]);
        this.sourceList = [];
        this.packingList = [];
        this.isOrder = false;
        let nums = Number(num);
        let p = this.productItem;
        let list = [];
        if (this.isConsumable == 0) {
          for (let i = 0; i < nums; i++) {
            let obj = {
              id: p.id,
              batchNo: p.batchNo,
              categoryCode: p.code, //编码
              categoryName: p.name, //名称
              measureQuantity: 1,
              measureUnit: p.measuringUnit, //计量单位
              weightUnit: p.weightUnit, //重量单位
              weight: p.netWeight //重量
            };
            list.push(obj);
          }
        } else if (this.isConsumable == 1) {
          let obj = {
            id: p.id,
            batchNo: p.batchNo,
            categoryCode: p.code, //编码
            categoryName: p.name, //名称
            measureQuantity: nums, //计量数量
            measureUnit: p.measuringUnit, //计量单位
            weightUnit: p.weightUnit, //重量单位
            weight: p.netWeight * nums //重量
          };
          list.push(obj);
        }
        console.log('数据22222');
        console.log(this.isOrder);
        // this.$refs.table12.setData(list);
        this.sourceList = list;
        this.packingList = list;

        // *** 如果检验方式是全量的话 还需要同步样品清单数据
        if (
          this.baseForm.qualityMode == 1 &&
          this.baseForm.inspectionStandards
        ) {
          this.isFormNumber = false;
          console.log('+++++++++2');
          this.handleSampleList();
        }
        console.log(this.baseForm, 'form --');
      },

      //成品类型检验类型，计划来源库存台账, 生成来源清单
      changesStokledgerNumberModal(val, dimension, type) {
        console.log(val, dimension, '获取成品检验订单数据', type);
        // this.$refs.table12.setData([]);
        this.sourceList = [];
        this.packingList = [];
        if (dimension) this.dimensionType = dimension;
        if (dimension == 3) {
          // this.$refs.table12.setData(val);
          this.sourceList = val;
          this.packingList = val;
          this.calculateWeightAndQuantity(val);
          if (this.baseForm.qualityMode == '1' || type) {
            this.handleUnpackCase(val);
          } else if (this.baseForm.qualityMode == '2' || type) {
            this.sampleList = [];
          }
          return;
        }
        console.log('其他', 'dimension');
        let item = val[0];
        let num = Number(item.outboundNum);
        let list = [];
        // let weight = (item.weight / item.measureQuantity).toFixed(2);
        let weight = (
          (item.weight / item.measureQuantity) *
          item.outboundNum
        ).toFixed(2);
        list.push({
          ...item,
          id: 1,
          packingQuantity: null,
          measureQuantity: item.outboundNum,
          weight
        });

        // for (let i = 0; i < num; i++) {
        //   list.push({
        //     ...item,
        //     id: i + 1,
        //     packingQuantity: null,
        //     measureQuantity: 1,
        //     weight
        //   });
        // }
        // list.push({
        //   ...item
        // });
        console.log(list, 'for循环成品检验订单数据');
        // this.$refs.table12.setData(list);
        this.sourceList = list;
        this.packingList = list;
        if (this.baseForm.qualityMode == '1' || type) {
          this.handleUnpackCase(list);
        } else if (this.baseForm.qualityMode == '2' || type) {
          this.sampleList = [];
        }
      },

      // changesStokledgerNumberModal(val, dimension) {
      //   console.log(val, dimension, '获取成品检验订单数据');
      //   this.$refs.table12.setData([]);
      //   if (dimension) this.dimensionType = dimension;
      //   if (dimension == 3) return this.$refs.table12.setData(val);
      //   let item = val[0];
      //   let num = Number(item.outboundNum);
      //   let list = [];
      //   let weight = (item.weight / item.measureQuantity).toFixed(2);
      //   for (let i = 0; i < num; i++) {
      //     list.push({
      //       ...item,
      //       id: i + 1,
      //       packingQuantity: null,
      //       measureQuantity: 1,
      //       weight
      //     });
      //   }
      //   console.log(list, 'for循环成品检验订单数据');
      //   this.$refs.table12.setData(list);
      //   if (this.baseForm.qualityMode == '1') {
      //     this.handleUnpackCase(list);
      //   } else if (this.baseForm.qualityMode == '2') {
      //     this.sampleList = [];
      //   }
      // },

      //获取基本信息中计量方式
      getInspectionStandards(data) {
        console.log(data, 'data');
        this.baseForm.inspectionStandards = data;
        if (this.baseForm.type == '3' && this.baseForm.planSource == '6') {
          // this.isOrder = false;
          this.handleSampleList();
        }
        if (this.btnType == 'edit' && !this.isOnce) {
          this.isOrder = false;
          this.handleSampleList();
        }
        this.isOnce = false;
      },
      async datasource({ page, limit, where }) {
        // console.log(this.btnType);
        // console.log(this.isScheme, this.isOrder);
        // const res = await getInventoryListByPlanId({
        //   ...where,
        //   pageNum: page,
        //   size: limit
        // });
        // console.log(res.list);
        // this.packingList = res.list;
        // return res;

        return await getInventoryListByPlanId({
          ...where,
          pageNum: page,
          size: limit
        });
      },
      // 切换质检内容
      handleClick(tab) {
        this.activeName = tab.name;
      },
      async open(type, row) {
        this.kkconditionType = row?.conditionType;
        this.visible = true;
        this.activeName = '1';
        this.btnType = type;
        this.title =
          type == 'add'
            ? '新增'
            : type == 'edit'
            ? '编辑'
            : type == 'issued'
            ? '下发'
            : '详情';

        if (this.btnType === 'add') {
          const code = await getCode('qms_plan_code');
          this.baseForm.code = code;
          this.rowIds = '';
          return;
        } else {
          await this.handleEditOrDetail(row);
        }
      },
      addInspectionTemplate(type) {
        this.$refs.inspectionTemplateRef.open(type);
      },
      async inspectionTemplateSuccess(select) {
        let data = await getQualityTemplateByIds({
          templateIds: select.map((item) => item.id)
        });
        console.log('---------------------------');
        this.isScheme = false;

        this.schemeList.push(...data);

        const strings = this.schemeList.map((item) => JSON.stringify(item));
        const removeDupList = [...new Set(strings)];
        const result = removeDupList.map((item) => JSON.parse(item));
        this.schemeList = result;

        this.schemePagination.total = this.schemeList.length;
      },
      async handleEditOrDetail(row) {
        console.log('row====', row);
        row.accessory = row.accessory || [];

        this.baseForm = {
          ...JSON.parse(JSON.stringify(row)),
          groupId: row.groupId,
          qualityMode: row.qualityMode
        };

        this.$nextTick(() => {
          if (this.$refs.baseInfoRefs) {
            // 获取人员
            if (this.baseForm.groupId) {
              this.$refs.baseInfoRefs.getUserList({
                groupId: this.baseForm.groupId
              });
            }
            //根据类型获取计划来源
            if (this.baseForm.type) {
              this.$refs.baseInfoRefs.typeChange(this.baseForm.type, '1111');
            }
            if (this.baseForm.productId) {
              this.$refs.baseInfoRefs.getProductDetails(
                this.baseForm.productId
              );
            }
          }
        });

        // 如果是编辑或者详情，则查询物料清单、质检方案和样品列表
        if (row.id) {
          this.rowIds = row.id;
          this.isScheme = true;
          this.schemePagination.currentPage = 1;
          this.schemePagination.pageSize = 10;
          this.schemePagination.total = 0;
          this.samplePagination.pageSize = 10;
          this.samplePagination.currentPage = 1;
          this.samplePagination.total = 0;
          this.isFormNumber = true;
          this.isOrder = true;
          console.log('edit true');

          if (row.isUnpack === 1) {
            this.isCheck = true;
          } else {
            this.isCheck = false;
          }
          await this.getSourceList(row.id);
          //操作行点击时查询清单
          // await this.getInventoryList();
          await this.reload({ planId: row.id });
          //操作行点击时查询样品
          await this.getSampleList(row.id);
          //操作行点击时查询质检
          await this.getTemplateList(row.id);
        }
      },
      reload(where) {
        this.$nextTick(() => {
          if (this.$refs.table12 && this.$refs.table12.reload)
            this.$refs.table12.reload({ page: 1, where: where });
        });
      },

      async getSourceList(id) {
        const listData = await getInventoryListByPlanId({
          planId: id,
          pageNum: 1,
          size: -1
        });
        this.sourceList = listData.list;
        console.log(this.sourceList);
      },

      async getSampleList(id) {
        let res = await getSampleListByPlanId({
          planId: id,
          pageNum: this.samplePagination.currentPage,
          size: this.samplePagination.pageSize
        });
        console.log(res.list, 'yyyyyyyyyyyyyy样品----------------------------');

        this.sampleList = res?.list || [];
        this.samplePagination.total = res.count;

        let newRes = await getSampleListByPlanId({
          planId: id,
          pageNum: 1,
          size: -1
        });

        this.newSampleList = newRes?.list || [];
      },

      async getTemplateList(id) {
        let res = await getTemplateListByPlanId({
          planId: id,
          pageNum: this.schemePagination.currentPage,
          size: this.schemePagination.pageSize
        });
        console.log(res.list, 'fffffffffffffff方案--------------------------');
        this.schemeList = res?.list || [];
        this.schemePagination.total = res.count;
      },
      async getList(
        receiveNo,
        productCode,
        productCategoryId,
        productCategoryName,
        categoryid,
        batchNo,
        supplierName,
        supplierMark
      ) {
        //通过来源和产品 获取来料清单
        await this.getGoodsList(
          receiveNo,
          productCode,
          null,
          productCategoryId,
          productCategoryName,
          categoryid,
          batchNo,
          supplierName,
          supplierMark
        );

        //通过来源和产品 获取质检方案
        await this.getQualityTemplate(productCode);
      },
      async getGoodsList(
        receiveNo,
        productCode,
        ids,
        productCategoryId,
        productCategoryName,
        categoryid,
        batchNo,
        supplierName,
        supplierMark
      ) {
        // this.$refs.table12.setData([]);
        this.sourceList = [];
        this.packingList = [];

        let res;
        const res1 = await outInRecordsPage({
          sourceBizNo: receiveNo,
          categoryCode: productCode,
          categoryId: categoryid,
          qualityQlanId: ids,
          size: -1
        });
        console.log(res1, 'res1');
        if (res1.list.length > 0) {
          console.log(res1.list[0].status, 'status=2 不赋值');
          if (res1.list[0].status != 2) {
            res = res1.list;
            this.isCheck = true;
            console.log('this.isCheck=true', this.isCheck);
          } else {
            res = [];
            this.$message.error('此数据已质检，无需再次质检！');
            return;
          }
        } else {
          let resData = await getBatchInfoData({
            sourceBizNo: receiveNo,
            categoryCode: productCode,
            batchNo: batchNo
          });
          console.log(resData, 'resData');
          if (resData) {
            if (resData.qualityControl != 2) {
              this.isCheck = false;
              res = [resData];
            } else {
              res = [];
              this.$message.error('此数据已质检，无需再次质检！');
              return;
            }
          }
        }

        console.log(res, '来料清单');
        if (res.length > 0) {
          const _arr1 = res.map((m) => {
            m.sourceId = m.id;
            m.productCategoryId = productCategoryId;
            m.productCategoryName = productCategoryName;
            delete m.id;
            return { ...m };
          });

          this.packingList = _arr1;
          // this.$refs.table12.setData(_arr1); //赋值
          this.sourceList = _arr1;
          this.packingList = _arr1;
          // const _arr2 = this.$refs.table12.getData();
          // if (_arr2.length > 1) {
          //   this.baseForm.productNumber = _arr2.length;
          // } else {
          //   this.baseForm.productNumber = _arr2[0].measureQuantity;
          // }
          this.baseForm.totalWeight = this.sourceList.reduce((acc, pre) => {
            return pre.weight ? acc + Number(pre.weight) : acc;
          }, 0);

          if (this.sourceList.length > 1) {
            this.baseForm.productNumber = this.sourceList.reduce((acc, pre) => {
              return pre.measureQuantity
                ? acc + Number(pre.measureQuantity)
                : acc;
            }, 0);
          } else {
            this.baseForm.productNumber = this.sourceList[0].measureQuantity;
          }

          //处理样品清单
          console.log('处理来源清单数据');
          // await this.handleSampleList();
          await this.updatePackingList(_arr1);
        } else {
          console.log('来料清单数据为空');
          // this.$refs.table12.setData([]);
          this.sourceList = val;
          this.packingList = [];
        }
      },
      async handleSampleList() {
        // let packingList = this.$refs.table12.getData();

        if (this.baseForm.type == '1' && this.btnType != 'detail') {
          if (this.baseForm.inspectionStandards == '2') {
            console.log(13131313213);
            this.sampleList = [];
            let list = [];
            if (this.baseForm.productNumber) {
              let p = this.productItem;
              console.log(p);
              let obj = {
                id: p.id,
                batchNo: p.batchNo,
                categoryCode: p.code, //编码
                categoryName: p.name, //名称
                measureQuantity: this.baseForm.productNumber, //计量数量
                measureUnit: p.measuringUnit, //计量单位
                weightUnit: p.weightUnit, //重量单位
                weight: p.netWeight * this.baseForm.productNumber //重量
              };
              list.push(obj);
            }
            if (list.length > 0 && list[0].categoryCode) {
              // this.$refs.table12.setData(list);
              this.sourceList = list;
              this.packingList = list;
              let packList = this.$refs.table12.getData();
              this.getFullInspectionWeight(packList);
            }

            // this.$refs.table12.setData(list);
            // let packList = this.$refs.table12.getData();
            // console.log(list);
            // console.log(1654646);
            // this.getFullInspectionWeight(packList);
            // this.getFullInspectionWeight(list);
          } else {
            if (this.$refs.table12) {
              let packingList = this.$refs.table12.getData();
              if (
                Math.ceil(Number(this.baseForm.productNumber || 0)) ===
                packingList.length
              ) {
                console.log(
                  '--->',
                  Math.ceil(Number(this.baseForm.productNumber || 0))
                );
                console.log('--->', packingList.length);
                await this.handleUnpackCase(packingList);
                return;
              } else {
                this.getFullInspectionWeight(packingList);
              }
            }
            // let packingList = this.$refs.table12.getData();
            // if (
            //   Math.ceil(Number(this.baseForm.productNumber || 0)) ===
            //   packingList.length
            // ) {
            //   await this.handleUnpackCase(packingList);
            //   return;
            // } else {
            //   this.getFullInspectionWeight(packingList);
            // }
          }
        }

        //全检时 计量时
        else if (
          this.baseForm.qualityMode == 1 &&
          this.baseForm.inspectionStandards == 1 &&
          this.btnType != 'detail'
        ) {
          this.sampleList = [];
          console.log(this.baseForm, '---isUnpack---');
          if (this.baseForm.productNumber) {
            console.log('数据777777');
            if (this.$refs.table12) {
              // this.$refs.table12.setData([]);
              this.sourceList = [];
              this.packingList = [];
              let nums = Number(this.baseForm.productNumber);
              let p = this.productItem;
              let list = [];

              for (let i = 0; i < nums; i++) {
                let obj = {
                  id: p.id,
                  batchNo: p.batchNo,
                  categoryCode: p.code, //编码
                  categoryName: p.name, //名称
                  measureQuantity: 1,
                  measureUnit: p.measuringUnit, //计量单位
                  weightUnit: p.weightUnit, //重量单位
                  weight: p.netWeight //重量
                };
                list.push(obj);
              }
              console.log('数据666666');
              // this.$refs.table12.setData(list);
              this.sourceList = list;
              this.packingList = list;
              let packList = this.$refs.table12.getData();
              await this.handleUnpackCase(packList);

              return;
            }
            // this.$refs.table12.setData([]);
            // let nums = Number(this.baseForm.productNumber);
            // let p = this.productItem;
            // let list = [];

            // for (let i = 0; i < nums; i++) {
            //   let obj = {
            //     id: p.id,
            //     batchNo: p.batchNo,
            //     categoryCode: p.code, //编码
            //     categoryName: p.name, //名称
            //     measureQuantity: 1,
            //     measureUnit: p.measuringUnit, //计量单位
            //     weightUnit: p.weightUnit, //重量单位
            //     weight: p.netWeight //重量
            //   };
            //   list.push(obj);
            // }
            // console.log('数据666666');
            // this.$refs.table12.setData(list);
            // let packList = this.$refs.table12.getData();
            // await this.handleUnpackCase(packList);

            // return;
          }
          // if (this.rowIds) {
          //   const res = await getInventoryListByPlanId({
          //     planId: this.rowIds,
          //     pageNum: 1,
          //     size: 5000
          //   });
          //   // console.log(res.list);
          //   if (res.list.length > 0) {
          //     await this.handleUnpackCase(res.list);
          //   }
          // } else {
          // await this.handleUnpackCase(packingList);
          // }

          // if (this.baseForm.isUnpack != null && this.baseForm.isUnpack != undefined && this.baseForm.isUnpack != '') {
          //   //拆包
          //   if (this.baseForm.isUnpack == 1) {
          //     await this.handleUnpackCase(packingList);
          //   } else if (this.baseForm.isUnpack == 0) {
          //     await this.updatePackingList(packingList);
          //   }
          // } else {
          //   console.log(this.isCheck, 'this.isCheck')
          //   if (!this.isCheck) {
          //     await this.handleUnpackCase(packingList);
          //   } else {
          //     await this.updatePackingList(packingList);
          //   }
          // }
          //全检 计重时
        } else if (
          this.baseForm.qualityMode == 1 &&
          this.baseForm.inspectionStandards == 2 &&
          this.btnType != 'detail'
          // (this.btnType != 'detail' || this.btnType != 'edit')
          // this.btnType == 'add'
        ) {
          this.sampleList = [];
          let list = [];
          if (this.baseForm.productNumber) {
            let p = this.productItem;
            let obj = {
              id: p.id,
              batchNo: p.batchNo,
              categoryCode: p.code, //编码
              categoryName: p.name, //名称
              measureQuantity: this.baseForm.productNumber, //计量数量
              measureUnit: p.measuringUnit, //计量单位
              weightUnit: p.weightUnit, //重量单位
              weight: p.netWeight * this.baseForm.productNumber //重量
            };
            list.push(obj);
          }
          console.log('数据55555');
          console.log(list);
          if (list.length > 0 && list[0].categoryCode) {
            // this.$refs.table12.setData(list);
            this.sourceList = list;
            this.packingList = list;
            let packList = this.$refs.table12.getData();
            this.getFullInspectionWeight(packList);
          }
          // this.$refs.table12.setData(list);
          // let packList = this.$refs.table12.getData();
          // this.getFullInspectionWeight(packList);
          // this.getFullInspectionWeight(packList);
        } else {
          console.log('进来了这里');

          this.sampleList = [];
        }
      },

      //全检 计重时生成样品清单
      async getFullInspectionWeight(packingList) {
        this.updatePackingList(packingList);
      },

      //拆包处理样品清单数据
      async handleUnpackCase(packingList) {
        if (this.baseForm.type == '3') {
          this.getFullInspectionWeight(packingList);
        } else {
          const num = Number(this.baseForm.productNumber || 0);
          console.log('num:' + num);
          if (num) {
            await this.getUnpackSamList(packingList, num);
          }
        }
      },
      //获取样品编码
      async getSampleCode() {
        return await getCode('sample_code');
      },

      // 创建计量数量为1的样品清单函数，用于计数类型的
      async createSampleList(list) {
        if (this.baseForm.qualityMode != null) {
          const ProductSampleList = [];
          console.log(list, 'list');
          for (const oldItem of list) {
            const count = oldItem.measureQuantity;
            const newMeasureQuantity = oldItem.measureQuantity / count;
            const newWeight = parseFloat((oldItem.weight / count).toFixed(2));

            console.log(typeof oldItem.qualitySampleTemplateList, 'ssssss');

            // 遍历新数组设置 qualityResults 默认值
            this.schemeList.forEach((item) => {
              if (typeof item === 'object' && item !== null) {
                item.qualityResults = 1; // 设置默认值
              }
              delete item.id;
            });

            console.log(oldItem, 'oldItem');
            console.log(count, newMeasureQuantity, newWeight);
            delete oldItem.id;

            if (
              oldItem.qualitySampleTemplateList == undefined ||
              oldItem.qualitySampleTemplateList == null ||
              oldItem.qualitySampleTemplateList.length == 0
            ) {
              oldItem.qualitySampleTemplateList = JSON.parse(
                JSON.stringify(this.schemeList)
              );
              for (let i = 0; i < count; i++) {
                ProductSampleList.push({
                  ...oldItem,
                  measureQuantity: newMeasureQuantity,
                  weight: newWeight,
                  sampleCode: await this.getSampleCode(),
                  qualitySampleTemplateList: JSON.parse(
                    JSON.stringify(this.schemeList)
                  )
                });
              }
              console.log(ProductSampleList, 'ProductSampleList');
              this.sampleList = ProductSampleList;
              const pNum = ProductSampleList.reduce((sum, item) => {
                return sum + Number(item.weight || 0);
              }, 0);
              this.baseForm.totalWeight = parseFloat(pNum.toFixed(2));
            } else {
              for (let i = 0; i < count; i++) {
                ProductSampleList.push({
                  ...oldItem,
                  measureQuantity: newMeasureQuantity,
                  weight: newWeight,
                  sampleCode: await this.getSampleCode(),
                  qualitySampleTemplateList: JSON.parse(
                    JSON.stringify(oldItem.qualitySampleTemplateList)
                  )
                });
              }
              console.log(ProductSampleList, 'ProductSampleList');
              this.sampleList = ProductSampleList;
              const pNum = ProductSampleList.reduce((sum, item) => {
                return sum + Number(item.weight || 0);
              }, 0);
              this.baseForm.totalWeight = parseFloat(pNum.toFixed(2));
            }
          }
        }
      },

      //更新样品清单数据
      async updatePackingList(list) {
        // 计量类型1是数量，2是重量
        if (this.baseForm.inspectionStandards == 1) {
          this.createSampleList(list);
        }

        if (this.baseForm.inspectionStandards == 2) {
          for (let i = 0; i < list.length; i++) {
            list[i].sampleCode = await this.getSampleCode();
          }
          // this.updatePackingList(list, this.form.total);
          // this.handleWeightFullSample(this.form.total);
        }

        console.log(this.baseForm.inspectionStandards);

        this.sampleList = list;
        this.baseForm.sampleNumber = list.length;
        this.samplePagination.currentPage = 1;
        this.samplePagination.total = list.length;

        // const sampleProportion = this
        // this.samplePagination.total = this.sampleList.length;
      },

      async getUnpackSamList(list, num) {
        console.log(list, num);
        let data = [];
        list.forEach((oldItem, index) => {
          const newMeasureQuantity =
            oldItem.measureQuantity / this.baseForm.productNumber;
          const newWeight = parseFloat(
            (oldItem.weight / this.baseForm.productNumber).toFixed(2)
          );

          // 将 measureQuantity 转换为数字
          const measureQuantity = Number(oldItem.measureQuantity);
          // 判断是否有小数部分
          const hasDecimal = measureQuantity % 1 !== 0;
          let roundedQuantity;
          if (hasDecimal) {
            // 有小数部分，向上取整
            roundedQuantity = Math.ceil(measureQuantity);
          } else {
            roundedQuantity = measureQuantity;
          }

          delete oldItem.id;

          for (let i = 0; i < roundedQuantity; i++) {
            data.push({
              ...oldItem,
              // measureQuantity: 1,
              weight: this.netWeight || 0
              // weight:
              //   num - index >= 1
              //     ? this.netWeight
              //     : ((num * 100000 - index * 100000) / 100000) * this.netWeight
            });
          }
        });

        console.log(data, '样品数据-条数', num);
        await this.updatePackingList(data);
      },
      async getQualityTemplate(productCode, ids) {
        await getQualityTemplateList({
          type: this.baseForm.type,
          productCode: productCode,
          qualityQlanId: ids
        }).then((res) => {
          if (Object.keys(res).length === 0) {
            return;
          }

          this.baseForm.sampleProportion = res.checkProportion;
          // this.baseForm.inspectionStandards = res?.inspectionStandards;

          let combinedList = [];
          for (let i = 0; i < res.qualityTemplateVOList.length; i++) {
            res.qualityTemplateVOList[i].inspectionItemVOList =
              res.qualityTemplateVOList[i]?.inspectionItemVOList.map((item) => {
                item.templateId = res.qualityTemplateVOList[i]?.id;
                item.qualitySchemeTemplateCode =
                  res.qualityTemplateVOList[i]?.qualitySchemeTemplateCode;
                item.qualitySchemeTemplateName =
                  res.qualityTemplateVOList[i]?.qualitySchemeTemplateName;

                delete item.id;

                return {
                  ...item
                };
              });
            combinedList = combinedList.concat(
              res.qualityTemplateVOList[i].inspectionItemVOList
            );
            console.log(combinedList, '质检方案');
            this.schemeList = combinedList;
            this.schemePagination.currentPage = 1;
            this.schemePagination.total = this.schemeList.length;
          }
        });
      },
      //来料列表表格选择事件
      handleSelectionChange(selection) {
        console.log(selection, '勾选');
        this.selectedList = selection;
        //如果取小样
        if (this.conditionType == 2) {
          if (this.isCheck) {
            this.formData.portion = selection.length;
            this.baseForm.sampleNumber = selection.length;
          } else {
            this.baseForm.sampleNumber = this.formData.portion;
          }
          const data1 = this.$refs.table12.getData();
          this.$set(this.formData, 'sampleUnit', data1[0]?.measureUnit);
          this.$set(this.baseForm, 'sampleMeasureUnit', data1[0]?.measureUnit);
        } else if (this.conditionType == 1) {
          this.baseForm.sampleNumber = this.formData.portion;
          this.formData.number = 0;
        }
      },
      //取样方式选择
      async handleSampleNumber(val) {
        console.log(val, 'val');
        this.conditionType = val;
        //清空样品清单列表
        this.sampleList = [];
        // const dataS = this.$refs.table12.getData();
        //取整样
        // if (val == 1) {
        //   if (this.selectedList.length == 0) {
        //     this.$message.warning('请先选择样品！');
        //   } else {
        //     if (this.isCheck) {
        //       for (let i = 0; i < this.selectedList.length; i++) {
        //         for (let j = 0; j < this.selectedList[i].measureQuantity; j++) {
        //           // this.selectedList[i].sampleCode = await this.getSampleCode();
        //           this.sampleList.push({
        //             ...this.selectedList[i],
        //             sampleCode: await this.getSampleCode(),
        //             measureQuantity: 1,
        //             weight: this.selectedList[i].weight / this.selectedList[i].measureQuantity
        //           });
        //         }
        //       }
        //     } else {
        //       for (let i = 0; i < this.selectedList.length; i++) {
        //         let forNum = 0;
        //         if (this.formData.portion != null && this.formData.portion != '') {
        //           forNum = this.formData.portion;
        //         } else {
        //           forNum = this.selectedList[i].measureQuantity;
        //         }
        //         for (let j = 0; j < forNum; j++) {
        //           // this.selectedList[i].sampleCode = await this.getSampleCode();
        //           this.sampleList.push({
        //             ...this.selectedList[i],
        //             sampleCode: await this.getSampleCode(),
        //             measureQuantity: 1,
        //             weight: this.selectedList[i].weight / this.selectedList[i].measureQuantity
        //           });
        //         }
        //       }

        //     }
        //     this.formData.portion = this.sampleList.length;
        //     this.activeName = '2';
        //     this.$message.success('取样成功！');
        //   }
        // } else if (val == 2) {
        //   this.formData.sampleUnit = dataS[0].measureUnit;

        //   this.$refs.table12.clearSelection();
        //   //小样
        //   if (this.selectedList.length == 0) {
        //     this.$message.warning('请先选择样品！');
        //   } else {
        //     if (this.formData.number == null || this.formData.sampleUnit == '') {
        //       this.$message.warning('请先选择取样的数量和单位！');
        //     }
        //   }
        // }
      },

      handleInputNumber(val) {
        let packingList = this.$refs.table12.getData();

        const maxValue =
          packingList.length > 1
            ? packingList.length
            : packingList[0].measureQuantity;

        if (val > maxValue) {
          this.$message.warning('数量不能大于计量数量！');
          this.formData.number = maxValue;
          return;
        }
      },

      // 整样输入框事件
      handleInput(val) {
        if (val == 0 || val == '' || val == null) {
          this.$refs.table12.clearSelection();
          return;
        }
        let packingList = this.$refs.table12.getData();
        if (!packingList || packingList.length === 0) {
          return;
        }
        // 计算 packingList 中 measureQuantity 字段的总和
        const measureQuantitySum = packingList.reduce((sum, item) => {
          const quantity = Number(item.measureQuantity) || 0;
          return sum + quantity;
        }, 0);
        const portion = Number(this.formData.portion);
        // 清空当前选中
        this.$refs.table12.clearSelection();
        if (this.conditionType == 2) {
          // 取小样
          // 确保 portion 不超过数据列表长度
          const safePortion = Math.min(portion, packingList.length);
          if (this.isCheck) {
            // 是否拆包  false 不拆包
            if (portion > packingList.length) {
              this.$message.warning('取样数量不能大于来源清单数量！');
              this.formData.portion = packingList.length;
            }
          } else {
            const maxQuantity = Number(packingList[0].measureQuantity);
            if (portion > maxQuantity) {
              this.$message.warning('取样数量不能大于计量数量！');
              this.formData.portion = maxQuantity;
            }
          }
          // 选中前 safePortion 行
          packingList.slice(0, safePortion).forEach((row) => {
            this.$refs.table12.toggleRowSelection(row, true);
          });
        } else if (this.conditionType == 1) {
          // 确保 portion 不超过数据列表长度
          const safePortion = Math.min(portion, measureQuantitySum);
          if (portion > measureQuantitySum) {
            this.$message.warning('取样数量不能大于计量数量！');
            this.formData.portion = measureQuantitySum;
          }
          // 选中前 safePortion 行
          packingList.slice(0, safePortion).forEach((row) => {
            this.$refs.table12.toggleRowSelection(row, true);
          });
        }
      },
      // 选中物品后触发了这个事件
      async getCategoryInfo(val) {
        console.log(this.baseForm.type, this.baseForm.planSource);
        // this.baseForm.isUnpack = val.categoryWms.isUnpack;
        console.log(val, '产品信息');
        if (this.baseForm.type == 2 && this.baseForm.planSource == '4') {
          if (val.category.id) {
            const res1 = await getProductSteup(val.category.id);

            const index = res1.findIndex(
              (item) => item.taskId == val.category.taskId
            );

            if (index) {
              const res2 = await getProductOrder({
                taskId: res1[index - 1].taskId,
                workOrderId: val.category.id
              });

              if (res2[0].semiProductList.length > 1) {
                this.baseForm.productNumber = res2[0].semiProductList.length;
              } else {
                this.baseForm.productNumber =
                  res2[0].semiProductList.measureQuantity;
              }
            }

            this.isConsumable = val.category.isConsumable;
            this.netWeight = val.category.netWeight;
            this.productItem = val.category;

            console.log('+++++++++');
            this.handleSampleList();
            return;
          }
        }

        this.isConsumable = val.category.isConsumable;
        this.netWeight = val.category.netWeight;
        this.productItem = val.category; //产品信息
      },
      changeSamUnit(val) {
        console.log(val);
        this.$refs.baseInfoRefs.getsampleMeasureUnit(val);
      },

      calculateWeightAndQuantity(list) {
        console.log(list);
        this.baseForm.totalWeight = list.reduce((acc, pre) => {
          return pre.weight ? acc + Number(pre.weight) : acc;
        }, 0);
        this.baseForm.productNumber = list.reduce((acc, pre) => {
          return pre.measureQuantity ? acc + Number(pre.measureQuantity) : acc;
        }, 0);
      },

      //整样确认按钮-样品列表右上角确认按钮
      // handleExtractFull() {
      //   this.$refs.ruleForm.validate((valid) => {
      //     if (valid) {
      //       if (!this.selectedList || this.selectedList.length == 0) {
      //         this.$message.warning('请先选择样品！');
      //         return;
      //       }
      //       this.sampleList = []
      //       //取样条数
      //       let safePortion = Number(this.formData.portion);
      //       //计量数量
      //       let measureQ = this.formData.number || 1;
      //       //计量单位
      //       let unit = this.formData.sampleUnit;
      //       //抽检计量整样小样或者抽检计重小样
      //       if ((this.baseForm.inspectionStandards === 1) || (this.baseForm.inspectionStandards === 2 && this.conditionType == 2)) {
      //         if (this.conditionType == 2) {
      //           if (measureQ <= 0) {
      //             this.$message.info('取样计量数量必须大于0');
      //             return
      //           }
      //         }
      //         // 计算总计量数量
      //         const totalQuantity = this.selectedList.reduce((sum, item) => sum + item['measureQuantity'], 0);
      //         // 验证取样总量不超过总计量数量,只有计量单位相同才进行验证
      //         if (this.selectedList[0].measureUnit == unit || this.conditionType == 1) {
      //           if (measureQ * safePortion > totalQuantity) {
      //             this.$message.info('取样计量数量不能大于总计量数量');
      //             return
      //           }
      //           // 验证每条数据的计量数量都大于等于取样计量数量
      //           for (const item of this.selectedList) {
      //             if (item['measureQuantity'] < measureQ) {
      //               this.$message.info(`条目计量数量小于取样计量数量`);
      //               return
      //             }
      //           }
      //         }

      //         if (unit === 'KG') {
      //           let totalMaxPossible = 0;
      //           this.selectedList.map(item => {
      //           const maxPossible = item['measureQuantity'] / measureQ;
      //           totalMaxPossible += maxPossible;});
      //           if (totalMaxPossible < safePortion) {
      //             this.formData.portion = totalMaxPossible;
      //             return this.$message.info(`最大取样条数为${totalMaxPossible}`);
      //           }
      //           // 计算总重量
      //           let totalWeight = this.selectedList.reduce((sum, item) => sum + item['weight'], 0);
      //           let weightUnit = this.selectedList[0].weightUnit;
      //           if (weightUnit === 'G') {
      //             totalWeight = totalWeight / 1000
      //           }
      //           if (measureQ * safePortion > totalWeight) {
      //             this.$message.info('取样计量重量不能大于总计量重量');
      //             return
      //           }
      //           for (const item of this.selectedList) {
      //             let weight = weightUnit === 'G' ? item.weight / 1000 : item.weight
      //             if (weight < measureQ) {
      //               this.$message.info(`勾选条目重量小于取样重量`);
      //               return
      //             }
      //           }
      //         }

      //         this.getNewFullSampleList(Math.ceil(safePortion), measureQ, unit);
      //         //抽检计重整样
      //       } else if (this.baseForm.inspectionStandards === 2 && this.conditionType == 1) {
      //         for (const item of this.selectedList) {
      //           if (item['measureQuantity'] < safePortion) {
      //             this.$message.info(`所选的条目计量数量小于取样计量数量`);
      //             return
      //           }
      //         }
      //         let list = [];
      //         for (let i = 0; i < this.selectedList.length; i++) {
      //           list.push({
      //             ...this.selectedList[i],
      //             measureQuantity: safePortion, //作为计量数量
      //           });
      //         }
      //         this.updatePackingList(list);
      //       }
      //       this.activeName = '2'
      //     }
      //   });
      // },

      //从来源数组取样到目标数组
      async getNewFullSampleList(sampleCount, sampleQuantity, sampleUnit) {
        console.log(
          '从来源数组取样到目标数组',
          sampleCount,
          sampleQuantity,
          sampleUnit
        );
        const sourceArray = this.selectedList;
        // 检查单位是否匹配
        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;

        // 尽可能均匀地从各条目取样
        while (remainingCount > 0) {
          // 按剩余可取样比例排序
          items.sort(
            (a, b) =>
              b.remainingQuantity / b['measureQuantity'] -
              a.remainingQuantity / a['measureQuantity']
          );

          let distributed = false;

          for (const item of items) {
            if (
              (!isUnitMismatch && remainingCount > 0) ||
              (item.remainingQuantity >= sampleQuantity && remainingCount > 0)
            ) {
              // 添加到结果数组
              this.samplePagination.total = 0;
              let sampleCode = await this.getSampleCode();
              if (
                this.conditionType == 1 &&
                this.baseForm.inspectionStandards == 1
              ) {
                result.push({ ...item, measureQuantity: 1, sampleCode });
              } else if (
                this.conditionType == 2 &&
                (this.baseForm.inspectionStandards == 1 ||
                  this.baseForm.inspectionStandards == 2)
              ) {
                let weight = (item.weight / item.maxPossible).toFixed(2);
                result.push({
                  ...item,
                  measureQuantity: sampleQuantity,
                  measureUnit: sampleUnit,
                  sampleCode,
                  weight
                });
              }

              // 更新剩余数量
              if (!isUnitMismatch) {
                item.remainingQuantity -= sampleQuantity;
              }
              remainingCount--;
              distributed = true;
            }
          }

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

        console.log('样品清单', this.sampleList);
        console.log('样品清单List', result);
        this.sampleList = result;

        this.samplePagination.total = result.length;

        this.baseForm.sampleNumber = this.sampleList.length; // 更新样品数量

        this.changeSamUnit(sampleUnit);
      },

      //抽样确认按钮事件-样品列表右上角确认按钮
      handleSampleSubmit() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.sampleList = [];
            this.baseForm.sampleMeasureUnit = this.formData.sampleUnit;
            let measureQ = this.formData.number;
            let unit = this.formData.sampleUnit;
            let nums = Number(this.formData.portion);

            console.log(measureQ, unit, nums, 'measureQ, unit, nums');
            this.getNewFullSampleList(nums, measureQ, unit);
            // if (this.conditionType == 1) {
            //   this.sampleList = this.selectedList
            // } else {
            //   let measureQ = this.formData.number;
            //   let unit = this.formData.sampleUnit;
            //   let nums = Number(this.formData.portion);
            //
            //   console.log(measureQ, unit, nums, 'measureQ, unit, nums')
            //   this.getNewSampleList(measureQ, unit, nums)
            // }
            this.activeName = '2';
          }
        });
      },

      //更新计量数量、单位后重新生成样品列表数据
      // async getNewSampleList(measureQ, unit, nums) {
      //   this.sampleList = [];
      //   if (!this.selectedList || this.selectedList.length == 0) {
      //     this.$message.warning('请先选择样品！');
      //     return;
      //   }

      //   if (!this.isCheck) {
      //     let measureQuantity = 1;
      //     if (this.conditionType == 2) {
      //       measureQuantity = this.formData.number;
      //     }
      //     for (let i = 0; i < nums; i++) {
      //       this.sampleList.push({
      //         ...this.selectedList[0],
      //         sampleCode: await this.getSampleCode(),
      //         measureQuantity: measureQuantity,
      //         measureUnit: unit,
      //         weight: this.netWeight || 0
      //       });
      //     }
      //   } else {
      //     if (this.conditionType == 1) {
      //       measureQ = 1;
      //     }
      //     for (let i = 0; i < this.selectedList.length; i++) {
      //       this.sampleList.push({
      //         ...this.selectedList[i],
      //         sampleCode: await this.getSampleCode(),
      //         measureQuantity: measureQ,
      //         measureUnit: unit,
      //         weight: this.netWeight || 0
      //       });
      //     }

      //   }
      // },
      //监听类型变化
      resetTable() {
        this.$nextTick(() => {
          this.table1();
          this.table2();
        });
      },
      table1() {
        this.$refs.table12.setData([]);
        this.sourceList = [];
        this.packingList = [];
        this.schemeList = [];
      },
      table2() {
        this.$nextTick(() => {
          // if (this.btnType == 'edit' && !this.isOnce) {
          //   this.isOrder = false;
          this.sampleList = [];
          // }
        });
      },
      resetForm() {
        this.baseForm = { ...this.defaultForm() };
      },
      handleClose() {
        this.$nextTick(() => {
          // 关闭后，销毁所有的表单数据
          this.resetForm();
          this.resetTable();
          this.isScheme = true;
          this.isOrder = true;
          this.packingList = [];
          this.sampleList = [];
          this.samplePagination = {
            currentPage: 1,
            pageSize: 10,
            total: 0
          };
          (this.schemeList = []),
            (this.schemePagination = {
              currentPage: 1,
              pageSize: 10,
              total: 0
            });
          // 表单验证规则
          this.visible = false;
          this.btnType = null;
          this.title = null;
          this.loading = false;
          this.listPage = [];
          this.activeName = '1';
          this.selectedList = [];
          this.isCheck = false; // 是否拆包  false 不拆包 true 拆包
          this.rowIds = '';
          (this.formData = {
            number: 1,
            sampleUnit: '',
            portion: null
          }),
            (this.rules = {
              number: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ],
              sampleUnit: [
                {
                  required: true,
                  message: '请选择样品单位',
                  trigger: 'change'
                }
              ],
              portion: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'blur'
                }
              ]
            });
          this.isConsumable = ''; //0 单件 1批量
          this.netWeight = ''; // 净重
          this.conditionType = null;
          this.isFormNumber = true;
          this.sampleListCode = '';
          this.productItem = {}; //产品信息
          this.$refs['baseInfoRefs'] &&
            this.$refs['baseInfoRefs'].$refs.form1.resetFields();
          this.visible = false;
          this.baseForm.groupId = '';
          this.baseForm.qualityMode = '';
          this.baseForm = { ...this.defaultForm() };
          this.isChangeNumber = true;
          this.isChangeType = true;
          this.isOnce = true;
          this.dimensionType = '';
          this.isPackingList = true;
          this.isSampleList = true;
        });
      },

      /* 保存编辑 */
      handleSave() {
        this.$refs.baseInfoRefs.$refs.form1.validate((valid) => {
          if (!valid) {
            return false;
          }

          this.loading = true;
          if (this.baseForm.isUnpack == null || this.baseForm.isUnpack == '') {
            this.baseForm.isUnpack = this.isCheck ? 1 : 2;
          }
          this.baseForm.conditionType = this.conditionType;
          // isSampleList: true,
          // isPackingList: true,

          console.log(this.isSampleList);
          console.log(this.isPackingList);
          console.log(this.$refs.table12.getData());

          const qualityListData =
            this.btnType == 'add'
              ? this.sourceList
              : this.btnType == 'edit' && this.isPackingList
              ? []
              : this.sourceList;
          const sampleListData =
            this.btnType == 'add'
              ? this.sampleList
              : this.btnType == 'edit' && this.isSampleList
              ? this.newSampleList
              : this.sampleList;

          // let params = {
          //   ...this.baseForm,
          //   qualityInventoryList: this.$refs.table12.getData(),
          //   sampleList: this.sampleList,
          //   planTemplateList: this.schemeList
          // };

          let params = {
            ...this.baseForm,
            qualityInventoryList: qualityListData,
            sampleList: sampleListData,
            planTemplateList: this.schemeList
          };

          console.log(params, 'params');

          if (this.btnType == 'issued' && this.schemeList.length < 1) {
            this.$message.warning('质检方案不能为空！');
            this.loading = false;
            return;
          }
          let URL =
            this.btnType == 'add' ? save : this.btnType == 'edit' ? update : '';
          console.log(params, 'params');

          URL(params)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.handleClose();
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },
      handleIssued() {
        if (this.sampleList.length == 0) {
          this.$message.warning('样品清单为空！先进行修改操作再下发！');
          return;
        }
        this.$refs.baseInfoRefs.$refs.form1.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;

          if (this.baseForm.isUnpack == null || this.baseForm.isUnpack == '') {
            this.baseForm.isUnpack = this.isCheck ? 1 : 2;
          }
          this.baseForm.conditionType =
            this.conditionType ?? this.kkconditionType;
          // let params = {
          //   ...this.baseForm,
          //   qualityInventoryList: this.$refs.table12.getData(),
          //   sampleList: this.sampleList,
          //   planTemplateList: this.schemeList
          // };
          // const qualityListData =
          //   this.btnType == 'add'
          //     ? this.sourceList
          //     : this.btnType == 'edit' && this.isPackingList
          //     ? []
          //     : this.sourceList;
          console.log(this.newSampleList, 'newSampleList');
          const qualityListData = this.sourceList;
          const sampleListData =
            this.btnType == 'add'
              ? this.sampleList
              : this.btnType == 'issued' && this.isSampleList
              ? this.newSampleList
              : this.sampleList;

          // let params = {
          //   ...this.baseForm,
          //   qualityInventoryList: this.$refs.table12.getData(),
          //   sampleList: this.sampleList,
          //   planTemplateList: this.schemeList
          // };
          let params = {
            ...this.baseForm,
            qualityInventoryList: qualityListData,
            sampleList: sampleListData,
            planTemplateList: this.schemeList
          };

          console.log(params, 'params');

          if (this.btnType == 'issued' && this.schemeList.length < 1) {
            this.$message.warning('质检方案不能为空！');
            this.loading = false;
            return;
          }

          planIssued(params)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.handleClose();
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },
      // 样品列表分页方法
      async handleSampleSizeChange(val) {
        this.samplePagination.pageSize = val;
        this.samplePagination.currentPage = 1;
        if (this.rowIds && this.isOrder) {
          await this.getSampleList(this.rowIds);
        }
        //操作行点击时查询样品
      },
      async handleSampleCurrentChange(val) {
        this.samplePagination.currentPage = val;
        if (this.rowIds && this.isSampleList) {
          await this.getSampleList(this.rowIds);
        }
      },
      // 质检方案分页方法
      async handleSchemeSizeChange(val) {
        this.schemePagination.pageSize = val;
        this.schemePagination.currentPage = 1;
        //操作行点击时查询质检
        if (this.rowIds && this.isScheme) {
          await this.getTemplateList(this.rowIds);
        }
      },
      async handleSchemeCurrentChange(val) {
        this.schemePagination.currentPage = val;
        //操作行点击时查询质检
        if (this.rowIds && this.isScheme) {
          await this.getTemplateList(this.rowIds);
        }
      },
      //检验方式改变时，重新获取样品列表
      changeModel(val) {
        console.log('更改检验方式');
        this.baseForm.qualityMode = val;
        this.isSampleList = false;
        if (this.btnType != 'issued') {
          this.baseForm.sampleNumber = '';
        }

        if (this.baseForm.type == '3') {
          console.log(this.sourceList, this.dimensionType, '更改检验方式223');
          if (
            this.sourceList &&
            this.dimensionType &&
            this.baseForm.qualityMode == '1'
          ) {
            // const listData = this.$refs.table12.getData();
            console.log(this.sourceList, '成品检验订单数据');
            this.changesStokledgerNumberModal(
              this.sourceList,
              this.dimensionType,
              'type'
            );
            return;
          } else if (
            this.sourceList &&
            this.dimensionType &&
            this.baseForm.qualityMode == '2'
          ) {
            this.sampleList = [];
          } else {
            if (
              this.baseForm.qualityMode == '1' &&
              this.sourceList.length > 1
            ) {
              this.changesStokledgerNumberModal(this.sourceList, '3', 'type');
            } else if (
              this.baseForm.qualityMode == '2' &&
              this.sourceList.length > 1
            ) {
              this.sampleList = [];
            } else if (
              this.baseForm.qualityMode == '1' &&
              this.sourceList.length > 0
            ) {
              this.changesStokledgerNumberModal(
                this.sourceList,
                this.dimensionType,
                'type'
              );
            } else {
              this.sampleList = [];
            }
          }

          // if (this.$refs.table12 && this.dimensionType) {
          //   const listData = this.$refs.table12.getData();
          //   console.log(listData, '成品检验订单数据');
          //   this.changesStokledgerNumberModal(
          //     listData,
          //     this.dimensionType,
          //     'type'
          //   );
          //   // if (this.dimensionType == 3) {
          //   //   if (this.baseForm.qualityMode == '1') {
          //   //     this.handleUnpackCase(val);
          //   //   } else if (this.baseForm.qualityMode == '2') {
          //   //     this.sampleList = [];
          //   //   }
          //   // } else {
          //   //   if (this.baseForm.qualityMode == '1') {
          //   //     this.handleUnpackCase(listData);
          //   //   } else if (this.baseForm.qualityMode == '2') {
          //   //     this.sampleList = [];
          //   //   }
          //   // }
          // }
          return;
        }
        // 全检
        if (this.baseForm.qualityMode == 1) {
          // console.log('+++++++++1');
          // this.handleSampleList();
          this.updatePackingList(this.sourceList);
        } else {
          this.sampleList = [];
        }
      },

      changeType() {
        this.isPackingList = false;
      },

      changeSource() {
        this.isSampleList = false;
      },

      //确定按钮
      handleExtractFull() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid || !this.validateSelection()) return;
          this.isSampleList = false;
          this.baseForm.sampleMeasureUnit = this.formData.sampleUnit;
          this.sampleList = [];
          const sampleCount = Number(this.formData.portion);
          const measureQ = this.formData.number || 1;
          const unit = this.formData.sampleUnit;
          // console.log(this.conditionType, this.baseForm.inspectionStandards);
          // console.log(this.isStandard1OrWeightSample())
          // console.log(this.isWeightStandardFullSample())
          try {
            if (this.isStandard1OrWeightSample()) {
              //抽检计量整样小样或者抽检计重小样
              if (!this.validateMeasureQuantity(measureQ, unit, sampleCount))
                return;
              if (unit === 'KG' && !this.validateWeight(measureQ, sampleCount))
                return; // 若计量单位为重量，还需验证总重量是否足够
              console.log('getNewFullSampleList');
              if (this.conditionType == '1' && this.baseForm.type == '3') {
                await this.handleWeightFullSample(sampleCount);
              } else {
                await this.getNewFullSampleList(
                  Math.ceil(sampleCount),
                  measureQ,
                  unit
                );
              }
            } else if (this.isWeightStandardFullSample()) {
              console.log('handleWeightFullSample');
              //抽检取计重取整样
              if (!this.validateSampleCount(sampleCount)) return;
              await this.handleWeightFullSample(sampleCount);
            }
            this.activeName = '2';
          } catch (error) {
            console.error('取样处理失败:', error);
            this.$message.error('取样处理失败');
          }
        });
      },
      validateSelection() {
        if (!this.selectedList?.length) {
          this.$message.warning('请先选择样品！');
          return false;
        }
        return true;
      },

      isStandard1OrWeightSample() {
        return (
          this.baseForm.inspectionStandards === 1 ||
          (this.baseForm.inspectionStandards === 2 && this.conditionType == 2)
        );
      },

      isWeightStandardFullSample() {
        return (
          this.baseForm.inspectionStandards === 2 && this.conditionType == 1
        );
      },

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

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

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

        return true;
      },

      validateWeight(measureQ, sampleCount) {
        let totalMaxPossible = 0;
        this.selectedList.forEach((item) => {
          totalMaxPossible += item.measureQuantity / measureQ;
        });

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

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

        console.log(measureQ * sampleCount, totalWeight);

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

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

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

        return true;
      },

      validateSampleCount(sampleCount) {
        // const invalidItem = this.selectedList.find(
        //   (item) => item.measureQuantity < sampleCount
        // );

        // const totalNumber = this.sourceList.reduce((acc, pro) => {
        //   return pro.measureQuantity ? acc + Number(pro.measureQuantity) : acc;
        // }, 0);

        const chooseNumber = this.selectedList.reduce((acc, pro) => {
          return pro.measureQuantity ? acc + Number(pro.measureQuantity) : acc;
        }, 0);

        const invalidItem = chooseNumber < sampleCount;

        if (invalidItem) {
          this.$message.info('所选的条目计量数量小于取样计量数量');
          return false;
        }
        return true;
      },

      async handleWeightFullSample(sampleCount) {
        // console.log(sampleCount, 'sampleCount');
        // console.log(this.selectedList, 'this.selectedList');
        let currentNum = sampleCount - this.selectedList.length;
        let currentNum1 = sampleCount;
        let list = [];
        this.selectedList.forEach((item) => {
          if (sampleCount >= this.selectedList.length) {
            list.push({
              ...item,
              measureQuantity: 1, //作为计量数量
              weight: item.singleWeight
                ? (Number(item.singleWeight) * Number(sampleCount)).toFixed(2)
                : item.outboundNum
                ? (
                    (Number(item.weight) / Number(item.outboundNum)) *
                    Number(sampleCount)
                  ).toFixed(2)
                : item.weight
            });
          } else {
            if (list.length < sampleCount) {
              list.push({
                ...item,
                measureQuantity: currentNum1 > 1 ? 1 : currentNum1, //作为计量数量
                weight: item.singleWeight
                  ? (Number(item.singleWeight) * Number(sampleCount)).toFixed(2)
                  : item.outboundNum
                  ? (
                      (Number(item.weight) / Number(item.outboundNum)) *
                      Number(sampleCount)
                    ).toFixed(2)
                  : item.weight
              });
              currentNum1 -= 1;
            }
          }
          if (sampleCount > this.selectedList.length) {
            list.forEach((item) => {
              if (currentNum > 0) {
                let data = this.selectedList.find((val) => val.id == item.id);
                item['measureQuantity'] =
                  data.measureQuantity - 1 - currentNum > 0
                    ? currentNum + 1
                    : data.measureQuantity;
                currentNum = currentNum - (data.measureQuantity - 1);
              }
            });
          }

          // ...item,
          // // measureQuantity: sampleCount,
          // weight: item.singleWeight
          //   ? (Number(item.singleWeight) * Number(sampleCount)).toFixed(2)
          //   : item.outboundNum
          //   ? (
          //       (Number(item.weight) / Number(item.outboundNum)) *
          //       Number(sampleCount)
          //     ).toFixed(2)
          //   : item.weight
          // weight: item.singleWeight ? Number(item.singleWeight) : item.weight
        });
        // if (this.selectedList.length > sampleCount) {
        //   const newList = list.splice(0, sampleCount);
        //   await this.updatePackingList(newList);
        // } else {
        //   await this.updatePackingList(list);
        // }
        await this.updatePackingList(list);
      },
      handDel(index) {
        console.log(index);
        this.schemeList.splice(index, 1);
      }
    }
  };
</script>

<style lang="scss" scoped>
  .location-warp {
    display: flex;

    .detail {
      margin-left: 10px;
    }
  }

  :deep(.el-form-item__content .el-input-group__prepend) {
    background-color: #fff;
  }

  :deep(
      .el-dialog:not(.ele-dialog-form)
        .el-dialog__body
        .el-form
        .el-form-item:last-child
    ) {
    margin-bottom: 22px;
  }

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

  .el-pagination {
    padding: 12px 16px;
    background: #fff;
    border: 1px solid#ebeef5;
    border-top: none;
  }

  .flex {
    display: flex;
    align-items: center;
  }
</style>
