<template>
  <div class="step-container">
    <div v-if="loading" class="loading-wrapper flex-display-center">
      <span class="text-tip-2 text-tip-1">加载中...</span>
    </div>
    <template v-else-if="stats">
      <div class="content-wrapper">
        <div class="stats-section">
          <div class="stats-header">
            <div class="header-left">
              <div class="flex-display-center section-title-row">
                <img src="../assets/document.svg">
                <span class="text-title-3-bold text-primary-80-clor">筛选结果统计</span>
              </div>
              <p class="text-tip-2 stats-subtitle text-tip-1" style="margin-left: 21px;">基于筛选条件匹配的历史相似法案</p>
            </div>
            <div class="header-right">
              <div class="total-number-row">
                <span class="total-number main-color">{{ stats.totalBills }}</span>
                <span class="total-unit main-color">项</span>
              </div>
              <p class="total-label main-color">历史相似法案</p>
            </div>
          </div>
          <div class="stats-cards">
            <div
              v-for="stat in statsItems"
              :key="stat.label"
              class="stat-card"
            >
              <span class="text-title-2-bold text-primary-80-clor">{{ stat.label }}</span>
              <span class="main-color stat-value">{{ stat.value }}</span>
            </div>
          </div>
          <div class="select-row">
            <label class="select-all-label flex-display-center">
              <input
                type="checkbox"
                :checked="isAllSelected"
                class="checkbox"
                @change="toggleSelectAll"
              />
              <span class="text-compact">全选</span>
            </label>
            <span class="text-tip-1">已选择{{ selectedCount }}项法案</span>
          </div>
          <div class="bills-list">
            <BillCard
              v-for="bill in bills"
              :key="bill.id"
              :bill="bill"
              @toggle-select="toggleBillSelect"
            />
          </div>
        </div>
      </div>
      <div class="action-footer">
        <button class="btn-secondary flex-display-center" @click="handleBack">
          <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
            <path d="M3 3v5h5" />
          </svg>
          <span>返回设置</span>
        </button>
        <button class="btn-primary flex-display-center" @click="handleStartAnalysis">
          <span>开始预测分析</span>
          <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="5" y1="12" x2="19" y2="12" />
            <polyline points="12 5 19 12 12 19" />
          </svg>
        </button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, inject, watch } from 'vue'
import type { FilterStats, BillInfo } from '../api'
import { fetchFilterStats, fetchBillList } from '../api'
import { getSimiBills, transformSimiBillsData } from '@/api/bill/billHome'
import BillCard from './BillCard.vue'

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

// 从父组件注入筛选参数
const filterParams = inject<any>('filterParams', null)

// 筛选统计数据
const stats = ref<FilterStats | null>(null)
// 法案列表
const bills = ref<BillInfo[]>([])
// 加载状态
const loading = ref(true)

// 统计项配置，使用循环避免重复代码
const statsItems = computed(() => {
  if (!stats.value) return []
  return [
    { label: '成为法律', value: `${stats.value.becameLaw}个` },
    { label: '未通过/搁置', value: `${stats.value.notPassedOrShelved}个` },
    { label: '中位数耗时', value: `${stats.value.medianDays}天` },
    { label: '法案通过率', value: `${stats.value.passRate}%` }
  ]
})

// 计算属性：是否全选
const isAllSelected = computed(() => {
  return bills.value.length > 0 && bills.value.every(bill => bill.selected)
})

// 计算属性：已选中数量
const selectedCount = computed(() => {
  return bills.value.filter(bill => bill.selected).length
})

// 加载数据
async function loadData() {
  loading.value = true
  try {
    // 优先使用真实 API
    const params = {
      patternType: filterParams?.governmentType || '统一政府',
      proposalType: '两党共同提案'
    }
    
    const response = await getSimiBills(params)
    
    if (response && response.success && response.data) {
      const { stats: apiStats, bills: apiBills } = transformSimiBillsData(response)
      stats.value = apiStats
      bills.value = apiBills
    } else {
      // 如果 API 失败，使用模拟数据
      const [statsData, billsData] = await Promise.all([
        fetchFilterStats(),
        fetchBillList()
      ])
      stats.value = statsData
      bills.value = billsData
    }
  } catch (error) {
    console.error('获取相似法案失败:', error)
    // 使用模拟数据作为 fallback
    const [statsData, billsData] = await Promise.all([
      fetchFilterStats(),
      fetchBillList()
    ])
    stats.value = statsData
    bills.value = billsData
  } finally {
    loading.value = false
  }
}

// 加载数据
onMounted(() => {
  loadData()
})

// 监听筛选参数变化，重新加载数据
watch(() => filterParams, () => {
  loadData()
}, { deep: true })

// 切换全选
function toggleSelectAll() {
  const newValue = !isAllSelected.value
  bills.value.forEach(bill => {
    bill.selected = newValue
  })
}

// 切换单个法案选中状态
function toggleBillSelect(id: string) {
  const bill = bills.value.find(b => b.id === id)
  if (bill) {
    bill.selected = !bill.selected
  }
}

// 返回设置
function handleBack() {
  emit('previous')
}

// 开始预测分析
function handleStartAnalysis() {
  emit('next')
}
</script>

<style scoped>
.text-tip-1 {
  color: #5f656c;
}

.step-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.loading-wrapper {
  flex: 1;
}

.content-wrapper {
  flex: 1;
  overflow: auto;
}

.stats-section {
  display: flex;
  flex-direction: column;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.section-title-row {
  gap: 8px;
  justify-content: left;
}

.stats-subtitle {
  margin: 0;
}

.header-right {
  text-align: right;
}

.total-number-row {
  display: flex;
  align-items: baseline;
  justify-content: flex-end;
}

.total-number {
  font-size: 36px;
  font-weight: bold;
  line-height: 1;
}

.total-unit {
  font-size: 14px;
  margin-left: 4px;
}

.total-label {
  font-size: 14px;
  margin: 4px 0 0 0;
}

.stats-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-radius: 10px;
  border: 1px solid rgba(234, 236, 238, 1);
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  left: 0;
  top: 15px;
  bottom: 15px;
  width: 4px;
  border-radius: 0 2px 2px 0;
  background-color: var(--color-red-100);
}

.stat-label {
  font-size: 16px;
  font-weight: 400;
  color: rgb(59, 65, 75);
}

.stat-value {
  font-size: 30px;
  font-weight: 700;
  color: var(--color-red-100);
}

.select-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-black-5);
  margin-bottom: 16px;
}

.select-all-label {
  gap: 8px;
  cursor: pointer;
}

.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
  accent-color: var(--color-primary-100);
}

.bills-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.action-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 24px;
  border-top: 1px solid var(--border-black-5);
  margin-top: 24px;
}

.btn-secondary {
  gap: 8px;
  padding: 8px 16px;
  border: 1px solid var(--bg-black-10);
  border-radius: var(--radius-10);
  background-color: var(--bg-white-100);
  font-size: 14px;
  color: var(--text-primary-65-color);
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-secondary:hover {
  background-color: var(--bg-black-2);
}

.btn-primary {
  gap: 8px;
  padding: 8px 24px;
  border: none;
  border-radius: var(--radius-10);
  background-color: var(--color-primary-100);
  font-size: 14px;
  color: var(--bg-white-100);
  min-width: 200px;
  justify-content: center;
  cursor: pointer;
  transition: opacity 0.2s;
}

.btn-primary:hover {
  opacity: 0.9;
}

.icon {
  width: 16px;
  height: 16px;
}

.icon-sm {
  width: 16px;
  height: 16px;
  color: var(--color-primary-100);
}

.btn-secondary .icon {
  color: var(--text-primary-65-color);
}
</style>
