<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="管理耳号" prop="manageTags">
        <el-input
            v-model="queryParams.manageTags"
            placeholder="请输入管理耳号"
            clearable
            @keyup.enter="handleQuery"
            @blur="validateManageTagsInQuery"
        />
      </el-form-item>
      <el-form-item label="事件类型" prop="eventType">
        <el-input
            v-model="queryParams.eventType"
            placeholder="请输入事件类型"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="死亡日期" prop="deathDate">
        <el-date-picker clearable
                        v-model="queryParams.deathDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择死亡日期">
        </el-date-picker>
      </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>
          <el-option label="深埋" value="深埋" />
          <el-option label="无害化" value="无害化" />
        </el-select>
      </el-form-item>
      <el-form-item label="技术员" prop="technician">
        <el-input
            v-model="queryParams.technician"
            placeholder="请输入技术员"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处理人" prop="handler">
        <el-input
            v-model="queryParams.handler"
            placeholder="请输入处理人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班组" prop="workGroup">
        <el-input
            v-model="queryParams.workGroup"
            placeholder="请输入班组"
            clearable
            @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"
        @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="请输入管理耳号"
                  @blur="validateManageTagsInForm"
                  :loading="validatingTags"
              />
            </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="请选择死亡日期">
              </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-input v-model="form.technician" placeholder="请输入技术员"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="处理人" prop="handler">
              <el-input v-model="form.handler" placeholder="请输入处理人"/>
            </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} from "@/api/sheep_death/death"

const {proxy} = getCurrentInstance()

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 validatingTags = ref(false) // 验证管理耳号的loading状态
const diseaseOptions = ref([]) // 疾病类型选项
const diseaseSubtypeOptions = ref([]) // 疾病子类型选项

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageTags: null,
    eventType: null,
    deathDate: null,
    diseaseTypeId: null,
    diseaseSubtypeId: null,
    disposalDirection: null,
    technician: null,
    handler: null,
    workGroup: null,
    comment: null,
    isDelete: null
  },
  rules: {
    manageTags: [
      {required: true, message: "管理耳号不能为空", trigger: "blur"}
    ],
    deathDate: [
      {required: true, message: "死亡日期不能为空", trigger: "blur"}
    ],
  }
})

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

/** 查询羊只死淘记录列表 */
function getList() {
  loading.value = true
  listDeath(queryParams.value).then(response => {
    deathList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

/** 疾病类型改变时，更新子类型选项 */
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 validateManageTagsInQuery() {
  const manageTags = queryParams.value.manageTags
  if (manageTags && manageTags.trim()) {
    validateManageTags(manageTags.trim(), 'query')
  }
}

/** 验证表单中的管理耳号 */
function validateManageTagsInForm() {
  const manageTags = form.value.manageTags
  if (manageTags && manageTags.trim()) {
    validateManageTags(manageTags.trim(), 'form')
  }
}

/** 验证管理耳号是否存在 */
function validateManageTags(manageTags, source) {
  if (validatingTags.value) return // 防止重复请求

  validatingTags.value = true

  getSheepInfo(manageTags).then(response => {
    if (response.code === 200 && response.data) {
      if (source === 'form') {
        proxy.$modal.msgSuccess("羊只验证成功")
      } else {
        proxy.$modal.msgSuccess("耳号验证成功")
      }
    } else {
      // 耳号不存在时清空输入并提示
      if (source === 'form') {
        form.value.manageTags = null
      } else {
        queryParams.value.manageTags = null
      }
      proxy.$modal.msgError("该耳号不存在")
    }
  }).catch(error => {
    // 验证失败时清空输入并提示
    if (source === 'form') {
      form.value.manageTags = null
    } else {
      queryParams.value.manageTags = null
    }
    proxy.$modal.msgError("该耳号不存在")
  }).finally(() => {
    validatingTags.value = false
  })
}

// 取消按钮
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,
    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() {
  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() {
  proxy.download('sheep_death/death/export', {
    ...queryParams.value
  }, `death_${new Date().getTime()}.xlsx`)
}

// 初始化
getDiseaseTreeData()
getList()
</script>

<style scoped>
</style>