<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" 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="治疗日期" style="width: 308px">
        <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="status">
        <el-select v-model="queryParams.status" placeholder="请选择治疗状态" style="width: 120px;">
          <el-option v-for="u in treat_status" :key="u.value" :label="u.label" :value="u.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="兽医" prop="veterinary">
        <el-select v-model="editForm.veterinary" 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>

    <!-- 按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <!-- 按钮区域新增“诊疗” -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="DocumentAdd" @click="handleAddDiagnosis" :disabled="multiple">诊疗</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="treatmentList" @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="monthAge" sortable="custom" />
      <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="parity" sortable="custom" />
      <el-table-column label="繁殖状态" align="center" prop="breed" />
      <el-table-column label="泌乳天数" align="center" prop="lactDay" sortable="custom" width="120px" />
      <el-table-column label="怀孕天数" align="center" prop="gestDay" sortable="custom" width="120px" />
      <el-table-column label="疾病类型" align="center" prop="diseaseName" />
      <el-table-column label="治疗状态" align="center" prop="treatmentPlan">
        <template #default="scope"><dict-tag :options="treat_status" :value="scope.row.status" /></template>
      </el-table-column>
      <el-table-column label="兽医" align="center" prop="veterinary" />
      <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="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)">修改</el-button>
          <el-button link type="primary" @click="gotDiag(scope.row)"
            v-if="scope.row.status == 0 || scope.row.status == 1">诊断</el-button>
          <el-button link type="danger" icon="Delete" @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" />

    <!-- 新增弹窗 -->
    <el-dialog title="添加治疗记录" v-model="addDialog" width="70%" top="5vh" append-to-body destroy-on-close>
      <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="80px" size="large">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="羊只耳号" required>
              <el-input v-model="sheepInput" placeholder="输入耳号后按回车验证" style="width: 300px"
                @keyup.enter="validateSheep" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
              <!-- 已选耳号 -->
              <el-form-item v-if="selectedSheepList.length > 0" label="">
                <p style="font-size: 12px; color: #999; 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-col>
        </el-row>

        <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="selectedPresId" filterable clearable placeholder="请选择处方" style="width: 100%"
                @change="handleSelectPrescription">
                <el-option v-for="item in presOptions" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疾病大类" prop="diseasePid">
              <el-select v-model="addForm.diseasePid" placeholder="请选择" style="width: 100%"
                @change="handleDiseaseTypeChange">
                <el-option v-for="item in parentDiseaseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="疾病子类" prop="diseaseId">
              <el-select v-model="addForm.diseaseId" :disabled="!addForm.diseasePid" placeholder="请选择"
                style="width: 100%">
                <el-option v-for="item in childDiseaseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">治疗记录</el-divider>
        <div class="mb20">
          <el-button type="primary" icon="Plus" @click="handleAddSwPresDetail">添加药品</el-button>
        </div>

        <el-table :data="swPresDetailList" border stripe>
          <el-table-column label="序号" width="60">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="药品" width="160px">
            <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="160px">
            <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="单位">
            <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="使用方法">
            <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="使用时间" width="160px">
            <template #default="scope">
              <el-date-picker v-model="scope.row.usetime" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width:100%;" />
            </template>
          </el-table-column>
          <el-table-column label="生产厂家" width="160px">
            <template #default="scope">
              <el-input v-model="scope.row.manufacturer" placeholder="生产厂家" />
            </template>
          </el-table-column>
          <el-table-column label="生产批号" width="160px">
            <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="deletePresDetail(scope.row)" />
            </template>
          </el-table-column>
        </el-table>

        <el-row :gutter="20" style="margin-top:20px;">
          <el-col :span="12">
            <el-form-item label="兽医">
              <el-select v-model="addForm.veterinarian" 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="addForm.status" placeholder="请选择治疗状态">
                <el-option v-for="u in treat_status" :key="u.value" :label="u.label" :value="u.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

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

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

    <!-- 修改弹窗 -->
    <el-dialog title="修改治疗记录" v-model="editDialog" width="70%" top="5vh" append-to-body destroy-on-close>
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="80px" size="large">
        <!-- 羊只基本信息展示（只读） -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="羊只耳号:">
              <el-text>{{ editForm.sheepNo }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="羊只性别:">
              <el-text>{{ editForm.gender }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品种:">
              <el-text>{{ editForm.variety }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="羊只类别:">
              <el-text>{{ editForm.sheepType }}</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="月龄">
              <el-text>{{ editForm.monthAge }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="胎次">
              <el-text>{{ editForm.parity }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="繁殖状态">
              <el-text>{{ editForm.breed }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="泌乳天数">
              <el-text>{{ editForm.lactDay }}天</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="怀孕天数">
              <el-text>{{ editForm.gestDay }}天</el-text>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 可编辑内容 -->
        <el-divider content-position="left">治疗记录</el-divider>
        <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%" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="处方">
              <el-select v-model="selectedPresId" filterable clearable placeholder="请选择处方" style="width: 100%"
                @change="handleSelectPrescription">
                <el-option v-for="item in presOptions" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疾病大类" prop="diseasePid">
              <el-select v-model="editForm.diseasePid" placeholder="请选择" style="width: 100%"
                @change="handleDiseaseTypeChange">
                <el-option v-for="item in parentDiseaseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="疾病子类" prop="diseaseId">
              <el-select v-model="editForm.diseaseId" :disabled="!editForm.diseasePid" placeholder="请选择"
                style="width: 100%">
                <el-option v-for="item in childDiseaseOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="mb20">
          <el-button type="primary" icon="Plus" @click="handleAddSwPresDetail">添加药品</el-button>
        </div>

        <el-table :data="swPresDetailList" border stripe>
          <el-table-column label="序号" width="60">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <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="单位">
            <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="使用方法">
            <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="使用时间" width="160px">
            <template #default="scope">
              <el-date-picker v-model="scope.row.usetime" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="生产厂家" width="160px">
            <template #default="scope">
              <el-input v-model="scope.row.manufacturer" placeholder="生产厂家" />
            </template>
          </el-table-column>
          <el-table-column label="生产批号" width="160px">
            <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="deletePresDetail(scope.row)" />
            </template>
          </el-table-column>
        </el-table>

        <el-row :gutter="20" style="margin-top:20px;">
          <el-col :span="12">
            <el-form-item label="兽医">
              <el-select v-model="editForm.veterinarian" 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.status" placeholder="请选择治疗状态">
                <el-option v-for="u in treat_status" :key="u.value" :label="u.label" :value="u.value + ''" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

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


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增诊疗弹窗 -->
    <el-dialog title="新增诊疗记录" v-model="diagnosisDialog" width="50%" append-to-body destroy-on-close>
      <el-form label-width="120px">
        <el-form-item label="选中羊只">
          <el-tag v-for="no in selectedSheepNos" :key="no" style="margin-right: 5px">{{ no }}</el-tag>
        </el-form-item>
        <el-form-item label="治疗日期" prop="datetime">
          <el-date-picker v-model="addDia.datetime" type="date" style="width: 100%" />
        </el-form-item>
        <el-form-item label="诊疗结果" prop="result">
          <el-select v-model="addDia.result" placeholder="请选择治疗结果" style="width: 100%;">
            <el-option v-for="item in diag_result" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="转入羊舍" prop="sheepfoldId">
          <el-select v-model="addDia.sheepfoldId" filterable placeholder="请选择转入羊舍" style="width: 100%;">
            <el-option v-for="item in sheepfolds" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="diagnosisDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDiagnosis">确认</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { listTreatment, getTreatment, delTreatment, addTreatment, updateTreatment } from '@/api/biosafety/treatment'
import { listDisease } from '@/api/biosafety/disease'
import { listSheepfold_management } from "@/api/fileManagement/sheepfold_management"
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 request from '@/utils/request'
import { useRouter } from 'vue-router'
import { searchEarNumbers } from '@/api/common/sheep'
import { getUserByPost } from '@/api/common/user'

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

// 获取技术员列表
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 || '获取技术员列表失败')
      }
    })

}

const router = useRouter()

const { proxy } = getCurrentInstance()
const { sheep_gender, diag_result, treat_status } = proxy.useDict("sheep_gender", "diag_result", "treat_status")


/* ---------- 列表区域 ---------- */
const treatmentList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const daterangeDatetime = ref([])
const sheepfolds = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  sheepNo: null,
  allEarNumbers: [],
  veterinary: 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 addDialog = ref(false)
const editDialog = ref(false)

/* ---------- 表单与数据 ---------- */
const sheepInput = ref('')
const selectedSheepList = ref([])

const selectedPresId = ref()
const presOptions = ref([])
const parentDiseaseOptions = ref([])
const childDiseaseOptions = ref([])
const units = ref([])
const usages = ref([])
const medicines = ref([])

const addForm = reactive({
  id: null,
  eventType: '诊疗',
  datetime: new Date(),
  diseasePid: null,
  diseaseId: null,
  veterinarian: '',
  stats: '',
  comment: ''
})

const editForm = reactive({
  id: null,
  eventType: '诊疗',
  datetime: new Date(),
  diseasePid: null,
  diseaseId: null,
  veterinarian: '',
  comment: '',
  sheepNo: '',
  barnName: '',
  variety: '',
  sheepType: '',
  monthAge: '',
  gender: '',
  status: '',
  parity: '',
  breed: '',
  lactDay: '',
  gestDay: ''
})

const rules = {
  datetime: [{ required: true, message: '请选择日期', trigger: 'change' }],
  diseasePid: [{ required: true, message: '请选择疾病大类', trigger: 'change' }],
  diseaseId: [{ required: true, message: '请选择疾病子类型', trigger: 'change' }]
}

const swPresDetailList = ref([
  { mediId: null, dosage: 0, unit: null, usageId: null, usetime: new Date().toISOString().slice(0, 10), manufacturer: '', batchNumber: '' }
])

/* ---------- 新增诊疗 ---------- */
const diagnosisDialog = ref(false)
const selectedSheepNos = ref([])
const addDia = reactive({
  sheepfoldId: null,
  result: null,
  datetime: new Date().toISOString().slice(0, 10)
})


function handleAddDiagnosis() {
  if (!ids.value.length) {
    proxy.$modal.msgWarning('请至少选择一条治疗记录')
    return
  }
  selectedSheepNos.value = treatmentList.value
    .filter(item => ids.value.includes(item.id))
    .map(item => item.sheepNo)
  diagnosisDialog.value = true
}

function submitDiagnosis() {
  const data = {
    treatIds: ids.value,
    result: addDia.result,
    datetime: addDia.datetime,
    sheepfoldId: addDia.sheepfoldId
  }
  request.post('/diagnosis/diagnosis/adds', data).then(() => {
    proxy.$modal.msgSuccess('诊疗成功')
    diagnosisDialog.value = false
    getList()
  })
}

/* ---------- 列表查询 ---------- */
function getList() {
  loading.value = true
  const qp = { ...queryParams }
  qp.params = {}
  if (daterangeDatetime.value && daterangeDatetime.value.length) {
    qp.params.beginDatetime = daterangeDatetime.value[0]
    qp.params.endDatetime = daterangeDatetime.value[1]
  }
  listTreatment(qp).then(res => {
    treatmentList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

/* ---------- 疾病联动 ---------- */
function handleDiseaseTypeChange(pid) {
  if (!pid) {
    childDiseaseOptions.value = []
    addForm.diseaseId = null
    editForm.diseaseId = null
    return
  }
  listDisease({ pid }).then(res => (childDiseaseOptions.value = res.data))
}

/* ---------- 处方联动 ---------- */
function handleSelectPrescription(id) {
  if (!id) return
  getPrescription(id).then(res => {
    swPresDetailList.value = res.data.swPresDetailList?.map(i => ({
      mediId: i.mediId,
      dosage: i.dosage,
      unit: i.unitId,
      usageId: i.usageId,
      manufacturer: '',
      batchNumber: ''
    })) || []
  })
}

/* ---------- 药品明细 ---------- */
function handleAddSwPresDetail() {
  swPresDetailList.value.push({
    mediId: null,
    dosage: 0,
    unit: null,
    usageId: null,
    usetime: new Date().toISOString().slice(0, 10),
    manufacturer: '',
    batchNumber: ''
  })
}
function deletePresDetail(row) {
  swPresDetailList.value.splice(swPresDetailList.value.indexOf(row), 1)
}

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() {
  resetForm(addForm)
  addDialog.value = true
}
function submitAddForm() {
  proxy.$refs.addFormRef.validate(valid => {
    if (!valid) return
    if (!selectedSheepList.value.length) {
      proxy.$modal.msgError('请至少添加一只羊'); return
    }
    const data = {
      ...addForm,
      datetime: addForm.datetime ? new Date(addForm.datetime).getTime() : null,
      usageDetails: swPresDetailList.value,
      sheepIds: selectedSheepList.value.map(s => s.sheepId)
    }
    addTreatment(data).then(() => {
      proxy.$modal.msgSuccess('新增成功')
      addDialog.value = false
      getList()
    })
  })
}

/* ---------- 修改 ---------- */
function handleUpdate(row) {
  resetForm(editForm)
  getTreatment(row.id).then(res => {
    Object.assign(editForm, {
      id: res.data.id,
      datetime: res.data.datetime ? new Date(res.data.datetime) : new Date(),
      diseasePid: res.data.diseasePid,
      diseaseId: res.data.diseaseId,
      usageId: res.data.usageId,
      veterinarian: res.data.veterinarian,
      comment: res.data.comment,
      sheepNo: res.data.sheepNo,
      barnName: res.data.sheepfoldName,
      variety: res.data.variety,
      sheepType: res.data.sheepType,
      monthAge: res.data.monthAge,
      gender: res.data.gender,
      parity: res.data.parity,
      breed: res.data.breed,
      status: res.data.status,
      lactDay: res.data.lactDay,
      gestDay: res.data.gestDay
    })
    swPresDetailList.value = res.data.usageDetails || []
    selectedPresId.value = res.data.prescriptionId || null
    if (editForm.diseasePid) handleDiseaseTypeChange(editForm.diseasePid)
    editDialog.value = true
  })
}
function submitEditForm() {
  proxy.$refs.editFormRef.validate(valid => {
    if (!valid) return
    const data = {
      ...editForm,
      datetime: editForm.datetime ? new Date(editForm.datetime).getTime() : null,
      usageDetails: swPresDetailList.value
    }
    updateTreatment(data).then(() => {
      proxy.$modal.msgSuccess('修改成功')
      editDialog.value = false
      getList()
    })
  })
}

/* ---------- 通用 ---------- */
function resetQuery() {
  daterangeDatetime.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}
function handleDelete(row) {
  const id = row.id || ids.value
  proxy.$modal.confirm('是否确认删除治疗记录编号为"' + id + '"的数据项？')
    .then(() => delTreatment(id))
    .then(() => { getList(); proxy.$modal.msgSuccess('删除成功') })
}
function handleExport() {
  proxy.download('treatment/treatment/export', { ...queryParams }, `治疗记录_${Date.now()}.xlsx`)
}
function resetForm(formObj) {
  Object.assign(formObj, {
    id: null,
    datetime: new Date(),
    diseasePid: null,
    diseaseId: null,
    veterinarian: '',
    comment: '',
    sheepNo: '',
    barnName: '',
    variety: '',
    sheepType: '',
    monthAge: '',
    gender: '',
    parity: '',
    breed: '',
    lactDay: '',
    gestDay: ''
  })
  selectedPresId.value = null
  swPresDetailList.value = [{ mediId: null, dosage: 0, unit: null, usageId: null, manufacturer: '', batchNumber: '' }]
}
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  
    queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
  }
  getList()
}

/* 跳转诊疗 */
function gotDiag(row) {
  router.push({ path: '/biosafety/diagnosis/add', query: { tId: row.id, sId: row.sheepId } })
}


/* ---------- 初始化 ---------- */
onMounted(() => {
  getList()
  listDisease().then(res => {
    parentDiseaseOptions.value = res.data.filter(item => item.pid === 0)
  })
  listPrescription({ status: 1, persType: 4 }).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 }))
  })
  listSheepfold_management().then(res => {
    sheepfolds.value = res.rows.map(item => ({ id: item.id, name: item.sheepfoldName }))
  })
  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>
