<template>
  <div class="app-container">
    <PageHeader :proposal-info="proposalInfo" />
    <main class="layout-main-center">
      <div class="content-card background-as-card">
        <StepSidebar
          v-if="!loading && steps.length > 0"
          :steps="steps"
          :current-step="currentStep"
        />
        <div class="content-area">
          <template v-if="!loading">
            <Step1FilterCondition
              v-if="currentStep === 1"
              :proposal-info="proposalInfo"
              :default-filters="defaultFilters"
              @next="handleStep1Next"
            />
            <Step2FilterBills
              v-else-if="currentStep === 2"
              @previous="goToPreviousStep"
              @next="handleStep2Next"
            />
            <Step3PredictionAnalysis
              v-else-if="currentStep === 3"
              :data="predictionResult"
              :loading="predictionLoading"
              @prev="goToPreviousStep"
              @repredict="handleRepredict"
            />
          </template>
          <div v-else class="loading-container">
            <span class="text-tip-2 text-primary-50-clor">加载中...</span>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, provide } from 'vue'
import { useRoute } from 'vue-router'
import type { Step, ProposalInfo } from './api'
import { STEPS } from './api'
import { getProgressPrediction, parseBillId, transformProposalInfo, generateDefaultFilters, getPassProd } from '@/api/bill/billHome.js'
import PageHeader from './components/PageHeader.vue'
import StepSidebar from './components/StepSidebar.vue'
import Step1FilterCondition from './components/Step1FilterCondition.vue'
import Step2FilterBills from './components/Step2FilterBills.vue'
import Step3PredictionAnalysis from './components/Step3PredictionAnalysis.vue'

const route = useRoute()

// 步骤列表数据
const steps = ref<Step[]>([])
// 当前步骤
const currentStep = ref(1)
// 加载状态
const loading = ref(true)
// 提案信息
const proposalInfo = ref<ProposalInfo | null>(null)
// 默认筛选条件
const defaultFilters = ref<Record<string, string[]>>({})
// 法案ID
const billId = ref('')
// 当前筛选参数（传递给 Step2）
const currentFilterParams = ref<any>(null)
// 第一页接口原始数据（包含 bill_actions、bill_sponsors）
const rawProposalData = ref<any>(null)
// 第三页预测结果
const predictionResult = ref<any>(null)
// 预测加载状态
const predictionLoading = ref(false)

// 向子组件提供提案信息和筛选参数
provide('proposalInfo', proposalInfo)
provide('defaultFilters', defaultFilters)
provide('filterParams', currentFilterParams)

// 页面初始化时加载数据
onMounted(async () => {
  try {
    // 步骤数据使用固定配置
    steps.value = STEPS
    
    // 获取路由参数中的 id
    const routeId = route.params.id as string || '1'
    billId.value = parseBillId(routeId)
    
    // 获取提案信息
    const predictionData = await getProgressPrediction(billId.value).catch(err => {
      console.error(' 获取预测数据失败:', err)
      return null
    })
    
    if (predictionData) {
      // 保存原始数据（包含 bill_actions、bill_sponsors 等）
      rawProposalData.value = predictionData.data
      // 转换 API 数据为组件所需格式
      proposalInfo.value = transformProposalInfo(predictionData)
      // 根据提案信息生成默认筛选条件
      if (proposalInfo.value) {
        defaultFilters.value = generateDefaultFilters(proposalInfo.value)
        // 初始化筛选参数（Step2 会用到）
        currentFilterParams.value = {
          billIds: billId.value,
          domains: proposalInfo.value.areas || [],
          patternType: proposalInfo.value.patternType || '统一政府',
          proposalType: '两党共同提案',
          timeFrame: []
        }
      }
    }
  } finally {
    loading.value = false
  }
})

// 下一步
function goToNextStep() {
  if (currentStep.value < steps.value.length) {
    currentStep.value++
  }
}

// Step1 下一步：更新筛选参数中的 domains 和 timeFrame
function handleStep1Next(selectedFilters: Record<string, string[]>) {
  // 用已选的筛选条件更新 currentFilterParams
  if (currentFilterParams.value) {
    currentFilterParams.value.domains = selectedFilters.policyArea || []
    currentFilterParams.value.patternType = selectedFilters.governmentType?.[0] || '统一政府'
    currentFilterParams.value.proposalType = selectedFilters.oppositionProposer?.[0] || '两党共同提案'
    currentFilterParams.value.timeFrame = selectedFilters.proposalTime || []
  }
  // 进入下一步
  goToNextStep()
}

// Step2 下一步：调用预测接口
async function handleStep2Next(selectedBills: any[]) {
  predictionLoading.value = true
  predictionResult.value = null
  
  // 先进入第三页显示加载状态
  goToNextStep()
  
  try {
    // TODO: 暂行版本 - 使用固定参数，等后端接口完善后替换为真实数据
    // 真实参数应从 rawProposalData 和 selectedBills 获取
    const params = {
      bill_name: '《人工智能监督法案》(AI OVERWATCH Act)',
      bill_actions: [
        {
          action_date: '2025-12-18',
          action_type: 'IntroReferral',
          org_name: 'House floor actions',
          action_content: 'Referred to the House Committee on Foreign Affairs.'
        },
        {
          action_date: '2025-12-18',
          action_type: 'IntroReferral',
          org_name: 'Library of Congress',
          action_content: 'Introduced in House'
        }
      ],
      bill_sponsors: [
        {
          person_name: 'Moolenaar, John R.',
          sponsor_type: '共同提案人',
          party_name: '共和党'
        }
      ],
      bill_proposal_type: '两党共同提案',
      poli_pattern_type: '统一政府',
      poli_pattern_desc: '2025年12月18日，美国处于统一政府：共和党籍总统就职，共和党在参议院以53席对47席掌握多数，在众议院以220席对215席占据多数。',
      simi_bills: [
        {
          bill_name: '2025年NASA过渡授权法案',
          bill_actions: [
            {
              action_date: '2025-03-11',
              action_type: 'IntroReferral',
              org_name: 'Senate',
              action_content: 'Read twice and referred to the Committee on Commerce, Science, and Transportation.'
            },
            {
              action_date: '2025-03-11',
              action_type: 'IntroReferral',
              org_name: 'Library of Congress',
              action_content: 'Introduced in Senate'
            }
          ],
          bill_proposal_type: '两党共同提案',
          bill_proposal_desc: '两党共同提案',
          poli_pattern_type: '统一政府',
          poli_pattern_desc: '2025-03-11，共和党总统唐纳德·特朗普执政；参议院共和党53席、民主党47席；众议院共和党220席、民主党215席（含空缺）。'
        }
      ]
    }
    
    const response = await getPassProd(params)
    
    if (response && response.data) {
      // 转换预测结果为组件所需格式
      predictionResult.value = transformPredictionResult(response.data)
    }
  } catch (error) {
    console.error(' 获取预测分析失败:', error)
  } finally {
    predictionLoading.value = false
  }
}

// 根据通过概率转换为风险等级
function probabilityToRisk(probability: string): 'high' | 'medium' | 'low' {
  const num = parseInt(probability) || 0
  if (num >= 70) return 'high'
  if (num >= 40) return 'medium'
  return 'low'
}

// 根据通过概率转换为进度等级 (1-3)
function probabilityToProgressLevel(probability: string): number {
  const num = parseInt(probability) || 0
  if (num >= 70) return 3
  if (num >= 40) return 2
  return 1
}

// 转换预测结果为组件所需格式
function transformPredictionResult(data: any) {
  const overall = data?.overall_analysis || {}
  const stages = data?.stage_analysis || []
  const factors = data?.factor_analysis || []

  // 转换阶段分析
  const phases = stages.map((stage: any, index: number) => ({
    id: index + 1,
    title: `阶段${index + 1}：${stage.stage}`,
    description: stage.stage,
    riskLevel: probabilityToRisk(stage.predicted_pass_probability),
    progressLevel: probabilityToProgressLevel(stage.predicted_pass_probability),
    estimatedDays: `预计耗时${stage.predicted_passing_time}天`,
    modelInputs: [stage.analysis],
    supportingFacts: {
      title: '通过性预测依据',
      basedOn: '此阶段预测基于以下观点',
      stats: [
        { value: `${stage.predicted_pass_probability}`, label: '通过概率' },
        { value: `${stage.predicted_passing_time}天`, label: '预计耗时' }
      ]
    },
    predictionBasis: stage.prediction_basis
  }))
  
  return {
    title: '立法进展阶段预测分析',
    subtitle: `基于相似法案的历史数据与预测模型`,
    overallRisk: probabilityToRisk(overall.predicted_pass_probability),
    overallProgressLevel: probabilityToProgressLevel(overall.predicted_pass_probability),
    overallEstimatedDays: `预计耗时${overall.predicted_passing_time || '—'}天`,
    highlightText: overall.analysis || '',
    overallProbability: overall.predicted_pass_probability || '',
    phases,
    factorAnalysis: factors
  }
}

// 上一步
function goToPreviousStep() {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

// 重新预测：返回第一步
function handleRepredict() {
  currentStep.value = 1
}
</script>

<style scoped>
.app-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-black-2);
  overflow-y: auto;
  overflow-x: hidden;
  white-space: pre-line;
  max-height: calc(100vh - 80px);
  box-sizing: border-box;
}

.layout-main-center {
  width: 100%;
  max-width: 1600px;
  flex: 1;
  padding-bottom: 32px;
  box-sizing: border-box;
  margin: 0 auto;
}

.content-card {
  display: flex;
  overflow: hidden;
  border-radius: var(--radius-10);
  border: 1px solid var(--border-black-5);
}

.content-area {
  flex: 1;
  padding: 10px 26px 29px 25px;
  overflow: auto;
}

.loading-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
