<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    width="80%"
    append-to-body
    :maxable="true"
    @close="cancel"
  >
    <div class="switch" v-if="type == 'view'">
      <div class="switch_left">
        <ul>
          <li
            v-for="item in tabOptions"
            :key="item.key"
            :class="{ active: activeComp == item.key }"
            @click="activeComp = item.key"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div>
    <el-form
      v-show="activeComp === 'main'"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="el-form-box"
      :disabled="type == 'view'"
    >
      <header-title title="基本信息"></header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="质检工单编码：" prop="qualityWorkOrderCode">
            <el-input
              :disabled="!isSampleRecord || (isSampleRecord && type != 'add')"
              readonly
              v-model="form.qualityWorkOrderCode"
              placeholder=" "
              @click.native="$refs.inspectionWorkDialog.open()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质检工单名称：" prop="qualityWorkOrderName">
            <el-input
              disabled
              v-model="form.qualityWorkOrderName"
              placeholder=" "
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="来源单号：" prop="sourceCode">
            <el-input
              disabled
              :value="form.qualityPlanCode || form.workOrderCode"
              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-col :span="8">
          <el-form-item label="总数：" prop="total">
            <el-input disabled v-model="form.total" placeholder=" ">
              <template slot="append">
                {{ tableList[0]?.measureUnit }}
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="样品数：" prop="sampleQuantity">
            <el-input disabled v-model="form.sampleQuantity" placeholder=" ">
              <template slot="append">
                {{ form.qualityMode == 1 ? form.measureUnit : form.unit }}
              </template>
            </el-input>
          </el-form-item>
        </el-col> -->
      </el-row>
      <header-title title="来源清单"></header-title>
      <ele-pro-table
        ref="sourceTable"
        :columns="tableColumns"
        :datasource="tableList"
        :initLoad="false"
        :needPage="false"
        height="300px"
        full-height="calc(100vh - 120px)"
        :selection.sync="selection"
      >
        <template v-slot:toolbar>
          累计取样数量：{{ workSampleQuantity
          }}{{
            form.conditionType == '1' ? tableList[0]?.measureUnit : form.unit
          }}
        </template>
      </ele-pro-table>
      <header-title title="请样信息"> </header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="请样目的：" prop="pleasePurpose">
            <el-input
              v-model="form.pleasePurpose"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="请样数量：" prop="pleaseQuantity">
            <el-input v-model="form.pleaseQuantity" placeholder="请输入">
              <template slot="append">
                {{ tableList[0]?.measureUnit }}
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="4">
          <el-form-item label="单位：" prop="pleaseUnit">
            <DictSelection
              dictName="计量单位"
              clearable
              v-model="form.pleaseUnit"
              filter-placeholder="请输入计量单位搜索"
              @change="changeSamUnit"
            ></DictSelection>
          </el-form-item>
        </el-col> -->
      </el-row>
      <header-title title="取样信息"> </header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="质检方式：" prop="qualityMode">
            <DictSelection
              dictName="取样类型"
              v-model="form.qualityMode"
              @change="handleQualityModeChange"
              :disabled="form.isFirstSampling != '1'"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="记录方法：" prop="recordingMethod">
            <el-select
              style="width: 100%"
              v-model="form.recordingMethod"
              placeholder="请选择"
              :disabled="form.isFirstSampling != '1'"
            >
              <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="conditionType">
            <el-select
              style="width: 100%"
              v-model="form.conditionType"
              placeholder="请选择"
              :disabled="form.isFirstSampling != '1'"
            >
              <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="quantity">
                <el-input
                  v-model="form.quantity"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="form.conditionType == 2">
              <el-form-item prop="unit" label-width="0">
                <DictSelection
                  dictName="计量单位"
                  clearable
                  :disabled="form.isFirstSampling != '1'"
                  v-model="form.unit"
                  filter-placeholder="请输入计量单位搜索"
                ></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="unit" label="单位">
                <el-select
                  v-model="form.packingUnit"
                  placeholder="请选择"
                  :disabled="form.isFirstSampling != '1'"
                >
                  <el-option
                    v-for="item in packingSpecificationOption"
                    :key="item.id"
                    :label="item.conversionUnit"
                    :value="item.id"
                    @click.native="handlePackingUnitChange(item)"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :span="4"
              style="text-align: right"
              v-if="form.conditionType == 2 && type != 'view'"
            >
              <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 && type != 'view'"
            >
              <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>
    <bpmDetail
      v-if="activeComp == 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></bpmDetail>
    <template v-slot:footer>
      <el-button
        type="primary"
        @click="save()"
        v-loading="loading"
        v-if="type != 'view'"
        >确认</el-button
      >

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

<script>
  const defForm = {
    code: '', //编码
    name: '', //名称
    conditionType: '',
    quantity: '',
    unit: '',
    portion: '',
    qualityMode: '',
    recordingMethod: 1,
    pleaseQuantity: '',
    pleasePurpose: '',
    pleaseUnit: '',
    sampleQuantity: '',
    qualityWorkOrderId: '',
    qualityWorkOrderCode: '',
    qualityWorkOrderName: '',
    isFirstSampling: ''
  };
  import {
    queryQualityInventory,
    queryQualityTempleContent
  } from '@/api/inspectionWork';
  import {
    samplingrecordSave,
    getById,
    samplingrecordUpdate,
    samplingRecordsPage
  } from '@/api/samplingRecords';
  import bpmDetail from '@/views/bpm/processInstance/detail.vue';
  import inspectionWorkDialog from '@/views/inspectionWork/components/inspectionWorkDialog.vue';
  import { getCodeList, getCode } from '@/api/login';
  export default {
    components: { bpmDetail, inspectionWorkDialog },
    props: {
      isSampleRecord: {
        default: false
      }
    },
    data() {
      return {
        form: { ...defForm },
        activeComp: 'main',
        tabOptions: [
          { key: 'main', name: '取样详情' },
          { key: 'bpm', name: '流程详情' }
        ],
        workSampleQuantity: 0,
        visible: false,
        loading: false,
        rules: {
          qualityWorkOrderCode: [
            { required: true, message: '请选择质检工单', trigger: 'change' }
          ],
          qualityMode: [
            { required: true, message: '请选择质检方式', trigger: 'change' }
          ],
          recordingMethod: [
            { required: true, message: '请选择记录方法', trigger: 'change' }
          ],
          conditionType: [
            { required: true, message: '请选择取样类型', trigger: 'change' }
          ],
          quantity: [{ required: true, message: '请输入', trigger: 'change' }],
          portion: [{ required: true, message: '请输入', trigger: 'change' }],
          unit: [{ 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: [],
        tableList: [],
        type: 'add',
        title: ''
      };
    },

    computed: {},
    created() {},
    methods: {
      handlePackingUnitChange(val) {
        this.$set(this.form, 'unit', val.conversionUnit);
      },
      async open(type, row) {
        this.activeComp = 'main';
        this.visible = true;
        this.type = type;
        this.title =
          type == 'add' ? '取样' : type == 'edit' ? '修改取样' : '详情';
        if (type == 'add') {
          if (row) {
            this.init(row);
          }
        } else {
          this.getById(row.id);
        }
      },
      async init(row) {
        let data = await samplingRecordsPage({
          qualityWorkOrderId: row.id
        });
        let list = data.list.filter((item) => item.status === 0);
        if (list?.length) {
          this.getById(list[0].id);
          this.type = 'edit';
          this.title = '修改取样';
        } else {
          row.sourceCode = row.qualityPlanCode || row.workOrderCode;
          this.form = JSON.parse(JSON.stringify(row));
          this.form.qualityWorkOrderId = row.id;
          this.form.qualityWorkOrderCode = row.code;
          this.form.qualityWorkOrderName = row.name;
          this.workSampleQuantity = Number(row.sampleQuantity) || 0;

          if (!data?.list.length) {
            this.form.isFirstSampling = 1;
          } else {
            this.$set(this.form, 'unit', data?.list[0].unit);
          }
          await this.datasource(data?.list[0]?.unit);
          await this.queryQualityTempleContent(
            !data?.list.length && row.qualityMode == 1
          );
        }
      },
      getById(id) {
        getById(id).then((res) => {
          this.workSampleQuantity =
            Number(res.qualityWorkOrderVO.sampleQuantity) || 0;
          [
            'id',
            'code',
            'name',
            'createTime',
            'createUserId',
            'status',
            'approvalStatus',
            'approvalUserId',
            'sampleQuantity',
            'processInstanceId'
          ].forEach((it) => {
            delete res.qualityWorkOrderVO[it];
          });
          this.form = { ...res, ...res.qualityWorkOrderVO };
          this.datasource(this.form.unit);
          this.queryQualityTempleContent();
          if (this.form.qualityMode == 2) {
            if (res.qualityWorkOrderVO.conditionType == 1) {
              // if (res.unit != res.qualitySampleList[0].measureUnit) {
              //   this.$set(this.form, 'portion', res.qualitySampleList.length);
              // } else {

              // }
              this.$set(this.form, 'portion', res.quantity);
              this.$set(this.form, 'quantity', 0);
            } else {
              this.$set(this.form, 'portion', res.copies);
              // this.$set(this.form, 'quantity', res.quantity / res.copies);
            }
          }

          this.sampleList = res.qualitySampleList;
        });
      },
      /* 查询质检模板内容 */
      async queryQualityTempleContent(is) {
        const res = await queryQualityTempleContent({
          qualityWorkerId: this.form.qualityWorkOrderId,
          page: 1,
          size: 10000
        });
        this.schemeList = res.list;
        if (is) {
          this.updatePackingList();
        }
      },
      cancel() {
        this.form = {
          ...defForm
        };
        this.schemeList = [];
        this.packingSpecificationOption = [];
        this.sampleList = [];
        this.tableList = [];

        this.visible = false;
      },
      changeParent(row) {
        this.init(row);
      },
      async datasource(unit) {
        const res = await queryQualityInventory({
          qualityWorkerId: this.form.qualityWorkOrderId,
          pageNum: 1,
          size: -1
        });

        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'
          });
        }
        if (unit) {
          this.$set(
            this.form,
            'packingUnit',
            listArr.find((item) => unit == item.conversionUnit)?.id
          );
        }
        this.form.pleaseUnit = res.list[0]?.measureUnit;
        res.list.map((el) => {
          el.weightProportion = el.weight
            ? (el.weight / el.measureQuantity).toFixed(4)
            : 0;
          el.weightProportion = el.weightProportion - 0;
        });
        this.packingSpecificationOption = listArr;
        this.tableList = res.list;
        return res;
      },

      handleSampleSubmit() {
        // this.$refs.ruleForm.validate((valid) => {
        // if (valid) {
        let params = {
          conditionType: this.form.conditionType,
          quantity: this.form.quantity,
          sampleUnit: this.form.unit,
          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 quantity = data.quantity || 1;
        const unit = data.sampleUnit;
        const sampleCount = Number(data.portion);
        try {
          // 2 取小样
          if (this.form.conditionType == 2) {
            if (!this.validateMeasureQuantity(quantity, unit, sampleCount))
              return; //取样数量验证
            if (unit === 'KG' && !this.validateWeight(quantity, sampleCount))
              return; // 若计量单位为重量，还需验证总重量是否足够
            await this.getNewFullSampleList(
              Math.ceil(sampleCount),
              // sampleCount,
              quantity,
              unit,
              specifications
            );
          } else {
            let isFlag = this.validateSampleQuantity(
              sampleCount,
              specifications
            );
            if (!isFlag) return;
            if (this.form.inspectionStandards == 1) {
              await this.getNewFullSampleList(
                Math.ceil(sampleCount),
                quantity,
                unit,
                specifications
              );
            } else {
              await this.handleWeightFullSample(sampleCount, specifications);
            }
          }
        } catch (error) {
          console.error('取样处理失败:', error);
          this.$message.error('取样处理失败');
        }
      },
      validateWeight(quantity, sampleCount) {
        let totalMaxPossible = 0;
        this.selection.forEach((item) => {
          totalMaxPossible += item.measureQuantity / quantity;
        });

        if (totalMaxPossible < sampleCount) {
          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 (quantity * 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 < quantity;
        });

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

        return true;
      },

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

        const totalQuantity =
          this.selection.reduce((sum, item) => sum + item.measureQuantity, 0) -
          this.workSampleQuantity;

        if (
          this.selection[0].measureUnit === unit &&
          quantity * sampleCount > totalQuantity
        ) {
          this.$message.info('取样计量数量不能大于总计量数量');
          return false;
        }

        const invalidItem = this.selection.find(
          (item) => item.measureQuantity < quantity
        );
        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 getCode('sample_code'),
              qualitySampleTemplateList
            });
          } else {
            if (dataList.length < sampleCount) {
              dataList.push({
                ...item,
                measureQuantity: currentNum1 > 1 ? 1 : currentNum1, //作为计量数量
                sampleCode: await getCode('sample_code'),
                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;
        this.getTotal();
      },
      // 小数点数据判断
      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);
        }
        this.getTotal();
      },
      // 当计量类型 是数量的时候 取整样 校验
      validateSampleQuantity(sampleCount, specifications) {
        let packingUnit = this.selection[0].packingUnit?.trim() || '';
        let totalS = 0;
        let measureQuantityCount = 0;
        let labelKey =
          packingUnit == specifications.conversionUnit.trim()
            ? 'packingQuantity'
            : 'measureQuantity';
        let labelName = labelKey == 'packingQuantity' ? '包装数量' : '计量数量';
        totalS = this.selection.reduce((total, el) => total + el[labelKey], 0);
        let formTotalS = this.tableList.reduce(
          (total, el) => total + el.measureQuantity,
          0
        );
        if (sampleCount > totalS) {
          this.$message.info(
            `所填的条目数量不能超过所选${labelName}总和${totalS}`
          );
          return false;
        }
        if (labelKey == 'packingQuantity') {
          measureQuantityCount =
            sampleCount * this.selection[0].measureQuantity;
        } else {
          measureQuantityCount = sampleCount;
        }
        if (measureQuantityCount > formTotalS - this.workSampleQuantity) {
          this.$message.info(
            `取样数量不能大于${formTotalS - this.workSampleQuantity} ${
              this.selection[0].measureUnit
            }`
          );
          return false;
        }
        return true;
      },

      handleQualityModeChange(val) {
        if (val == 1) {
          this.updatePackingList();
        } else {
          this.sampleList = [];
          this.getTotal();
        }
      },
      // 全检
      async updatePackingList() {
        let list = this.tableList;

        let sampleCount = this.form.total;

        const dataList = [];
        let count = list ? list.length : 0;
        console.log(count, 'count');
        const codeList = await this.batchCodes(count);
        for (const [index, item] of list.entries()) {
          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 >= list.length) {
          dataList.push({
            ...item,
            measureQuantity: item.measureQuantity, //作为计量数量
            sampleCode: codeList[index],
            qualitySampleTemplateList
          });
          // }
        }
        console.log(dataList, 'dataList');

        this.sampleList = dataList;
        this.getTotal();
      },
      getTotal() {
        this.form.sampleQuantity = this.sampleList
          .reduce((total, el) => total + Number(el.measureQuantity), 0)
          .toFixed(2);
        this.form.sampleWeight = this.sampleList
          .reduce((total, el) => total + Number(el.weight), 0)
          .toFixed(2);
      },
      async batchCodes(count) {
        if (count <= 0) return;
        let params = { count };
        const res = await getCodeList('sample_code', params);
        return res;
      },
      /* 保存编辑 */
      save() {
        if (this.type == 'add') {
          [
            'id',
            'code',
            'name',
            'createTime',
            'createUserId',
            'status',
            'approvalStatus',
            'approvalUserId'
          ].forEach((key) => {
            delete this.form[key];
          });
        }
        let data = JSON.parse(JSON.stringify(this.form));

        let api =
          this.type == 'add' ? samplingrecordSave : samplingrecordUpdate;
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (!this.sampleList.length) {
              this.$message.error('样品清单不能为空！');
              return;
            }
            //抽检
            if (data.qualityMode == 2) {
              //取整样
              if (data.conditionType == 1) {
                data.quantity = data.portion;
                // if (data.unit != data.measureUnit) {
                //   data.quantity = this.sampleList.reduce(
                //     (total, el) => total + Number(el.measureQuantity),
                //     0
                //   );
                // } else {
                //   data.quantity = this.form.portion;
                // }
                data.measureUnit = this.tableList[0].measureUnit;
              } else {
                data.measureUnit = data.unit;
                data.copies = data.portion;
                // data.quantity = data.quantity * data.copies;
              }
            }
            this.loading = true;

            api({
              ...data,
              sampleList: this.sampleList
            })
              .then((res) => {
                this.$message.success('操作成功');
                this.cancel();
                this.$emit('reload');
              })
              .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>
