<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" inline v-show="showSearch" label-width="68px">


      <!-- <el-form-item label="羊只耳号" prop="sheepNo">
        <el-input v-model="queryParams.sheepNo" placeholder="请输入耳号,多个用空格分隔" clearable @keyup.enter="getList" />
      </el-form-item> -->
      <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="allEarNumbers">
        <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
          <!-- 主选择器：不显示已选标签 -->
          <el-select v-model="queryParams.allEarNumbers" multiple filterable remote reserve-keyword placeholder="输入耳号搜索"
            :remote-method="searchEarNumber" :loading="earNumberLoading" allow-create default-first-option collapse-tags
            :max-collapse-tags="0" style="width: 300px" @change="handleEarNumberChange">
            <el-option v-for="item in earNumberOptions" :key="item" :label="item" :value="item" />
          </el-select>


          <!-- 辅助粘贴输入框 -->
          <el-input v-model="pasteInput" placeholder="或粘贴多个耳号(空格/换行/逗号分隔)" style="width: 300px" @paste="handlePaste"
            @keyup.enter="handlePasteSubmit" clearable>
            <template #append>
              <el-button @click="handlePasteSubmit" :icon="Plus">添加</el-button>

            </template>

          </el-input>


          <!-- 耳号计数显示 -->
          <el-tag v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0" type="info" effect="plain"
            size="large">
            已选: {{ queryParams.allEarNumbers.length }} 个
          </el-tag>


          <!-- 清空按钮 -->
          <el-button type="danger" plain @click="clearAllEarNumbers"
            v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0" :icon="Delete">
            清空全部
          </el-button>

        </div>


        <!-- 已选耳号展示区域（默认显示2个，可展开） -->
        <div v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0"
          class="selected-ear-numbers-display" style="margin-top: 10px;">
          <!-- 显示前2个或全部耳号 -->
          <el-tag v-for="(tag, index) in displayedEarNumbers" :key="tag" closable @close="handleRemoveEarNumber(tag)"
            style="margin: 4px;" type="success">
            {{ tag }}
          </el-tag>


          <!-- 展开/收起按钮 -->
          <el-button v-if="queryParams.allEarNumbers.length > defaultShowCount" type="primary" link
            @click="toggleExpand" style="margin-left: 8px;">
            {{ isExpanded ? '收起' : `展开剩余 ${queryParams.allEarNumbers.length - defaultShowCount} 个` }}
            <el-icon class="el-icon--right">
              <component :is="isExpanded ? ArrowUp : ArrowDown" />
            </el-icon>

          </el-button>

        </div>

      </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 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-select v-model="queryParams.sampler" filterable clearable placeholder="请输入采样员姓名" style="width: 100%"
          @change="handleTechnicalChange">
          <el-option v-for="item in technicalOptions" :key="item.value" :label="item.label" :value="item.value">
            <span style="float: left">{{ item.label }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="检疫员" prop="quarOfficer">
        <el-select v-model="queryParams.quarOfficer" filterable clearable placeholder="请输入检疫员姓名" style="width: 100%"
          @change="handleTechnicalChange">
          <el-option v-for="item in technicalOptions" :key="item.value" :label="item.label" :value="item.value">
            <span style="float: left">{{ item.label }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否在群" prop="isDelete">
        <el-select v-model="queryParams.isDelete" placeholder="全部" clearable style="min-width:120px">
          <el-option label="全部" value="" />
          <el-option label="在群" :value="0" />
          <el-option label="离群" :value="1" />
        </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="['biosafety:quarantine:add']">新增</el-button>
      <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
        v-hasPermi="['biosafety:quarantine:edit']">修改</el-button>
      <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
        v-hasPermi="['biosafety:quarantine:remove']">删除</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport"
        v-hasPermi="['biosafety:quarantine:export']">导出</el-button>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="quarantineList" @selection-change="handleSelectionChange" max-height="600px"
      @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="variety" />
      <el-table-column label="检疫日期" align="center" prop="datetime" width="180"
        :formatter="(_, __, v) => parseTime(v, '{y}-{m}-{d}')" />
      <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="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="['biosafety: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="['biosafety: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>
         <p style="font-size: 12px; color: #999; margin: 5px 0 0 0; width: 100%; display: block;">
            羊只总数：{{ addForm.sheepList.length }}
            <el-button v-if="addForm.sheepList.length > 0" link type="danger" size="small" @click="clearAllSheep"
              style="margin-left: 10px;">
              清空全部
            </el-button>
          </p>
          <el-tag v-for="(item, i) in addForm.sheepList" :key="item.id" closable @close="addForm.sheepList.splice(i, 1)"
            style="margin: 0px 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-select v-model="addForm.sampler" filterable clearable placeholder="请输入采样员姓名" style="width: 100%"
                @change="handleTechnicalChange">
                <el-option v-for="item in technicalOptions" :key="item.value" :label="item.label" :value="item.value">
                  <span style="float: left">{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检疫员" prop="quarOfficer">
             <el-select v-model="addForm.quarOfficer" filterable clearable placeholder="请输入检疫员姓名" style="width: 100%"
                @change="handleTechnicalChange">
                <el-option v-for="item in technicalOptions" :key="item.value" :label="item.label" :value="item.value">
                  <span style="float: left">{{ item.label }}</span>
                </el-option>
              </el-select>
            </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="羊只品种">
              <span>{{ editForm.variety }}</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-select v-model="editForm.sampleOfficer" filterable clearable placeholder="请输入采样员姓名" style="width: 100%"
                @change="handleTechnicalChange">
                <el-option v-for="item in technicalOptions" :key="item.value" :label="item.label" :value="item.value">
                  <span style="float: left">{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="检疫员">
             <el-select v-model="editForm.quarOfficer" filterable clearable placeholder="请输入检疫员姓名" style="width: 100%"
                @change="handleTechnicalChange">
                <el-option v-for="item in technicalOptions" :key="item.value" :label="item.label" :value="item.value">
                  <span style="float: left">{{ item.label }}</span>
                </el-option>
              </el-select>
            </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'
import { searchEarNumbers } from '@/api/common/sheep'
import { getUserByPost } from '@/api/common/user'

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



const technicalOptions = ref([])   //自定义技术员数组变量

// 获取技术员列表
const fetchTechnicalList = () => {
  getUserByPost({ postCode: "" })
    .then(res => {
      if (res.code === 200 && Array.isArray(res.data)) {
        technicalOptions.value = res.data.map(item => ({
          // value: item.userId,
          value: item.nickName,
          label: item.nickName,
          // postName: item.postName,      // 保留用于下拉显示
          // postCode: item.postCode       // 保留用于逻辑判断
        }))
        console.log(technicalOptions.value);

      } else {
        technicalOptions.value = []
        ElMessage.warning(res.msg || '获取技术员列表失败')
      }
    })

}


/* 基础数据 */
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,
  allEarNumbers: [],  // 修改：改为数组，支持多耳号
  orderByColumn: null,   // 新增
  isAsc: null            // 新增
})


// 响应式数据
const pasteInput = ref('')           // 批量粘贴输入框
const earNumberOptions = ref([])     // 耳号下拉选项
const earNumberLoading = ref(false)  // 耳号加载状态
const isExpanded = ref(false)        // 控制耳号展开/折叠状态
const defaultShowCount = 2           // 默认显示的耳号数量

// 计算属性：控制显示的耳号列表
const displayedEarNumbers = computed(() => {
  if (!queryParams.allEarNumbers || queryParams.allEarNumbers.length === 0) {
    return []
  }

  // 如果展开或总数<=2，显示全部；否则只显示前2个
  if (isExpanded.value || queryParams.allEarNumbers.length <= defaultShowCount) {
    return queryParams.allEarNumbers
  } else {
    return queryParams.allEarNumbers.slice(0, defaultShowCount)
  }
})
/** 处理粘贴事件 */
function handlePaste(event) {
  nextTick(() => {
    handlePasteSubmit()
  })
}

/** 处理粘贴内容提交 */
function handlePasteSubmit() {
  if (!pasteInput.value || pasteInput.value.trim() === '') {
    return
  }

  // 支持多种分隔符: 空格、换行、逗号、制表符
  const separators = /[\s,，\n\r\t]+/
  const earNumbers = pasteInput.value
    .trim()
    .split(separators)
    .filter(item => item.trim() !== '')
    .map(item => item.trim())

  if (earNumbers.length === 0) {
    return
  }

  // 去重并添加到已选列表
  const existingSet = new Set(queryParams.value.allEarNumbers || [])
  const newEarNumbers = []
  const duplicates = []

  earNumbers.forEach(earNumber => {
    if (!existingSet.has(earNumber)) {
      newEarNumbers.push(earNumber)
      existingSet.add(earNumber)
    } else {
      duplicates.push(earNumber)
    }
  })

  // 添加新耳号
  if (newEarNumbers.length > 0) {
    queryParams.value.allEarNumbers = [
      ...(queryParams.value.allEarNumbers || []),
      ...newEarNumbers
    ]

    const message = `成功添加 ${newEarNumbers.length} 个耳号，当前共 ${queryParams.value.allEarNumbers.length} 个` +
      (duplicates.length > 0 ? `，已忽略 ${duplicates.length} 个重复耳号` : '')

    proxy.$modal.msgSuccess(message)
  } else if (duplicates.length > 0) {
    proxy.$modal.msgWarning(`所有耳号均已存在，当前共 ${queryParams.value.allEarNumbers.length} 个`)
  }

  // 清空输入框
  pasteInput.value = ''
}

/** 远程搜索耳号 */
function searchEarNumber(query) {
  if (query !== '') {
    earNumberLoading.value = true

    const queries = query.trim().split(/[\s,，]+/).filter(q => q)

    if (queries.length === 1) {
      // 单个耳号模糊搜索
      searchEarNumbers(query).then(response => {
        earNumberOptions.value = response.data || []
        earNumberLoading.value = false
      }).catch(() => {
        earNumberOptions.value = []
        earNumberLoading.value = false
      })
    } else {
      // 多个耳号直接作为选项
      earNumberOptions.value = queries
      earNumberLoading.value = false
    }
  } else {
    earNumberOptions.value = []
  }
}

/** 耳号选择变化处理 */
function handleEarNumberChange(value) {
  queryParams.value.allEarNumbers = [...new Set(value)]
  console.log(`已选择 ${queryParams.value.allEarNumbers.length} 个耳号:`, queryParams.value.allEarNumbers)
}

/** 切换展开/收起状态 */
function toggleExpand() {
  isExpanded.value = !isExpanded.value
}

/** 移除单个耳号 */
function handleRemoveEarNumber(tag) {
  const index = queryParams.value.allEarNumbers.indexOf(tag)
  if (index > -1) {
    queryParams.value.allEarNumbers.splice(index, 1)
    proxy.$modal.msgSuccess('已移除该耳号')
  }

  // 如果删除后剩余<=2个，自动收起
  if (queryParams.value.allEarNumbers.length <= defaultShowCount) {
    isExpanded.value = false
  }
}

/** 清空所有耳号 */
function clearAllEarNumbers() {
  proxy.$modal.confirm('确定要清空所有已选择的耳号吗？').then(() => {
    queryParams.value.allEarNumbers = []
    pasteInput.value = ''
    earNumberOptions.value = []
    isExpanded.value = false  // 重置展开状态
    proxy.$modal.msgSuccess('已清空所有耳号')
  }).catch(() => { })
}

/* 多选 */
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 clearAllSheep() {
  proxy.$modal.confirm('确认清空所有已选羊只？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    addForm.value.sheepList = []
    validSheepId.value = false
    proxy.$modal.msgSuccess('已清空全部羊只')
  }).catch(() => { })
}

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?.notInHerd?.length > 0) {
      const notFoundEars = res.data.notInHerd.join(' ')
      proxy.$modal.msgWarning(`以下耳号未查询到：${notFoundEars} 请检查后重新输入` )
    }

    // 处理查询到的耳号
    if (res.data?.inHerd?.length > 0) {
      res.data.inHerd.forEach(earNum => {
        // 检查是否已存在
        if (!addForm.value.sheepList.some(s => s.ear === earNum)) {
          const sheep = res.data.sheepDetails.find(s => s.manageTags === earNum)
          if (sheep) {
            addForm.value.sheepList.push({
              id: sheep.id,
              ear: sheep.manageTags
            })
          }
        }
      })
      validSheepId.value = true
    }

    // 只要 inHerd 有数据就清空输入框
    if (res.data?.inHerd?.length > 0) {
      addForm.value.sheepIdInput = ''
    }
  }).catch(err => {
    proxy.$modal.msgError('查询失败，请稍后重试')
  })
}

function submitAddForm() {
  if (addForm.value.sheepList.length === 0) {
    return proxy.$modal.msgError('请至少添加一个耳号')
  }
  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()
fetchTechnicalList()
</script>

<style scoped>
/* 已选耳号展示区样式 */
.selected-ear-numbers-display {
  max-height: 150px;
  overflow-y: auto;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.selected-ear-numbers-display::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.selected-ear-numbers-display::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.selected-ear-numbers-display::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.selected-ear-numbers-display .el-tag {
  margin: 4px;
  cursor: pointer;
}

.selected-ear-numbers-display .el-tag:hover {
  opacity: 0.8;
}

/* 隐藏 el-select 的下拉箭头（可选） */
:deep(.el-select__caret) {
  display: none;
}
</style>
