<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划名称" prop="planName">
        <el-input
            v-model="queryParams.planName"
            placeholder="请输入计划名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划类型" prop="planType">
        <el-select v-model="queryParams.planType" placeholder="请选择计划类型" clearable>
          <el-option label="同期发情配种计划" value="1"></el-option>
          <el-option label="本交配种计划" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="计划日期" prop="planDate">
        <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateRangeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待审批" value="0"></el-option>
          <el-option label="已审批" value="1"></el-option>
          <el-option label="已拒绝" value="2"></el-option>
        </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="handleGenerate"
            v-hasPermi="['mating_plan:generate:add']"
        >生成配种计划</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['mating_plan:generate:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="breedPlanGenerateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="计划类型" align="center" prop="planType">
        <template #default="scope">
          <el-tag v-if="scope.row.planType === 1" type="primary">同期发情配种计划</el-tag>
          <el-tag v-else-if="scope.row.planType === 2" type="success">本交配种计划</el-tag>
          <el-tag v-else type="info">未知类型</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计划日期" align="center" prop="planDate" width="180">
        <template #default="scope">
          <span>{{ scope.row.planDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="母羊数量" align="center" prop="totalEweCount" />
      <el-table-column label="公羊数量" align="center" prop="totalRamCount" />
      <el-table-column label="配种比例" align="center" prop="breedRatio" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">待审批</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">已审批</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">已拒绝</el-tag>
          <el-tag v-else type="info">未知状态</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approver" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handleView(scope.row)"
              v-hasPermi="['mating_plan:generate:view']"
          >查看</el-button>
          <el-button
              link
              type="success"
              icon="Check"
              @click="handleApprove(scope.row)"
              v-hasPermi="['mating_plan:generate:approve']"
              v-if="scope.row.status == 0"
          >审批</el-button>

          <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['mating_plan:generate: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="生成配种计划" v-model="generateOpen" width="1200px" append-to-body>
      <el-form ref="generateFormRef" :model="generateForm" :rules="generateRules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="计划类型" prop="planType">
              <el-radio-group v-model="generateForm.planType">
                <el-radio :label="1">同期发情配种计划</el-radio>
                <el-radio :label="2">本交配种计划</el-radio>
              </el-radio-group>
              <div style="margin-top: 10px; color: #666; font-size: 12px;">
                计划名称将自动生成为：{{ getCurrentDate() }}{{ getPlanTypeName(generateForm.planType) }}
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="符合条件的母羊" name="ewe">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" @click="selectEligibleEwe">筛选符合条件的母羊</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info">已选择: {{ selectedEwe.length }} 只</el-button>
            </el-col>
          </el-row>
          <el-table
              v-loading="eweLoading"
              :data="eligibleEweList"
              @selection-change="handleEweSelectionChange"
              max-height="400"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="管理耳号" align="center" prop="bs_manage_tags" />
            <el-table-column label="品种" align="center" prop="variety" />
            <el-table-column label="家系" align="center" prop="family" />
            <el-table-column label="羊只类型" align="center" prop="sheep_type" />
            <el-table-column label="月龄" align="center" prop="month_age" />
            <el-table-column label="当前体重(kg)" align="center" prop="current_weight" />
            <el-table-column label="产后天数" align="center" prop="post_lambing_day" />
            <el-table-column label="繁殖状态" align="center" prop="breed" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="符合条件的公羊" name="ram">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" @click="selectEligibleRam">筛选符合条件的公羊</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info">已选择: {{ selectedRam.length }} 只</el-button>
            </el-col>
          </el-row>
          <el-table
              v-loading="ramLoading"
              :data="eligibleRamList"
              @selection-change="handleRamSelectionChange"
              max-height="400"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="管理耳号" align="center" prop="bs_manage_tags" />
            <el-table-column label="品种" align="center" prop="variety" />
            <el-table-column label="家系" align="center" prop="family" />
            <el-table-column label="羊只类型" align="center" prop="sheep_type" />
            <el-table-column label="月龄" align="center" prop="month_age" />
            <el-table-column label="当前体重(kg)" align="center" prop="current_weight" />
            <el-table-column label="繁殖状态" align="center" prop="breed" />
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="generateBreedPlan" :disabled="selectedEwe.length === 0 || selectedRam.length === 0">
            生成配种计划
          </el-button>
          <el-button @click="generateOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 审批配种计划对话框 -->
    <el-dialog title="审批配种计划" v-model="approveOpen" width="1400px" append-to-body>
      <el-descriptions :column="3" border class="mb8">
        <el-descriptions-item label="计划名称">{{ approveData.planInfo.planName }}</el-descriptions-item>
        <el-descriptions-item label="计划类型">
          <el-tag v-if="approveData.planInfo.planType === 1" type="primary">同期发情配种计划</el-tag>
          <el-tag v-else-if="approveData.planInfo.planType === 2" type="success">本交配种计划</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="计划日期">{{ approveData.planInfo.planDate }}</el-descriptions-item>
        <el-descriptions-item label="母羊数量">{{ approveData.planInfo.totalEweCount }}</el-descriptions-item>
        <el-descriptions-item label="公羊数量">{{ approveData.planInfo.totalRamCount }}</el-descriptions-item>
        <el-descriptions-item label="配种比例">{{ approveData.planInfo.breedRatio }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">配种计划详情（可编辑）</el-divider>
      <el-table
          :data="approveData.planDetails"
          style="width: 100%"
          max-height="500"
          border
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="母羊耳号" align="center" prop="ewe_manage_tags" width="120" />
        <el-table-column label="母羊品种" align="center" prop="ewe_variety" width="100" />
        <el-table-column label="核心羊群" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.ewe_is_core" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否种用" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.ewe_is_breeding" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="详情" align="center" width="80">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="showEweDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>

        <el-table-column label="配种公羊" align="center" width="200">
          <template #default="scope">
            <el-select
                v-model="scope.row.ram_id"
                placeholder="选择公羊(可为空)"
                @change="handleRamChange(scope.$index, scope.row)"
                filterable
                clearable
            >
              <el-option label="不参与配种" :value="null" />
              <el-option
                  v-for="ram in availableRamList"
                  :key="ram.id"
                  :label="ram.bs_manage_tags"
                  :value="ram.id"
              />
            </el-select>
            <!-- 如果当前选中的公羊不在可选列表中，显示当前公羊耳号 -->
            <div v-if="scope.row.ram_id && !availableRamList.find(r => r.id == scope.row.ram_id)"
                 style="font-size: 12px; color: #666; margin-top: 4px;">
              当前: {{ scope.row.ram_manage_tags || scope.row.ram_id }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="公羊品种" align="center" prop="ram_variety" width="100" />
        <el-table-column label="详情" align="center" width="80">
          <template #default="scope">
            <el-button
                link
                type="primary"
                icon="View"
                @click="showRamDetail(scope.row)"
                :disabled="!scope.row.ram_id"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="confirmApprove">确认审批</el-button>
          <el-button type="danger" @click="rejectApprove">拒绝审批</el-button>
          <el-button @click="approveOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看配种计划详情对话框 -->
    <el-dialog title="配种计划详情" v-model="viewOpen" width="1200px" append-to-body>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="计划名称">{{ planInfo.planName }}</el-descriptions-item>
        <el-descriptions-item label="计划类型">
          <el-tag v-if="planInfo.planType === 1" type="primary">同期发情配种计划</el-tag>
          <el-tag v-else-if="planInfo.planType === 2" type="success">本交配种计划</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="计划日期">{{ planInfo.planDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="planInfo.status === 0" type="warning">待审批</el-tag>
          <el-tag v-else-if="planInfo.status === 1" type="success">已审批</el-tag>
          <el-tag v-else-if="planInfo.status === 2" type="danger">已拒绝</el-tag>
          <el-tag v-else type="info">未知状态</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="母羊数量">{{ planInfo.totalEweCount }}</el-descriptions-item>
        <el-descriptions-item label="公羊数量">{{ planInfo.totalRamCount }}</el-descriptions-item>
        <el-descriptions-item label="配种比例">{{ planInfo.breedRatio }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ planInfo.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ planInfo.createTime }}</el-descriptions-item>
        <el-descriptions-item label="审批人">{{ planInfo.approver }}</el-descriptions-item>
      </el-descriptions>

      <!-- 只有已审批状态才显示导出按钮 -->
      <el-row :gutter="10" class="mb8" style="margin-top: 16px;" v-if="planInfo.status === 1">
        <el-col :span="1.5">
          <el-button type="success" icon="Download" @click="exportBreedPlanDetails">导出配种计划详情</el-button>
        </el-col>
      </el-row>

      <el-divider content-position="left">配种计划详情</el-divider>
      <el-table :data="planDetails" max-height="600" border stripe>
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="母羊耳号" align="center" prop="ewe_manage_tags" width="120" />
        <el-table-column label="母羊品种" align="center" prop="ewe_variety" width="100" />
        <el-table-column label="核心羊群" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.ewe_is_core" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否种用" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.ewe_is_breeding" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="母羊详情" align="center" width="100">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="showEweDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>

        <el-table-column label="公羊耳号" align="center" prop="ram_manage_tags" width="120" />
        <el-table-column label="公羊品种" align="center" prop="ram_variety" width="100" />
        <el-table-column label="公羊详情" align="center" width="100">
          <template #default="scope">
            <el-button
                link
                type="primary"
                icon="View"
                @click="showRamDetail(scope.row)"
                :disabled="!scope.row.ram_id"
            >查看</el-button>
          </template>
        </el-table-column>

        <el-table-column label="配种类型" align="center" prop="breed_type" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.breed_type === 1" type="primary">同期发情</el-tag>
            <el-tag v-else-if="scope.row.breed_type === 2" type="success">本交</el-tag>
            <el-tag v-else type="warning">未知类型</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 羊只详情对话框 -->
    <el-dialog :title="sheepDetailTitle" v-model="sheepDetailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="耳号">{{ sheepDetail.manage_tags }}</el-descriptions-item>
        <el-descriptions-item label="品种">{{ sheepDetail.variety }}</el-descriptions-item>
        <el-descriptions-item label="家系">{{ sheepDetail.family }}</el-descriptions-item>
        <el-descriptions-item label="羊只类别">{{ sheepDetail.sheep_type }}</el-descriptions-item>
        <el-descriptions-item label="繁育状态" v-if="sheepDetail.breed_status">{{ sheepDetail.breed_status }}</el-descriptions-item>
        <el-descriptions-item label="生日" v-if="sheepDetail.birthday">{{ sheepDetail.birthday }}</el-descriptions-item>
        <el-descriptions-item label="月龄">{{ sheepDetail.month_age }}</el-descriptions-item>
        <el-descriptions-item label="当前体重">{{ sheepDetail.current_weight }}kg</el-descriptions-item>
        <el-descriptions-item label="胎次" v-if="sheepDetail.parity">{{ sheepDetail.parity }}</el-descriptions-item>
        <el-descriptions-item label="是否核心羊群" v-if="sheepDetail.is_core !== undefined">
          <el-tag v-if="sheepDetail.is_core" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否种用" v-if="sheepDetail.is_breeding !== undefined">
          <el-tag v-if="sheepDetail.is_breeding" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="羊舍" v-if="sheepDetail.sheepfold_name">{{ sheepDetail.sheepfold_name }}</el-descriptions-item>
        <el-descriptions-item label="备注" v-if="sheepDetail.comment">{{ sheepDetail.comment }}</el-descriptions-item>
        <el-descriptions-item label="繁殖情况" v-if="sheepDetail.reproduction_info">{{ sheepDetail.reproduction_info }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="BreedPlanGenerate">
import {ref, reactive, toRefs, onMounted, getCurrentInstance} from 'vue'
import {
  listBreedPlanGenerate,
  getBreedPlanGenerate,
  delBreedPlanGenerate,
  selectEligibleEwe as apiSelectEligibleEwe,
  selectEligibleRam as apiSelectEligibleRam,
  autoGenerateBreedPlan,
  getApproveBreedPlan,
  confirmApproveBreedPlan,
  viewBreedPlan
} from "@/api/mating_plan/generate"

const {proxy} = getCurrentInstance()

const breedPlanGenerateList = ref([])
const eligibleEweList = ref([])
const eligibleRamList = ref([])
const availableRamList = ref([])
const selectedEwe = ref([])
const selectedRam = ref([])
const planInfo = ref({})
const planDetails = ref([])
const approveData = ref({
  planInfo: {},
  planDetails: []
})
const sheepDetail = ref({})
const sheepDetailTitle = ref('')
const generateOpen = ref(false)
const viewOpen = ref(false)
const approveOpen = ref(false)
const sheepDetailOpen = ref(false)
const loading = ref(true)
const eweLoading = ref(false)
const ramLoading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const multiple = ref(true)
const total = ref(0)
const activeTab = ref('ewe')
const dateRange = ref([])

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: null,
    planType: null,
    status: null,
    params: {}
  },
  generateForm: {
    planType: 1
  },
  generateRules: {
    planType: [
      { required: true, message: '请选择计划类型', trigger: 'change' }
    ]
  }
})

const {queryParams, generateForm, generateRules} = toRefs(data)

/** 查询配种计划生成列表 */
function getList() {
  loading.value = true
  listBreedPlanGenerate(queryParams.value).then(response => {
    breedPlanGenerateList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(error => {
    console.error('获取列表失败:', error)
    loading.value = false
    breedPlanGenerateList.value = []
    total.value = 0
  })
}

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

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  queryParams.value.params = {}
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 日期范围变化处理 */
function handleDateRangeChange(dates) {
  if (dates && dates.length === 2) {
    queryParams.value.params.beginTime = dates[0]
    queryParams.value.params.endTime = dates[1]
  } else {
    queryParams.value.params = {}
  }
}

/** 获取当前日期 */
function getCurrentDate() {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/** 获取计划类型名称 */
function getPlanTypeName(planType) {
  return planType === 1 ? '同期发情配种计划' : '本交配种计划'
}

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

// 母羊选择变化
function handleEweSelectionChange(selection) {
  selectedEwe.value = selection.map(item => item.id)
}

// 公羊选择变化
function handleRamSelectionChange(selection) {
  selectedRam.value = selection.map(item => item.id)
}

// 标签页切换
function handleTabClick(tab) {
  activeTab.value = tab.name
}

/** 生成配种计划按钮操作 */
function handleGenerate() {
  generateOpen.value = true
  generateForm.value.planType = 1
  selectedEwe.value = []
  selectedRam.value = []
  eligibleEweList.value = []
  eligibleRamList.value = []
}

/** 筛选符合条件的母羊 */
function selectEligibleEwe() {
  eweLoading.value = true
  apiSelectEligibleEwe().then(response => {
    eligibleEweList.value = response.data
    eweLoading.value = false
  })
}

/** 筛选符合条件的公羊 */
function selectEligibleRam() {
  ramLoading.value = true
  apiSelectEligibleRam().then(response => {
    eligibleRamList.value = response.data
    ramLoading.value = false
  })
}

/** 生成配种计划 */
function generateBreedPlan() {
  proxy.$refs.generateFormRef.validate((valid) => {
    if (!valid) return

    if (selectedEwe.value.length === 0) {
      proxy.$modal.msgError("请选择母羊")
      return
    }
    if (selectedRam.value.length === 0) {
      proxy.$modal.msgError("请选择公羊")
      return
    }

    const params = {
      planType: generateForm.value.planType,
      eweIds: selectedEwe.value,
      ramIds: selectedRam.value
    }

    autoGenerateBreedPlan(params).then(response => {
      proxy.$modal.msgSuccess("配种计划生成成功")
      generateOpen.value = false
      getList()
      // 重置表单和选择
      generateForm.value = { planType: 1 }
      selectedEwe.value = []
      selectedRam.value = []
      eligibleEweList.value = []
      eligibleRamList.value = []
    }).catch(error => {
      console.error('生成配种计划失败:', error)
      proxy.$modal.msgError("生成配种计划失败")
    })
  })
}



/** 查看配种计划详情 */
function handleView(row) {
  viewBreedPlan(row.id).then(response => {
    planInfo.value = response.data.planInfo
    planDetails.value = response.data.planDetails
    viewOpen.value = true
  })
}

/** 审批配种计划 */
function handleApprove(row) {
  getApproveBreedPlan(row.id).then(response => {
    approveData.value = response.data
    availableRamList.value = response.data.availableRams || []

    // 确保每行数据都有正确的公羊ID映射
    if (approveData.value.planDetails) {
      approveData.value.planDetails.forEach(detail => {
        // 如果ram_id是字符串，转换为数字用于下拉框匹配
        if (detail.ram_id && typeof detail.ram_id === 'string') {
          detail.ram_id = parseInt(detail.ram_id, 10)
        }

        // 如果当前公羊不在可选列表中，添加到列表中以显示当前选择
        if (detail.ram_id && detail.ram_manage_tags &&
            !availableRamList.value.find(ram => ram.id === detail.ram_id)) {
          availableRamList.value.push({
            id: detail.ram_id,
            bs_manage_tags: detail.ram_manage_tags
          })
        }
      })
    }

    approveOpen.value = true
  })
}

/** 公羊选择变化处理 */
function handleRamChange(index, row) {
  if (row.ram_id === null) {
    // 不参与配种
    row.ram_manage_tags = ''
    row.ram_variety = ''
    row.ram_family = ''
    row.ram_sheep_type = ''
    row.ram_birthday = ''
    row.ram_month_age = ''
    row.ram_current_weight = ''
    row.breed_type = null
  } else {
    // 确保ram_id是数字类型进行匹配
    const ramId = typeof row.ram_id === 'string' ? parseInt(row.ram_id, 10) : row.ram_id
    const selectedRam = availableRamList.value.find(ram => ram.id === ramId)

    if (selectedRam) {
      row.ram_manage_tags = selectedRam.bs_manage_tags
      row.ram_variety = selectedRam.variety
      row.ram_family = selectedRam.family
      row.ram_sheep_type = selectedRam.sheep_type
      row.ram_birthday = selectedRam.birthday
      row.ram_month_age = selectedRam.month_age
      row.ram_current_weight = selectedRam.current_weight
      // 设置默认配种类型
      if (!row.breed_type) {
        row.breed_type = 1 // 默认同期发情
      }
    }
  }
}

/** 显示母羊详情 */
function showEweDetail(row) {
  sheepDetail.value = {
    manage_tags: row.ewe_manage_tags,
    variety: row.ewe_variety,
    family: row.ewe_family,
    sheep_type: row.ewe_sheep_type,
    breed_status: row.ewe_breed_status,
    parity: row.ewe_parity,
    month_age: row.ewe_month_age,
    current_weight: row.ewe_current_weight,
    is_core: row.ewe_is_core,
    is_breeding: row.ewe_is_breeding,
    sheepfold_name: row.ewe_sheepfold_name,
    comment: row.ewe_comment,
    reproduction_info: row.ewe_reproduction_info
  }
  sheepDetailTitle.value = '母羊详情'
  sheepDetailOpen.value = true
}

/** 显示公羊详情 */
function showRamDetail(row) {
  if (!row.ram_id) {
    proxy.$modal.msgWarning("该母羊未分配公羊")
    return
  }

  sheepDetail.value = {
    manage_tags: row.ram_manage_tags,
    variety: row.ram_variety,
    family: row.ram_family,
    sheep_type: row.ram_sheep_type,
    birthday: row.ram_birthday,
    month_age: row.ram_month_age,
    current_weight: row.ram_current_weight
  }
  sheepDetailTitle.value = '公羊详情'
  sheepDetailOpen.value = true
}

/** 确认审批 */
function confirmApprove() {
  proxy.$modal.confirm('确认审批通过此配种计划？').then(function () {
    const params = {
      planId: approveData.value.planInfo.id,
      planDetails: approveData.value.planDetails,
      status: 1,
      approveRemark: '审批通过'
    }
    return confirmApproveBreedPlan(params)
  }).then(() => {
    proxy.$modal.msgSuccess("审批成功")
    approveOpen.value = false
    getList()
  }).catch(() => {})
}

/** 拒绝审批 */
function rejectApprove() {
  proxy.$modal.prompt('请输入拒绝原因', '拒绝审批', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '拒绝原因不能为空'
  }).then(({ value }) => {
    const params = {
      planId: approveData.value.planInfo.id,
      status: 2,
      approveRemark: value
    }
    return confirmApproveBreedPlan(params)
  }).then(() => {
    proxy.$modal.msgSuccess("已拒绝审批")
    approveOpen.value = false
    getList()
  }).catch(() => {})
}

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

/** 导出配种计划详情 */
function exportBreedPlanDetails() {
  if (!planInfo.value || !planDetails.value || planDetails.value.length === 0) {
    proxy.$modal.msgError("暂无数据可导出")
    return
  }

  // 检查是否已审批
  if (planInfo.value.status !== 1) {
    proxy.$modal.msgError("只有已审批的配种计划才能导出")
    return
  }

  // 使用proxy.download方法，会自动携带认证信息
  proxy.download(`/mating_plan/generate/export/${planInfo.value.id}`, {}, `${planInfo.value.planName}_配种计划详情_${new Date().getTime()}.xlsx`)
}

// 页面挂载时加载数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>