<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="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"></el-input>
        </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:violate: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:violate: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="seriesNoGroup"></el-table-column>
        <el-table-column label="溯源单号"  prop="traceRecordNo"></el-table-column>
        <el-table-column label="检疫证号"  prop="animalCertNo" />
        <el-table-column label="抽检头数"  prop="checkAmount" />
        <el-table-column label="检验项目" >
          <template slot-scope="scope">
            <template v-if="scope.row.examineItems">
              <div class="text-blue" @click="openModal(scope.row.examineItems)">查看详细检测项目</div>
            </template>
            <template v-else>
              <span>暂无检测项目</span>
            </template>
          </template>
        </el-table-column>
<!--        <el-table-column label="检验内容"  prop="checkConten" />-->
        <el-table-column label="抽检结果"  prop="result"></el-table-column>
        <el-table-column label="检验人"  prop="examinerConfirm"></el-table-column>
        <el-table-column label="操作" width="180"  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:violate:edit']"
              style="margin-right: 10px"
            >修改</el-button>
            <el-popconfirm
              v-hasPermi="['app:violate: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="120px">
        <el-form-item label="进场批次" prop="entranceBatchId">
          <el-select style="width: 100%" v-model="form.entranceBatchId">
            <el-option v-for="item in batchList" :key="item.id" :value="item.id" :label="item.desc"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="form.supplierName" disabled placeholder="选择进场批次自动填充"></el-input>
        </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="checkTime">
          <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="traceRecordNo">
          <el-input v-model="form.traceRecordNo"  placeholder="请输入溯源单号"></el-input>
        </el-form-item>
        <el-form-item label="抽检头数" prop="checkAmount">
          <el-input v-model.number="form.checkAmount"  placeholder="请输入抽检头数"></el-input>
        </el-form-item>
<!--        <el-form-item label="检验项目" prop="checkProject">-->
<!--          <el-select v-model="form.checkProject" style="width: 100%">-->
<!--            <el-option v-for="item in inspectionList" :key="item.id" :value="item.drugName" :label="item.drugName"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="检验内容" prop="checkConten">-->
<!--          <el-input v-model="form.checkConten" type="textarea" :autosize="{ minRows: 2 }"  disabled placeholder="选择检验项目自动填充"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="抽检结果" prop="result" style="width: 100%">-->
<!--          <el-select v-model="form.result" style="width: 100%">-->
<!--            <el-option v-for="item in resultArr" :key="item.name" :value="item.name" :label="item.name"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
              <el-divider content-position="left">检验项目</el-divider>
              <el-row class="mb20">
                <el-col :span="8">
                  <div>
                    检验项目</div>
                </el-col>
                <el-col :span="8">
                  <div>
                    检验结果</div>
                </el-col>
              </el-row>
              <el-row v-for="(itemRow, i) in form.examineList" :key="i">
                <el-col :span="8">
                  <el-form-item
                    label=""
                    label-width="0"
                    :prop="'examineList.' + i + '.name'"
                    :rules="[{ required: true, message: '检测项目不能为空', trigger: 'blur' }]"
                  >
                    <el-select
                      v-model="itemRow.name"
                      filterable
                      clearable
                      placeholder="请选择检验检疫项目"
                      style="width: 180px"
                      disabled
                    >
                      <el-option
                        v-for="(item,i) in inspectionList"
                        :key="i"
                        :label="item.itemName"
                        :value="item.itemName"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label=""
                    label-width="0"
                    :prop="'examineList.' + i + '.value'"
                    :rules="[{ required: true, message: '检测结果不能为空', trigger: 'blur' }]"
                  >
                    <el-select
                      v-model="itemRow.value"
                      filterable
                      placeholder="请选择检验结果"
                      style="width: 180px"
                    >
                      <el-option
                        v-for="(item,i) in getAtResultList(itemRow.name)"
                        :key="i"
                        :label="item.name"
                        :value="item.name"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
<!--                <el-col :span="8">-->
<!--                  <el-button-->
<!--                    class="item-add"-->
<!--                    type="primary"-->
<!--                    v-if="i == form.examineItems.length - 1"-->
<!--                    @click="addItem"-->
<!--                    ><i class="el-icon-plus"></i-->
<!--                  ></el-button>-->
<!--                  <el-button-->
<!--                    class="item-del"-->
<!--                    type="danger"-->
<!--                    v-if="i > 0 || form.examineItems.length > 1"-->
<!--                    @click="removeItem(i)"-->
<!--                    ><i class="el-icon-minus"></i-->
<!--                  ></el-button>-->
<!--                </el-col>-->
              </el-row>
        <el-form-item label="检验人" prop="examinerConfirm">
          <el-select v-model="form.examinerConfirm" style="width: 100%">
            <el-option v-for="item in staffList" :key="item.id" :value="item.realname" :label="item.realname"></el-option>
          </el-select>
<!--          <el-input v-model="form.examinerConfirm" placeholder="请输入检验人"></el-input>-->
        </el-form-item>
        <!--        <el-form-item label="处理方式" prop="dealWay">-->
        <!--          <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.dealWay" maxlength="50" show-word-limit placeholder="请输入处理方式" />-->
        <!--        </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>
    <el-dialog title="检测项目详情" :visible.sync="show" width="550px" append-to-body @close="resetShow">
      <el-table border stripe  :data="selectList">
        <el-table-column label="检测项目" prop="name" />
        <el-table-column label="检测值" prop="value" />
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import { getFindByKey, formatDate, changeDate } from "../../../utils";
import { listEntranceBatchAll } from "../../../api/app/entranceBatch";
import { getViolatePage, getViolateDetail, editViolatePage, addViolatePage, delViolatePage } from "../../../api/app/violate";
import { getDrugList } from "../../../api/app/drug";
import { required, rules } from "../../../utils/formRules";
import XSpace from "@/components/XSpace/XSpace.vue";
import { listStaff } from "../../../api/app/staff";
import moment from "moment";

export default {
  name: "violate",
  components: {
    XSpace
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        animalCertNo: null,
        startTime: null,
        endTime: null,
        checkType: '违禁药物'
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为当天的 00:00:00

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        }
      },
      // 表单参数
      form: {
        id: null,
        animalCertNo: '',
        checkAmount: '',
        checkConten: '',
        checkProject: '',
        checkTime: formatDate(new Date()),
        entranceBatchId: '',
        result: '',
        supplierId: '',
        supplierName: '',
        traceRecordNo: null
      },
      rules: {
        checkTime: [required('抽检时间不能为空')],
        supplierName: [required('供应商不能为空')],
        animalCertNo: [required('检疫证号不能为空')],
        checkAmount: [required('抽检头数不能为空'), rules.just],
        checkProject: [required('检验项目不能为空')],
        checkConten: [required('检验内容不能为空')],
        result: [required('抽检结果不能为空')],
        examinerConfirm: [required('检验人不能为空')],
        traceRecordNo: [
          {
            validator: (rule, value, callback) => {
              // 如果值为空或 null，直接通过
              if (value === null || value === '' || value === undefined) {
                callback();
                return;
              }
              // 否则检查是否是字母和数字组合
              if (/^[A-Za-z0-9]+$/.test(value)) {
                callback();
              } else {
                callback(new Error("只能包含字母和数字"));
              }
            },
            trigger: "blur", // 触发方式：失去焦点时验证
          },
        ]
      },
      // 入场批次
      batchList: [],
      // 检验项目
      inspectionList: [],
      resultArr: [],
      staffList: [],
      show: false,
      selectList: []
    }
  },
  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.entranceBatchId": {
      handler(newVal) {
        if(newVal) {
          let item = getFindByKey(this.batchList, newVal, 'id')
          if(item) {
            //默认抽检时间根据入场时间+10min
            this.form.checkTime = moment(new Date(item.entranceTime).getTime() + 1000 * 60 * 10).format('YYYY-MM-DD HH:mm:ss');
            this.form.supplierName = item.supplierName
            this.form.supplierId = item.supplierId
            this.form.animalCertNo = item.animalCertNo
          }
        } else {
          this.form.checkTime = moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss');
          this.form.supplierName = null
          this.form.supplierId = null
          this.form.animalCertNo = null
        }
      },
      deep: true
    },
    "form.checkProject": {
      handler(newVal) {
        if(newVal) {
          this.resultArr = []
          // this.form.result = null
          let item = getFindByKey(this.inspectionList, newVal, 'drugName')
          if(item) {
            this.form.checkConten = item.content
            this.resultArr = item.result ? JSON.parse(item.result) : []
          }
        } else {
          this.form.checkConten = null
        }
      },
      deep: true
    },
  },
  created() {
    this.getStaff()
    this.getList();
    this.getDrug()
  },
  methods: {
    addItem() {
      this.form.examineItems.push({
        name: null,
        value: null,
      });
    },
    getAtResultList(name) {
      let arr = []
      this.inspectionList.forEach(item => {
        if(item.itemName === name) {
          arr = item.result
        }
      })
      return arr
    },
    /** getStaff **/
    getStaff() {
      let params = {
        pageNum: 1,
        pageSize: 1000,
        postId: 19
      }
      listStaff(params).then(res => {
        this.staffList = res.data.records;
      })
    },
    /** 入场批次 **/
    getBatch() {
      let params = {
        entranceTime: formatDate(new Date().getTime() - 1000*60 * 60 * 24 * 2)
      }
      listEntranceBatchAll(params).then(res => {

        this.batchList = res.rows
      })
    },
    /** 违禁药物list **/
    getDrug() {
      let params = {
        type: '违禁药物'
      }
      getDrugList(params).then(res => {
        res.data.forEach(item => {
          item.itemName = item.drugName
          item.result = item.result
            ? JSON.parse(item.result)
            : [];
        })
        this.inspectionList = res.data
      })
    },
    /** 查询检验项目列表 */
    getList() {
      getViolatePage(this.queryParams).then(res => {
        res.data.records.forEach(item => {
          if(item.seriesNoGroup) {
            item.seriesNoList = item.seriesNoGroup.split(',')
          } else {
            item.seriesNoList = []
          }
        })
        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,
        checkType: '违禁药物'
      }
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      await this.getBatch()
      let arr = []
      this.inspectionList.forEach(item => {
        arr.push({  name: item.itemName,
          value: item.result[0].name,
        })
      })
      this.$set(this.form, 'examineList', arr)
      this.open = true;
      this.isView = false;
      this.title = "添加违禁药物登记";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      await this.reset();
      await this.getBatch()
      const id = row.id;
      let params = {
        id: id
      }
      await getViolateDetail(params).then(res => {
        this.form = res.data;
        let arr = res.data.examineItems ? JSON.parse(res.data.examineItems) : null
        this.$set(this.form, 'examineList', arr)
        this.open = true;
        this.isView = false;
        this.title = "修改违禁药物登记";
      })
    },
    /** 查看按钮操作 */
    async handleView(row) {
      await this.reset();
      await this.getBatch()
      const id = row.id;
      let params = {
        id: id
      }
      await getViolateDetail(params).then(res => {
        this.form = res.data;
        let arr = res.data.examineItems ? JSON.parse(res.data.examineItems) : null
        this.$set(this.form, 'examineList', arr)
        this.open = true;
        this.isView = true;
        this.title = "查看违禁药物登记";
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    async reset() {
      this.form = {
        id: null,
        animalCertNo: '',
        checkAmount: '',
        checkConten: '',
        checkProject: '',
        checkTime: formatDate(new Date()),
        entranceBatchId: '',
        result: '',
        supplierId: '',
        supplierName: '',
        traceRecordNo: '',
        examinerConfirm: '',
        checkType: '违禁药物',
        examineList: [],
        examineItems: null,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            this.form.examineItems = JSON.stringify(this.form.examineList)
            editViolatePage(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.reset();
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            this.form.examineItems = JSON.stringify(this.form.examineList)
            addViolatePage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.reset();
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delViolatePage(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delViolatePage(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    },
    openModal(item) {
      this.selectList = item ? JSON.parse(item) : []
      this.show = true
    },
    resetShow() {
      this.show = false
      this.selectList = []
    }
  }
}
</script>

<style scoped lang="scss">
.text-blue {
  color: #1853C5;
  cursor: pointer;
}
</style>
