<template>
  <div class="app-container">
    <!-- 1. 搜索 -->
    <el-form :model="queryParams" ref="queryRef" inline v-show="showSearch" label-width="68px">
     <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="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" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="技术员" prop="technical">
          <el-select v-model="queryParams.technical" 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="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 2. 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
    </el-row>

    <!-- 3. 列表 -->
    <el-table v-loading="loading" :data="dewormList" @selection-change="handleSelectionChange" max-height="650px"
      @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="sheepType" />
      <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="monthAge" sortable="custom" />
      <el-table-column label="胎次" align="center" prop="parity" sortable="custom" />
      <el-table-column label="繁殖状态" align="center" prop="breed" />
      <el-table-column label="技术员" align="center" prop="technical" />
      <el-table-column label="驱虫日期" align="center" prop="datetime" width="180">
        <template #default="scope">{{ parseTime(scope.row.datetime, '{y}-{m}-{d}') }}</template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="comment" />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</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" />

    <!-- 4. 新增弹窗（羊舍多选 + 无卡片 + 自动剔除） -->
    <el-dialog title="新增驱虫记录" v-model="addOpen" width="60%" top="5vh" append-to-body>
      <el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">

        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 耳号追加 -->
            <el-form-item label="耳号">
              <el-input v-model="sheepInput" placeholder="输入耳号回车添加" style="width: 220px" @keyup.enter="validateSheep" />
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <!-- 羊舍多选 -->
            <el-form-item label="羊舍" prop="barnIds">
              <el-select v-model="selectedBarnIds" multiple collapse-tags placeholder="请选择羊舍" style="width: 100%"
                @change="handleBarnChange">
                <el-option v-for="b in barns" :key="b.id" :label="b.sheepfoldName" :value="b.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

  
        <!-- 已选耳号 -->
        <el-form-item v-if="selectedSheepList.length > 0" label="">
            <p style="font-size: 12px; color: #999; margin: 5px 0 0 0; width: 100%; display: block;">
          羊只总数：{{ selectedSheepList.length }}
          <el-button  link type="danger" size="small" @click="clearAllSheep"
            style="margin-left: 10px;">
            清空全部
          </el-button>
        </p>
          <el-tag v-for="(tag, idx) in selectedSheepList" :key="tag.sheepId" closable @close="removeSheep(idx)"
            style="margin-right: 6px">
            {{ tag.sheepNo }}
          </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" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处方">
              <el-select v-model="addForm.prescriptionId" filterable clearable placeholder="请选择处方" style="width: 100%"
                @change="handleSelectPrescription">
                <el-option v-for="p in presOptions" :key="p.id" :label="p.label" :value="p.id" />
              </el-select>
            </el-form-item>
          </el-col>
         <el-col :span="12">
              <el-form-item label="技术员">
                <el-select v-model="addForm.technical" 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>
        <div style="margin: 8px 5px;">
          <!-- 药品明细 -->
          <el-button type="primary" icon="Plus" size="small" @click="handleAddDetail">添加药品</el-button>
          <el-table :data="usageDetails" border stripe style="margin-top: 8px">
            <el-table-column label="药品">
              <template #default="scope">
                <el-select v-model="scope.row.mediId" filterable placeholder="请选择药品">
                  <el-option v-for="m in medicines" :key="m.value" :label="m.label" :value="m.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="用量" width="160">
              <template #default="scope">
                <el-input-number v-model="scope.row.dosage" :min="0" :precision="1" />
              </template>
            </el-table-column>
            <el-table-column label="单位" width="120">
              <template #default="scope">
                <el-select v-model="scope.row.unit" placeholder="单位">
                  <el-option v-for="u in units" :key="u.value" :label="u.label" :value="u.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="用法" width="120">
              <template #default="scope">
                <el-select v-model="scope.row.usageId" placeholder="用法">
                  <el-option v-for="u in usages" :key="u.value" :label="u.label" :value="u.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="生产厂家">
              <template #default="scope">
                <el-input v-model="scope.row.manufacturer" placeholder="生产厂家" />
              </template>
            </el-table-column>
            <el-table-column label="生产批号">
              <template #default="scope">
                <el-input v-model="scope.row.batchNumber" placeholder="批号" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template #default="scope">
                <el-button link type="danger" icon="Delete" @click="usageDetails.splice(scope.$index, 1)" />
              </template>
            </el-table-column>
          </el-table>

        </div>


        <el-form-item label="备注">
          <el-input type="textarea" :rows="3" v-model="addForm.comment" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

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

    <!-- 5. 修改弹窗（羊舍只读下拉） -->
    <el-dialog title="修改驱虫记录" v-model="editOpen" width="60%" top="5vh" append-to-body>
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="羊只耳号">
              <span>{{ editForm.sheepNo }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="品种">
              <span>{{ editForm.variety }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="羊只类别">
              <span>{{ editForm.sheepType }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <span> <dict-tag :options="sheep_gender" :value="editForm.gender" /></span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="繁殖状态">
              <span>{{ editForm.breed }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="驱虫日期" prop="datetime">
              <el-date-picker v-model="editForm.datetime" type="date" style="width: 100%" readonly />
            </el-form-item>
          </el-col>
         <el-col :span="12">
              <el-form-item label="技术员">
                <el-select v-model="editForm.technical" 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>
        <div style="margin: 10px 10px;">
          <el-button type="primary" icon="Plus" size="small" @click="handleAddDetail">添加药品</el-button>
          <el-table :data="usageDetails" border stripe style="margin-top: 8px">
            <el-table-column label="药品">
              <template #default="scope">
                <el-select v-model="scope.row.mediId" filterable placeholder="请选择药品">
                  <el-option v-for="m in medicines" :key="m.value" :label="m.label" :value="m.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="用量" width="160">
              <template #default="scope">
                <el-input-number v-model="scope.row.dosage" :min="0" :precision="1" style="width: 120px;" />
              </template>
            </el-table-column>
            <el-table-column label="单位" width="120">
              <template #default="scope">
                <el-select v-model="scope.row.unit" placeholder="单位">
                  <el-option v-for="u in units" :key="u.value" :label="u.label" :value="u.value+''" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="用法" width="120">
              <template #default="scope">
                <el-select v-model="scope.row.usageId" placeholder="用法">
                  <el-option v-for="u in usages" :key="u.value" :label="u.label" :value="u.value+''" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="生产厂家">
              <template #default="scope">
                <el-input v-model="scope.row.manufacturer" placeholder="生产厂家" />
              </template>
            </el-table-column>
            <el-table-column label="生产批号">
              <template #default="scope">
                <el-input v-model="scope.row.batchNumber" placeholder="批号" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template #default="scope">
                <el-button link type="danger" icon="Delete" @click="usageDetails.splice(scope.$index, 1)" />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-form-item label="备注">
          <el-input type="textarea" :rows="3" v-model="editForm.comment" placeholder="请输入备注" />
        </el-form-item>
      </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="Deworm">
  import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
  import { listDeworm, getDeworm, delDeworm, addDeworm, updateDeworm } from '@/api/biosafety/deworm'
  import { listPrescription, getPrescription } from '@/api/biosafety/prescription'
  import { listUnit } from '@/api/biosafety/unit'
  import { listUsage } from '@/api/biosafety/usage'
  import { listMedicine } from '@/api/biosafety/medicine'
  import { searchEarNumbers } from '@/api/common/sheep'
  import request from '@/utils/request'
  import { parseTime } from '@/utils/ruoyi'
  import { getUserByPost } from '@/api/common/user'

  const { proxy } = getCurrentInstance()
  const { sheep_gender } = proxy.useDict('sheep_gender')

  /* ------------------ 列表 ------------------ */
  const loading = ref(true)
  const showSearch = ref(true)
  const total = ref(0)
  const dewormList = ref([])
  const daterangeDatetime = ref([])
  const technicalOptions = ref([])


  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    sheepNo: null,
    technical: null,
 
    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 getList() {
    loading.value = true
    const qp = { ...queryParams }
    qp.params = {}
    if (daterangeDatetime.value?.length) {
      qp.params.beginDatetime = daterangeDatetime.value[0]
      qp.params.endDatetime = daterangeDatetime.value[1]
    }
    listDeworm(qp).then(res => {
      dewormList.value = res.rows
      total.value = res.total
      loading.value = false
    })
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    multiple.value = !selection.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()
  }

  function handleQuery() {
    queryParams.pageNum = 1
    getList()
  }
  function resetQuery() {
    daterangeDatetime.value = []
    proxy.resetForm('queryRef')
    handleQuery()
  }

  /* ------------------ 新增 ------------------ */
  const addOpen = ref(false)
  const addForm = reactive({
    datetime: new Date(),
    technical: '',
    comment: '',
    prescriptionId: null
  })
  const addRules = {
    datetime: [{ required: true, message: '请选择日期', trigger: 'change' }]
  }
  const selectedBarnIds = ref([])
  const selectedSheepList = ref([])
  const barns = ref([])
  const sheepInput = ref('')

  function getBarns() {
    request({ url: '/sheepfold_management/sheepfold_management/list', method: 'get' })
      .then(res => (barns.value = res.rows))
  }
  function handleBarnChange(barnIds) {
    // 1. 当前所有已选羊舍的 id 集合
    const currentIds = new Set(barnIds || [])

    // 2. 把已选羊只中不属于当前羊舍的过滤掉
    selectedSheepList.value = selectedSheepList.value.filter(
      s => currentIds.has(s.barnId)
    )

    // 3. 追加新增羊舍的羊只（已去重）
    const taskArr = [...currentIds].filter(id =>
      !selectedSheepList.value.some(s => s.barnId === id)
    )
    if (!taskArr.length) return

    Promise.all(
      taskArr.map(id =>
        request({ url: `/sheepfold_management/sheepfold_management/getSheepById`, params: { id } })
      )
    ).then(resArr => {
      const list = resArr.flatMap(r => (r.data || []).map(s => ({
        sheepNo: s.manageTags,
        sheepId: s.id,
        barnId: s.barnId
      })))
      const map = new Map(selectedSheepList.value.map(s => [s.sheepId, s]))
      list.forEach(item => map.set(item.sheepId, item))
      selectedSheepList.value = [...map.values()]
    })
  }

  function clearAllSheep() {
    proxy.$modal.confirm('确认清空所有已选羊只？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      selectedSheepList.value = []
      proxy.$modal.msgSuccess('已清空全部羊只')
    }).catch(() => { })
  }

  function validateSheep() {
    const no = sheepInput.value.trim()
    if (!no) return

    // 检查是否已选择
    if (selectedSheepList.value.some(s => s.sheepNo === no)) {
      proxy.$modal.msgWarning('该耳号已存在')
      sheepInput.value = ''
      return
    }

    request.get(`/sheep/sheep/byManageTags/${no}`).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 (!selectedSheepList.value.some(s => s.sheepNo === earNum)) {
            const sheep = res.data.sheepDetails.find(s => s.manageTags === earNum)
            if (sheep) {
              selectedSheepList.value.push({
                sheepId: sheep.id,
                sheepNo: sheep.manageTags
              })
            }
          }
        })
      }

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

  function handleAdd() {
    Object.assign(addForm, {
      datetime: new Date(),
      technical: '',
      comment: '',
      prescriptionId: null
    })
    selectedBarnIds.value = []
    selectedSheepList.value = []
    usageDetails.value = [{ mediId: null, dosage: 0, unit: null, usageId: null,manufacturer:null,batchNumber:null }]
    getBarns()
    addOpen.value = true
  }

  function submitAddForm() {
    proxy.$refs.addFormRef.validate(valid => {
      if (!valid || !selectedSheepList.value.length) {
        proxy.$modal.msgError('请完善表单并至少选择一只羊')
        return
      }
      addDeworm({
        ...addForm,
        datetime: new Date(addForm.datetime).getTime(),
        sheepIds: selectedSheepList.value.map(s => s.sheepId),
        usageDetails: usageDetails.value
      }).then(() => {
        proxy.$modal.msgSuccess('新增成功')
        addOpen.value = false
        getList()
      })
    })
  }

  /* ------------------ 修改 ------------------ */
  const editOpen = ref(false)
  const editForm = reactive({})
  const editRules = {
    datetime: [{ required: true, message: '请选择日期', trigger: 'change' }]
  }

  function handleUpdate(row) {
    getDeworm(row.id).then(res => {
      Object.assign(editForm, res.data)
      selectedSheepList.value = [{ sheepNo: res.data.sheepNo, sheepId: res.data.sheepId }]
      usageDetails.value = res.data.usageDetails || []
      editOpen.value = true
    })
  }

  function submitEditForm() {
    proxy.$refs.editFormRef.validate(valid => {
      if (!valid) return
      updateDeworm({
        ...editForm,
        datetime: new Date(editForm.datetime).getTime(),
        usageDetails: usageDetails.value
      }).then(() => {
        proxy.$modal.msgSuccess('修改成功')
        editOpen.value = false
        getList()
      })
    })
  }

  /* ------------------ 功能函数 ------------------ */
  function handleDelete(row) {
    const id = row.id || ids.value
    proxy.$modal.confirm('确认删除？')
      .then(() => delDeworm(id))
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      })
  }

  function handleExport() {
    proxy.download('biosafety/deworm/export', { ...queryParams }, `驱虫_${Date.now()}.xlsx`)
  }

  /* ------------------ 药品/处方/下拉 ------------------ */
  const usageDetails = ref([])
  const presOptions = ref([])
  const units = ref([])
  const usages = ref([])
  const medicines = ref([])

  function handleSelectPrescription(id) {
    if (!id) return
    getPrescription(id).then(res => {
      usageDetails.value = res.data?.swPresDetailList?.map(i => ({
        mediId: i.mediId,
        dosage: i.dosage,
        unit: i.unitId,
        usageId: i.usageId
      })) || []
    })
  }

  function handleAddDetail() {
    usageDetails.value.push({ mediId: null, dosage: 0, unit: null, usageId: null,manufacturer:null,batchNumber:null })
  }
  // 获取技术员列表
  const fetchTechnicalList = () => {
    getUserByPost({ postCode: "techs" })
      .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 || '获取技术员列表失败')
        }
      })

  }

  /* ------------------ 初始化 ------------------ */
  onMounted(() => {

    getList()
    getBarns()
    listPrescription({ status: 1, persType: 1 }).then(res => {
      presOptions.value = res.rows.map(item => ({ id: item.id, label: item.name }))
    })
    listUnit().then(res => {
      units.value = res.rows.map(item => ({ value: item.id, label: item.name }))
    })
    listUsage().then(res => {
      usages.value = res.rows.map(item => ({ value: item.id, label: item.name }))
    })
    listMedicine().then(res => {
      medicines.value = res.rows.map(item => ({ value: item.id, label: item.name }))
    })
    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>
