<template>
  <div class="step-container">
    <div v-if="loading" class="loading-wrapper flex-display-center">
      <span class="text-tip-2 text-primary-50-clor">加载中...</span>
    </div>
    <template v-else>
      <div class="content-wrapper">
        <ProposalInfoSection v-if="currentProposalInfo" :info="currentProposalInfo" />
        <FilterSection
          :fields="filterFields"
          @update:fields="filterFields = $event"
          @set-as-current="handleSetAsCurrent"
        />
      </div>
      <ActionButtons
        @reset="handleReset"
        @next="handleNext"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import type { ProposalInfo, FilterField } from '../api'
import { fetchProposalInfo, fetchFilterFields } from '../api'
import ProposalInfoSection from './ProposalInfoSection.vue'
import FilterSection from './FilterSection.vue'
import ActionButtons from './ActionButtons.vue'

const props = defineProps<{
  proposalInfo?: ProposalInfo | null
  defaultFilters?: Record<string, string[]>
}>()

const emit = defineEmits<{
  next: []
}>()

// 提案信息（优先使用 props，否则从 API 获取）
const currentProposalInfo = ref<ProposalInfo | null>(null)
// 筛选字段列表
const filterFields = ref<FilterField[]>([])
// 加载状态
const loading = ref(true)
// 初始筛选字段（用于重置）
const initialFilterFields = ref<FilterField[]>([])

// 监听 props.proposalInfo 变化
watch(() => props.proposalInfo, (newInfo) => {
  if (newInfo) {
    currentProposalInfo.value = newInfo
  }
}, { immediate: true })

// 页面初始化时加载数据
onMounted(async () => {
  try {
    // 如果没有从 props 获取到提案信息，则从 API 获取
    if (!props.proposalInfo) {
      currentProposalInfo.value = await fetchProposalInfo()
    }
    
    // 获取筛选字段配置
    const fields = await fetchFilterFields()
    
    // 如果有默认筛选条件，应用到筛选字段
    if (props.defaultFilters && Object.keys(props.defaultFilters).length > 0) {
      filterFields.value = fields.map(field => ({
        ...field,
        selectedValues: props.defaultFilters?.[field.id] || field.selectedValues
      }))
    } else {
      filterFields.value = fields
    }
    
    // 保存初始状态用于重置
    initialFilterFields.value = JSON.parse(JSON.stringify(filterFields.value))
  } finally {
    loading.value = false
  }
})

// 重置所有筛选条件
function handleReset() {
  filterFields.value = JSON.parse(JSON.stringify(initialFilterFields.value))
}

// 设置为当前提案
function handleSetAsCurrent() {
  // 根据当前提案信息重新设置筛选条件
  if (currentProposalInfo.value) {
    filterFields.value = filterFields.value.map(field => {
      // 根据提案信息设置默认值
      const defaultValues = getDefaultValuesForField(field.id, currentProposalInfo.value!)
      return {
        ...field,
        selectedValues: defaultValues.length > 0 ? defaultValues : field.selectedValues
      }
    })
  }
}

// 根据字段 ID 和提案信息获取默认值
function getDefaultValuesForField(fieldId: string, info: ProposalInfo): string[] {
  const areaMap: Record<string, string> = {
    '能源': 'energy',
    '集成电路': 'ic',
    '人工智能': 'ai',
    '生物技术': 'biotech'
  }
  
  switch (fieldId) {
    case 'policyArea':
      return info.areas.map(area => areaMap[area] || area.toLowerCase())
    case 'proposerPosition':
      return info.proposerPosition === '委员会主席' ? ['chairman'] : []
    case 'governmentType':
      return info.governmentType.includes('一致') ? ['unified'] : ['divided']
    case 'electionPhase':
      return info.electionPhase.includes('蜜月') ? ['honeymoon'] : []
    default:
      return []
  }
}

// 下一步
function handleNext() {
  emit('next')
}
</script>

<style scoped>
.step-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.loading-wrapper {
  flex: 1;
}

.content-wrapper {
  flex: 1;
  overflow: auto;
}
</style>
