<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>

        <div
            v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0"
            class="selected-ear-numbers-display"
            style="margin-top: 10px;"
        >
          <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="datetime">
        <el-date-picker clearable
                        v-model="queryParams.datetime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择孕检日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="孕检结果" prop="result">
        <el-select v-model="queryParams.result" placeholder="请选择孕检结果" clearable>
          <el-option label="怀孕" value="怀孕" />
          <el-option label="未孕" value="未孕" />
          <el-option label="流产" value="流产" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="技术员" prop="technician">
        <el-select 
            v-model="queryParams.technician" 
            placeholder="请选择技术员" 
            filterable 
            clearable
            style="width: 200px"
            @change="handleQuery"
        >
          <el-option 
              v-for="item in technicalOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
          />
        </el-select>
      </el-form-item>

      <el-form-item label="孕检方式" prop="way">
        <el-select v-model="queryParams.way" placeholder="请选择孕检方式" clearable>
          <el-option label="B超" value="B超" />
          <el-option label="试纸" value="试纸" />
          <el-option label="血检" value="血检" />
        </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"
            v-hasPermi="['Pregnancy_Test:Pregnancy_Test:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['Pregnancy_Test:Pregnancy_Test:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['Pregnancy_Test:Pregnancy_Test:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['Pregnancy_Test:Pregnancy_Test:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="InfoFilled"
            @click="handleDebugTest"
        >调试测试</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="Pregnancy_TestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="耳号" align="center" prop="manageTags" width="120" />
      <el-table-column label="品种" align="center" prop="variety" width="100" />
      <el-table-column label="事件类型" align="center" width="80">
        <template #default="scope">
          <span>孕检</span>
        </template>
      </el-table-column>
      <el-table-column label="孕检日期" align="center" prop="datetime" width="120" />
      <el-table-column label="孕检原因" align="center" prop="reason" width="100" />
      <el-table-column label="孕检结果" align="center" prop="result" width="80">
        <template #default="scope">
          <el-tag :type="getResultTagType(scope.row.result)">
            {{ scope.row.result }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="配种公羊" prop="fatherManageTags"min-width="120" show-overflow-tooltip />
      <el-table-column label="配种公羊品种" prop="fatherVariety" min-width="120" show-overflow-tooltip />

      <el-table-column label="供体母羊" prop="donorEwe" />
      <el-table-column label="供体母羊品种" prop="donorEweVariety" min-width="120" show-overflow-tooltip />
      <el-table-column label="供体公羊" prop="donorRam" />
      <el-table-column label="供体公羊品种" prop="donorRamVariety" min-width="120" show-overflow-tooltip/>
      <el-table-column label="移胚数" prop="embryoCount" />

      <el-table-column label="配种类型" prop="matingTypeName" />
      <el-table-column label="配种日期" prop="matingDate" width="110" />
      <el-table-column label="胎儿数量" prop="fetusCount" />
      <el-table-column label="月龄" prop="monthAge" />
      <el-table-column label="孕检时羊只类别" prop="breedStatus" min-width="120" show-overflow-tooltip />
      <el-table-column label="胎次" prop="parity" />
      <el-table-column label="配次" prop="matingCounts" />
      <el-table-column label="当前羊舍" prop="sheepfoldName" />
      <el-table-column label="技术员" prop="technician" />
      <el-table-column label="繁育状态" prop="breedStatus" />
      <el-table-column label="预产日期" align="center" prop="expectedDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次事件日期" align="center" prop="lastEventDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastEventDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="孕检方式" align="center" prop="way" width="80" />
      <el-table-column label="创建人" align="center" prop="createBy" width="80" />
      <el-table-column label="创建日期" align="center" prop="createTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在牧场" align="center" prop="ranchName" width="100" />
      <el-table-column label="备注" align="center" prop="remark" width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['Pregnancy_Test:Pregnancy_Test:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Pregnancy_Test:Pregnancy_Test: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="title" v-model="open" width="900px" append-to-body>
      <el-form ref="Pregnancy_TestRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="耳号" prop="manageTags">
              <el-input v-model="form.manageTags" placeholder="请输入耳号" @blur="getSheepAndBreedInfo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="孕检日期" prop="datetime">
              <el-date-picker clearable
                              v-model="form.datetime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择孕检日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="孕检结果" prop="result">
              <el-select v-model="form.result" placeholder="请选择孕检结果" @change="onResultChange" style="width: 100%">
                <el-option label="怀孕" value="怀孕" />
                <el-option label="未孕" value="未孕" />
                <el-option label="流产" value="流产" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="孕检原因" prop="reason">
              <el-select v-model="form.reason" placeholder="请选择孕检原因" style="width: 100%">
                <el-option label="初检" value="初检" />
                <el-option label="复检" value="复检" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="胎儿数量" prop="fetusCount">
              <el-input-number
                  v-model="form.fetusCount"
                  :min="0"
                  :max="10"
                  placeholder="请输入胎儿数量"
                  :disabled="form.result !== '怀孕'"
                  style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="技术员" prop="technician">
              <el-select 
                  v-model="form.technician" 
                  placeholder="请选择技术员" 
                  filterable 
                  clearable
                  style="width: 100%"
              >
                <el-option 
                    v-for="item in technicalOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="孕检方式" prop="way">
              <el-select v-model="form.way" placeholder="请选择孕检方式" style="width: 100%">
                <el-option label="B超" value="B超" />
                <el-option label="试纸" value="试纸" />
                <el-option label="血检" value="血检" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">配种信息</el-divider>
        <el-row :gutter="30" v-if="breedInfo.manageTags">
          <el-col :span="8">
            <el-form-item label="配种类型">
              <el-input v-model="breedInfo.matingTypeName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配种公羊">
              <el-input v-model="breedInfo.fatherManageTags" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配种日期">
              <el-input :value="parseTime(breedInfo.matingDate, '{y}-{m}-{d}')" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!breedInfo.manageTags && form.manageTags">
          <el-col :span="24">
            <el-alert
                title="未找到该羊只的配种信息"
                type="warning"
                show-icon
                :closable="false">
            </el-alert>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Pregnancy_Test">
import {
  listPregnancy_Test,
  getPregnancy_Test,
  delPregnancy_Test,
  addPregnancy_Test,
  updatePregnancy_Test,
  getSheepByManageTags,
  getBreedInfoByManageTags,
  searchEarNumbers
} from "@/api/Pregnancy_Test/Pregnancy_Test"
import { getUserByPost } from '@/api/common/user' // 新增引入
import { ref, computed, nextTick } from 'vue'
import { ArrowUp, ArrowDown, Plus, Delete } from '@element-plus/icons-vue'
import {parseTime} from "@/utils/ruoyi.js";

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

// 新增：技术员选项
const technicalOptions = ref([])

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

  // 如果展开或总数<=2，显示全部；否则只显示前2个
  if (isExpanded.value || queryParams.value.allEarNumbers.length <= defaultShowCount) {
    return queryParams.value.allEarNumbers
  } else {
    return queryParams.value.allEarNumbers.slice(0, defaultShowCount)
  }
})
const { proxy } = getCurrentInstance()

const Pregnancy_TestList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const breedInfo = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageTags: null,
    datetime: null,
    allEarNumbers: [],  // ✅ 添加这一行！
    result: null,
    technician: null,
    way: null,
  },
  rules: {
    manageTags: [
      { required: true, message: "耳号不能为空", trigger: "blur" }
    ],
    datetime: [
      { required: true, message: "孕检日期不能为空", trigger: "change" }
    ],
    result: [
      { required: true, message: "孕检结果不能为空", trigger: "change" }
    ],
    technician: [
      { required: true, message: "技术员不能为空", trigger: "blur" }
    ],
    way: [
      { required: true, message: "孕检方式不能为空", trigger: "change" }
    ],
    fetusCount: [
      {
        validator: (rule, value, callback) => {
          if (form.value.result === '怀孕') {
            if (!value || value <= 0) {
              callback(new Error('孕检结果为怀孕时，胎儿数量必须填写且大于0'))
            } else if (value > 10) {
              callback(new Error('胎儿数量不能超过10个'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 新增：获取技术员列表
const fetchTechnicalList = () => {
  getUserByPost({ postCode: "techs" })
      .then(res => {
        if (res.code === 200 && Array.isArray(res.data)) {
          technicalOptions.value = res.data.map(item => ({
            value: item.nickName,
            label: item.nickName
          }))
        } else {
          technicalOptions.value = []
        }
      })
      .catch(err => {
        technicalOptions.value = []
      })
}

/** 处理粘贴事件 */
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(() => {})
}
/** 孕检结果标签类型 */
function getResultTagType(result) {
  switch (result) {
    case '怀孕':
      return 'success'
    case '未孕':
      return 'info'
    case '流产':
      return 'danger'
    default:
      return 'info'
  }
}

/** 孕检结果变化处理 */
function onResultChange(value) {
  if (value === '未孕' || value === '流产') {
    form.value.fetusCount = 0
  } else if (value === '怀孕') {
    if (!form.value.fetusCount || form.value.fetusCount <= 0) {
      form.value.fetusCount = 1
    }
  }
}

/** 查询孕检记录列表 */
function getList() {
  loading.value = true
  console.log("发送查询请求，参数：", queryParams.value)

  listPregnancy_Test(queryParams.value).then(response => {
    console.log("查询响应：", response)
    Pregnancy_TestList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false

    console.log("查询结果：", Pregnancy_TestList.value.length, "条记录")

    // 打印前3条记录的耳号
    if (Pregnancy_TestList.value.length > 0) {
      for (let i = 0; i < Math.min(3, Pregnancy_TestList.value.length); i++) {
        console.log(`记录${i+1}：ID=${Pregnancy_TestList.value[i].id}, 耳号=${Pregnancy_TestList.value[i].manageTags}`)
      }
    }
  }).catch(error => {
    console.error("查询失败：", error)
    Pregnancy_TestList.value = []
    total.value = 0
    loading.value = false
  })
}

/** 根据耳号获取羊只信息和配种信息 */
function getSheepAndBreedInfo() {
  if (form.value.manageTags) {
    const cleanTag = form.value.manageTags.trim()
    console.log("查询羊只信息，耳号：", cleanTag)

    // 获取羊只基本信息
    getSheepByManageTags(cleanTag).then(response => {
      console.log("羊只信息响应：", response)
      if (response.data) {
        form.value.sheepId = response.data.id
        console.log("找到羊只，ID：", response.data.id)
      } else {
        proxy.$modal.msgError("未找到该耳号的羊只信息")
        form.value.sheepId = null
      }
    }).catch(error => {
      console.error("查询羊只信息失败：", error)
      proxy.$modal.msgError("查询羊只信息失败")
      form.value.sheepId = null
    })

    // 获取配种信息
    getBreedInfoByManageTags(cleanTag).then(response => {
      console.log("配种信息响应：", response)
      if (response.data) {
        breedInfo.value = response.data
      } else {
        breedInfo.value = {}
      }
    }).catch(error => {
      console.error("查询配种信息失败：", error)
      breedInfo.value = {}
    })
  }
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    sheepId: null,
    manageTags: null,
    datetime: null,
    result: null,
    fetusCount: null,
    technician: null,
    way: 'B超', // 默认孕检方式为B超
    remark: null,
    reason: null, // ✅ 确保新增时该字段被重置
    createBy: null,
    createTime: null
  }
  breedInfo.value = {}
  proxy.resetForm("Pregnancy_TestRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log("执行搜索，原始参数：", queryParams.value)

  // 清理搜索参数
  if (queryParams.value.manageTags) {
    queryParams.value.manageTags = queryParams.value.manageTags.trim()
    console.log("清理后的耳号参数：", queryParams.value.manageTags)
  }
  if (queryParams.value.technician) {
    queryParams.value.technician = queryParams.value.technician.trim()
  }

  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  console.log("重置搜索条件")
  queryParams.value.allEarNumbers = []  // ✅ 添加这一行
  earNumberOptions.value = []            // ✅ 添加这一行
  isExpanded.value = false
  proxy.resetForm("queryRef")
  queryParams.value.manageTags = null
  queryParams.value.datetime = null
  queryParams.value.result = null
  queryParams.value.technician = null
  queryParams.value.way = null
  handleQuery()
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加孕检记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPregnancy_Test(_id).then(response => {
    form.value = response.data
    form.value.manageTags = response.data.manageTags
    // 获取配种信息用于显示
    if (response.data.manageTags) {
      getSheepAndBreedInfo()
    }
    open.value = true
    title.value = "修改孕检记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["Pregnancy_TestRef"].validate(valid => {
    if (valid) {
      // 四、提示：配种当天不许孕检
      if (form.value.datetime && breedInfo.value.matingDate) {
        // 统一格式化为 YYYY-MM-DD 进行字符串比较
        const matingDateStr = parseTime(breedInfo.value.matingDate, '{y}-{m}-{d}');
        const pregnancyDateStr = form.value.datetime; // 已是格式化后的字符串

        if (matingDateStr === pregnancyDateStr) {
          proxy.$modal.msgError("操作拦截：该羊只在 " + matingDateStr + " 刚进行过配种，配种当天不允许进行孕检！");
          return; // 终止提交
        }
      }
      // 清理表单数据
      if (form.value.manageTags) {
        form.value.manageTags = form.value.manageTags.trim()
      }
      if (form.value.technician) {
        form.value.technician = form.value.technician.trim()
      }
      if (form.value.remark) {
        form.value.remark = form.value.remark.trim()
      }

      console.log("提交表单数据：", form.value)

      if (form.value.id != null) {
        updatePregnancy_Test(form.value).then(response => {
          console.log("修改成功响应", response)
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList(); // 修改完直接刷新
        }).catch((error) => {
          console.error("修改失败", error)
          proxy.$modal.msgError("修改失败")
        })
      } else {
        addPregnancy_Test(form.value).then(response => {
          console.log("新增成功响应", response)
          if (response && response.code === 200) {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            // 关键：重置查询条件，防止被之前的搜索框内容过滤掉新数据
            resetQuery();
          } else {
            console.error("新增返回异常", response)
            proxy.$modal.msgError("新增失败")
          }
        }).catch((error) => {
          console.error("新增失败", error)
          proxy.$modal.msgError("新增失败")
        })
      }
    }
  })
}

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

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

/** 调试测试按钮 */
function handleDebugTest() {
  console.log("执行调试测试")
  proxy.$http({
    url: '/Pregnancy_Test/Pregnancy_Test/debug/test',
    method: 'get'
  }).then(response => {
    console.log("调试测试响应：", response)
    proxy.$modal.msgSuccess(response.msg || "调试测试完成")
  }).catch(error => {
    console.error("调试测试失败：", error)
    proxy.$modal.msgError("调试测试失败")
  })
}

// 页面初始化
onMounted(() => {
  fetchTechnicalList() // 初始化加载技术员列表
  console.log("页面初始化，开始加载数据")
  getList()
})
</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>