<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="母羊耳号" prop="eweManageTags">
        <el-input
            v-model="queryParams.eweManageTags"
            placeholder="请输入母羊耳号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公羊耳号" prop="ramManageTags">
        <el-input
            v-model="queryParams.ramManageTags"
            placeholder="请输入公羊耳号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="母羊品种" prop="eweVariety">
        <el-input
            v-model="queryParams.eweVariety"
            placeholder="请输入母羊品种"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公羊品种" prop="ramVariety">
        <el-input
            v-model="queryParams.ramVariety"
            placeholder="请输入公羊品种"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配种方式" prop="breedType">
        <el-select v-model="queryParams.breedType" placeholder="请选择配种方式" clearable>
          <el-option label="同期发情" value="1"></el-option>
          <el-option label="本交" value="2"></el-option>
          <el-option label="冲胚" value="3"></el-option>
          <el-option label="自然发情人工授精" value="4"></el-option>
        </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="pregnancyResult">
        <el-select v-model="queryParams.pregnancyResult" placeholder="请选择孕检结果" clearable>
          <el-option label="怀孕" value="怀孕"></el-option>
          <el-option label="空怀" value="空怀"></el-option>
          <el-option label="疑似怀孕" value="疑似怀孕"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否孕检" prop="isPregnancyChecked">
        <el-select v-model="queryParams.isPregnancyChecked" placeholder="请选择是否已孕检" clearable>
          <el-option label="已孕检" value="1"></el-option>
          <el-option label="未孕检" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
            v-model="queryParams.createBy"
            placeholder="请输入创建人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择创建日期">
        </el-date-picker>
      </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="['Breeding_records:Breeding_records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['Breeding_records:Breeding_records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['Breeding_records:Breeding_records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['Breeding_records:Breeding_records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="Breeding_recordsList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :default-sort="{prop: 'createTime', order: 'descending'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- 创建日期作为第一列,支持排序 -->
      <el-table-column
          label="创建日期"
          align="center"
          prop="createTime"
          width="180"
          fixed="left"
          sortable="custom"
          sort-by="createTime"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="耳号" align="center" prop="eweManageTags" width="120" />
      <el-table-column label="品种" align="center" prop="eweVariety" width="100" />
      <el-table-column label="事件类型" align="center" width="100">
        <template #default="scope">
          <el-tag type="success">配种</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="配种公羊" align="center" prop="ramManageTags" width="120" />
      <el-table-column label="配种公羊品种" align="center" prop="ramVariety" width="120" />
      <el-table-column label="配种方式" align="center" prop="matingType" width="140">
        <template #default="scope">
          <span>{{ getBreedTypeText(scope.row.breedType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="月龄" align="center" prop="eweMonthAge" width="80" />
      <el-table-column label="配种时羊只类别" align="center" prop="sheepType" width="120" />
      <el-table-column label="胎次" align="center" prop="eweParity" width="80" />
      <el-table-column label="配次" align="center" prop="matingCount" width="80" />
      <el-table-column label="发情后配种时间(小时)" align="center" prop="timeSincePlanning" width="140">
        <template #default="scope">
          <span>{{ scope.row.timeSincePlanning || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前羊舍" align="center" prop="eweSheepfoldName" width="120" />
      <el-table-column label="技术员" align="center" prop="technician" width="100" />
      <el-table-column label="羊只备注" align="center" prop="eweComment" width="120" show-overflow-tooltip />
      <el-table-column label="繁育状态" align="center" prop="eweBreedStatus" width="100" />
      <el-table-column label="是否性控" align="center" prop="eweControlled" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.eweControlled === 1 ? 'success' : 'info'">
            {{ scope.row.eweControlled === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="耗精量" align="center" prop="breedDrugs" width="100" />

      <!-- 孕检相关字段 -->
      <el-table-column label="孕检状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isPregnancyChecked === 1 ? 'success' : 'warning'">
            {{ scope.row.isPregnancyChecked === 1 ? '已孕检' : '未孕检' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="孕检日期" align="center" prop="pregnancyCheckDate" width="120">
        <template #default="scope">
          <span>{{ scope.row.pregnancyCheckDate ? parseTime(scope.row.pregnancyCheckDate, '{y}-{m}-{d}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="孕检结果" align="center" prop="pregnancyResult" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.pregnancyResult"
                  :type="getPregnancyResultType(scope.row.pregnancyResult)">
            {{ scope.row.pregnancyResult }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="胎数" align="center" prop="fetusCount" width="80">
        <template #default="scope">
          <span>{{ scope.row.fetusCount || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="孕检方式" align="center" prop="pregnancyWay" width="100">
        <template #default="scope">
          <span>{{ scope.row.pregnancyWay || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配种到孕检间隔(天)" align="center" prop="daysToPregnancyCheck" width="140">
        <template #default="scope">
          <span>{{ scope.row.daysToPregnancyCheck || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      <el-table-column label="所在牧场" align="center" prop="ranchName" width="120" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['Breeding_records:Breeding_records:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Breeding_records:Breeding_records: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="800px" append-to-body>
      <el-form ref="Breeding_recordsRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="母羊耳号" prop="eweManageTags">
              <el-input v-model="form.eweManageTags" placeholder="请输入母羊耳号" @blur="getEweInfoAndPlan" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公羊耳号" prop="ramManageTags">
              <el-input v-model="form.ramManageTags" placeholder="请输入公羊耳号" @blur="getRamInfoByTags" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="配种方式" prop="breedType">
              <el-select v-model="form.breedType" placeholder="请选择配种方式">
                <el-option label="同期发情" :value="1"></el-option>
                <el-option label="本交" :value="2"></el-option>
                <el-option label="冲胚" :value="3"></el-option>
                <el-option label="自然发情人工授精" :value="4"></el-option>
              </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="breedDrugs">
              <el-input v-model="form.breedDrugs" 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-row v-if="eweInfo">
          <el-col :span="24">
            <el-divider content-position="left">母羊信息</el-divider>
          </el-col>
          <el-col :span="8">
            <el-form-item label="品种">
              <el-input v-model="eweInfo.variety" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="月龄">
              <el-input v-model="eweInfo.month_age" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="胎次">
              <el-input v-model="eweInfo.parity" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="繁育状态">
              <el-input v-model="eweInfo.breed_status" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前羊舍">
              <el-input v-model="eweInfo.sheepfold_name" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否性控">
              <el-input :value="eweInfo.controlled === 1 ? '是' : '否'" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 显示配种计划信息区域 -->
        <el-row v-if="breedPlan">
          <el-col :span="24">
            <el-divider content-position="left">配种计划信息</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划公羊">
              <el-input v-model="breedPlan.ram_manage_tags" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划配种方式">
              <el-input v-model="breedPlan.breed_type_name" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 显示孕检信息区域(如果已有孕检记录) -->
        <el-row v-if="form.pregnancyResult">
          <el-col :span="24">
            <el-divider content-position="left">孕检信息</el-divider>
          </el-col>
          <el-col :span="8">
            <el-form-item label="孕检日期">
              <el-input :value="form.pregnancyCheckDate ? parseTime(form.pregnancyCheckDate, '{y}-{m}-{d}') : ''" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="孕检结果">
              <el-input v-model="form.pregnancyResult" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="胎数">
              <el-input v-model="form.fetusCount" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="孕检方式">
              <el-input v-model="form.pregnancyWay" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="孕检技术员">
              <el-input v-model="form.pregnancyTechnician" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配种到孕检间隔">
              <el-input :value="form.daysToPregnancyCheck + '天'" readonly />
            </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="Breeding_records">
import {
  listBreeding_records,
  getBreeding_records,
  delBreeding_records,
  addBreeding_records,
  updateBreeding_records,
  getSheepInfoByTags,
  getLatestBreedPlanByEweTags
} from "@/api/Breeding_records/Breeding_records"

const {proxy} = getCurrentInstance()

const Breeding_recordsList = 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 eweInfo = ref(null)
const breedPlan = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    eweManageTags: null,
    ramManageTags: null,
    eweVariety: null,
    ramVariety: null,
    breedType: null,
    technician: null,
    createBy: null,
    createTime: null,
    pregnancyResult: null,
    isPregnancyChecked: null,
    // 添加排序参数
    orderByColumn: 'createTime',
    isAsc: 'desc'
  },
  rules: {
    eweManageTags: [
      {required: true, message: "母羊耳号不能为空", trigger: "blur"}
    ],
    ramManageTags: [
      {required: true, message: "公羊耳号不能为空", trigger: "blur"}
    ],
    technician: [
      {required: true, message: "技术员不能为空", trigger: "blur"}
    ],
    breedType: [
      {required: true, message: "配种方式不能为空", trigger: "change"}
    ]
  }
})

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

/** 获取配种方式文字显示 */
function getBreedTypeText(breedType) {
  if (breedType === 1) return '同期发情'
  if (breedType === 2) return '本交'
  if (breedType === 3) return '冲胚'
  if (breedType === 4) return '自然发情人工授精'
  return '-'
}

/** 获取孕检结果标签类型 */
function getPregnancyResultType(result) {
  if (result === '怀孕') return 'success'
  if (result === '空怀') return 'danger'
  if (result === '疑似怀孕') return 'warning'
  return 'info'
}

/** 查询配种记录列表 */
function getList() {
  loading.value = true
  listBreeding_records(queryParams.value).then(response => {
    Breeding_recordsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 表格排序变化处理
function handleSortChange({column, prop, order}) {
  queryParams.value.orderByColumn = prop
  queryParams.value.isAsc = order === 'ascending' ? 'asc' : 'desc'
  getList()
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    sheepId: null,
    ramId: null,
    eweId: null,
    eweManageTags: null,
    ramManageTags: null,
    technician: null,
    breedDrugs: null,
    breedType: null,
    comment: null,
    createBy: null,
    createTime: null,
    pregnancyCheckDate: null,
    pregnancyResult: null,
    pregnancyWay: null,
    fetusCount: null,
    pregnancyTechnician: null,
    pregnancyRemark: null,
    daysToPregnancyCheck: null
  }
  eweInfo.value = null
  breedPlan.value = null
  proxy.resetForm("Breeding_recordsRef")
}

/** 搜索按钮操作 */
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()
  open.value = true
  title.value = "添加配种记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBreeding_records(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改配种记录"

    // 如果有母羊耳号,加载母羊信息
    if (form.value.eweManageTags) {
      getEweInfoAndPlan()
    }
  })
}

/** 根据母羊耳号获取羊只信息和配种计划信息 */
function getEweInfoAndPlan() {
  if (form.value.eweManageTags) {
    // 获取母羊信息
    getSheepInfoByTags(form.value.eweManageTags).then(response => {
      if (response.data) {
        eweInfo.value = response.data
        form.value.eweId = response.data.id
      } else {
        proxy.$modal.msgError("未找到该母羊耳号对应的羊只信息")
        eweInfo.value = null
      }
    }).catch(() => {
      proxy.$modal.msgError("查询母羊信息失败")
      eweInfo.value = null
    })

    // 获取配种计划信息(使用最新的获取方法)
    getLatestBreedPlanByEweTags(form.value.eweManageTags).then(response => {
      if (response.data) {
        breedPlan.value = response.data
        // 自动填充公羊耳号和配种方式(但允许用户修改)
        if (!form.value.ramManageTags) {
          form.value.ramManageTags = response.data.ram_manage_tags
        }
        if (!form.value.breedType) {
          form.value.breedType = response.data.breed_type
        }

        proxy.$modal.msgSuccess("已自动匹配配种计划信息,可手动调整")
      } else {
        breedPlan.value = null
        proxy.$modal.msgWarning("未找到该母羊的配种计划,请手动输入配种信息")
      }
    }).catch(() => {
      proxy.$modal.msgWarning("查询配种计划失败,请手动输入配种信息")
      breedPlan.value = null
    })
  }
}

/** 根据公羊耳号获取羊只信息 */
function getRamInfoByTags() {
  if (form.value.ramManageTags) {
    getSheepInfoByTags(form.value.ramManageTags).then(response => {
      if (response.data) {
        form.value.ramId = response.data.id
      } else {
        proxy.$modal.msgError("未找到该公羊耳号对应的羊只信息")
      }
    }).catch(() => {
      proxy.$modal.msgError("查询公羊信息失败")
    })
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["Breeding_recordsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBreeding_records(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBreeding_records(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 delBreeding_records(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('Breeding_records/Breeding_records/export', {
    ...queryParams.value
  }, `配种记录_${new Date().getTime()}.xlsx`)
}

// 页面初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
/* 样式保持不变 */
</style>