<template>
  <div class="advanced-search">
    <a-card size="small">
      <template #title>
        <a-space>
          <SearchOutlined />
          高级搜索
        </a-space>
      </template>
      
      <template #extra>
        <a-space>
          <a-button size="small" @click="handleReset">
            重置
          </a-button>
          <a-button 
            size="small" 
            @click="toggleExpanded"
            :icon="expanded ? h(UpOutlined) : h(DownOutlined)"
          >
            {{ expanded ? '收起' : '展开' }}
          </a-button>
        </a-space>
      </template>

      <a-form 
        :model="searchForm" 
        layout="inline" 
        @finish="handleSearch"
        class="search-form"
      >
        <!-- 基础搜索行 -->
        <div class="search-row basic-row">
          <a-form-item label="关键词" name="keyword">
            <a-input
              v-model:value="searchForm.keyword"
              placeholder="请输入关键词"
              style="width: 200px"
              allow-clear
              @pressEnter="handleSearch"
            >
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="状态" name="status">
            <a-select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              style="width: 120px"
              allow-clear
            >
              <a-select-option 
                v-for="status in statusOptions" 
                :key="status.value" 
                :value="status.value"
              >
                <a-tag :color="status.color" size="small">{{ status.label }}</a-tag>
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="时间范围" name="dateRange">
            <a-range-picker
              v-model:value="searchForm.dateRange"
              style="width: 240px"
              :placeholder="['开始时间', '结束时间']"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </a-form-item>

          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="searching">
                <SearchOutlined />
                搜索
              </a-button>
              <a-button @click="handleReset">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </div>

        <!-- 高级搜索行 -->
        <div v-show="expanded" class="search-row advanced-row">
          <!-- 用户相关字段 -->
          <template v-if="searchType === 'user'">
            <a-form-item label="用户类型" name="userType">
              <a-select
                v-model:value="searchForm.userType"
                placeholder="请选择用户类型"
                style="width: 120px"
                allow-clear
              >
                <a-select-option value="normal">普通用户</a-select-option>
                <a-select-option value="vip">VIP用户</a-select-option>
                <a-select-option value="admin">管理员</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="注册来源" name="registerSource">
              <a-select
                v-model:value="searchForm.registerSource"
                placeholder="请选择注册来源"
                style="width: 120px"
                allow-clear
              >
                <a-select-option value="web">网页端</a-select-option>
                <a-select-option value="wechat">微信小程序</a-select-option>
                <a-select-option value="app">移动应用</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="年龄范围" name="ageRange">
              <a-slider
                v-model:value="searchForm.ageRange"
                range
                :min="0"
                :max="100"
                style="width: 200px"
                :tooltip-formatter="(value: number) => `${value}岁`"
              />
            </a-form-item>

            <a-form-item label="地区" name="region">
              <a-cascader
                v-model:value="searchForm.region"
                :options="regionOptions"
                placeholder="请选择地区"
                style="width: 200px"
                change-on-select
                allow-clear
              />
            </a-form-item>
          </template>

          <!-- 动物相关字段 -->
          <template v-if="searchType === 'animal'">
            <a-form-item label="动物类型" name="animalType">
              <a-select
                v-model:value="searchForm.animalType"
                placeholder="请选择动物类型"
                style="width: 120px"
                allow-clear
              >
                <a-select-option value="dog">狗</a-select-option>
                <a-select-option value="cat">猫</a-select-option>
                <a-select-option value="bird">鸟</a-select-option>
                <a-select-option value="other">其他</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="品种" name="breed">
              <a-input
                v-model:value="searchForm.breed"
                placeholder="请输入品种"
                style="width: 150px"
                allow-clear
              />
            </a-form-item>

            <a-form-item label="年龄范围" name="animalAgeRange">
              <a-input-group compact style="width: 200px">
                <a-input-number
                  v-model:value="searchForm.minAge"
                  placeholder="最小年龄"
                  :min="0"
                  :max="30"
                  style="width: 50%"
                />
                <a-input-number
                  v-model:value="searchForm.maxAge"
                  placeholder="最大年龄"
                  :min="0"
                  :max="30"
                  style="width: 50%"
                />
              </a-input-group>
            </a-form-item>

            <a-form-item label="性别" name="gender">
              <a-radio-group v-model:value="searchForm.gender">
                <a-radio value="male">雄性</a-radio>
                <a-radio value="female">雌性</a-radio>
                <a-radio value="unknown">未知</a-radio>
              </a-radio-group>
            </a-form-item>

            <a-form-item label="健康状态" name="healthStatus">
              <a-select
                v-model:value="searchForm.healthStatus"
                placeholder="请选择健康状态"
                style="width: 120px"
                allow-clear
              >
                <a-select-option value="healthy">健康</a-select-option>
                <a-select-option value="sick">生病</a-select-option>
                <a-select-option value="injured">受伤</a-select-option>
                <a-select-option value="recovering">康复中</a-select-option>
              </a-select>
            </a-form-item>
          </template>

          <!-- 订单相关字段 -->
          <template v-if="searchType === 'order'">
            <a-form-item label="订单类型" name="orderType">
              <a-select
                v-model:value="searchForm.orderType"
                placeholder="请选择订单类型"
                style="width: 120px"
                allow-clear
              >
                <a-select-option value="adoption">认领</a-select-option>
                <a-select-option value="donation">捐赠</a-select-option>
                <a-select-option value="service">服务</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="金额范围" name="amountRange">
              <a-input-group compact style="width: 200px">
                <a-input-number
                  v-model:value="searchForm.minAmount"
                  placeholder="最小金额"
                  :min="0"
                  style="width: 50%"
                />
                <a-input-number
                  v-model:value="searchForm.maxAmount"
                  placeholder="最大金额"
                  :min="0"
                  style="width: 50%"
                />
              </a-input-group>
            </a-form-item>

            <a-form-item label="支付方式" name="paymentMethod">
              <a-select
                v-model:value="searchForm.paymentMethod"
                placeholder="请选择支付方式"
                style="width: 120px"
                allow-clear
              >
                <a-select-option value="wechat">微信支付</a-select-option>
                <a-select-option value="alipay">支付宝</a-select-option>
                <a-select-option value="bank">银行卡</a-select-option>
              </a-select>
            </a-form-item>
          </template>

          <!-- 通用高级字段 -->
          <a-form-item label="创建人" name="creator">
            <a-input
              v-model:value="searchForm.creator"
              placeholder="请输入创建人"
              style="width: 150px"
              allow-clear
            />
          </a-form-item>

          <a-form-item label="排序方式" name="sortBy">
            <a-select
              v-model:value="searchForm.sortBy"
              placeholder="请选择排序方式"
              style="width: 150px"
            >
              <a-select-option value="created_at_desc">创建时间降序</a-select-option>
              <a-select-option value="created_at_asc">创建时间升序</a-select-option>
              <a-select-option value="updated_at_desc">更新时间降序</a-select-option>
              <a-select-option value="updated_at_asc">更新时间升序</a-select-option>
              <a-select-option value="name_asc">名称升序</a-select-option>
              <a-select-option value="name_desc">名称降序</a-select-option>
            </a-select>
          </a-form-item>
        </div>

        <!-- 快速筛选标签 -->
        <div class="quick-filters" v-if="quickFilters.length > 0">
          <a-divider orientation="left" orientation-margin="0">快速筛选</a-divider>
          <a-space wrap>
            <a-tag
              v-for="filter in quickFilters"
              :key="filter.key"
              :color="filter.active ? 'blue' : 'default'"
              style="cursor: pointer"
              @click="handleQuickFilter(filter)"
            >
              {{ filter.label }}
            </a-tag>
          </a-space>
        </div>

        <!-- 搜索历史 -->
        <div class="search-history" v-if="searchHistory.length > 0 && expanded">
          <a-divider orientation="left" orientation-margin="0">搜索历史</a-divider>
          <a-space wrap>
            <a-tag
              v-for="(history, index) in searchHistory.slice(0, 5)"
              :key="index"
              closable
              @close="removeSearchHistory(index)"
              @click="applySearchHistory(history)"
              style="cursor: pointer"
            >
              {{ history.keyword || '无关键词' }}
            </a-tag>
          </a-space>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, h } from 'vue'
import { 
  SearchOutlined, 
  DownOutlined, 
  UpOutlined 
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

interface SearchForm {
  keyword?: string
  status?: string
  dateRange?: [string, string]
  userType?: string
  registerSource?: string
  ageRange?: [number, number]
  region?: string[]
  animalType?: string
  breed?: string
  minAge?: number
  maxAge?: number
  gender?: string
  healthStatus?: string
  orderType?: string
  minAmount?: number
  maxAmount?: number
  paymentMethod?: string
  creator?: string
  sortBy?: string
  [key: string]: any
}

interface StatusOption {
  value: string
  label: string
  color: string
}

interface QuickFilter {
  key: string
  label: string
  active: boolean
  params: Partial<SearchForm>
}

interface Props {
  searchType: 'user' | 'animal' | 'order' | 'travel'
  statusOptions?: StatusOption[]
  defaultValues?: Partial<SearchForm>
}

const props = withDefaults(defineProps<Props>(), {
  statusOptions: () => [
    { value: 'active', label: '激活', color: 'green' },
    { value: 'inactive', label: '禁用', color: 'red' },
    { value: 'pending', label: '待审核', color: 'orange' }
  ]
})

const emit = defineEmits<{
  'search': [params: SearchForm]
  'reset': []
}>()

// 响应式数据
const expanded = ref(false)
const searching = ref(false)

const searchForm = reactive<SearchForm>({
  keyword: '',
  status: undefined,
  dateRange: undefined,
  sortBy: 'created_at_desc',
  ageRange: [0, 100],
  ...props.defaultValues
})

// 地区选项（示例数据）
const regionOptions = ref([
  {
    value: 'beijing',
    label: '北京市',
    children: [
      { value: 'chaoyang', label: '朝阳区' },
      { value: 'haidian', label: '海淀区' },
      { value: 'dongcheng', label: '东城区' }
    ]
  },
  {
    value: 'shanghai',
    label: '上海市',
    children: [
      { value: 'huangpu', label: '黄浦区' },
      { value: 'xuhui', label: '徐汇区' },
      { value: 'changning', label: '长宁区' }
    ]
  }
])

// 快速筛选
const quickFilters = ref<QuickFilter[]>([])

// 搜索历史
const searchHistory = ref<SearchForm[]>([])

// 初始化快速筛选
const initQuickFilters = () => {
  const baseFilters: QuickFilter[] = [
    {
      key: 'today',
      label: '今日新增',
      active: false,
      params: {
        dateRange: [
          new Date().toISOString().split('T')[0],
          new Date().toISOString().split('T')[0]
        ] as [string, string]
      }
    },
    {
      key: 'week',
      label: '本周新增',
      active: false,
      params: {
        dateRange: [
          new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          new Date().toISOString().split('T')[0]
        ] as [string, string]
      }
    },
    {
      key: 'active',
      label: '仅显示激活',
      active: false,
      params: { status: 'active' }
    }
  ]

  // 根据搜索类型添加特定筛选
  switch (props.searchType) {
    case 'user':
      baseFilters.push(
        {
          key: 'vip',
          label: 'VIP用户',
          active: false,
          params: { userType: 'vip' }
        },
        {
          key: 'wechat',
          label: '微信用户',
          active: false,
          params: { registerSource: 'wechat' }
        }
      )
      break
    
    case 'animal':
      baseFilters.push(
        {
          key: 'healthy',
          label: '健康动物',
          active: false,
          params: { healthStatus: 'healthy' }
        },
        {
          key: 'young',
          label: '幼年动物',
          active: false,
          params: { minAge: 0, maxAge: 2 }
        }
      )
      break
  }

  quickFilters.value = baseFilters
}

/**
 * 切换展开/收起
 */
const toggleExpanded = () => {
  expanded.value = !expanded.value
}

/**
 * 执行搜索
 */
const handleSearch = () => {
  searching.value = true
  
  // 清理空值
  const cleanParams = Object.keys(searchForm).reduce((acc, key) => {
    const value = searchForm[key]
    if (value !== undefined && value !== null && value !== '' && 
        !(Array.isArray(value) && value.length === 0)) {
      acc[key] = value
    }
    return acc
  }, {} as SearchForm)

  // 保存搜索历史
  saveSearchHistory(cleanParams)
  
  emit('search', cleanParams)
  
  setTimeout(() => {
    searching.value = false
  }, 500)
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (key === 'sortBy') {
      searchForm[key] = 'created_at_desc'
    } else if (key === 'ageRange') {
      searchForm[key] = [0, 100]
    } else {
      searchForm[key] = undefined
    }
  })
  
  // 重置快速筛选
  quickFilters.value.forEach(filter => {
    filter.active = false
  })
  
  emit('reset')
}

/**
 * 快速筛选
 */
const handleQuickFilter = (filter: QuickFilter) => {
  filter.active = !filter.active
  
  if (filter.active) {
    // 应用筛选参数
    Object.assign(searchForm, filter.params)
  } else {
    // 移除筛选参数
    Object.keys(filter.params).forEach(key => {
      searchForm[key] = undefined
    })
  }
  
  handleSearch()
}

/**
 * 保存搜索历史
 */
const saveSearchHistory = (params: SearchForm) => {
  // 避免重复
  const exists = searchHistory.value.some(history => 
    JSON.stringify(history) === JSON.stringify(params)
  )
  
  if (!exists) {
    searchHistory.value.unshift(params)
    // 最多保存10条历史
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
  }
}

/**
 * 应用搜索历史
 */
const applySearchHistory = (history: SearchForm) => {
  Object.assign(searchForm, history)
  handleSearch()
}

/**
 * 删除搜索历史
 */
const removeSearchHistory = (index: number) => {
  searchHistory.value.splice(index, 1)
}

// 初始化
initQuickFilters()

// 监听搜索类型变化
watch(() => props.searchType, () => {
  initQuickFilters()
  handleReset()
})
</script>

<style scoped>
.advanced-search {
  margin-bottom: 16px;
}

.search-form {
  width: 100%;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 24px;
  margin-bottom: 16px;
}

.basic-row {
  align-items: center;
}

.advanced-row {
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.quick-filters,
.search-history {
  margin-top: 16px;
}

.quick-filters :deep(.ant-divider),
.search-history :deep(.ant-divider) {
  margin: 8px 0;
}

:deep(.ant-form-item) {
  margin-bottom: 8px;
}

:deep(.ant-form-item-label) {
  width: auto;
  min-width: 60px;
}

@media (max-width: 768px) {
  .search-row {
    flex-direction: column;
    gap: 8px;
  }
  
  :deep(.ant-form-item) {
    width: 100%;
  }
}
</style>