<template>
  <!-- 模板部分保持不变 -->
  <div class="custom-filter">
    <el-button type="primary" @click="openFilterDialog">
      <i class="el-icon-search"></i>
      筛选条件
    </el-button>

    <el-dialog 
      v-model="filterDialogVisible" 
      title="自定义筛选条件" 
      width="800px"
      :close-on-click-modal="false"
    >
      <!-- 条件定义区域 -->
      <div class="condition-definition">
        <h4>添加筛选条件</h4>
        <el-row :gutter="10" align="middle">
          <el-col :span="6">
            <el-select 
              v-model="currentCondition.field" 
              placeholder="选择字段" 
              @change="handleFieldChange"
              clearable
            >
              <el-option
                v-for="field in availableFields"
                :key="field.value"
                :label="field.label"
                :value="field.value"
              />
            </el-select>
          </el-col>
          
          <el-col :span="6">
            <el-select 
              v-model="currentCondition.operator" 
              placeholder="选择条件"
              :disabled="!currentCondition.field"
              @change="handleOperatorChange"
            >
              <el-option
                v-for="op in availableOperators"
                :key="op.value"
                :label="op.label"
                :value="op.value"
              />
            </el-select>
          </el-col>
          
          <el-col :span="10">
            <div v-if="showValueInput">
              <el-input
                v-if="currentFieldType === 'text' && currentCondition.operator !== 'in'"
                v-model="currentCondition.value"
                :placeholder="`请输入${getCurrentFieldLabel()}`"
                clearable
              />
              
              <!-- 多选下拉框（在列表中） -->
              <el-select
                v-else-if="currentCondition.operator === 'in'"
                v-model="currentCondition.selectedOriginalValues"
                multiple
                filterable
                :placeholder="`选择${getCurrentFieldLabel()}`"
                style="width: 100%"
                :loading="loadingFieldValues"
              >
                <el-option
                  v-for="item in fieldValues"
                  :key="item.originalValue"
                  :label="item.displayLabel"
                  :value="item.originalValue"
                />
              </el-select>
              
              <el-input-number
                v-else-if="currentFieldType === 'number'"
                v-model="currentCondition.value"
                :placeholder="`请输入${getCurrentFieldLabel()}`"
                controls-position="right"
                style="width: 100%"
              />
              
              <el-date-picker
                v-else-if="currentFieldType === 'date'"
                v-model="currentCondition.value"
                type="date"
                :placeholder="`选择${getCurrentFieldLabel()}`"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
              
              <el-select
                v-else-if="currentFieldType === 'dict' && currentCondition.operator !== 'in'"
                v-model="currentCondition.value"
                :placeholder="`选择${getCurrentFieldLabel()}`"
                style="width: 100%"
              >
                <el-option
                  v-for="item in getDictOptions(currentCondition.field)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            
            <div v-else-if="currentCondition.operator === 'null' || currentCondition.operator === 'notNull'">
              <el-tag type="info">
                {{ currentCondition.operator === 'null' ? '为空' : '不为空' }}
              </el-tag>
            </div>
          </el-col>
          
          <el-col :span="2">
            <el-button 
              type="primary" 
              @click="addCondition" 
              :disabled="!canAddCondition"
              icon="el-icon-plus"
            >
              添加
            </el-button>
          </el-col>
        </el-row>
      </div>

      <div class="condition-list" v-if="conditions.length > 0">
        <h4>已添加的条件</h4>
        <div class="condition-item" v-for="(condition, index) in conditions" :key="index">
          <span class="condition-text">
            {{ getConditionText(condition) }}
          </span>
          <el-button 
            link 
            type="danger" 
            @click="removeCondition(index)"
            icon="el-icon-delete"
          >
            删除
          </el-button>
        </div>
      </div>
      
      <div class="condition-list" v-else>
        <el-empty description="暂无筛选条件" :image-size="80"></el-empty>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetFilter">重置</el-button>
          <el-button @click="cancelFilter">取消</el-button>
          <el-button type="primary" @click="applyFilters" :disabled="conditions.length === 0">
            保存条件
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue'
import { getFieldValues } from '@/api/fileManagement/sheep_file'

const { proxy } = getCurrentInstance()

// 直接使用 useDict 加载字典（这些是 Ref 对象）
const { sheep_gender, sheep_status, breed_type } = proxy.useDict('sheep_gender', 'sheep_status', 'breed_type')

// 响应式数据
const filterDialogVisible = ref(false)
const conditions = ref([])
const fieldValues = ref([])
const loadingFieldValues = ref(false)

// 当前正在定义的条件
const currentCondition = ref({
  field: '',
  operator: '',
  value: '',
  selectedOriginalValues: []
})

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

// 字典映射配置 - 存储 Ref 对象
const dictMap = {
  'gender': sheep_gender,
  'status_id': sheep_status, 
  'mating_type_id': breed_type
}

console.log('字典数据详情:', {
  sheep_gender: sheep_gender.value, // 访问 .value 获取实际数据
  sheep_status: sheep_status.value,
  breed_type: breed_type.value
})

// 计算属性
const currentFieldType = computed(() => {
  const field = availableFields.value.find(f => f.value === currentCondition.value.field)
  return field ? field.type : 'text'
})

const showValueInput = computed(() => {
  return currentCondition.value.operator && 
         currentCondition.value.operator !== 'null' && 
         currentCondition.value.operator !== 'notNull'
})

const canAddCondition = computed(() => {
  const { field, operator, value, selectedOriginalValues } = currentCondition.value
  if (!field || !operator) return false
  
  if (showValueInput.value) {
    if (operator === 'in') {
      return selectedOriginalValues && selectedOriginalValues.length > 0
    } else {
      return value !== null && value !== undefined && value !== ''
    }
  }
  
  return true
})

const availableOperators = computed(() => {
  const fieldOperatorConfig = {
    'bs_manage_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
    ],
    'electronic_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
      { label: '不为空', value: 'notNull' }
    ],
    'father_manage_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
    ],
    'mother_manage_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
    ],
    'receptor_manage_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
    ],
    'dr_ranch':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
     'sheepfold_name':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'variety':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'family':[
        {label:'在列表中',value:'in'},
    ],
    'name':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'day_age': 'number',
    'month_age': 'number',
    'parity': 'number',
    'birth_weight': 'number',
    'weaning_weight': 'number',
    'current_weight': 'number',
    'weaning_day_age': 'number',
    'weaning_daily_gain': 'number',
    'breed': [
      {label:'在列表中',value:'in'},
      {label: '为空', value: 'null' },
    ],
    'birthday': 'date',
    'weaning_date': 'date',
    'gender':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'status_id':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'mating_type_id':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'preg_date':'date',
    'lambing_date':'date',
    'lambing_day':'number',
    'mating_day':'number',
    'gestation_day':'number',
    'expected_date':'date',
    'post_lambing_day':'number',
    'lactation_day':'number',
    'anestrous_day':'number',
    'mating_counts':'number',
    'mating_total':'number',
    'miscarriage_counts':'number',
    'body':'number',
    'breast':'number',
    'source_date':'date',
    'update_time':'date',
    'create_time':'date',
  }
  
  const currentField = currentCondition.value.field
  
  if (fieldOperatorConfig[currentField]) {
    if (Array.isArray(fieldOperatorConfig[currentField])) {
      return fieldOperatorConfig[currentField]
    } else if (typeof fieldOperatorConfig[currentField] === 'string') {
      const type = fieldOperatorConfig[currentField]
      return getDefaultOperatorsByType(type)
    }
  }
  
  return getDefaultOperatorsByType(currentFieldType.value)
})

function getDefaultOperatorsByType(type) {
  const operators = {
    text: [
      { label: '等于', value: 'eq' },
      { label: '包含', value: 'like' },
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
      { label: '不为空', value: 'notNull' }
    ],
    number: [
      { label: '等于', value: 'eq' },
      { label: '大于', value: 'gt' },
      { label: '小于', value: 'lt' },
      { label: '大于等于', value: 'ge' },
      { label: '小于等于', value: 'le' },
      { label: '为空', value: 'null' },
      { label: '不为空', value: 'notNull' }
    ],
    date: [
      { label: '等于', value: 'eq' },
      { label: '大于', value: 'gt' },
      { label: '小于', value: 'lt' },
      { label: '大于等于', value: 'ge' },
      { label: '小于等于', value: 'le' },
      { label: '为空', value: 'null' },
    ],
    dict: [
      { label: '等于', value: 'eq' },
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
      { label: '不为空', value: 'notNull' }
    ]
  }
  
  return operators[type] || operators.text
}

// 方法定义
function openFilterDialog() {
  filterDialogVisible.value = true
  conditions.value = []
  currentCondition.value = { 
    field: '', 
    operator: '', 
    value: '',
    selectedOriginalValues: []
  }
}

function getCurrentFieldLabel() {
  const field = availableFields.value.find(f => f.value === currentCondition.value.field)
  return field ? field.label : ''
}

/**
 * 获取字典选项（用于单选）
 */
function getDictOptions(field) {
  const dictRef = dictMap[field]
  return dictRef ? dictRef.value : [] // 访问 .value 获取实际数组
}

/**
 * 根据字典字段和原始值获取字典标签
 */
function getDictLabel(field, value) {
  const dictRef = dictMap[field]
  if (!dictRef) {
    console.warn(`字段 ${field} 没有对应的字典`)
    return String(value)
  }
  
  const dictData = dictRef.value // 访问 .value 获取实际数组
  console.log(`字典转换: field=${field}, value=${value}, dictData=`, dictData)
  
  if (!dictData || !Array.isArray(dictData) || dictData.length === 0) {
    console.warn('字典数据无效，返回原始值')
    return String(value)
  }
  
  // 将原始值转换为字符串进行比较（确保类型一致）
  const valueStr = String(value)
  
  // 在字典中查找匹配的选项
  const option = dictData.find(item => {
    // 比较时都转换为字符串
    return String(item.value) === valueStr
  })
  
  if (option) {
    console.log(`找到匹配: ${value} -> ${option.label}`)
    return option.label
  } else {
    console.warn(`未找到匹配的字典项: value=${value}`)
    // 如果没有找到匹配，返回原始值
    return String(value)
  }
}

function getOperatorsByField(field, fieldType) {
  const fieldOperatorConfig = {
    'bs_manage_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
    ],
    'electronic_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
      { label: '不为空', value: 'notNull' }
    ],
    'father_manage_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
    ],
    'mother_manage_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
    ],
    'receptor_manage_tags': [
      { label: '在列表中', value: 'in' },
      { label: '为空', value: 'null' },
    ],
    'dr_ranch':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
     'sheepfold_name':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'variety':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'family':[
        {label:'在列表中',value:'in'},
    ],
    'name':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'day_age': 'number',
    'month_age': 'number',
    'parity': 'number',
    'birth_weight': 'number',
    'weaning_weight': 'number',
    'current_weight': 'number',
    'weaning_day_age': 'number',
    'weaning_daily_gain': 'number',
    'breed':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'birthday': 'date',
    'weaning_date': 'date',
    'gender':[
        {label:'在列表中',value:'in'},
        {label: '为空', value: 'null' },
    ],
    'status_id': 'dict',
    'mating_type_id': 'dict'
  }
  
  if (fieldOperatorConfig[field]) {
    if (Array.isArray(fieldOperatorConfig[field])) {
      return fieldOperatorConfig[field]
    } else if (typeof fieldOperatorConfig[field] === 'string') {
      const type = fieldOperatorConfig[field]
      return getDefaultOperatorsByType(type)
    }
  }
  
  return getDefaultOperatorsByType(fieldType)
}

function getConditionText(condition) {
  const field = availableFields.value.find(f => f.value === condition.field)
  const operators = getOperatorsByField(condition.field, field ? field.type : 'text')
  const operator = operators.find(op => op.value === condition.operator)
  
  if (!field || !operator) {
    console.warn('未知条件:', condition)
    return '未知条件'
  }
  
  let valueText = ''
  
  if (condition.operator === 'in') {
    if (Array.isArray(condition.value)) {
      if (field.type === 'dict') {
        valueText = condition.value.map(originalValue => 
          getDictLabel(condition.field, originalValue)
        ).join(', ')
      } else {
        valueText = condition.value.join(', ')
      }
    } else {
      valueText = condition.value
    }
  } else if (condition.operator === 'null' || condition.operator === 'notNull') {
    valueText = ''
  } else {
    if (field.type === 'dict') {
      valueText = getDictLabel(condition.field, condition.value)
    } else {
      valueText = condition.value
    }
  }
  
  let displayText = `${field.label} ${operator.label}`
  if (valueText) {
    displayText += ` ${valueText}`
  }
  
  return displayText
}

function handleFieldChange() {
  currentCondition.value.operator = ''
  currentCondition.value.value = ''
  currentCondition.value.selectedOriginalValues = []
  fieldValues.value = []
}

function handleOperatorChange() {
  currentCondition.value.value = ''
  currentCondition.value.selectedOriginalValues = []
  
  if (currentCondition.value.operator === 'in') {
    loadFieldValues()
  }
}

async function loadFieldValues() {
  if (!currentCondition.value.field) return
  
  loadingFieldValues.value = true
  try {
    const response = await getFieldValues(currentCondition.value.field)
    const rawValues = response.data || []
    
    console.log('=== 字段值加载调试 ===')
    console.log('字段:', currentCondition.value.field)
    console.log('字段类型:', currentFieldType.value)
    console.log('后端返回的原始值:', rawValues)
    
    const dictRef = dictMap[currentCondition.value.field]
    console.log('对应的字典引用:', dictRef)
    console.log('对应的字典数据:', dictRef ? dictRef.value : '无')
    
    // 处理字段值，将原始值转换为显示用的标签
    fieldValues.value = rawValues.map(rawValue => {
      // 如果是字典字段，使用字典转换
      if (currentFieldType.value === 'dict') {
        const displayLabel = getDictLabel(currentCondition.value.field, rawValue)
        
        console.log(`转换: ${rawValue} -> ${displayLabel}`)
        
        return {
          originalValue: rawValue,
          displayLabel: displayLabel
        }
      } else {
        // 普通字段直接使用原始值
        return {
          originalValue: rawValue,
          displayLabel: String(rawValue)
        }
      }
    })
    
    console.log('最终字段值:', fieldValues.value)
    console.log('========================')
    
  } catch (error) {
    console.error('获取字段值失败:', error)
    proxy.$modal.msgError('获取字段值失败')
    fieldValues.value = []
  } finally {
    loadingFieldValues.value = false
  }
}

function addCondition() {
  if (canAddCondition.value) {
    const condition = JSON.parse(JSON.stringify(currentCondition.value))
    
    if (condition.operator === 'in') {
      condition.value = condition.selectedOriginalValues
      delete condition.selectedOriginalValues
    }
    
    conditions.value.push(condition)
    
    currentCondition.value = { 
      field: '', 
      operator: '', 
      value: '',
      selectedOriginalValues: []
    }
    fieldValues.value = []
    
    proxy.$modal.msgSuccess('条件添加成功')
  }
}

function removeCondition(index) {
  conditions.value.splice(index, 1)
  proxy.$modal.msgSuccess('条件删除成功')
}

function cancelFilter() {
  filterDialogVisible.value = false
  conditions.value = []
}

// 1. 修改 applyFilters 函数，只传递筛选条件，不触发查询
function applyFilters() {
  if (conditions.value.length === 0) {
    proxy.$modal.msgWarning('请至少添加一个筛选条件')
    return
  }
  
  const queryParams = {}
  
  conditions.value.forEach(condition => {
    const { field, operator, value } = condition
    
    switch (operator) {
      case 'eq':
        queryParams[field] = value
        break
      case 'like':
        queryParams[field] = value
        break
      case 'in':
        if (Array.isArray(value) && value.length > 0) {
          queryParams[field] = value.join(',')
        }
        break
      case 'null':
        queryParams[field] = 'IS_NULL'
        break
      case 'notNull':
        queryParams[field] = 'NOT_NULL'
        break
      case 'gt':
        queryParams[field] = `GT:${value}`
        break
      case 'lt':
        queryParams[field] = `LT:${value}`
        break
      case 'ge':
        queryParams[field] = `GE:${value}`
        break
      case 'le':
        queryParams[field] = `LE:${value}`
        break
    }
  })
  
  // 传递筛选条件给父组件，不触发查询
  emit('filter', queryParams)
  filterDialogVisible.value = false
  proxy.$modal.msgSuccess('筛选条件已保存')
}

// 2. 添加重置功能
function resetFilter() {
  conditions.value = []
  currentCondition.value = { 
    field: '', 
    operator: '', 
    value: '',
    selectedOriginalValues: []
  }
  fieldValues.value = []
  proxy.$modal.msgSuccess('筛选条件已重置')
}

const emit = defineEmits(['filter'])

defineExpose({
  openFilterDialog
})
</script>

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

.condition-definition h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.condition-list {
  max-height: 300px;
  overflow-y: auto;
}

.condition-list h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.condition-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  margin: 8px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.condition-text {
  flex: 1;
  font-size: 14px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.custom-filter {
  display: inline-block;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>