<template>
  <div class="app-container">
    <el-card>
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="88px"
      >
        <el-form-item label="畜种" prop="animalType">
          <el-select v-model="queryParams.animalType">
            <el-option v-for="(item, i) in animalList" :key="i" :value="item.typeValue" :label="item.typeName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检验时间" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检疫证号" prop="animalCertNo">
          <el-input
            v-model="queryParams.animalCertNo"
            placeholder="请输入检疫证号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['app:quarantine:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteAll"
            v-hasPermi="['app:quarantine:remove']"
            >删除</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </el-card>
    <br />
    <el-card>
      <el-table
        border
        stripe
        height="600"
        v-loading="loading"
        ref="multipleTable"
        :data="disposalList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <!--  <el-table-column label="ID"  prop="id" width="80" />  -->
        <el-table-column label="检验时间" prop="checkTime" width="160" />
        <el-table-column label="供应商" prop="supplierName" />
        <el-table-column label="检疫证号" prop="animalCertNo" />
        <el-table-column label="畜种">
          <template slot-scope="scope">
            {{animalName(scope.row.animalType)}}
          </template>
        </el-table-column>
        <el-table-column label="产品名称" prop="produceName" />
        <el-table-column label="检验项目" prop="checkProject" />
        <el-table-column label="数量/重量" prop="number">
          <template slot-scope="scope">
            <span v-if="scope.row.types === 0">{{ scope.row.number }}kg</span>
            <span v-else>{{ scope.row.number }}{{ scope.row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="抽检份数" prop="inspectNum" />
        <el-table-column label="检测结果" prop="detectionValue" />
        <el-table-column label="合格数量/重量" prop="qualifiedNum">
          <template slot-scope="scope">
            <span v-if="scope.row.types === 0"
              >{{ scope.row.qualifiedNum }}kg</span
            >
            <span v-else>{{ scope.row.qualifiedNum }}{{ scope.row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="不合格数量/重量" prop="unqualifiedNum">
          <template slot-scope="scope">
            <span v-if="scope.row.types === 0"
              >{{ scope.row.unqualifiedNum }}kg</span
            >
            <span v-else
              >{{ scope.row.unqualifiedNum }}{{ scope.row.unit }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="不合格原因" prop="unqualifiedReason" />
        <el-table-column label="处理方式" prop="method">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.method === 0">高温</el-tag>
            <el-tag v-else-if="scope.row.method === 1" type="success"
              >化制</el-tag
            >
            <el-tag v-else-if="scope.row.method === 2" type="info">焚烧</el-tag>
            <el-tag v-else-if="scope.row.method === 3" type="warning"
              >深埋</el-tag
            >
            <el-tag v-else-if="scope.row.method === 4" type="danger"
              >委托处理</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="检验人" prop="userName"></el-table-column>
        <!--      <el-table-column label="处理方式"  prop="dealWay" />-->
        <el-table-column
          label="操作"
          width="180"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['app:quarantine:edit']"
              style="margin-right: 10px"
              >修改</el-button
            >
            <el-popconfirm
              v-hasPermi="['app:quarantine:remove']"
              :title="'是否确认删除所选数据项？'"
              @confirm="handleDelete(scope.row)"
            >
              <el-button
                size="mini"
                type="text"
                slot="reference"
                icon="el-icon-delete"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改死淘处理方式对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form
        ref="form"
        label-position="left"
        :model="form"
        :rules="rules"
        :disabled="isView"
        label-width="110px"
      >
        <el-form-item
          label="分圈批次"
          prop="entranceBatchId"
          v-if="!isHideCheck"
        >
          <el-select v-model="form.entranceBatchId" :disabled="form.id !== null" style="width: 100%">
            <el-option
              v-for="item in batchList"
              :key="item.entranceBatchId"
              :value="item.entranceBatchId"
              :label="item.desc"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierName" v-if="!isHideCheck">
          <el-input
            v-model="form.supplierName"
            disabled
            placeholder="选择进场批次自动填充"
          ></el-input>
        </el-form-item>
        <el-form-item label="检验时间" prop="checkTime" v-if="!isHideCheck">
          <el-date-picker
            v-model="form.checkTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检验时间" prop="checkTime" v-if="isHideCheck">
          <el-date-picker
            v-model="form.checkTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="检疫证号" prop="animalCertNo">-->
        <!--          <el-input v-model="form.animalCertNo" disabled placeholder="选择进场批次自动填充"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="畜种" prop="animalType">
          <el-select v-model="form.animalType" disabled>
            <el-option v-for="(item, i) in animalList" :key="i" :value="item.typeValue" :label="item.typeName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="produceName">
          <el-radio-group v-model="form.produceName" :disabled="form.id !== null">
            <el-radio
              v-for="item in productionList"
              :key="item.id"
              :label="item.productName"
              class="large_radio"
              >{{ item.productName }}</el-radio
            >
          </el-radio-group>
          <!--          <el-select v-model="form.produceName">-->
          <!--            <el-option v-for="item in productionList" :key="item.id" :value="item.productName" :label="item.productName"></el-option>-->
          <!--          </el-select>-->
        </el-form-item>
        <el-form-item label="检测项目" prop="checkProject" v-if="!isHideCheck">
          <el-select v-model="form.checkProject"  style="width: 100%">
            <el-option
              v-for="item in inspectionList"
              :key="item.id"
              :value="item.projectName"
              :label="item.projectName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抽检份数" prop="inspectNum" v-if="!isHideCheck">
          <el-input
            v-model.number="form.inspectNum"
            min="1"
            placeholder="请输入抽检份数"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="检测值"
          prop="detectionValueArr"
          v-if="!isHideCheck && checkType === 1"
        >
          <div class="line-input">
            <el-input
              style="width: 180px"
              v-for="(itemRow, i) in form.detectionValueArr"
              :key="i"
              v-model="itemRow.result"
              placeholder="检测值"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item
          label="检测结果详情"
          prop="detectionValueArr"
          v-if="!isHideCheck && checkType === 0"
        >
          <div class="line-input">
            <el-select
              v-for="(itemRow, i) in form.detectionValueArr"
              :key="i"
              v-model="itemRow.result"
              filterable
              placeholder="检验结果"
              style="width: 180px"
            >
              <el-option
                v-for="(item, i) in getAtResultList(form.checkProject)"
                :key="i"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>

            <!-- <el-col :span="10">
              <el-button class="item-add" type="primary" v-if="i == form.detectionValueArr.length - 1" @click="addItem(i)"
                ><i class="el-icon-plus"></i
              ></el-button>
              <el-button
                class="item-del"
                type="danger"
                v-if="i > 0 || form.detectionValueArr.length > 1"
                @click="removeItem(i)"
                ><i class="el-icon-minus"></i
              ></el-button>
            </el-col> -->
          </div>
        </el-form-item>

        <el-form-item label="单位类型" prop="types">
          <el-radio-group v-model="form.types" disabled>
            <el-radio :label="0">重量</el-radio>
            <el-radio :label="1">数量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          required
          :label="form.types === 0 ? '重量' : '数量'"
          prop="number"
        >
          <el-input v-model="form.number" placeholder="请填写">
            <template #append>
              <span>{{ form.types === 0 ? "kg" : form.unit }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          required
          :label="form.types === 0 ? '合格重量' : '合格数量'"
          prop="qualifiedNum"
        >
          <el-input v-model="form.qualifiedNum" placeholder="请填写">
            <template #append>
              <span>{{ form.types === 0 ? "kg" : form.unit }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          required
          :label="form.types === 0 ? '不合格重量' : '不合格数量'"
          prop="unqualifiedNum"
        >
          <el-input
            v-model="form.unqualifiedNum"
            disabled
            placeholder="自动计算"
          >
            <template #append>
              <span>{{ form.types === 0 ? "kg" : form.unit }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="不合格原因" prop="unqualifiedReason">
          <el-input
            v-model="form.unqualifiedReason"
            type="textarea"
            :autosize="{ minRows: 2 }"
            :placeholder="isView ? '' : '请输入不合格原因'"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="处理方式" prop="method">
          <el-radio-group v-model="form.method">
            <el-radio :label="0">高温</el-radio>
            <el-radio :label="1">化制</el-radio>
            <el-radio :label="2">焚烧</el-radio>
            <el-radio :label="3">深埋</el-radio>
            <el-radio :label="4">委托处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="检验人" prop="userName">
          <el-input
            v-model="form.userName"
            show-word-limit
            maxlength="10"
            placeholder="请输入检验人"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!isView">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getQuarantinePage,
  getQuarantineDetail,
  addQuarantinePage,
  editQuarantinePage,
  delQuarantinePage,
} from "../../../api/app/quarantine";
import { getSampleDetail, getSampleNewDetail } from "../../../api/app/sample";
import { listProductCategoryAll } from "../../../api/app/productCategory";
import { formatDate, changeDate, getFindByKey } from "../../../utils";
import { required, rules } from "../../../utils/formRules";
import { getInspectionList } from "../../../api/app/inspection";
import { getUserProfile } from "../../../api/system/user";
import { getPartItem } from "../../../api/app/part";
import { getProducePlanDetail} from "../../../api/app/producePlan";
import moment from "moment";
import {mapState} from "vuex";
export default {
  name: "Quarantine",
  data() {
    // 自定义验证整个数组的函数
    const validateDetectionArray = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('至少需要一个检测结果'));
        return;
      }

      // 检查数组中是否有 result 为空的情况
      const emptyResults = [];
      value.forEach((item, index) => {
        if (item.result === null || item.result === undefined || item.result === '') {
          emptyResults.push(index + 1);
        }
      });

      if (emptyResults.length > 0) {
        callback(new Error(`第 ${emptyResults.join(', ')} 个结果不能为空`));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView: false,
      // 是否显示弹出层
      open: false,
      //是否隐藏检查项目和批次
      isHideCheck: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        animalCertNo: null,
        startTime: null,
        endTime: null,
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为当天的 00:00:00

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        },
      },
      isUpdating: false,
      //
      defaultDetectionValue:"",
      // 表单参数
      form: {
        id: null,
        animalCertNo: null,
        animalType: null,
        checkProject: null,
        checkTime: formatDate(new Date()),
        entranceBatchId: null,
        method: 4,
        number: null,
        produceName: null,
        inspectNum: null,
        qualifiedNum: null,
        supplierId: null,
        supplierName: null,
        types: 0,
        unqualifiedNum: null,
        unqualifiedReason: null,
        userName: null,
        unit: "",
        detectionValue: null,
        detectionValueArr: [
          {
            result: null,
          },
        ], //如果是选择的检查结果就存入这里

      },
      rules: {
        checkTime: [required("检验时间不能为空")],
        number: [
          {
            validator: this.validateNumber,
            trigger: "blur",
            message: "请输入数量/重量",
          },
        ],
        qualifiedNum: [
          {
            validator: this.validateNumber,
            trigger: "blur",
            message: "请输入合格数量/重量",
          },
        ],
        unqualifiedNum: [
          {
            validator: this.validateNumber,
            trigger: "blur",
            message: "请输入不合格数量/重量",
          },
        ],
        method: [required("处理方式不能为空")],
        userName: [required("检验人不能为空")],
        detectionValue: [required('检测值不能为空')],
        detectionValueArr: [
          required('检测值不能为空'),
          { validator: validateDetectionArray, trigger: 'blur' }
        ]
      },
      // 分圈批次
      batchList: [],
      // 产品名称列表
      productionList: [],
      // 检验项目
      inspectionList: [],
      user: {},
      // 从样品那拿到的值
      sampleList: [],
      // 判断是否是值还是选项
      checkType: 0,
      bugOp: true,
      isFromDetail: false,
    };
  },
  watch: {
    "queryParams.timeRange": {
      handler(newVal) {
        if (newVal) {
          this.queryParams.startTime = newVal[0];
          this.queryParams.endTime = newVal[1];
        } else {
          this.queryParams.startTime = null;
          this.queryParams.endTime = null;
        }
      },
      deep: true,
    },
    "form.inspectNum": {
      handler(newVal) {
        this.generateInput(newVal,false);
      },
      deep: true,
    },
    "form.entranceBatchId": {
      handler(newVal) {
        if (newVal) {
          this.getProducePlan(); //根据生产计划设置检查时间默认值
          // this.getDefaultCheckResult();//根据样品登记设置水分检测默认值
          let item = getFindByKey(this.batchList, newVal, "entranceBatchId");
          if (item) {
            this.form.supplierName = item.supplierName;
            this.form.supplierId = item.supplierId;
            this.form.animalCertNo = item.animalCertNo;
            this.form.animalType = item.animalType
          }
          if(this.isView) {
            console.log(this.isView)
            return
          }
          if(!this.form.produceName) {
            return
          }
          this.getDefaultCheckResult()
        } else {
          this.form.supplierName = null;
          this.form.supplierId = null;
          this.form.animalCertNo = null;
          this.form.animalType = null
        }
      },
      deep: true,
    },
    "form.produceName": {
      handler(newVal) {
        this.productionList.forEach((item) => {
          if (item.productName === newVal) {
            this.form.unit = item.unit;
          }
        });
        //
       if (newVal == "不可食用（修割三腺）") {
          this.form.checkProject = null;
          this.isHideCheck = true;
          this.form.types = 0;
          this.form.inspectNum = null;
          this.generateInput(this.form.inspectNum);
        } else {
          this.form.types = 1;
          // this.form.checkProject = "快速检测法";
          this.isHideCheck = false;
          this.generateInput(this.form.inspectNum);
          //快速检测法采用水分检测，通过入场批次获取样品检测的水分值结果
          if(this.form.entranceBatchId){
            this.getDefaultCheckResult();
          }
        }
      },
      deep: true,
    },
    "form.types": {
      handler(newVal) {
        if (this.form.id === null) {
          this.form.number = null;
          this.form.qualifiedNum = null;
          this.form.unqualifiedNum = null;
        }
      },
      deep: true,
    },
    "form.number": {
      handler(newVal) {
        if (this.form.qualifiedNum) {
          if (this.form.types === 0) {
            this.form.unqualifiedNum = (
              Number(newVal) - Number(this.form.qualifiedNum)
            ).toFixed(2);
          } else {
            this.form.unqualifiedNum = Number(newVal) - Number(this.form.qualifiedNum);
          }
        }
      },
    },
    "form.qualifiedNum": {
      handler(newVal) {
        if (this.form.number) {
          if (this.form.types === 0) {
            this.form.unqualifiedNum = (
              Number(this.form.number) - Number(newVal)
            ).toFixed(2);
          } else {
            this.form.unqualifiedNum =
              Number(this.form.number) - Number(newVal);
          }
        }
      },
    },
    "form.checkProject": {
      handler(newVal) {
        this.inspectionList.forEach(item => {
          if(item.projectName === newVal) {
            this.checkType = item.checkType
          }
        })
        if(this.isView) {
          return
        }
        let item = getFindByKey(this.sampleList, newVal, "name");
        if(item) {
          this.form.inspectNum = item.num;
          this.generateInput(item.num)
          let items = []
          item.values.forEach(i => {
            items.push({result: i})
          })
          this.form.detectionValueArr = items
        } else {
            if(this.bugOp === false) {
              this.form.inspectNum = 1
              this.generateInput(1)
              this.form.detectionValueArr = [{result: null}]
            }
        }
        this.bugOp = false
      },
      deep: true,
    },
    "form.animalType": {
      handler(newVal) {
        this.getProduction()
      },
      deep: true
    },
  },
  created() {
    this.getUser();
    this.getInspection();
    this.getProduction();
    this.getList();
  },
  computed: {
    ...mapState({
      animalList: state => state.user.animalList
    }),
    animalName() {
      return (value) => {
        if (value === null) return '未知'
        const animal = this.animalList.find(item =>
          String(item.typeValue) === String(value)
        )
        return animal ? animal.typeName : '未知'
      }
    }
  },
  methods: {
    //获取批次的生产计划,检验时间根据生产计划的屠宰开始时间+2min提供默认值
    getProducePlan(){
      let params = {
        entranceBatchId: this.form.entranceBatchId
      }
      getProducePlanDetail(params).then(res => {
        if(res.data && res.data.planStartTime){
          this.form.checkTime = moment(new Date(res.data.planStartTime).getTime() + 1000 * 60 * 2).format('YYYY-MM-DD HH:mm:ss');
        }
      })
    },
    //水分检测值获取样品检测的检查结果
    getDefaultCheckResult() {
      let params = {
        entranceBatchId: this.form.entranceBatchId,
        produceName: this.form.produceName,
      };
      getSampleNewDetail(params).then((res) => {
        if(res.data.length > 0) {
          let arr = []
          res.data.forEach(item => {
            let examineItemsArr = item.examineItems
                ? JSON.parse(item.examineItems)
                : [];
            arr = arr.concat(examineItemsArr)
          })
          let list = this.mergeObjectsByKey(arr, 'name')
          this.sampleList = list
          if(this.form.id === null) {
            if(this.sampleList.length > 0) {
              this.form.checkProject = this.sampleList[0].name;
              this.form.inspectNum = this.sampleList[0].num;
              this.generateInput(this.sampleList[0].num)
              let items = []
              this.sampleList[0].values.forEach(item => {
                items.push({result: item})
              })
              this.form.detectionValueArr = items
            }
          }
        }
        // if (res.data) {
        //   let defaultValueArr = [];
        //   let examineItemsArr = res.data.examineItems
        //     ? JSON.parse(res.data.examineItems)
        //     : [];
        //   examineItemsArr.forEach((item) => {
        //     if (item.name && item.name.trim() == "水份检测" && item.value && item.value.trim() != "") {
        //       defaultValueArr.push(item.value);
        //     }
        //   });
        //
        //   if(this.form.detectionValueArr.length>0){
        //     this.form.detectionValueArr[0].result = defaultValueArr.join(" | ");
        //   }
        // }
      });
    },
    // 合并函数
   mergeObjectsByKey(arr, key) {
      const result = [];
      const map = new Map();

      arr.forEach(item => {
        if (!map.has(item[key])) {
          // 创建新对象并初始化
          const newObj = {
            ...item,
            values: [item.value], // 改为数组形式
            num: 1
          };
          // 删除原来的value属性
          delete newObj.value;
          map.set(item[key], newObj);
          result.push(newObj);
        } else {
          // 合并已有对象
          const existingObj = map.get(item[key]);
          existingObj.values.push(item.value); // 向数组添加新值
          existingObj.num += 1;
        }
      });

      return result;
    },

    generateInput(newVal,rebuild=true) {
      if (this.isUpdating) {
        return;
      }

      if (newVal > 0) {
        if(rebuild){
          //如果选择了检查的产品，那么重新清空全部检测结果
          this.form.detectionValueArr = [];
          for (var i = 0; i < newVal; i++) {
            this.form.detectionValueArr.push({
              result: null,
            });
          }
        }else{
          //否则只是改变了检测份数，追加或减少检测结果数量就行
          let num = newVal - this.form.detectionValueArr.length;
          if (num < 0) {
            this.form.detectionValueArr.splice(num);
          } else {
            for (var i = 0; i < num; i++) {
              this.form.detectionValueArr.push({
                result: null,
              });
            }
          }
        }

      } else {
        this.form.detectionValueArr = [
          {
            result: null,
          },
        ];
      }
    },
    getAtResultList(name) {
      let arr = [];
      this.inspectionList.forEach((item) => {
        if (item.projectName === name) {
          arr = JSON.parse(item.result);
        }
      });

      return arr;
    },
    addItem(i) {
      this.form.detectionValueArr.push({
        result: null,
      });
    },
    removeItem(i) {
      this.form.detectionValueArr.splice(i, 1);
    },
    /** getUser **/
    getUser() {
      getUserProfile().then((response) => {
        this.user = response.data;
        this.form.userName = response.data.nickName;
      });
    },
    validateNumber(rule, value, callback) {
      if (value === null) {
        // 判断是否是 重量还是数量 0=重量 1=数量
        if (this.form.types === 0) {
          if (rule.field === "number") {
            return callback(new Error("重量不能为空"));
          } else if (rule.field === "qualifiedNum") {
            return callback(new Error("合格重量不能为空"));
          } else if (rule.field === "unqualifiedNum") {
            return callback(new Error("不合格重量不能为空"));
          }
        } else {
          if (rule.field === "number") {
            return callback(new Error("数量不能为空"));
          } else if (rule.field === "qualifiedNum") {
            return callback(new Error("合格数量不能为空"));
          } else if (rule.field === "unqualifiedNum") {
            return callback(new Error("不合格数量不能为空"));
          }
        }
      }
      let xiaoshu = /^\d+(\.\d{1,2})?$/;
      let zhengshu = /^(0|[1-9]\d*)$/;
      if (this.form.types === 0) {
        if (!xiaoshu.test(value)) {
          return callback(new Error("只能最多2位小数"));
        }
      } else {
        if (!zhengshu.test(value)) {
          return callback(new Error("必须是整数"));
        }
      }
      callback();
    },
    /** 入场批次 **/
    getBatch() {
      let params = {
        entranceTime:
          changeDate(new Date().getTime() - 1000 * 60 * 60 * 24) + " 23:59:59",
      };
      getPartItem(params).then((res) => {

        this.batchList = res.data.data;
      });
    },
    /** 产品列表 **/
    getProduction() {
      if (this.isFromDetail) return;
      if(!this.form.animalType) return;
      let params = {
        animalType: this.form.animalType
      }
      listProductCategoryAll(params).then((res) => {
        this.productionList = res.rows;
      });
    },
    /** 检验项目list **/
    getInspection() {
      getInspectionList().then((res) => {
        this.inspectionList = res.data;
      });
    },
    /** 查询检验项目列表 */
    getList() {
      getQuarantinePage(this.queryParams).then((res) => {
        this.disposalList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        animalCertNo: null,
        startTime: null,
        endTime: null,
        animalType: null
      };
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getBatch();
      this.open = true;
      this.isView = false;
      this.title = "添加生产检验检疫登记";
      this.inspectionList.forEach((item) => {
        if (item.defaultFlag) {
          this.form.checkProject = item.projectName;
        }
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();

      const id = row.id;
      this.isView = false;
      await this.getBatch();
      let params = {
        id: id,
      };
      this.isUpdating = true; // 开始更新，阻止watch执行
      // 第一次进来不修改
      this.bugOp = true
      await getQuarantineDetail(params)
        .then((res) => {
          this.form = res.data;
          if (this.form.detectionValue) {
            // 使用 $set 确保响应式
            this.$set(
              this.form,
              "detectionValueArr",
              this.form.detectionValue.split(",").map((item) => ({
                result: item.trim(),
              }))
            );
          }

          this.open = true;
          this.title = "修改生产检验检疫登记";
        })
        .catch((error) => {
          console.error("获取详情失败:", error);
        })
        .finally(() => {
          this.isUpdating = false; // 更新完成，恢复watch
        });
    },
    /** 查看按钮操作 */
    async handleView(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id,
      };
      this.isUpdating = true; // 开始更新，阻止watch执行
      await getQuarantineDetail(params)
        .then((res) => {
          this.form = res.data;
          if (this.form.detectionValue) {
            // 使用 $set 确保响应式
            this.$set(
              this.form,
              "detectionValueArr",
              this.form.detectionValue.split(",").map((item) => ({
                result: item.trim(),
              }))
            );
          }

          this.open = true;
          this.isView = true;
          this.title = "查看生产检验检疫登记";
        })
        .catch((error) => {
          console.error("获取详情失败:", error);
        })
        .finally(() => {
          this.isUpdating = false; // 更新完成，恢复watch
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        animalCertNo: null,
        animalType: null,
        checkProject: null,
        checkTime: formatDate(new Date()),
        entranceBatchId: null,
        method: 4,
        number: null,
        produceName: null,
        inspectNum: 1,
        qualifiedNum: null,
        supplierId: null,
        supplierName: null,
        types: 0,
        unqualifiedNum: null,
        unqualifiedReason: null,
        userName: this.user.nickName,
        unit: null,
        detectionValue: null,
        detectionValueArr: [
          {
            result: null,
          },
        ],
      };
      this.sampleList = [];
      this.checkType = 0;
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // if (
          //   this.form.checkProject == "旋毛虫检验" ||
          //   this.form.checkProject == "快速检测法"
          // ) {
          //
          // }else{
          //   this.form.detectionValue = "";
          // }
          let checkRes = this.form.detectionValueArr.map((item) => {
            return item.result;
          });
          this.form.detectionValue = checkRes.join(",");

          if(this.isHideCheck){
            //不可食用（修割三腺）,采用日期选择
            this.form.checkTime = changeDate(this.form.checkTime);
          }

          if (this.form.id != null) {
            // 编辑
            editQuarantinePage(this.form).then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增
            addQuarantinePage(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids,
      };
      delQuarantinePage(params).then((res) => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      });
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm("是否确认删除所选数据项？").then(() => {
        let params = {
          ids: ids.join(","),
        };
        delQuarantinePage(params).then((res) => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.large_radio {
  margin-bottom: 10px;
}
.line-input {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}
</style>

