
<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-option label="本交" :value="3"></el-option>
          <el-option label="自然发情人工授精" :value="4"></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="warning">供体母羊配种</el-tag>
          <el-tag v-else-if="scope.row.planType === 2" type="primary">同期发情人工授精</el-tag>
          <el-tag v-else-if="scope.row.planType === 3" type="success">本交</el-tag>
          <el-tag v-else-if="scope.row.planType === 4" type="info">自然发情人工授精</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 :label="3">本交</el-radio>
                <el-radio :label="4">自然发情人工授精</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">
          <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 15px;">
            <el-select
                v-model="queryParams.allEarNumbers"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="输入耳号搜索"
                :remote-method="searchEarNumber"
                :loading="earNumberLoading"
                allow-create
                default-first-option
                collapse-tags
                :max-collapse-tags="0"
                style="width: 300px"
                @change="handleEarNumberChange"
            >
              <el-option
                  v-for="item in earNumberOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>

            <el-input
                v-model="pasteInput"
                placeholder="或粘贴多个耳号(空格/换行/逗号分隔)"
                style="width: 300px"
                @paste="handlePaste"
                @keyup.enter="handlePasteSubmit"
                clearable
            >
              <template #append>
                <el-button @click="handlePasteSubmit" icon="Plus">添加</el-button>
              </template>
            </el-input>

            <el-tag
                v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0"
                type="info"
                effect="plain"
                size="large"
            >
              已选: {{ queryParams.allEarNumbers.length }} 个
            </el-tag>

            <el-button type="primary" @click="selectEligibleEwe">执行筛选</el-button>

            <el-button
                type="danger"
                plain
                @click="clearAllEarNumbers"
                v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0"
                icon="Delete"
            >
              清空全部
            </el-button>
          </div>

          <div
              v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0"
              class="selected-ear-numbers-display"
              style="margin-bottom: 15px;"
          >
            <el-tag
                v-for="(tag, index) in displayedEarNumbers"
                :key="tag"
                closable
                @close="handleRemoveEarNumber(tag)"
                style="margin: 4px;"
                type="success"
            >
              {{ tag }}
            </el-tag>

            <el-button
                v-if="queryParams.allEarNumbers.length > defaultShowCount"
                type="primary"
                link
                @click="toggleExpand"
                style="margin-left: 8px;"
            >
              {{ isExpanded ? '收起' : `展开剩余 ${queryParams.allEarNumbers.length - defaultShowCount} 个` }}
              <el-icon class="el-icon--right">
                <component :is="isExpanded ? 'ArrowUp' : 'ArrowDown'" />
              </el-icon>
            </el-button>
          </div>

          <el-table
              ref="eweTableRef"
              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">
          <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 15px;">
            <el-select
                v-model="queryParams.allEarNumbers"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="输入耳号搜索"
                :remote-method="searchEarNumber"
                :loading="earNumberLoading"
                allow-create
                default-first-option
                collapse-tags
                :max-collapse-tags="0"
                style="width: 300px"
                @change="handleEarNumberChange"
            >
              <el-option
                  v-for="item in earNumberOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>

            <el-input
                v-model="pasteInput"
                placeholder="或粘贴多个耳号(空格/换行/逗号分隔)"
                style="width: 300px"
                @paste="handlePaste"
                @keyup.enter="handlePasteSubmit"
                clearable
            >
              <template #append>
                <el-button @click="handlePasteSubmit" icon="Plus">添加</el-button>
              </template>
            </el-input>

            <el-tag
                v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0"
                type="info"
                effect="plain"
                size="large"
            >
              已选: {{ queryParams.allEarNumbers.length }} 个
            </el-tag>

            <el-button type="primary" @click="selectEligibleRam">执行筛选</el-button>

            <el-button
                type="danger"
                plain
                @click="clearAllEarNumbers"
                v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0"
                icon="Delete"
            >
              清空全部
            </el-button>
          </div>

          <div
              v-if="queryParams.allEarNumbers && queryParams.allEarNumbers.length > 0"
              class="selected-ear-numbers-display"
              style="margin-bottom: 15px;"
          >
            <el-tag
                v-for="(tag, index) in displayedEarNumbers"
                :key="tag"
                closable
                @close="handleRemoveEarNumber(tag)"
                style="margin: 4px;"
                type="success"
            >
              {{ tag }}
            </el-tag>

            <el-button
                v-if="queryParams.allEarNumbers.length > defaultShowCount"
                type="primary"
                link
                @click="toggleExpand"
                style="margin-left: 8px;"
            >
              {{ isExpanded ? '收起' : `展开剩余 ${queryParams.allEarNumbers.length - defaultShowCount} 个` }}
              <el-icon class="el-icon--right">
                <component :is="isExpanded ? 'ArrowUp' : 'ArrowDown'" />
              </el-icon>
            </el-button>
          </div>
          <el-table
              ref="ramTableRef"
              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="warning">供体母羊配种</el-tag>
          <el-tag v-else-if="approveData.planInfo.planType === 2" type="primary">同期发情人工授精</el-tag>
          <el-tag v-else-if="approveData.planInfo.planType === 3" type="success">本交</el-tag>
          <el-tag v-else-if="approveData.planInfo.planType === 4" type="info">自然发情人工授精</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="approveData.planInfo.planType === 1" type="warning">供体母羊配种</el-tag>
          <el-tag v-else-if="approveData.planInfo.planType === 2" type="primary">同期发情人工授精</el-tag>
          <el-tag v-else-if="approveData.planInfo.planType === 3" type="success">本交</el-tag>
          <el-tag v-else-if="approveData.planInfo.planType === 4" type="info">自然发情人工授精</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="planInfo.planType === 1" type="warning">供体母羊配种</el-tag>
            <el-tag v-else-if="planInfo.planType === 2" type="primary">同期发情人工授精</el-tag>
            <el-tag v-else-if="planInfo.planType === 3" type="success">本交</el-tag>
            <el-tag v-else-if=" planInfo.planType === 4" type="info">自然发情人工授精</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, computed, nextTick} from 'vue'
import {
  listBreedPlanGenerate,
  getBreedPlanGenerate,
  delBreedPlanGenerate,
  selectEligibleEwe as apiSelectEligibleEwe,
  selectEligibleRam as apiSelectEligibleRam,
  autoGenerateBreedPlan,
  getApproveBreedPlan,
  confirmApproveBreedPlan,
  viewBreedPlan,
  searchEarNumbers
} from "@/api/mating_plan/generate"
import { ArrowDown, ArrowUp, Plus, Delete, Search } from '@element-plus/icons-vue'

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 pasteInput = ref('')
const ramSearchTag = ref('')
const earNumberOptions = ref([])
const earNumberLoading = ref(false)
const isExpanded = ref(false)
const defaultShowCount = 6

const eweTableRef = ref(null)
const ramTableRef = ref(null) // 新增这一行
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: null,
    planType: null,
    allEarNumbers: [],
    status: null,
    params: {}
  },
  generateForm: {
    planType: 1
  },
  generateRules: {
    planType: [
      { required: true, message: '请选择计划类型', trigger: 'change' }
    ]
  }
})

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

const displayedEarNumbers = computed(() => {
  if (!queryParams.value.allEarNumbers || queryParams.value.allEarNumbers.length === 0) return []
  if (isExpanded.value || queryParams.value.allEarNumbers.length <= defaultShowCount) {
    return queryParams.value.allEarNumbers
  } else {
    return queryParams.value.allEarNumbers.slice(0, defaultShowCount)
  }
})

function getList() {
  loading.value = true
  listBreedPlanGenerate(queryParams.value).then(response => {
    breedPlanGenerateList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

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()
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
}

function getPlanTypeName(planType) {
  switch (planType) {
    case 1: return '供体母羊配种计划'
    case 2: return '同期发情人工授精计划'
    case 3: return '本交配种计划'
    case 4: return '自然发情人工授精计划'
    default: return '未知计划'
  }
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

/** 母羊选择变化 - 实现同步到顶部标签 */
function handleEweSelectionChange(selection) {
  selectedEwe.value = selection.map(item => item.id)

  const currentTableTags = eligibleEweList.value.map(item => item.bs_manage_tags)
  const selectedTableTags = selection.map(item => item.bs_manage_tags)

  // 逻辑：保留那些不在当前列表中的历史耳号，但根据当前表格的勾选状态更新当前列表中的耳号
  const otherTags = queryParams.value.allEarNumbers.filter(tag => !currentTableTags.includes(tag))
  queryParams.value.allEarNumbers = [...new Set([...otherTags, ...selectedTableTags])]
}

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 = []
  queryParams.value.allEarNumbers = []
}

/** 筛选符合条件的母羊 - 增加排序与自动勾选逻辑 */
function selectEligibleEwe() {
  eweLoading.value = true
  // 如果有已粘贴的耳号，传给后端进行初步筛选（取决于后端接口实现）
  const searchTags = queryParams.value.allEarNumbers.length > 0 ? queryParams.value.allEarNumbers.join(',') : ''

  apiSelectEligibleEwe(searchTags).then(response => {
    let rawData = response.data || []
    const selectedSet = new Set(queryParams.value.allEarNumbers)

    // 核心：将匹配到的耳号排在最前面
    rawData.sort((a, b) => {
      const aMatch = selectedSet.has(a.bs_manage_tags) ? 1 : 0
      const bMatch = selectedSet.has(b.bs_manage_tags) ? 1 : 0
      return bMatch - aMatch
    })

    eligibleEweList.value = rawData
    eweLoading.value = false

    // 核心：自动勾选匹配到的行
    nextTick(() => {
      if (eweTableRef.value) {
        eligibleEweList.value.forEach(row => {
          if (selectedSet.has(row.bs_manage_tags)) {
            eweTableRef.value.toggleRowSelection(row, true)
          }
        })
      }
    })
  })
}

function selectEligibleRam() {
  ramLoading.value = true
  // 如果公羊也想支持顶部耳号框的批量筛选，需调整传参逻辑
  const searchTags = queryParams.value.allEarNumbers.length > 0 ? queryParams.value.allEarNumbers.join(',') : ''

  apiSelectEligibleRam(searchTags).then(response => {
    let rawData = response.data || []
    const selectedSet = new Set(queryParams.value.allEarNumbers)

    // 1. 将匹配到的公羊排在最前面
    rawData.sort((a, b) => {
      const aMatch = selectedSet.has(a.bs_manage_tags) ? 1 : 0
      const bMatch = selectedSet.has(b.bs_manage_tags) ? 1 : 0
      return bMatch - aMatch
    })

    eligibleRamList.value = rawData
    ramLoading.value = false

    // 2. 核心：自动勾选匹配到的行
    nextTick(() => {
      if (ramTableRef.value) {
        eligibleRamList.value.forEach(row => {
          if (selectedSet.has(row.bs_manage_tags)) {
            ramTableRef.value.toggleRowSelection(row, true)
          }
        })
      }
    })
  })
}

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(() => {
      proxy.$modal.msgSuccess("配种计划生成成功")
      generateOpen.value = false
      getList()
    })
  })
}

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 || []
    approveOpen.value = true
  })
}

function handleRamChange(index, row) {
  if (row.ram_id === null) {
    row.ram_manage_tags = ''; row.ram_variety = ''; row.breed_type = null
  } else {
    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
      if (!row.breed_type && approveData.value.planInfo) {
        row.breed_type = approveData.value.planInfo.planType
      }
    }
  }
}

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()
  })
}

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()
  })
}

function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除配种计划？').then(function () {
    return delBreedPlanGenerate(_ids)
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功"); getList()
  })
}

function handlePaste(event) {
  nextTick(() => { handlePasteSubmit() })
}

/** 处理粘贴内容提交 - 增加自动筛选 */
function handlePasteSubmit() {
  if (!pasteInput.value || pasteInput.value.trim() === '') return

  const separators = /[\s,，\n\r\t]+/
  const earNumbers = pasteInput.value.trim().split(separators).filter(item => item.trim() !== '')

  if (earNumbers.length === 0) return

  const currentSet = new Set(queryParams.value.allEarNumbers || [])
  earNumbers.forEach(num => currentSet.add(num))
  queryParams.value.allEarNumbers = Array.from(currentSet)

  pasteInput.value = ''

  if (activeTab.value === 'ewe') {
    selectEligibleEwe()
  } else {
    selectEligibleRam()
  }
}

function searchEarNumber(query) {
  if (query !== '') {
    earNumberLoading.value = true

    const queries = query.trim().split(/[\s,，]+/).filter(q => q)

    if (queries.length === 1) {
      // 单个耳号模糊搜索
      searchEarNumbers(query).then(response => {
        earNumberOptions.value = response.data || []
        earNumberLoading.value = false
      }).catch(() => {
        earNumberOptions.value = []
        earNumberLoading.value = false
      })
    } else {
      // 多个耳号直接作为选项
      earNumberOptions.value = queries
      earNumberLoading.value = false
    }
  } else {
    earNumberOptions.value = []
  }
}

function handleEarNumberChange(value) {
  queryParams.value.allEarNumbers = [...new Set(value)]
  // 改变下拉框内容也触发一次筛选更新排序
  selectEligibleEwe()
}

function toggleExpand() { isExpanded.value = !isExpanded.value }

function handleRemoveEarNumber(tag) {
  const index = queryParams.value.allEarNumbers.indexOf(tag)
  if (index > -1) {
    queryParams.value.allEarNumbers.splice(index, 1)
    // 移除标签后，如果该行在表格中，取消勾选
    const row = eligibleEweList.value.find(r => r.bs_manage_tags === tag)
    if (row && eweTableRef.value) {
      eweTableRef.value.toggleRowSelection(row, false)
    }
  }
}

function clearAllEarNumbers() {
  proxy.$modal.confirm('确定要清空所有已选择的耳号吗？').then(() => {
    queryParams.value.allEarNumbers = []
    if (eweTableRef.value) eweTableRef.value.clearSelection()
    isExpanded.value = false
  })
}

function exportBreedPlanDetails() {
  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; }
.selected-ear-numbers-display {
  max-height: 150px;
  overflow-y: auto;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
</style>