<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="牧场名称" prop="drRanch" style="width: 100%">
            <el-select
              v-model="queryParams.drRanch"
              placeholder="请选择牧场"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="dict in da_ranch"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="耳号" prop="allEarNumbers" style="width: 100%">
            <el-select
              v-model="queryParams.allEarNumbers"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="输入耳号搜索"
              :remote-method="searchEarMethod"
              :loading="loadingEar"
              collapse-tags
              style="width: 100%"
            >
              <el-option
                v-for="item in earOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="电子耳号" prop="allEleEarNumbers" style="width: 100%">
            <el-select
              v-model="queryParams.allEleEarNumbers"
              multiple
              filterable
              allow-create
              default-first-option
              collapse-tags
              placeholder="输入号码"
              style="width: 100%"
            >
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="性别" prop="allGenders" style="width: 100%">
            <el-select 
              v-model="queryParams.allGenders" 
              multiple 
              collapse-tags
              placeholder="请选择性别" 
              style="width: 100%"
            >
              <el-option
                v-for="dict in sheep_gender"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="是否在群" prop="statusId" style="width: 100%">
             <el-radio-group v-model="queryParams.statusId">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
                <el-radio :label="null">全部</el-radio>
             </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="繁殖状态" prop="allBreedingStatus" style="width: 100%">
            <el-select 
              v-model="queryParams.allBreedingStatus" 
              multiple 
              collapse-tags
              placeholder="请选择繁殖状态" 
              style="width: 100%"
            >
              <el-option
                v-for="item in breedOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="羊只类型" prop="allSheepTypes" style="width: 100%">
            <el-select 
              v-model="queryParams.allSheepTypes" 
              multiple 
              collapse-tags
              placeholder="请选择类型" 
              style="width: 100%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item style="margin-left: 10px;">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
         <el-button type="info" plain icon="Setting" @click="openColumnDialog">显示列</el-button>
      </el-col>

      <el-col :span="1.5">
        <CustomFilter ref="customFilterRef" @filter="handleCustomFilter" />
        <span v-if="isCustomFilterActive" style="color: #67c23a; margin-left: 5px;">
          <i class="el-icon-success"></i> 筛选条件已激活
        </span>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sheep_file:sheep_file:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sheep_file:sheep_file:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div v-if="appliedFilters.length > 0" class="applied-filters mb8">
      <div class="filter-title">已应用筛选条件:</div>
      <el-tag
        v-for="(filter, index) in appliedFilters"
        :key="index"
        closable
        @close="removeAppliedFilter(index)"
        type="primary"
        style="margin-right: 8px; margin-bottom: 8px;"
      >
        {{ filter.text }}
      </el-tag>
      <el-button link type="primary" @click="clearAllFilters" style="margin-left: 10px;">
        清除所有
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="sheep_fileList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        v-if="columns['drRanch'].visible"
        label="牧场名称"
        align="center"
        prop="drRanch"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">牧场名称</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['bsManageTags'].visible"
        label="耳号"
        align="center"
        prop="bsManageTags"
        width="120"
        fixed="left"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">耳号</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['electronicTags'].visible"
        label="电子耳号"
        align="center"
        prop="electronicTags"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">电子耳号</span>
        </template>
        <template #default="scope">
          <el-tooltip :content="scope.row.electronicTags" placement="top">
            <span style="display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            {{ scope.row.electronicTags }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['gender'].visible"
        label="性别"
        align="center"
        prop="gender"
        width="120"
        sortable
      >
        <template #default="scope">
          <dict-tag :options="sheep_gender" :value="scope.row.gender"/>
        </template>
      </el-table-column>

      <el-table-column
        v-if="columns['statusId'].visible"
        label="羊只状态"
        align="center"
        prop="statusId"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">羊只状态</span>
        </template>
        <template #default="scope">
          <dict-tag :options="sheep_status" :value="scope.row.statusId"/>
        </template>
      </el-table-column>

      <el-table-column
        v-if="columns['breed'].visible"
        label="繁殖状态"
        align="center"
        prop="breed"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">繁殖状态</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['name'].visible"
        label="羊只类型"
        align="center"
        prop="name"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">羊只类型</span>
        </template>
      </el-table-column>
      
      <el-table-column
        v-if="columns['sheepfoldName'].visible"
        label="羊舍名称"
        align="center"
        prop="sheepfoldName"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">羊舍名称</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['variety'].visible"
        label="品种"
        align="center"
        prop="variety"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">品种</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['family'].visible"
        label="家系"
        align="center"
        prop="family"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">家系</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['birthday'].visible"
        label="出生日期"
        align="center"
        prop="birthday"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">出生日期</span>
        </template>
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['dayAge'].visible"
        label="日龄"
        align="center"
        prop="dayAge"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">日龄</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['monthAge'].visible"
        label="月龄"
        align="center"
        prop="monthAge"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">月龄</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['parity'].visible"
        label="胎次"
        align="center"
        prop="parity"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">胎次</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['birthWeight'].visible"
        label="出生体重"
        align="center"
        prop="birthWeight"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">出生体重</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['weaningDate'].visible"
        label="断奶日期"
        align="center"
        prop="weaningDate"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">断奶日期</span>
        </template>
        <template #default="scope">
          <span>{{ parseTime(scope.row.weaningDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['weaningWeight'].visible"
        label="断奶体重"
        align="center"
        prop="weaningWeight"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">断奶体重</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['currentWeight'].visible"
        label="当前体重"
        align="center"
        prop="currentWeight"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">当前体重</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['weaningDayAge'].visible"
        label="断奶日龄"
        align="center"
        prop="weaningDayAge"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">断奶日龄</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['weaningDailyGain'].visible"
        label="断奶日增重"
        align="center"
        prop="weaningDailyGain"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">断奶日增重</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['fatherManageTags'].visible"
        label="父亲耳号"
        align="center"
        prop="fatherManageTags"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">父亲耳号</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['motherManageTags'].visible"
        label="母亲耳号"
        align="center"
        prop="motherManageTags"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">母亲耳号</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['grandfatherManageTags'].visible"
        label="祖父耳号"
        align="center"
        prop="grandfatherManageTags"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">祖父耳号</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['grandmotherManageTags'].visible"
        label="祖母耳号"
        align="center"
        prop="grandmotherManageTags"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">祖母耳号</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['maternalGrandfatherManageTags'].visible"
        label="外祖父耳号"
        align="center"
        prop="maternalGrandfatherManageTags"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">外祖父耳号</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['maternalGrandmotherManageTags'].visible"
        label="外祖母耳号"
        align="center"
        prop="maternalGrandmotherManageTags"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">外祖母耳号</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['receptorManageTags'].visible"
        label="受体耳号"
        align="center"
        prop="receptorManageTags"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">受体耳号</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['matingDate'].visible"
        label="配种日期"
        align="center"
        prop="matingDate"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">最近配种日期</span>
        </template>
        <template #default="scope">
          <span>{{ parseTime(scope.row.matingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['matingTypeId'].visible"
        label="配种类型"
        align="center"
        prop="matingTypeId"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">最近配种类型</span>
        </template>
        <template #default="scope">
          <dict-tag :options="breed_type" :value="scope.row.matingTypeId"/>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['pregDate'].visible"
        label="孕检日期"
        align="center"
        prop="pregDate"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">最近孕检日期</span>
        </template>
        <template #default="scope">
          <span>{{ parseTime(scope.row.pregDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['lambingDate'].visible"
        label="产羔日期"
        align="center"
        prop="lambingDate"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">最近产羔日期</span>
        </template>
        <template #default="scope">
          <span>{{ parseTime(scope.row.lambingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['lambingDay'].visible"
        label="产羔时怀孕天数"
        align="center"
        prop="lambingDay"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">产羔时怀孕天数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['matingDay'].visible"
        label="配后天数"
        align="center"
        prop="matingDay"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">配后天数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['gestationDay'].visible"
        label="怀孕天数"
        align="center"
        prop="gestationDay"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">怀孕天数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['expectedDate'].visible"
        label="预产日期"
        align="center"
        prop="expectedDate"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">预产日期</span>
        </template>
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['postLambingDay'].visible"
        label="产后天数"
        align="center"
        prop="postLambingDay"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">产后天数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['lactationDay'].visible"
        label="泌乳天数"
        align="center"
        prop="lactationDay"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">泌乳天数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['anestrousDay'].visible"
        label="空怀天数"
        align="center"
        prop="anestrousDay"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">空怀天数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['matingCounts'].visible"
        label="配种次数"
        align="center"
        prop="matingCounts"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">配种次数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['matingTotal'].visible"
        label="累计配种次数"
        align="center"
        prop="matingTotal"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">累计配种次数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['miscarriageCounts'].visible"
        label="累计流产次数"
        align="center"
        prop="miscarriageCounts"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">累计流产次数</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['comment'].visible"
        label="备注"
        align="center"
        prop="comment"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">备注</span>
        </template>
        <template #default="scope">
          <el-tooltip :content="scope.row.comment" placement="top">
            <span style="display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
              {{ scope.row.comment }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['controlled'].visible"
        label="是否性控"
        align="center"
        prop="controlled"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">是否性控</span>
        </template>
        <template #default="scope">
          <dict-tag :options="controlled" :value="scope.row.controlled"/>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['body'].visible"
        label="体况评分"
        align="center"
        prop="body"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">体况评分</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['breast'].visible"
        label="乳房评分"
        align="center"
        prop="breast"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">乳房评分</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['source'].visible"
        label="入群来源"
        align="center"
        prop="source"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">入群来源</span>
        </template>
        <template #default="scope">
          <dict-tag :options="source" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['sourceDate'].visible"
        label="入群日期"
        align="center"
        prop="sourceDate"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">入群日期</span>
        </template>
        <template #default="scope">
          <span>{{ parseTime(scope.row.sourceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns['sourceRanch'].visible"
        label="来源牧场"
        align="center"
        prop="sourceRanch"
        width="120"
        sortable
      >
        <template #header>
          <span style="font-weight: bold; color: #333;">来源牧场</span>
        </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"
      :page-sizes="[20, 50, 100, 200, 500, 1000, 2000]"
    />

    <el-dialog v-model="columnDialogVisible" title="显示列设置" width="800px">
      <div style="max-height: 400px; overflow-y: auto; ">
        <el-checkbox-group v-model="selectedColumns" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;" >
          <el-checkbox label="bsManageTags">耳号</el-checkbox>
          <el-checkbox label="drRanch">牧场名称</el-checkbox>
          <el-checkbox label="sheepfoldName">羊舍名称</el-checkbox>
          <el-checkbox label="electronicTags">电子耳号</el-checkbox>
          <el-checkbox label="variety">品种</el-checkbox>
          <el-checkbox label="family">家系</el-checkbox>
          <el-checkbox label="name">羊只类型</el-checkbox>
          <el-checkbox label="gender">性别</el-checkbox>
          <el-checkbox label="birthday">出生日期</el-checkbox>
          <el-checkbox label="dayAge">日龄</el-checkbox>
          <el-checkbox label="monthAge">月龄</el-checkbox>
          <el-checkbox label="parity">胎次</el-checkbox>
          <el-checkbox label="birthWeight">出生体重</el-checkbox>
          <el-checkbox label="weaningDate">断奶日期</el-checkbox>
          <el-checkbox label="weaningWeight">断奶体重</el-checkbox>
          <el-checkbox label="currentWeight">当前体重</el-checkbox>
          <el-checkbox label="weaningDayAge">断奶日龄</el-checkbox>
          <el-checkbox label="weaningDailyGain">断奶日增重</el-checkbox>
          <el-checkbox label="breed">繁殖状态</el-checkbox>
          <el-checkbox label="fatherManageTags">父亲耳号</el-checkbox>
          <el-checkbox label="motherManageTags">母亲耳号</el-checkbox>
          <el-checkbox label="grandfatherManageTags">祖父耳号</el-checkbox>
          <el-checkbox label="grandmotherManageTags">祖母耳号</el-checkbox>
          <el-checkbox label="maternalGrandfatherManageTags">外祖父耳号</el-checkbox>
          <el-checkbox label="maternalGrandmotherManageTags">外祖母耳号</el-checkbox>
          <el-checkbox label="receptorManageTags">受体耳号</el-checkbox>
          <el-checkbox label="matingDate">配种日期</el-checkbox>
          <el-checkbox label="matingTypeId">配种类型</el-checkbox>
          <el-checkbox label="pregDate">孕检日期</el-checkbox>
          <el-checkbox label="lambingDate">产羔日期</el-checkbox>
          <el-checkbox label="lambingDay">产羔时怀孕天数</el-checkbox>
          <el-checkbox label="matingDay">配后天数</el-checkbox>
          <el-checkbox label="gestationDay">怀孕天数</el-checkbox>
          <el-checkbox label="expectedDate">预产日期</el-checkbox>
          <el-checkbox label="postLambingDay">产后天数</el-checkbox>
          <el-checkbox label="lactationDay">泌乳天数</el-checkbox>
          <el-checkbox label="anestrousDay">空怀天数</el-checkbox>
          <el-checkbox label="matingCounts">配种次数</el-checkbox>
          <el-checkbox label="matingTotal">累计配种次数</el-checkbox>
          <el-checkbox label="miscarriageCounts">累计流产次数</el-checkbox>
          <el-checkbox label="comment">备注</el-checkbox>
          <el-checkbox label="controlled">是否性控</el-checkbox>
          <el-checkbox label="body">体况评分</el-checkbox>
          <el-checkbox label="breast">乳房评分</el-checkbox>
          <el-checkbox label="source">入群来源</el-checkbox>
          <el-checkbox label="sourceDate">入群日期</el-checkbox>
          <el-checkbox label="sourceRanch">来源牧场</el-checkbox>
          <el-checkbox label="statusId">羊只状态</el-checkbox>
        </el-checkbox-group>
      </div>
      <div style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center;">
        <el-checkbox v-model="isAllSelected" @change="toggleAllSelection" >全选</el-checkbox>
        <div>
          <el-button type="primary" @click="confirmColumnSettings">提交</el-button>
          <el-button @click="resetColumnSettings">重置</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Sheep_file">
import { listSheep_file, getSheep_file, delSheep_file, getFieldValues } from "@/api/fileManagement/sheep_file"
import request from '@/utils/request'
// 新增：引入自定义筛选组件
import CustomFilter from '@/components/CustomFilter/index.vue'

// 新增：响应式数据
const customFilterRef = ref()
const appliedFilters = ref([])

// 1. 添加新的响应式变量来存储自定义筛选条件
const customFilterParams = ref({})
const isCustomFilterActive = ref(false)

const { proxy } = getCurrentInstance()
const { sheep_gender } = proxy.useDict('sheep_gender')
console.log('性别字典数据:', sheep_gender) // 添加这行来调试
const { breed_type } = proxy.useDict('breed_type')
const { controlled } = proxy.useDict('controlled')
const { source } = proxy.useDict('source')
const { sheep_status } = proxy.useDict('sheep_status')
const { da_ranch } = proxy.useDict('da_ranch')
const sheep_fileList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const columnDialogVisible = ref(false)

// 新增：下拉选项响应式数据
const earOptions = ref([])
const loadingEar = ref(false)
const breedOptions = ref([])
const typeOptions = ref([])

// 在 setup 中修改 selectedColumns 的默认值
const selectedColumns = ref([
    'drRanch',      // 牧场名称
    'bsManageTags', // 耳号
    'drRanch',      // 牧场名称
    'sheepfoldName', // 羊舍名称
    'electronicTags', // 电子耳号
    'variety',      // 品种
    'family',        //家系
    'name',         // 羊只类型
    'gender',       // 性别
    'birthday',     // 出生日期
    'dayAge',       // 日龄
    'monthAge',     //月龄
    'parity',       //胎次
    'birthWeight',  //出生体重
    'weaningDate',  //断奶日期
    'weaningWeight',//断奶体重
    'currentWeight', // 当前体重
    'breed',        // 繁殖状态
    'fatherManageTags', // 父亲耳号
    'motherManageTags', // 母亲耳号
    'grandfatherManageTags',//祖父
    'grandmotherManageTags',//祖母
    'maternalGrandfatherManageTags',//外祖父
    'maternalGrandmotherManageTags',//外祖母
    'comment'//备注
])
const isAllSelected = ref(false)
const columns = reactive({
  id: { visible: true },
  bsManageTags: { visible: true },
  ranchId: { visible: true },
  drRanch: { visible: true },
  sheepfoldId: { visible: true },
  sheepfoldName: { visible: true },
  electronicTags: { visible: true },
  varietyId: { visible: true },
  variety: { visible: true },
  family: { visible: true },
  name: { visible: true },
  gender: { visible: true },
  birthday: { visible: true },
  dayAge: { visible: true },
  monthAge: { visible: true },
  parity: { visible: true },
  birthWeight: { visible: true },
  weaningDate: { visible: true },
  statusId: { visible: true },
  weaningWeight: { visible: true },
  currentWeight: { visible: true },
  weaningDayAge: { visible: true },
  weaningDailyGain: { visible: true },
  breedStatusId: { visible: true },
  breed: { visible: true },
  bsFatherId: { visible: true },
  fatherManageTags: { visible: true },
  bsMotherId: { visible: true },
  motherManageTags: { visible: true },
  receptorId: { visible: true },
  receptorManageTags: { visible: true },
  fatherFatherId: { visible: true },
  grandfatherManageTags: { visible: true },
  fatherMotherId: { visible: true },
  grandmotherManageTags: { visible: true },
  fatherId: { visible: true },
  maternalGrandfatherManageTags: { visible: true },
  motherId: { visible: true },
  maternalGrandmotherManageTags: { visible: true },
  matingDate: { visible: true },
  matingTypeId: { visible: true },
  pregDate: { visible: true },
  lambingDate: { visible: true },
  lambingDay: { visible: true },
  matingDay: { visible: true },
  gestationDay: { visible: true },
  expectedDate: { visible: true },
  postLambingDay: { visible: true },
  lactationDay: { visible: true },
  anestrousDay: { visible: true },
  matingCounts: { visible: true },
  matingTotal: { visible: true },
  miscarriageCounts: { visible: true },
  comment: { visible: true },
  controlled: { visible: true },
  body: { visible: true },
  breast: { visible: true },
  source: { visible: true },
  sourceDate: { visible: true },
  sourceRanchId: { visible: true },
  sourceRanch: { visible: true },
  updateBy: { visible: true },
  updateTime: { visible: true },
  createBy: { visible: true },
  createTime: { visible: true }
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // 多选参数
    allEarNumbers: [],
    allEleEarNumbers: [],
    allGenders: [],
    allBreedingStatus: [],
    allSheepTypes: [],
    
    // 默认在群 (1)
    statusId: 1,

    // 其他单值参数
    drRanch: null,
    id: null,
    bsManageTags: null,
    electronicTags: null,
    variety: null,
    name: null,
    gender: null,
    breed: null,
  },
  rules: {
    id: [
      { required: true, message: "羊只id不能为空", trigger: "blur" }
    ],
  }
})

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

/** 初始化加载选项数据 */
function initOptions() {
  getFieldValues('breed').then(res => { breedOptions.value = res.data || [] })
  getFieldValues('name').then(res => { typeOptions.value = res.data || [] })
}

// 页面加载时初始化
initOptions()

/** 耳号远程搜索方法 */
function searchEarMethod(query) {
  if (query) {
    loadingEar.value = true
    request({
      url: '/sheep_file/sheep_file/searchEarNumbers',
      method: 'get',
      params: { query: query }
    }).then(res => {
      loadingEar.value = false
      earOptions.value = res.data || []
    }).catch(() => {
        loadingEar.value = false
        earOptions.value = []
    })
  } else {
    earOptions.value = []
  }
}

// 5. 修改 getList 函数，支持传入自定义参数
function getList(queryParamOverride = null) {
  loading.value = true
  
  // 准备查询参数
  const finalQueryParams = queryParamOverride || { ...queryParams.value }
  
  // 如果有自定义筛选条件，合并到查询参数中
  if (isCustomFilterActive.value && Object.keys(customFilterParams.value).length > 0) {
    Object.assign(finalQueryParams, customFilterParams.value)
  }
  
  listSheep_file(finalQueryParams).then(response => {
    sheep_fileList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    bsManageTags: null,
    ranchId: null,
    drRanch: null,
    sheepfoldId: null,
    sheepfoldName: null,
    electronicTags: null,
    varietyId: null,
    variety: null,
    family: null,
    name: null,
    gender: null,
    birthday: null,
    dayAge: null,
    monthAge: null,
    parity: null,
    birthWeight: null,
    weaningDate: null,
    statusId: null,
    weaningWeight: null,
    currentWeight: null,
    weaningDayAge: null,
    weaningDailyGain:null,
    breedStatusId: null,
    breed: null,
    bsFatherId: null,
    fatherManageTags: null,
    bsMotherId: null,
    motherManageTags: null,
    receptorId: null,
    receptorManageTags: null,
    fatherFatherId: null,
    grandfatherManageTags: null,
    fatherMotherId: null,
    grandmotherManageTags: null,
    fatherId: null,
    maternalGrandfatherManageTags: null,
    motherId: null,
    maternalGrandmotherManageTags: null,
    matingDate: null,
    matingTypeId: null,
    pregDate: null,
    lambingDate: null,
    lambingDay: null,
    matingDay: null,
    gestationDay: null,
    expectedDate: null,
    postLambingDay: null,
    lactationDay: null,
    anestrousDay: null,
    matingCounts: null,
    matingTotal: null,
    miscarriageCounts: null,
    comment: null,
    controlled: null,
    body: null,
    breast: null,
    source: null,
    sourceDate: null,
    sourceRanchId: null,
    sourceRanch: null,
    updateBy: null,
    updateTime: null,
    createBy: null,
    createTime: null,
    isDelete: null
  }
  proxy.resetForm("sheep_fileRef")
}

/** 搜索建议功能 */
function handleQuery() {
  queryParams.value.pageNum = 1
  
  // 准备查询参数
  const finalQueryParams = { ...queryParams.value }
  
  // 如果有自定义筛选条件，合并到查询参数中
  if (isCustomFilterActive.value && Object.keys(customFilterParams.value).length > 0) {
    Object.assign(finalQueryParams, customFilterParams.value)
  }
  
  // 执行查询
  loading.value = true
  listSheep_file(finalQueryParams).then(response => {
    sheep_fileList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 4. 修改 resetQuery 函数，重置所有筛选条件
function resetQuery() {
  proxy.resetForm("queryRef")
  
  // 重置新增的多选字段
  queryParams.value.allEarNumbers = []
  queryParams.value.allEleEarNumbers = []
  queryParams.value.allGenders = []
  queryParams.value.allBreedingStatus = []
  queryParams.value.allSheepTypes = []
  
  // 重置默认值
  queryParams.value.statusId = 1

  // 清空自定义筛选条件
  customFilterParams.value = {}
  appliedFilters.value = []
  isCustomFilterActive.value = false
  
  // 执行查询
  queryParams.value.pageNum = 1
  getList()
}

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

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

// 8. 修改 handleExport 函数，导出时也包含自定义筛选条件
function handleExport() {
  const exportParams = { ...queryParams.value }
  
  // 如果有自定义筛选条件，合并到导出参数中
  if (isCustomFilterActive.value && Object.keys(customFilterParams.value).length > 0) {
    Object.assign(exportParams, customFilterParams.value)
  }
  
  proxy.download('sheep_file/sheep_file/export', exportParams, `sheep_file_${new Date().getTime()}.xlsx`)
}

// 打开列设置对话框
function openColumnDialog() {
  // 加载上次选择的状态
  const savedColumns = localStorage.getItem('selectedColumns')
  if (savedColumns) {
    selectedColumns.value = JSON.parse(savedColumns)
    Object.keys(columns).forEach(column => {
      columns[column].visible = selectedColumns.value.includes(column)
    })
  }
  columnDialogVisible.value = true
}

// 全选功能
function toggleAllSelection() {
  if (isAllSelected.value) {
    selectedColumns.value = Object.keys(columns)
  } else {
    selectedColumns.value = []
  }
  updateColumnVisibility()
}

// 更新列的显示状态
function updateColumnVisibility() {
  Object.keys(columns).forEach(column => {
    columns[column].visible = selectedColumns.value.includes(column)
  })
}

// 确认列设置
function confirmColumnSettings() {
  updateColumnVisibility()
  // 保存当前选择到本地存储
  localStorage.setItem('selectedColumns', JSON.stringify(selectedColumns.value))
  columnDialogVisible.value = false
}

// 修改重置函数
function resetColumnSettings() {
  // 只重置为默认的核心字段
  selectedColumns.value = [
    'bsManageTags', // 耳号
    'drRanch',      // 牧场名称
    'sheepfoldName', // 羊舍名称
    'electronicTags', // 电子耳号
    'variety',      // 品种
    'family',        //家系
    'name',         // 羊只类型
    'gender',       // 性别
    'birthday',     // 出生日期
    'dayAge',       // 日龄
    'monthAge',     //月龄
    'parity',       //胎次
    'birthWeight',  //出生体重
    'weaningDate',  //断奶日期
    'weaningWeight',//断奶体重
    'currentWeight', // 当前体重
    'breed',        // 繁殖状态
    'fatherManageTags', // 父亲耳号
    'motherManageTags', // 母亲耳号
    'grandfatherManageTags',//祖父
    'grandmotherManageTags',//祖母
    'maternalGrandfatherManageTags',//外祖父
    'maternalGrandmotherManageTags',//外祖母
    'comment'//备注
  ]
  updateColumnVisibility()
  localStorage.setItem('selectedColumns', JSON.stringify(selectedColumns.value))
}

/**
 * 处理自定义筛选
 */
function handleCustomFilter(filterParams) {
  console.log('接收到筛选参数:', filterParams)
  
  // 构建应用筛选条件的显示文本
  appliedFilters.value = Object.keys(filterParams).map(field => {
    const fieldConfig = availableFields.find(f => f.value === field)
    const value = filterParams[field]
    let text = ''
    
    if (!fieldConfig) {
      text = `${field}: ${value}`
    } else if (value === 'IS_NULL') {
      text = `${fieldConfig.label}: 为空`
    } else if (value === 'NOT_NULL') {
      text = `${fieldConfig.label}: 不为空`
    } else if (value.startsWith('GT:')) {
      text = `${fieldConfig.label} > ${value.substring(3)}`
    } else if (value.startsWith('LT:')) {
      text = `${fieldConfig.label} < ${value.substring(3)}`
    } else if (value.startsWith('GE:')) {
      text = `${fieldConfig.label} ≥ ${value.substring(3)}`
    } else if (value.startsWith('LE:')) {
      text = `${fieldConfig.label} ≤ ${value.substring(3)}`
    } else if (value.includes(',')) {
      const values = value.split(',')
      if (['gender', 'status_id', 'mating_type_id'].includes(field)) {
        const dictLabels = values.map(v => getDictLabel(field, v)).join(', ')
        text = `${fieldConfig.label} 在 [${dictLabels}] 中`
      } else {
        text = `${fieldConfig.label} 在 [${value}] 中`
      }
    } else {
      if (['gender', 'status_id', 'mating_type_id'].includes(field)) {
        const dictLabel = getDictLabel(field, value)
        text = `${fieldConfig.label}: ${dictLabel}`
      } else {
        text = `${fieldConfig.label}: ${value}`
      }
    }
    
    return { field, value, text }
  })
  
  // 保存自定义筛选参数，不立即查询
  customFilterParams.value = filterParams
  isCustomFilterActive.value = Object.keys(filterParams).length > 0
}

/**
 * 获取字典标签
 */
function getDictLabel(field, value) {
  let dictOptions = []
  
  // 根据字段名映射到对应的字典
  if (field === 'gender') {
    dictOptions = sheep_gender.value || []
  } else if (field === 'status_id') {
    dictOptions = sheep_status.value || []
  } else if (field === 'mating_type_id') {
    dictOptions = breed_type.value || []
  } else if (field === 'controlled') {
    dictOptions = controlled.value || []
  } else if (field === 'source') {
    dictOptions = source.value || []
  }
  
  if (!dictOptions || !Array.isArray(dictOptions) || dictOptions.length === 0) {
    return String(value)
  }
  
  // 将原始值转换为字符串进行比较
  const valueStr = String(value)
  const item = dictOptions.find(item => String(item.value) === valueStr)
  
  return item ? item.label : String(value)
}

/**
 * 移除单个筛选条件
 */
function removeAppliedFilter(index) {
  const filter = appliedFilters.value[index]
  
  // 从自定义筛选参数中移除该字段
  if (customFilterParams.value[filter.field]) {
    delete customFilterParams.value[filter.field]
  }
  
  appliedFilters.value.splice(index, 1)
  
  // 如果没有筛选条件了，更新状态
  if (appliedFilters.value.length === 0) {
    isCustomFilterActive.value = false
  }
}

/**
 * 清除所有筛选条件
 */
function clearAllFilters() {
  customFilterParams.value = {}
  appliedFilters.value = []
  isCustomFilterActive.value = false
  
  // 不立即查询，等待用户点击搜索按钮
}

// 定义字段配置（用于显示）
const availableFields = [
  { label: '耳号', value: 'bs_manage_tags' },
  { label: '电子耳号', value: 'electronic_tags'},
  { label: '牧场名称', value: 'dr_ranch' },
  { label: '羊舍名称', value: 'sheepfold_name'},
  { label: '品种', value: 'variety'},
  { label: '家系', value: 'family' },
  { label: '羊只类型', value: 'name'},
  { label: '性别', value: 'gender'},
  { label: '出生日期', value: 'birthday'},
  { label: '日龄', value: 'day_age'},
  { label: '月龄', value: 'month_age'},
  { label: '胎次', value: 'parity'},
  { label: '出生体重', value: 'birth_weight' },
  { label: '断奶日期', value: 'weaning_date' },
  { label: '羊只状态', value: 'status_id' },
  { label: '断奶体重', value: 'weaning_weight' },
  { label: '当前体重', value: 'current_weight' },
  { label: '断奶日龄', value: 'weaning_day_age' },
  { label: '断奶日增重', value: 'weaning_daily_gain' },
  { label: '繁殖状态', value: 'breed' },
  { label: '父亲耳号', value: 'father_manage_tags' },
  { label: '母亲耳号', value: 'mother_manage_tags'},
  { label: '受体耳号', value: 'receptor_manage_tags' },
  { label: '配种类型', value: 'mating_type_id' },
  { label: '孕检日期', value: 'preg_date'},
  { label: '产羔日期', value: 'lambing_date'},
  { label: '产羔时怀孕天数', value: 'lambing_day'},
  { label: '配后天数', value: 'mating_day' },
  { label: '怀孕天数', value: 'gestation_day'},
  { label: '预产日期', value: 'expected_date'},
  { label: '产后天数', value: 'post_lambing_day'},
  { label: '泌乳天数', value: 'lactation_day'},
  { label: '空怀天数', value: 'anestrous_day' },
  { label: '配种次数', value: 'mating_counts' },
  { label: '累计配种次数', value: 'mating_total'},
  { label: '累计流产次数', value: 'miscarriage_counts' },
  { label: '体况评分', value: 'body' },
  { label: '乳房评分', value: 'breast'},
  { label: '入群日期', value: 'source_date' },
  { label: '修改日期', value: 'update_time'},
  { label: '创建日期', value: 'create_time'},
]


getList()
</script>

<style scoped>
:deep(.el-checkbox) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  margin: 5px;
  width: calc(30% - 20px);
}


.applied-filters {
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.filter-title {
  font-weight: 600;
  margin-bottom: 8px;
  color: #495057;
}

.filter-active-tip {
  display: inline-flex;
  align-items: center;
  margin-left: 8px;
  font-size: 12px;
  color: #67c23a;
}
</style>