<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" inline v-show="showSearch" label-width="68px">
      <el-form-item label="检疫日期">
        <el-date-picker v-model="daterangeDatetime" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>

      <el-form-item label="检疫项目" prop="quarItem">
        <el-select v-model="queryParams.quarItem" placeholder="请选择" filterable clearable style="width: 150px">
          <el-option v-for="i in quarantineItems" :key="i.value" :label="i.label" :value="i.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="采样员" prop="sampler">
        <el-input v-model="queryParams.sampler" placeholder="请输入采样员名字" clearable @keyup.enter="getList" />
      </el-form-item>

      <el-form-item label="检疫员" prop="quarOfficer">
        <el-input v-model="queryParams.quarOfficer" placeholder="请输入检疫员名字" clearable @keyup.enter="getList" />
      </el-form-item>

      <el-form-item label="羊只类型" prop="sheepType">
        <el-select v-model="queryParams.sheepType" placeholder="请选择" filterable clearable style="width: 150px">
          <el-option v-for="i in sheepTypes" :key="i.value" :label="i.makeLabelFormatter" :value="i.label" />
        </el-select>
      </el-form-item>

      <el-form-item label="样品类型" prop="sampleType">
        <el-select v-model="queryParams.sampleType" placeholder="请选择" filterable clearable style="width: 150px">
          <el-option v-for="i in sampleTypes" :key="i.value" :label="i.label" :value="i.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-button type="primary" plain icon="Plus" @click="handleAdd"
        v-hasPermi="['bisosafety:quarantine:add']">新增</el-button>
      <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
        v-hasPermi="['bisosafety:quarantine:edit']">修改</el-button>
      <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
        v-hasPermi="['bisosafety:quarantine:remove']">删除</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport"
        v-hasPermi="['bisosafety:quarantine:export']">导出</el-button>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="quarantineList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="羊只耳号" align="center" prop="sheepNo" />
      <el-table-column label="羊只性别" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :options="sheep_gender" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="羊只类别" align="center" prop="sheepType" />
      <el-table-column label="月龄" align="center" prop="monthAge" sortable="custom" />
      <el-table-column label="繁育状态" align="center" prop="breed" />
      <el-table-column label="检疫日期" align="center" prop="datetime" width="180"
        :formatter="(_, __, v) => parseTime(v, '{y}-{m}-{d}')" />
      <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" prop="createBy" />
      <el-table-column label="备注" align="center" prop="comment" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['bisosafety:quarantine:edit']">检疫</el-button>
          <el-button v-if="String(scope.row.result) === '1'" link type="success"
            @click="gotoTreatment(scope.row)">治疗</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" :page-sizes="[20, 50, 100, 200, 500, 1000, 2000]" @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-form-item label="羊只耳号" prop="sheepList" required>
          <el-input v-model="addForm.sheepIdInput" placeholder="输入耳号后回车验证" @keyup.enter="validateSheepId">
            <template #suffix>
              <div style="
                  display: flex;
                  align-items: center;
                  height: 100%;
                  margin-left: 8px;
                ">
                <span v-if="invalidSheepId" style="color: red; font-size: 12px">耳号不存在</span>
                <span v-else-if="validSheepId" style="color: green; font-size: 12px">已添加</span>
                <span v-else-if="alreadySelected" style="color: orange; font-size: 12px">该羊只已选择</span>
              </div>
            </template>
          </el-input>

          <el-tag v-for="(item, i) in addForm.sheepList" :key="item.id" closable @close="addForm.sheepList.splice(i, 1)"
            style="margin: 5px 5px 0 0">
            {{ item.ear }}
          </el-tag>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检疫日期" prop="datetime">
              <el-date-picker v-model="addForm.datetime" type="date" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检疫项目" prop="quarItem">
              <el-select v-model="addForm.quarItem" placeholder="请选择" filterable clearable>
                <el-option v-for="i in quarantineItems" :key="i.value" :label="i.label" :value="i.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="样品类型" prop="sampleType">
              <el-select v-model="addForm.sampleType" placeholder="请选择" filterable clearable>
                <el-option v-for="i in sampleTypes" :key="i.value" :label="i.label" :value="i.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="羊舍" prop="barnIds">
              <el-select v-model="addForm.barnIds" multiple collapse-tags placeholder="可多选" @change="handleBarnChange">
                <el-option v-for="b in barns" :key="b.value" :label="b.label" :value="b.value" />
              </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" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检疫员" prop="quarOfficer">
              <el-input v-model="addForm.quarOfficer" />
            </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="addForm.result" placeholder="检疫结果">
                <el-option v-for="i in quar_result" :key="i.value" :label="i.label" :value="i.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item label="备注" prop="comment">
              <el-input type="textarea" :rows="3" resize="vertical" v-model="addForm.comment" placeholder="请输入备注信息"
                maxlength="500" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
        <el-button @click="addOpen = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 修改弹窗 -->
    <el-dialog title="修改检疫记录" v-model="editOpen" width="560px" append-to-body :lock-scroll="false">
      <el-form ref="editQuarantineRef" :model="editForm" :rules="editRules" label-width="72px" size="default">
        <!-- 羊只基本信息（只读） -->
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="羊只耳号">
              <span>{{ editForm.sheepNo }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="羊只性别">
              <dict-tag :options="sheep_gender" :value="editForm.gender" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="羊只类别">
              <span>{{ editForm.sheepType }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月龄">
              <span>{{ editForm.monthAge }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="繁育状态">
              <span>{{ editForm.breed }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="检疫日期">
              <el-input :value="parseTime(editForm.datetime, '{y}-{m}-{d}')" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检疫项目">
              <el-select v-model="editForm.quarItem" placeholder="请选择" filterable clearable>
                <el-option v-for="i in quarantineItems" :key="i.value" :label="i.label" :value="i.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="样品类型">
              <el-select v-model="editForm.sampleType" placeholder="请选择" filterable clearable>
                <el-option v-for="i in sampleTypes" :key="i.value" :label="i.label" :value="i.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采样员">
              <el-input v-model="editForm.sampler" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="检疫员">
              <el-input v-model="editForm.quarOfficer" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检疫结果" prop="result">
              <el-select v-model="editForm.result" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="i in quar_result" :key="i.value" :label="i.label" :value="i.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="editForm.remark" :rows="3" maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="editOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </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 { parseTime } from '@/utils/ruoyi'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const { quar_result, quar_status, sheep_gender } = proxy.useDict(
  'quar_result',
  'quar_status',
  'sheep_gender'
)
const router = useRouter()

/* 基础数据 */
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const quarantineList = ref([])
const daterangeDatetime = ref([])

/* 查询参数 */
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  sheepId: null,
  orderByColumn: null,   // 新增
  isAsc: null            // 新增
})

/* 多选 */
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
function handleSelectionChange(sel) {
  ids.value = sel.map(s => s.id)
  single.value = sel.length !== 1
  multiple.value = !sel.length
}


function handleSortChange({ prop, order }) {
  if (!order) {   // 取消排序
    queryParams.orderByColumn = null
    queryParams.isAsc = null
  } else {
    queryParams.orderByColumn = prop   // monthAge 或 parity
    queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
  }
  getList()
}


/* 下拉数据 */
const quarantineItems = ref([])
const sampleTypes = ref([])
const sheepTypes = ref([])
const barns = ref([])

/* 获取基础下拉 */
function getItems() {
  listItems().then(res =>
    (quarantineItems.value = res.rows.map(i => ({ label: i.name, value: i.id })))
  )
}
function getSample() {
  listSample().then(res =>
    (sampleTypes.value = res.rows.map(i => ({ label: i.name, value: i.id })))
  )
}
function getBarns() {
  request
    .get('/sheepfold_management/sheepfold_management/list')
    .then(res =>
      (barns.value = res.rows.map(b => ({ label: b.sheepfoldName, value: b.id })))
    )
}
function getSheepType() {
  request.get('/base/base/list').then(res => {
    sheepTypes.value = res.rows.map(i => ({ label: i.name, value: i.id }))
  })
}

/* 列表查询 */
function getList() {
  loading.value = true
  queryParams.params = {}
  if (daterangeDatetime.value.length === 2) {
    queryParams.params.beginDatetime = daterangeDatetime.value[0]
    queryParams.params.endDatetime = daterangeDatetime.value[1]
  }
  listQuarantine(queryParams).then(res => {
    quarantineList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}
function resetQuery() {
  daterangeDatetime.value = []
  proxy.resetForm('queryRef')
  getList()
}

/* 新增相关 */
const addOpen = ref(false)
const addForm = ref({})
const addRules = {
  sheepList: [{ required: true, message: '请至少添加一个耳号', trigger: 'blur' }],
  datetime: [{ required: true, message: '请选择日期', trigger: 'change' }],
  quarItem: [{ required: true, message: '请选择项目', trigger: 'change' }],
  sampleType: [{ required: true, message: '请选择样品类型', trigger: 'change' }]
}

const invalidSheepId = ref(false)
const validSheepId = ref(false)
const alreadySelected = ref(false)
const barnSheepMap = reactive({})

function handleBarnChange(selectedBarnIds) {
  const oldBarnIds = Object.keys(barnSheepMap).map(Number)
  const newBarnIds = selectedBarnIds || []

  // 移除旧羊舍的耳号和ID
  oldBarnIds.forEach(barnId => {
    if (!newBarnIds.includes(barnId)) {
      const { tags = [], ids = [] } = barnSheepMap[barnId] || {}
      tags.forEach(tag => {
        const index = addForm.value.sheepList.findIndex(s => s.ear === tag)
        if (index !== -1) addForm.value.sheepList.splice(index, 1)
      })
      delete barnSheepMap[barnId]
    }
  })

  // 添加新羊舍的耳号和ID
  newBarnIds.forEach(barnId => {
    if (!barnSheepMap[barnId]) {
      request
        .get('/sheepfold_management/sheepfold_management/getSheepById', {
          params: { id: barnId }
        })
        .then(res => {
          const sheepList = res.data || []
          barnSheepMap[barnId] = {
            tags: sheepList.map(s => s.manageTags),
            ids: sheepList.map(s => s.id)
          }

          sheepList.forEach(s => {
            if (
              s.manageTags &&
              !addForm.value.sheepList.some(item => item.id === s.id)
            ) {
              addForm.value.sheepList.push({ id: s.id, ear: s.manageTags })
            }
          })
        })
    }
  })
}

function validateSheepId() {
  const ear = addForm.value.sheepIdInput.trim()
  if (!ear) return

  invalidSheepId.value = false
  validSheepId.value = false
  alreadySelected.value = false

  if (addForm.value.sheepList.some(s => s.ear === ear)) {
    alreadySelected.value = true
    addForm.value.sheepIdInput = ''
    return
  }

  request.get(`/sheep/sheep/byManageTags/${ear}`).then(res => {
    if (res.data) {
      addForm.value.sheepList.push({ id: res.data.id, ear })
      validSheepId.value = true
    } else {
      invalidSheepId.value = true
    }
    addForm.value.sheepIdInput = ''
  })
}

function submitAddForm() {
  addForm.value.ids = addForm.value.sheepList.map(s => s.id)
  addQuarantine(addForm.value).then(() => {
    proxy.$modal.msgSuccess('新增成功')
    addOpen.value = false
    getList()
  })
}

function handleAdd() {
  Object.assign(addForm.value, {
    sheepList: [],
    sheepIdInput: '',
    datetime: new Date().toISOString().slice(0, 10),
    quarItem: '',
    sampleType: '',
    sampler: '',
    quarOfficer: '',
    result: '',
    barnIds: []
  })
  Object.keys(barnSheepMap).forEach(k => delete barnSheepMap[k])
  invalidSheepId.value = false
  validSheepId.value = false
  alreadySelected.value = false
  addOpen.value = true
}

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

function handleUpdate(row) {
  Object.assign(editForm.value, row)
  editOpen.value = true
}

function submitEditForm() {
  editQuarantineRef.value.validate(valid => {
    if (!valid) return
    updateQuarantine(editForm.value).then(() => {
      proxy.$modal.msgSuccess('修改成功')
      editOpen.value = false
      getList()
    })
  })
}

/* 删除 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy
    .$modal.confirm(`是否确认删除记录编号为"${_ids}"的数据？`)
    .then(() => delQuarantine(_ids))
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
}

/* 导出 */
function handleExport() {
  proxy.download(
    '/biosafety/quarantine/export',
    queryParams,
    `检疫_${Date.now()}.xlsx`
  )
}

/* 跳转治疗 */
function gotoTreatment(row) {
  router.push({
    path: '/biosafety/treatment/add',
    query: { qId: row.id, sId: row.sheepId }
  })
}

/* 初始化 */
getList()
getItems()
getSample()
getBarns()
getSheepType()
</script>