<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="母羊耳号" prop="femaleEarNumber">
        <el-input
            v-model="queryParams.femaleEarNumber"
            placeholder="请输入母羊耳号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="母羊品种" prop="femaleBreed">
        <el-input
            v-model="queryParams.femaleBreed"
            placeholder="请输入母羊品种"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="胎次" prop="parity">
        <el-input
            v-model="queryParams.parity"
            placeholder="请输入胎次"
            clearable
            @keyup.enter="handleQuery"
        />
      </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="farm">
        <el-input
            v-model="queryParams.farm"
            placeholder="请输入所在牧场"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配种日期" prop="breedingDate">
        <el-date-picker
            v-model="queryParams.breedingDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD">
        </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="['breed:lambing_records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['breed:lambing_records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['breed:lambing_records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['breed:lambing_records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="lambing_recordsList" @selection-change="handleSelectionChange" row-key="id">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="母羊耳号" align="center" prop="femaleEarNumber" width="120" fixed="left" />
      <el-table-column label="母羊品种" align="center" prop="femaleBreed" width="100" />
      <el-table-column label="配种日期" align="center" prop="breedingDate" width="110">
        <template #default="scope">
          <span>{{ parseTime(scope.row.breedingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="胎次" align="center" prop="parity" width="80" />
      <el-table-column label="公羊耳号" align="center" prop="maleEarNumber" width="120" />
      <el-table-column label="公羊品种" align="center" prop="maleBreed" width="120" />
      <el-table-column label="产羔数量" align="center" prop="lambsBorn" width="90" />
      <el-table-column label="活羔数量" align="center" prop="survival" width="90" />
      <el-table-column label="折损数" align="center" prop="loss" width="80">
        <template #default="scope">
          <span>{{ (scope.row.lambsBorn || 0) - (scope.row.survival || 0) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="技术员" align="center" prop="technician" width="100" />
      <el-table-column label="月龄" align="center" prop="monthAge" width="80" />
      <el-table-column label="产羔评分" align="center" prop="score" width="90" />
      <el-table-column label="公羔数量" align="center" prop="maleCount" width="90" />
      <el-table-column label="母羔数量" align="center" prop="femaleCount" width="90" />
      <el-table-column label="留养公羔数量" align="center" prop="retainedMaleCount" width="130" />
      <el-table-column label="留养母羔数量" align="center" prop="retainedFemaleCount" width="130" />
      <el-table-column label="未留养公羔数量" align="center" prop="unretainedMaleCount" width="140" />
      <el-table-column label="未留养母羔数量" align="center" prop="unretainedFemaleCount" width="140" />
      <el-table-column label="产羔时怀孕天数" align="center" prop="pregnancyDays" width="140" />
      <el-table-column label="当前羊舍" align="center" prop="currentShed" width="100" />
      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      <el-table-column label="创建日期" align="center" prop="createTime" width="110">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在牧场" align="center" prop="farm" width="100" />
      <el-table-column label="备注" align="center" prop="comment" width="120" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleLambDetail(scope.row)" size="small">产羔详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['breed:lambing_records:edit']" size="small">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['breed:lambing_records:remove']" size="small">删除</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="lambing_recordsRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="母羊耳号" prop="femaleEarNumber">
              <el-input
                  v-model="form.femaleEarNumber"
                  placeholder="请输入母羊耳号"
                  @blur="handleEarNumberBlur"
                  @input="handleEarNumberInput"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="胎次" prop="parity">
              <el-input v-model="form.parity" placeholder="请输入胎次" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公羊耳号" prop="maleEarNumber">
              <el-input v-model="form.maleEarNumber" placeholder="公羊耳号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配种日期" prop="breedingDate">
              <el-input v-model="form.breedingDate" placeholder="配种日期" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="怀孕天数" prop="pregnancyDays">
              <el-input v-model="form.pregnancyDays" placeholder="怀孕天数" readonly />
            </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 :gutter="20">
          <el-col :span="12">
            <el-form-item label="产羔数量" prop="lambsBorn">
              <el-input
                  v-model.number="form.lambsBorn"
                  placeholder="请输入产羔数量"
                  type="number"
                  @input="handleLambsBornChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活羔数量" prop="survival">
              <el-input v-model.number="form.survival" placeholder="请输入活羔数量" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产羔评分" prop="score">
              <el-input v-model.number="form.score" placeholder="请输入产羔评分" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产羔日期" prop="createTime">
              <el-date-picker
                  clearable
                  v-model="form.createTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择产羔日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <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>

        <!-- 羔羊信息录入 -->
        <div v-if="form.lambsBorn > 0 && showLambForms">
          <el-divider content-position="left">羔羊信息录入</el-divider>
          <div v-for="(lamb, index) in lambForms" :key="index" class="lamb-form-item">
            <div class="lamb-form-header">
              <span class="lamb-title">第{{ index + 1 }}只羔羊</span>
            </div>
            <el-row :gutter="20" class="lamb-form-content">
              <el-col :span="8">
                <el-form-item :label="`羔羊耳号`" :prop="`lambForms.${index}.lambEarNumber`">
                  <el-input v-model="lamb.lambEarNumber" placeholder="请输入羔羊耳号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="`性别`" :prop="`lambForms.${index}.gender`">
                  <el-select v-model="lamb.gender" placeholder="请选择性别">
                    <el-option label="公" value="male"></el-option>
                    <el-option label="母" value="female"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="`是否留养`" :prop="`lambForms.${index}.isRetained`">
                  <el-switch
                      v-model="lamb.isRetained"
                      active-text="是"
                      inactive-text="否">
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" class="lamb-form-content">
              <el-col :span="8">
                <el-form-item :label="`体重(kg)`" :prop="`lambForms.${index}.birthWeight`">
                  <el-input v-model.number="lamb.birthWeight" placeholder="请输入体重" type="number" step="0.1" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="`品种`" :prop="`lambForms.${index}.lambBreed`">
                  <el-select
                      v-model="lamb.lambBreed"
                      placeholder="请选择品种"
                      filterable
                      clearable
                      style="width: 100%"
                  >
                    <el-option
                        v-for="variety in varietyList"
                        :key="variety.id"
                        :label="variety.variety"
                        :value="variety.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="`家系`" :prop="`lambForms.${index}.lineage`">
                  <el-input v-model="lamb.lineage" placeholder="请输入家系" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" class="lamb-form-content">
              <el-col :span="8">
                <el-form-item :label="`生日`" :prop="`lambForms.${index}.birthday`">
                  <el-date-picker
                      v-model="lamb.birthday"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="请选择生日">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </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>

    <!-- 产羔详情对话框 -->
    <el-dialog title="产羔详情" v-model="detailOpen" width="1000px" append-to-body>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="母羊耳号">{{ detailData.femaleEarNumber }}</el-descriptions-item>
        <el-descriptions-item label="母羊品种">{{ detailData.femaleBreed }}</el-descriptions-item>
        <el-descriptions-item label="胎次">{{ detailData.parity }}</el-descriptions-item>
        <el-descriptions-item label="公羊耳号">{{ detailData.maleEarNumber }}</el-descriptions-item>
        <el-descriptions-item label="公羊品种">{{ detailData.maleBreed }}</el-descriptions-item>
        <el-descriptions-item label="配种日期">{{ parseTime(detailData.breedingDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="产羔数量">{{ detailData.lambsBorn }}</el-descriptions-item>
        <el-descriptions-item label="活羔数量">{{ detailData.survival }}</el-descriptions-item>
        <el-descriptions-item label="技术员">{{ detailData.technician }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">羔羊信息</el-divider>
      <el-table :data="lambDetailList" border>
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="羔羊耳号" prop="lambEarNumber" align="center" />
        <el-table-column label="羔羊品种" prop="lambBreed" align="center">
          <template #default="scope">
            <span>{{ getVarietyName(scope.row.lambBreed) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" prop="gender" align="center">
          <template #default="scope">
            <el-tag :type="getGenderDisplay(scope.row.gender).type">
              {{ getGenderDisplay(scope.row.gender).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="出生重(kg)" prop="birthWeight" align="center" />
        <el-table-column label="是否留养" prop="isRetained" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isRetained ? 'success' : 'danger'">
              {{ scope.row.isRetained ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="家系" prop="lineage" align="center" />
        <el-table-column label="生日" prop="birthday" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Lambing_records">
import { listLambing_records, getLambing_records, delLambing_records, addLambing_records, updateLambing_records, getLambDetail, getVarietyList, getBreedingInfo } from "@/api/breed/lambing_records"

const { proxy } = getCurrentInstance()

const lambing_recordsList = ref([])
const open = ref(false)
const detailOpen = 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 showLambForms = ref(false)
const lambForms = ref([])
const detailData = ref({})
const lambDetailList = ref([])
const varietyList = ref([]) // 品种列表

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    femaleEarNumber: null,
    femaleBreed: null,
    sheepId: null,
    parity: null,
    lambsBorn: null,
    survival: null,
    technician: null,
    score: null,
    comment: null,
    createBy: null,
    createTime: null,
    farm: null,
    breedingDate: []
  },
  rules: {
    femaleEarNumber: [
      { required: true, message: "母羊耳号不能为空", trigger: "blur" }
    ],
    lambsBorn: [
      { required: true, message: "产羔数量不能为空", trigger: "blur" }
    ]
  }
})

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

/** 获取品种列表 */
function getVarietyData() {
  return getVarietyList().then(response => {
    console.log('品种列表数据:', response)
    varietyList.value = response.rows || []
    console.log('处理后的品种列表:', varietyList.value)
  }).catch(error => {
    console.error('获取品种列表失败:', error)
    varietyList.value = []
  })
}

/** 根据品种ID获取品种名称 */
function getVarietyName(varietyId) {
  if (!varietyId) return '-'
  const id = typeof varietyId === 'string' ? parseInt(varietyId) : varietyId
  const variety = varietyList.value.find(item => item.id === id)
  return variety ? variety.variety : `未知品种(${varietyId})`
}

/** 性别转换函数 - 前端显示转后端数值 */
function genderToNumber(gender) {
  if (gender === 'male') return 1
  if (gender === 'female') return 0
  return gender
}

/** 性别显示函数 - 后端数值转前端显示 */
function getGenderDisplay(gender) {
  if (gender === 2 || gender === 'male') {
    return { label: '公', type: 'primary' }
  } else if (gender === 1 || gender === 'female') {
    return { label: '母', type: 'success' }
  }
  return { label: '未知', type: 'info' }
}

/** 母羊耳号输入处理 */
function handleEarNumberInput() {
  // 清空相关联动字段
  form.value.sheepId = null
  form.value.parity = null
  form.value.maleEarNumber = null
  form.value.breedingDate = null
  form.value.pregnancyDays = null
  form.value.technician = null
}

/** 母羊耳号失焦处理 - 自动查询配种信息 */
function handleEarNumberBlur() {
  const earNumber = form.value.femaleEarNumber
  if (!earNumber || earNumber.trim() === '') {
    return
  }

  // 调用API查询配种信息
  getBreedingInfo(earNumber.trim()).then(response => {
    if (response.code === 200 && response.data) {
      const breedingData = response.data

      // 填充表单数据
      form.value.sheepId = breedingData.sheep_id
      form.value.parity = breedingData.parity
      form.value.maleEarNumber = breedingData.male_ear_number || '未找到公羊'
      form.value.breedingDate = breedingData.breeding_date
      form.value.pregnancyDays = breedingData.pregnancy_days
      form.value.technician = breedingData.technician || ''

      proxy.$modal.msgSuccess("已自动填充配种信息")
    } else {
      proxy.$modal.msgWarning(response.msg || "未找到该母羊的配种记录")
      // 清空相关字段
      form.value.sheepId = null
      form.value.parity = null
      form.value.maleEarNumber = null
      form.value.breedingDate = null
      form.value.pregnancyDays = null
    }
  }).catch(error => {
    console.error('查询配种信息失败:', error)
    proxy.$modal.msgError("查询配种信息失败")
  })
}

/** 查询产羔记录列表 */
function getList() {
  loading.value = true
  listLambing_records(queryParams.value).then(response => {
    lambing_recordsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    femaleEarNumber: null,
    sheepId: null,
    parity: null,
    maleEarNumber: null,
    breedingDate: null,
    pregnancyDays: null,
    lambsBorn: null,
    survival: null,
    technician: null,
    score: null,
    comment: null,
    createBy: null,
    createTime: null
  }
  showLambForms.value = false
  lambForms.value = []
  proxy.resetForm("lambing_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
  getLambing_records(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改产羔记录"
    // 如果是修改，不显示羔羊录入表单
    showLambForms.value = false
  })
}

/** 产羔数量变化处理 */
function handleLambsBornChange() {
  const count = parseInt(form.value.lambsBorn) || 0
  if (count > 0 && count <= 10) { // 限制最大数量
    showLambForms.value = true
    lambForms.value = Array.from({ length: count }, (_, index) => ({
      lambEarNumber: '',
      gender: '',
      isRetained: false,
      birthWeight: null,
      lambBreed: null,
      lineage: '',
      birthday: ''
    }))
  } else {
    showLambForms.value = false
    lambForms.value = []
  }
}

/** 查看产羔详情 */
function handleLambDetail(row) {
  detailData.value = row
  // 调用API获取羔羊详情列表
  getLambDetail(row.id).then(response => {
    lambDetailList.value = response.data || []
    detailOpen.value = true
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["lambing_recordsRef"].validate(valid => {
    if (valid) {
      const submitData = { ...form.value }

      // 处理日期格式
      if (submitData.createTime && typeof submitData.createTime === 'string') {
        if (submitData.createTime.length === 10) {
          submitData.createTime = submitData.createTime + ' 00:00:00'
        }
      }

      // 处理羔羊详情
      if (showLambForms.value && lambForms.value.length > 0) {
        // 过滤掉空的羔羊信息
        const validLambDetails = lambForms.value.filter(lamb =>
            lamb.lambEarNumber && lamb.lambEarNumber.trim() !== ''
        )

        // 处理羔羊详情的日期格式和数据类型
        validLambDetails.forEach(lamb => {
          if (lamb.birthday && typeof lamb.birthday === 'string' && lamb.birthday.length === 10) {
            // 保持日期格式为 YYYY-MM-DD，后端会自动处理
          }
          // 确保体重为数字类型
          if (lamb.birthWeight && typeof lamb.birthWeight === 'string') {
            lamb.birthWeight = parseFloat(lamb.birthWeight)
          }
          // 性别转换：'male' -> 1, 'female' -> 0
          lamb.gender = genderToNumber(lamb.gender)
          // 品种ID已经是数字，无需转换
        })

        submitData.lambDetails = validLambDetails
      }

      if (form.value.id != null) {
        updateLambing_records(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addLambing_records(submitData).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 delLambing_records(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

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

// 页面初始化
onMounted(() => {
  console.log('页面初始化开始')
  getVarietyData() // 先获取品种列表
      .then(() => {
        console.log('品种列表加载完成，开始获取产羔记录')
        getList() // 然后获取产羔记录列表
      })
})
</script>

<style scoped>
.lamb-form-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.lamb-form-header {
  margin-bottom: 15px;
}

.lamb-title {
  font-weight: bold;
  color: #409eff;
  font-size: 14px;
}

.lamb-form-content {
  margin-bottom: 10px;
}

.lamb-form-content:last-child {
  margin-bottom: 0;
}
</style>