<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="耳号" prop="manageTags">
        <el-input
            v-model="queryParams.manageTags"
            placeholder="请输入耳号，多个耳号用逗号分隔"
            clearable
            @keyup.enter="handleQuery"
            @clear="handleQuery"
        />
      </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-input
            v-model="queryParams.technician"
            placeholder="请输入技术员"
            clearable
            @keyup.enter="handleQuery"
        />
      </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="datetime" width="120" fixed="left">
        <template #default="scope">
          <span>{{ parseTime(scope.row.datetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <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="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="配种公羊" align="center" prop="fatherManageTags" width="100" />
      <el-table-column label="配种公羊品种" align="center" prop="fatherVariety" width="120" />
      <el-table-column label="配种类型" align="center" prop="matingTypeName" width="80" />
      <el-table-column label="配种日期" align="center" prop="matingDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.matingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 新增配后天数字段 -->
      <el-table-column label="配后天数" align="center" prop="daysAfterMating" width="80">
        <template #default="scope">
          <span v-if="scope.row.daysAfterMating !== null">{{ scope.row.daysAfterMating }}天</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="胎儿数量" align="center" prop="fetusCount" width="80" />
      <el-table-column label="月龄" align="center" prop="monthAge" width="60" />
      <el-table-column label="孕检时羊只类别" align="center" prop="breedStatus" width="120" />
      <el-table-column label="胎次" align="center" prop="parity" width="60" />
      <el-table-column label="配次" align="center" prop="matingCounts" width="60" />
      <el-table-column label="当前羊舍" align="center" prop="sheepfoldName" width="100" />
      <el-table-column label="技术员" align="center" prop="technician" width="80" />
      <el-table-column label="繁育状态" align="center" prop="breedStatus" width="80" />
      <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"
        @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="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-input v-model="form.technician" placeholder="请输入技术员" />
            </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 } from "@/api/Pregnancy_Test/Pregnancy_Test"

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

/** 孕检结果标签类型 */
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,
    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("重置搜索条件")
  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.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
          // 强制刷新页面数据
          setTimeout(() => {
            getList()
          }, 500)
        }).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
            // 强制刷新页面数据，延迟执行确保对话框关闭
            setTimeout(() => {
              getList()
            }, 500)
          } 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(() => {
  console.log("页面初始化，开始加载数据")
  getList()
})
</script>

<style scoped>
.el-table {
  font-size: 12px;
}

.el-table .cell {
  padding: 0 5px;
}

/* 调试样式 */
.debug-info {
  background-color: #f0f9ff;
  border: 1px solid #0ea5e9;
  border-radius: 4px;
  padding: 8px;
  margin: 8px 0;
  font-size: 12px;
  color: #0369a1;
}
</style>