<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="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="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>

    <!-- 添加调试信息显示 -->
    <div v-if="breedPlanGenerateList.length === 0 && !loading" style="text-align: center; padding: 20px;">
      <p>暂无数据</p>
      <p>数据数组长度: {{ breedPlanGenerateList.length }}</p>
      <p>总数: {{ total }}</p>
      <p>加载状态: {{ loading }}</p>
    </div>

    <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-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="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="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="viewOpen" width="1000px" append-to-body>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="计划名称">{{ planInfo.planName }}</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-divider content-position="left">配种计划详情</el-divider>
      <el-table :data="planDetails" max-height="400">
        <el-table-column label="公羊耳号" align="center" prop="ram_manage_tags" />
        <el-table-column label="公羊品种" align="center" prop="ram_variety" />
        <el-table-column label="母羊耳号" align="center" prop="ewe_manage_tags" />
        <el-table-column label="母羊品种" align="center" prop="ewe_variety" />
        <el-table-column label="母羊体重" align="center" prop="ewe_weight" />
        <el-table-column label="配种类型" align="center" prop="breed_type">
          <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-if="scope.row.breed_type === 3" type="info">胚胎移植</el-tag>
            <el-tag v-else type="warning">未知类型</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

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

const {proxy} = getCurrentInstance()
// 修复字典问题 - 使用 proxy.useDict 或直接定义
const dict = proxy.useDict ? proxy.useDict('breed_plan_status', 'breed_type') : {
  type: {
    breed_plan_status: [],
    breed_type: []
  }
}

const breedPlanGenerateList = ref([])
const eligibleEweList = ref([])
const eligibleRamList = ref([])
const selectedEwe = ref([])
const selectedRam = ref([])
const planInfo = ref({})
const planDetails = ref([])
const generateOpen = ref(false)
const viewOpen = 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 data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: null,
    status: null
  }
})

const {queryParams} = toRefs(data)

/** 查询配种计划生成列表 */
function getList() {
  loading.value = true
  console.log('开始获取配种计划列表...')
  console.log('查询参数:', queryParams.value)

  listBreedPlanGenerate(queryParams.value).then(response => {
    console.log('API完整响应:', response)

    // 处理API响应数据
    breedPlanGenerateList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false

    console.log('处理后的数据列表:', breedPlanGenerateList.value)
    console.log('数据列表长度:', breedPlanGenerateList.value.length)
    console.log('总数:', total.value)

  }).catch(error => {
    console.error('获取列表失败:', error)
    loading.value = false
    breedPlanGenerateList.value = []
    total.value = 0
  })
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
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
  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() {
  if (selectedEwe.value.length === 0) {
    proxy.$modal.msgError("请选择母羊")
    return
  }
  if (selectedRam.value.length === 0) {
    proxy.$modal.msgError("请选择公羊")
    return
  }

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

  autoGenerateBreedPlan(params).then(response => {
    proxy.$modal.msgSuccess("配种计划生成成功")
    generateOpen.value = false
    // 重新加载列表数据
    getList()
    // 重置选择的羊只
    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) {
  proxy.$modal.confirm('是否确认审批通过配种计划"' + row.planName + '"？').then(function () {
    return approveBreedPlan(row.id)
  }).then(() => {
    proxy.$modal.msgSuccess("审批成功")
    // 刷新列表
    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(() => {
  })
}

// 页面挂载时加载数据
onMounted(() => {
  console.log('配种计划生成页面已挂载')
  getList()
})

// 初始加载数据
getList()
</script>