<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      
      <el-form-item label="管理耳号" prop="manageTagsList">
        <el-select
            v-model="queryParams.manageTagsList"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入耳号"
            :remote-method="remoteSearchEarNo"
            :loading="loadingSearch"
            allow-create
            default-first-option
            clearable
            style="width: 240px"
        >
          <el-option
              v-for="item in earNoOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="死亡日期" prop="deathDateRange">
        <el-date-picker
            v-model="queryParams.deathDateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="羊只类型" prop="sheepTypeList">
        <el-select 
          v-model="queryParams.sheepTypeList" 
          placeholder="请选择羊只类型" 
          multiple 
          clearable 
          collapse-tags
          style="width: 200px">
           <el-option
            v-for="dict in sys_sheep_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="疾病类型" prop="diseaseTypeId">
        <el-tree-select
            v-model="queryParams.diseaseTypeId"
            :data="diseaseOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择疾病类型"
            check-strictly
            clearable
            style="width: 200px;"
        />
      </el-form-item>
      
      <el-form-item label="死淘去向" prop="disposalDirection">
        <el-select v-model="queryParams.disposalDirection" placeholder="请选择死淘去向" clearable style="width: 200px;">
          <el-option label="深埋" value="深埋" />
          <el-option label="无害化" value="无害化" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="技术员" prop="technicianList">
        <el-select
            v-model="queryParams.technicianList"
            multiple
            filterable
            clearable
            placeholder="请选择技术员"
            style="width: 200px"
        >
          <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="handlerList">
         <el-select
            v-model="queryParams.handlerList"
            multiple
            filterable
            clearable
            placeholder="请选择处理人"
            style="width: 200px"
        >
          <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="workGroupList">
        <el-select v-model="queryParams.workGroupList" placeholder="请选择班组" multiple clearable style="width: 200px">
           <el-option label="一组" value="一组" />
           <el-option label="二组" value="二组" />
           <el-option label="三组" value="三组" />
        </el-select>
      </el-form-item>

      <el-form-item label="羊只品种" prop="variety">
        <el-input
            v-model="queryParams.variety"
            placeholder="请输入羊只品种"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </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="['sheep_death:death:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['sheep_death:death:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['sheep_death:death:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['sheep_death:death:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deathList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="死亡日期" align="center" prop="deathDate" width="120" fixed="left">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deathDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主键ID" align="center" prop="id" width="80"/>
      <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" prop="eventType" width="100"/>
      <el-table-column label="羊只类型" align="center" prop="sheepType" width="130"/>
      <el-table-column label="性别" align="center" prop="gender" width="80">
        <template #default="scope">
          <span>{{ scope.row.gender === 1 ? '母' : scope.row.gender === 2 ? '公' : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日龄" align="center" prop="dayAge" width="80"/>
      <el-table-column label="胎次" align="center" prop="parity" width="80"/>
      <el-table-column label="疾病类型" align="center" prop="diseaseTypeName" width="120"/>
      <el-table-column label="疾病子类型" align="center" prop="diseaseSubtypeName" width="130"/>
      <el-table-column label="死淘去向" align="center" prop="disposalDirection" width="100"/>
      <el-table-column label="技术员" align="center" prop="technician" width="100"/>
      <el-table-column label="处理人" align="center" prop="handler" width="100"/>
      <el-table-column label="羊舍" align="center" prop="sheepfoldName" width="120"/>
      <el-table-column label="班组" align="center" prop="workGroup" width="100"/>
      <el-table-column label="繁育状态" align="center" prop="breedStatus" width="100"/>
      <el-table-column label="死亡时产后天数" align="center" prop="postLambingDay" width="130"/>
      <el-table-column label="死亡时泌乳天数" align="center" prop="lactationDay" width="130"/>
      <el-table-column label="死亡时怀孕天数" align="center" prop="gestationDay" width="130"/>
      <el-table-column label="创建人" align="center" prop="createBy" width="100"/>
      <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="comment" width="150"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['sheep_death:death:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['sheep_death:death: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="700px" append-to-body>
      <el-form ref="deathRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="管理耳号" prop="manageTags">
              <el-input
                  v-model="form.manageTags"
                  placeholder="请输入管理耳号 (可多个空格隔开)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="死亡日期" prop="deathDate">
              <el-date-picker clearable
                              v-model="form.deathDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择死亡日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="疾病类型" prop="diseaseTypeId">
              <el-tree-select
                  v-model="form.diseaseTypeId"
                  :data="diseaseOptions"
                  :props="{ value: 'id', label: 'name', children: 'children' }"
                  value-key="id"
                  placeholder="请选择疾病类型"
                  check-strictly
                  clearable
                  @change="onDiseaseTypeChange"
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="疾病子类型" prop="diseaseSubtypeId">
              <el-tree-select
                  v-model="form.diseaseSubtypeId"
                  :data="diseaseSubtypeOptions"
                  :props="{ value: 'id', label: 'name', children: 'children' }"
                  value-key="id"
                  placeholder="请选择疾病子类型"
                  check-strictly
                  clearable
                  style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="死淘去向" prop="disposalDirection">
              <el-select v-model="form.disposalDirection" 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="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-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="处理人" prop="handler">
              <el-select 
                  v-model="form.handler" 
                  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="workGroup">
              <el-input v-model="form.workGroup" placeholder="请输入班组"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="comment">
              <el-input v-model="form.comment" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </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="Death">
import {
  listDeath, 
  getDeath, 
  delDeath, 
  addDeath, 
  updateDeath, 
  getSheepInfo, 
  getDiseaseTree,
  searchEarNo,
  // searchTechnician, // 移除旧的远程搜索接口
  // searchHandler   // 移除旧的远程搜索接口
} from "@/api/sheep_death/death"
import { getUserByPost } from '@/api/common/user' // 新增引入

// 响应式数据
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 { sys_sheep_type } = proxy.useDict("sys_sheep_type");

const deathList = 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 diseaseOptions = ref([]) 
const diseaseSubtypeOptions = ref([])

// 远程搜索相关变量
const loadingSearch = ref(false)
const earNoOptions = ref([])
// const technicianOptions = ref([]) // 移除旧变量
// const handlerOptions = ref([])    // 移除旧变量

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageTagsList: [], // 多选耳号
    deathDateRange: [], // 死亡日期范围
    sheepTypeList: [],  // 多选羊只类型
    technicianList: [], // 多选技术员
    handlerList: [],    // 多选处理人
    workGroupList: [],  // 多选班组
    
    variety: null, 
    diseaseTypeId: null,
    diseaseSubtypeId: null,
    disposalDirection: null
  },
  rules: {
    manageTags: [
      {required: true, message: "管理耳号不能为空", trigger: "blur"}
    ],
    deathDate: [
      {required: true, message: "死亡日期不能为空", 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 getList() {
  loading.value = true
  
  // 处理日期范围
  let params = { ...queryParams.value };
  
  // 处理 params 对象 (BaseEntity 需要)
  params.params = {};
  if (queryParams.value.deathDateRange && queryParams.value.deathDateRange.length === 2) {
    params.params['beginDeathDate'] = queryParams.value.deathDateRange[0];
    params.params['endDeathDate'] = queryParams.value.deathDateRange[1];
  }
  
  listDeath(params).then(response => {
    deathList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 远程搜索耳号 */
function remoteSearchEarNo(query) {
  if (query) {
    loadingSearch.value = true
    searchEarNo(query).then(res => {
      earNoOptions.value = res.data || []
      loadingSearch.value = false
    })
  } else {
    earNoOptions.value = []
  }
}

// 移除旧的 remoteSearchTechnician 和 remoteSearchHandler 函数

/** 获取疾病树形列表 */
function getDiseaseTreeData() {
  getDiseaseTree().then(response => {
    if (response.code === 200) {
      diseaseOptions.value = proxy.handleTree(response.data, "id", "pid")
    }
  }).catch(() => {})
}

/** 疾病类型改变时，更新子类型选项 */
function onDiseaseTypeChange(value) {
  form.value.diseaseSubtypeId = null
  diseaseSubtypeOptions.value = []

  if (value) {
    const findChildren = (nodes, targetId) => {
      for (const node of nodes) {
        if (node.id === targetId) {
          return node.children || []
        }
        if (node.children) {
          const result = findChildren(node.children, targetId)
          if (result.length > 0) return result
        }
      }
      return []
    }
    diseaseSubtypeOptions.value = findChildren(diseaseOptions.value, value)
  }
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    sheepId: null,
    manageTags: null,
    eventType: "死亡",
    deathDate: new Date().toISOString().split('T')[0],
    diseaseTypeId: null,
    diseaseSubtypeId: null,
    disposalDirection: null,
    technician: null,
    allEarNumbers: [],  // 🔥 必须添加
    handler: null,
    workGroup: null,
    comment: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    isDelete: null
  }
  diseaseSubtypeOptions.value = []
  proxy.resetForm("deathRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  // 手动清空数组类型的查询条件
  queryParams.value.manageTagsList = []
  queryParams.value.sheepTypeList = []
  queryParams.value.technicianList = []
  queryParams.value.handlerList = []
  queryParams.value.workGroupList = []
  queryParams.value.deathDateRange = []
  
  proxy.resetForm("queryRef")
  handleQuery()
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getDiseaseTreeData()
  open.value = true
  title.value = "添加羊只死淘记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  getDiseaseTreeData()
  const _id = row.id || ids.value
  getDeath(_id).then(response => {
    form.value = response.data
    if (form.value.diseaseTypeId) {
      onDiseaseTypeChange(form.value.diseaseTypeId)
    }
    open.value = true
    title.value = "修改羊只死淘记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deathRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDeath(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDeath(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

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

/** 导出按钮操作 */
function handleExport() {
  // 导出参数构造
  let params = { ...queryParams.value };
  params.params = {};
  if (queryParams.value.deathDateRange && queryParams.value.deathDateRange.length === 2) {
    params.params['beginDeathDate'] = queryParams.value.deathDateRange[0];
    params.params['endDeathDate'] = queryParams.value.deathDateRange[1];
  }

  proxy.download('sheep_death/death/export', params, `death_${new Date().getTime()}.xlsx`)
}

// 初始化
getDiseaseTreeData()
getList()
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>