<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="羊只" prop="sheepId">
        <el-input v-model="queryParams.sheepId" placeholder="请输入羊只" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="检疫日期" style="width: 308px">
        <el-date-picker v-model="daterangeDatetime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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="Plus" @click="handleAdd"
          v-hasPermi="['bisosafety:quarantine:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['bisosafety:quarantine:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['bisosafety:quarantine:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['bisosafety:quarantine:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="quarantineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="羊只" align="center" prop="sheepNo" />
      <el-table-column label="检疫日期" align="center" prop="datetime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.datetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="羊只性别" align="center" prop="gender" />

      <el-table-column label="羊只类别" align="center" prop="sheepType" />
      <el-table-column label="月龄" align="center" prop="monthAge" />
      <el-table-column label="繁育状态" align="center" prop="breed" />
      <el-table-column label="检疫项目" align="center" prop="itemName" />
      <el-table-column label="样品类型" align="center" prop="sample" />
      <el-table-column label="采样员" align="center" prop="sampler" />
      <el-table-column label="检疫员" align="center" prop="quarOfficer" />
      <el-table-column label="检疫结果" align="center" prop="result">
        <template #default="scope">
          <dict-tag :options="quar_result" :value="scope.row.result" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="quar_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['bisosafety:quarantine:edit']">检疫</el-button>
          <el-button link type="success" @click="gotoTreatment(scope.row)" v-if="scope.row.result == 1">治疗</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['bisosafety:quarantine:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 新增检疫记录对话框 -->
    <el-dialog :title="'新增检疫记录'" v-model="addOpen" width="700px" append-to-body>
      <el-form ref="addQuarantineRef" :model="addForm" :rules="addRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="羊只耳号" prop="sheepIds" required>
              <div>
                <el-input v-model="addForm.sheepIdInput" placeholder="请输入羊只耳号，按回车验证" @keyup.enter="validateSheepId"
                  :disabled="isInputDisabled" />
                <div v-if="invalidSheepId" style="color: red; margin-top: 5px;">
                  该羊只耳号不存在
                </div>
                <div v-if="validSheepId" style="color: green; margin-top: 5px;">
                  该羊只耳号已存在
                </div>
                <div style="margin-top: 10px;">
                  <el-tag v-for="(id, index) in addForm.sheepIds" :key="index" closable @close="removeSheepId(index)"
                    style="margin-right: 10px; margin-bottom: 10px;">
                    {{ id }}
                  </el-tag>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检疫日期" prop="datetime">
              <el-date-picker clearable v-model="addForm.datetime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择检疫日期" :default-value="new Date()"></el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检疫项目" prop="quarantineItems">
              <el-select v-model="addForm.quarItems" placeholder="请选择检疫项目">
                <el-option v-for="item in quarantineItems" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="样品类型" prop="sampleType">
              <el-select v-model="addForm.sampleType" placeholder="请选择样品类型">
                <el-option v-for="item in sampleTypes" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采样员" prop="sampler">
              <el-input v-model="addForm.sampler" placeholder="请输入采样员姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检疫员" prop="quarantineOfficer">
              <el-input v-model="addForm.quarantineOfficer" placeholder="请输入检疫员姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
          <el-form-item label="检疫结果" prop="result">
            <el-select v-model="editForm.result" placeholder="请选择检疫结果" style="width: 200px;">
              <el-option v-for="items in quar_result" :key="items.id" :label="items.label"
                :value="items.value"></el-option>
            </el-select>
          </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="选择羊舍" prop="barnIds">
              <el-select v-model="addForm.barnIds" multiple filterable placeholder="请选择羊舍" @change="handleBarnChange">
                <el-option v-for="barn in barns" :key="barn.id" :label="barn.label" :value="barn.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddForm">确 定</el-button>
          <el-button @click="cancelAdd">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改检疫记录对话框 -->
    <el-dialog :title="'修改检疫记录'" v-model="editOpen" width="500px" append-to-body>
      <el-form ref="editQuarantineRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="检疫状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择检疫状态">
            <el-option label="未检疫" value="未检疫"></el-option>
            <el-option label="检疫中" value="检疫中"></el-option>
            <el-option label="检疫完成" value="检疫完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检疫类型" prop="quarantineType">
          <el-select v-model="editForm.quarantineType" placeholder="请选择检疫类型">
            <el-option label="常规检疫" value="常规检疫"></el-option>
            <el-option label="疫病检疫" value="疫病检疫"></el-option>
            <el-option label="进出口检疫" value="进出口检疫"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检疫结果" prop="result">
          <el-select v-model="editForm.result" placeholder="请选择检疫结果">
            <el-option label="阴性" value="阴性"></el-option>
            <el-option label="阳性" value="阳性"></el-option>
            <el-option label="待定" value="待定"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
          <el-button @click="cancelEdit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Quarantine">
import { listQuarantine, getQuarantine, delQuarantine, addQuarantine, updateQuarantine } from "@/api/biosafety/quarantine";
import { listItems } from "@/api/biosafety/items";
import { listSample } from "@/api/biosafety/sample";
import request from '@/utils/request'

import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();

const { proxy } = getCurrentInstance();
const { quar_result, quar_status } = proxy.useDict('quar_result', 'quar_status');

const quarantineList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeDatetime = ref([]);

// 检疫项目
const quarantineItems = ref([]);
function getItems() {
  listItems().then(response => { 
    
    console.log("检疫项目列表获取成功", quarantineItems.value);
    quarantineItems.value = response.rows.map(item => ({
      label: item.name,
      value: item.id
    }));
 
  });
}

// 样品类型
const sampleTypes = ref([]);

function getSample() {
  listSample().then(response => {
    sampleTypes.value = response.rows.map(item => ({
      label: item.name,
      value: item.id
    }));
  });
}

// 羊舍列表
const barns = ref([]);
/** 获取羊舍列表 */
function getBarns() {
  request.get("/sheepfold_management/sheepfold_management/list").then(response => {
    barns.value = response.rows.map(item => ({
      label: item.sheepfoldName,
      value: item.id
    }));
    
  });
}

// 新增相关
const addOpen = ref(false);
const addForm = ref({
  sheepIds: [], // 存储已验证的羊只耳号列表
  sheepIdInput: '', // 单行输入框绑定的值
  datetime: new Date().toISOString().slice(0, 10), // 设置默认日期为今天
  quarantineType: '',
  quarItems: "",
  sampleType: '',
  sampler: '',
  quarantineOfficer: '',
  barnIds: ""
});

const addRules = {
  sheepIds: [{ required: true, message: "请至少添加一个有效的羊只耳号", trigger: "blur" }],
  datetime: [{ required: true, message: "请选择检疫日期", trigger: "change" }],
  quarItem: [{ required: true, message: "请选择检疫类型", trigger: "change" }],
  sampleType: [{ required: true, message: "请选择样品类型", trigger: "change" }]
};
const addQuarantineRef = ref(null);
const invalidSheepId = ref(false); // 当前输入的耳号是否无效
const validSheepId = ref(false); // 当前输入的耳号是否已存在
const isInputDisabled = ref(false); // 输入框是否禁用

// 修改相关
const editOpen = ref(false);
const editForm = ref({
  id: null,
  status: '',
  quarantineType: '',
  result: '',
  remark: ''
});
const editRules = {
  status: [{ required: true, message: "请选择检疫状态", trigger: "change" }],
  quarantineType: [{ required: true, message: "请选择检疫类型", trigger: "change" }]
};
const editQuarantineRef = ref(null);

// 查询相关
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sheepId: null,
    datetime: null,
    quarItem: null,
    sampleType: null,
    sampler: null,
    quarOfficer: null,
    result: null,
    status: null,
  }
});

const { queryParams } = toRefs(data);

/** 查询检疫记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeDatetime.value && daterangeDatetime.value.length === 2) {
    queryParams.value.params["beginDatetime"] = daterangeDatetime.value[0];
    queryParams.value.params["endDatetime"] = daterangeDatetime.value[1];
  }
  listQuarantine(queryParams.value).then(response => {
    quarantineList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
}

// 表单重置
function reset() {
  addForm.value = {
    sheepIds: [],
    sheepIdInput: '',
    datetime: new Date().toISOString().slice(0, 10), // 重置时也设置默认日期
    quarantineType: '',
    quarItems: "",
    sampleType: '',
    sampler: '',
    quarantineOfficer: '',
    barnIds: []
  };
  invalidSheepId.value = false;
  validSheepId.value = false;
  proxy.resetForm("addQuarantineRef");
}

/** 搜索功能 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeDatetime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  addOpen.value = true;
}

// 校验单个羊只耳号
function validateSheepId() {
  if (!addForm.value.sheepIdInput.trim()) return;

  invalidSheepId.value = false;
  validSheepId.value = false;

  // 禁用输入框，防止重复提交
  isInputDisabled.value = true;

  request.get(`/sheep/sheep/${addForm.value.sheepIdInput.trim()}`).then(response => {
    if (response.exists) {
      // 耳号存在，添加到列表
      if (!addForm.value.sheepIds.includes(addForm.value.sheepIdInput.trim())) {
        addForm.value.sheepIds.push(addForm.value.sheepIdInput.trim());
        validSheepId.value = true;
      } else {
        proxy.$modal.msgWarning("该羊只耳号已添加");
      }
    } else {
      // 耳号不存在
      invalidSheepId.value = true;
    }
  }).finally(() => {
    // 清空输入框并启用
    addForm.value.sheepIdInput = '';
    isInputDisabled.value = false;
  });
}

// 移除羊只耳号
function removeSheepId(index) {
  addForm.value.sheepIds.splice(index, 1);
}

// 处理羊舍变更
function handleBarnChange(barnIds) {
  if (!barnIds || barnIds.length === 0) return;

  // 这里需要调用接口获取选中羊舍中的所有羊只耳号
  // 并将它们添加到输入框中
  // 示例代码，实际接口可能不同
  let allSheepIds = addForm.value.sheepIds;

  barnIds.forEach(barnId => {
    // 模拟从羊舍获取耳号，实际应替换为真实接口
    const barnSheepIds = getSheepIdsFromBarn(barnId);
    barnSheepIds.forEach(sheepId => {
      if (!allSheepIds.includes(sheepId)) {
        // 验证耳号有效性
        request.get(`/sheep/sheep/${sheepId}`).then(response => {
          if (response.exists && !allSheepIds.includes(sheepId)) {
            allSheepIds.push(sheepId);
            addForm.value.sheepIds = [...allSheepIds];
          }
        });
      }
    });
  });
}

/** 模拟从羊舍获取耳号（实际应替换为接口调用） */
function getSheepIdsFromBarn(barnId) {
  // 模拟数据，实际应从接口获取
  const barnSheepMap = {
    1: ['E001', 'E002', 'E003'],
    2: ['E004', 'E005'],
    3: ['E006']
  };
  return barnSheepMap[barnId] || [];
}

/** 提交新增表单 */
function submitAddForm() {
  addQuarantineRef.value.validate(valid => {
    if (valid) {
      if (addForm.value.sheepIds.length === 0) {
        proxy.$modal.msgError("请至少添加一个有效的羊只耳号");
        return;
      }

      const data = {
        ...addForm.value,
        sheepIds: addForm.value.sheepIds,
        quarItems: addForm.value.quarItems.join(','),
      };

      addQuarantine(data).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        addOpen.value = false;
        getList();
      });
    }
  });
}

/** 取消新增 */
function cancelAdd() {
  addOpen.value = false;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  resetEditForm();
  const _id = row.id || ids.value;
  getQuarantine(_id).then(response => {
    editForm.value = {
      ...response.data,
      status: response.data.status,
      quarantineType: response.data.quarantineType,
      result: response.data.result,
      remark: response.data.remark
    };
    editOpen.value = true;
  });
}

/** 重置修改表单 */
function resetEditForm() {
  editForm.value = {
    id: null,
    status: '',
    quarantineType: '',
    result: '',
    remark: ''
  };
  proxy.resetForm("editQuarantineRef");
}

/** 提交修改表单 */
function submitEditForm() {
  editQuarantineRef.value.validate(valid => {
    if (valid) {
      updateQuarantine(editForm.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        editOpen.value = false;
        getList();
      });
    }
  });
}

/** 取消修改 */
function cancelEdit() {
  editOpen.value = false;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除检疫记录编号为"' + _ids + '"的数据项？').then(function () {
    return delQuarantine(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('bisosafety/quarantine/export', {
    ...queryParams.value
  }, `quarantine_${new Date().getTime()}.xlsx`);
}

function gotoTreatment(row) {
  router.push({ path: '/biosafety/treatment/add', query: { qId: row.id, sId: row.sheepId } });
}

getList();
getItems(); // 获取检疫项目列表
getSample(); // 获取样品类型列表
getBarns(); // 获取羊舍列表
</script>