<!-- 用户编辑弹窗 -->
<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" @resetTable="resetTable"
      @changeModel="changeModel" @getList="getList" @table2="table2" :packingLists="packingList"
      @getCategoryInfo="getCategoryInfo"></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"
            @selection-change="handleSelectionChange" :initLoad="false">
            <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 && conditionType == 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">
                    <el-form-item prop="number" label-width="0" style="margin-bottom: 0;">
                      <el-input v-model="formData.number" placeholder="请输入" size="mini"
                        @change="handleInputNumber"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <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">
                    <el-form-item prop="portion" label="数量" style="margin: 0;">
                      <el-input v-model="formData.portion" placeholder="请输入" size="mini" @change="handleInput"
                        :disabled="conditionType == 1"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4" style="text-align: right;">
                    <el-button type="primary" size="mini" @click="handleSampleSubmit"
                      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="id">
            <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
            <template v-for="column in tableColumns2">
              <el-table-column :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="sampleList.length"
            style="margin-top: 10px"></el-pagination>
        </el-tab-pane>
        <el-tab-pane label="质检方案" name="3">
          <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">
            </el-table-column>
            <el-table-column label="质检方案名称" prop="qualitySchemeTemplateName" align="center"></el-table-column>
            <el-table-column label="质检类型" prop="categoryLevelClassName" align="center"></el-table-column>
            <el-table-column label="质检项编码" prop="inspectionCode" align="center"></el-table-column>
            <el-table-column label="质检项名称" prop="inspectionName" align="center"></el-table-column>
            <el-table-column label="工艺参数" prop="defaultValue" align="center">
            </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="schemeList.length"
            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>
    </template>
  </ele-modal>
</template>

<script>
import baseInfo from './baseInfo.vue';

import { getCode } from '@/api/login';
import { save, update, planIssued } from '@/api/inspectionPlan';
import {
  getQualityTemplateList,
  getTemplateListByPlanId,
  getSampleListByPlanId,
  getInventoryListByPlanId,
  outInRecordsPage,
  getBatchInfoData
} from '@/api/inspectionPlan/index.js';

export default {
  components: {
    baseInfo
  },
  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' },
        { 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: [],

      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,

      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'
          }
        ]

      },
      isConsumable: '',
      conditionType: null,

      sampleListCode: ''
    };
  },
  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

    },
    // 分页后的样品列表
    paginatedSampleList() {
      const { currentPage, pageSize } = this.samplePagination;
      const start = (currentPage - 1) * pageSize;
      const end = start + pageSize;
      return this.sampleList.slice(start, end);
    },
    // 分页后的质检方案列表
    paginatedSchemeList() {
      const { currentPage, pageSize } = this.schemePagination;
      const start = (currentPage - 1) * pageSize;
      const end = start + pageSize;
      return this.schemeList.slice(start, end);
    }
  },
  created() { },
  methods: {
    async datasource({ page, limit, where }) {
      const res = await getInventoryListByPlanId({ ...where, page, limit });
      if (res.list.length > 1) {
        this.isCheck = true
      } else {
        this.isCheck = false
      }
      this.packingList = res.list;
      return res.list;
    },
    // 切换质检内容
    handleClick(tab) {
      this.activeName = tab.name;
    },
    async open(type, row) {
      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;
        return;
      } else {
        await this.handleEditOrDetail(row);
      }

    },
    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);
          }
          if (this.baseForm.productId) {
            this.$refs.baseInfoRefs.getProductDetails(this.baseForm.productId);
          }
        }
      });

      // 如果是编辑或者详情，则查询物料清单、质检方案和样品列表
      if (row.id) {
        this.rowIds = 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 getSampleList(id) {
      let res = await getSampleListByPlanId({
        planId: id
      });
      console.log(res.list, 'yyyyyyyyyyyyyy样品----------------------------');

      this.sampleList = res?.list || [];
      this.samplePagination.currentPage = 1;
      this.samplePagination.total = this.sampleList.length;
    },

    async getTemplateList(id) {
      let res = await getTemplateListByPlanId({
        planId: id
      });
      console.log(res.list, 'fffffffffffffff方案--------------------------');
      this.schemeList = res?.list || [];
      this.schemePagination.currentPage = 1;
      this.schemePagination.total = this.schemeList.length;
    },
    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([])

      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];
            console.log('this.isCheck=false', this.isCheck)
          } 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 };
        });
        console.log(_arr1, '1234567890')

        this.packingList = _arr1;
        this.$refs.table12.setData(_arr1);//赋值
        const _arr2 = this.$refs.table12.getData();

        if (_arr2.length > 1) {
          this.baseForm.productNumber = _arr2.length;
        } else {
          this.baseForm.productNumber = _arr2[0].measureQuantity;
        }
        //处理样品清单
        await this.handleSampleList();
      } else {
        this.$refs.table12.setData([]);
      }
    },
    async handleSampleList() {
      let packingList = this.$refs.table12.getData();
      //全检时
      if (this.baseForm.qualityMode == 1) {
        this.sampleList = [];
        console.log(this.baseForm.isUnpack, '---isUnpack---')
        if (this.baseForm.isUnpack != null && this.baseForm.isUnpack != undefined && this.baseForm.isUnpack != '') {
          //拆包
          if (this.baseForm.isUnpack == 2) {
            await this.handleUnpackCase(packingList);
          } else if (this.baseForm.isUnpack == 1) {
            await this.updatePackingList(packingList);
          }
        } else {
          if (!this.isCheck) {
            await this.handleUnpackCase(packingList);
          } else {
            await this.updatePackingList(packingList);
          }
        }
      } else {
        this.sampleList = [];
      }
    },
    async handleUnpackCase(packingList) {
      const num = Number(this.baseForm.productNumber || 0);
      if (num) {
        await this.getUnpackSamList(packingList, num);
      }
    },
    //获取样品编码
    async getSampleCode() {
      return await getCode('sample_code');
    },
    async updatePackingList(list) {
      for (let i = 0; i < list.length; i++) {
        list[i].sampleCode = await this.getSampleCode();
      }
      this.sampleList = list;
      console.log(this.sampleList, 'this.sampleList222')
      this.samplePagination.currentPage = 1;
      this.samplePagination.total = list.length;
    },
    async getUnpackSamList(list, num) {
      console.log('拆包getUnpackSamList')
      let data = [];
      list.forEach(oldItem => {
        const newMeasureQuantity = oldItem.measureQuantity / this.baseForm.productNumber;
        const newWeight = parseFloat((oldItem.weight / this.baseForm.productNumber).toFixed(2))

        delete oldItem.id;

        for (let i = 0; i < num; i++) {
          data.push({
            ...oldItem,
            measureQuantity: newMeasureQuantity,
            weight: newWeight
          });
        }
      });

      console.log(data, '样品数据-条数', num)
      await this.updatePackingList(data);

    },
    async getQualityTemplate(productCode, ids) {

      await getQualityTemplateList({
        productCode: productCode,
        qualityQlanId: ids
      }).then((res) => {
        if (Object.keys(res).length === 0) {
          this.$message.error('请确认该物品是否配置质检方案！');
          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;
      this.formData.portion = selection.length;
      this.baseForm.sampleNumber = selection.length;
      //如果取小样
      if (this.conditionType == 2) {
        const data1 = this.$refs.table12.getData()
        this.$set(this.formData, 'sampleUnit', data1[0]?.measureUnit);
        this.$set(this.baseForm, 'sampleMeasureUnit', data1[0]?.measureUnit);
      }
    },
    //取样方式选择
    handleSampleNumber(val) {
      console.log(val, 'val');
      this.conditionType = val;
      //清空样品清单列表
      this.sampleList = []
      const dataS = this.$refs.table12.getData();
      //取整样
      if (val == 1) {
        this.sampleList = dataS;
        this.formData.portion = dataS.length;
        this.$refs.table12.toggleAllSelection();
        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;
      }

      const portion = Number(this.formData.portion);
      if (this.isCheck) {
        if (portion > packingList.length) {
          this.$message.warning('取样数量不能大于来源清单数量！');
          this.formData.portion = packingList.length;
          return;
        }
        packingList.slice(0, this.formData.portion).forEach(row => {
          this.$refs.table12.toggleRowSelection(row);
        });
      } else {
        const maxQuantity = Number(packingList[0].measureQuantity);
        if (portion > maxQuantity) {
          this.$message.warning('取样数量不能大于计量数量！');
          this.formData.portion = maxQuantity;
          return;
        }
      }
    },
    getCategoryInfo(val) {
      this.isConsumable = val.isConsumable;
    },
    changeSamUnit(val) {
      this.$refs.baseInfoRefs.getsampleMeasureUnit(val);
    },
    //抽样确认按钮事件-样品列表右上角确认按钮
    handleSampleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.sampleList = []
          this.baseForm.sampleMeasureUnit = this.formData.sampleUnit

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

      this.sampleList = this.selectedList.map(oldItem => {
        const newItem = JSON.parse(JSON.stringify(oldItem));
        newItem.measureQuantity = measureQ;
        newItem.measureUnit = unit;
        return newItem;
      });
    },
    //监听类型变化
    resetTable() {
      this.$nextTick(() => {
        this.table1();
        this.table2();
      });
    },
    table1() {
      this.$refs.table12.setData([])
      this.schemeList = [];
    },
    table2() {
      this.$nextTick(() => {
        this.sampleList = [];
      });
    },
    resetForm() {
      this.baseForm = { ...this.defaultForm() };
    },
    handleClose() {
      this.resetForm();
      this.resetTable();
      this.visible = false;
    },

    /* 保存编辑 */
    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;
        let params = {
          ...this.baseForm,
          qualityInventoryList: this.$refs.table12.getData(),
          sampleList: this.sampleList,
          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;
        let params = {
          ...this.baseForm,
          qualityInventoryList: this.$refs.table12.getData(),
          sampleList: this.sampleList,
          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;
          });
      });
    },
    // 样品列表分页方法
    handleSampleSizeChange(val) {
      this.samplePagination.pageSize = val;
      this.samplePagination.currentPage = 1;
    },
    handleSampleCurrentChange(val) {
      this.samplePagination.currentPage = val;
    },
    // 质检方案分页方法
    handleSchemeSizeChange(val) {
      this.schemePagination.pageSize = val;
      this.schemePagination.currentPage = 1;
    },
    handleSchemeCurrentChange(val) {
      this.schemePagination.currentPage = val;
    },
    //检验方式改变时，重新获取样品列表
    changeModel(val) {
      this.baseForm.qualityMode = val;
      this.baseForm.sampleNumber = '';
      console.log(this.baseForm.productNumber, 'productNumberproductNumber数量')
      if (this.baseForm.qualityMode == 1) {
        this.handleSampleList();
      } else {
        this.sampleList = [];
      }
    },
  }
};
</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>
