import { ref, reactive, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { getHistoryBillList, getBillStageConfig, getIndustryKeyList, getSortOptions } from '@/api/bill/billHome.js'

/**
 * 法案数据管理 composable
 */
export function useBills() {
  const route = useRoute()
  const personId = computed(() => route.params.personId || route.query.personId || '')
  const bills = ref([])
  const stageConfig = ref([])
  const total = ref(0)
  const loading = ref(false)

  const filterOptions = reactive({
    domains: [],
    timeRanges: [],
  })

  const sortOptions = ref([])

  const currentPage = ref(1)
  const pageSize = ref(10)

  const filters = reactive({
    searchText: '',
    selectedDomains: ['all'],
    selectedTimeRanges: ['all'],
    sortBy: 'latestMotionTimeDesc',
    isCN: true,
  })

  // 获取筛选项配置
  async function loadFilterOptions() {
    try {
      const res = await getIndustryKeyList()
      if (res.code === 200 && res.data) {
        // 行业列表
        filterOptions.domains = [
          { id: 'all', label: '全部' },
          ...res.data.map(item => ({
            id: item.id,
            label: item.name,
          }))
        ]
        // 发布时间：从当前年份向前推5年动态生成
        const currentYear = new Date().getFullYear()
        filterOptions.timeRanges = [
          { id: 'all', label: '全部' },
          ...Array.from({ length: 5 }, (_, i) => {
            const year = currentYear - i
            return { id: String(year), label: String(year) }
          }),
        ]
      }
    } catch (error) {
      console.error('加载筛选项失败:', error)
    }
  }

  // 获取排序选项
  async function loadSortOptions() {
    try {
      const res = await getSortOptions()
      if (res.code === 200 && res.data) {
        sortOptions.value = res.data
      }
    } catch (error) {
      console.error('加载排序选项失败:', error)
    }
  }

  // 构建请求参数（不包含分页）
  function buildParams() {
    const params = {}
    
    if (filters.searchText) {
      params.searchText = filters.searchText
    }
    
    if (filters.selectedDomains.length > 0 && !filters.selectedDomains.includes('all')) {
      params.industryIds = filters.selectedDomains
    }
    
    if (filters.selectedTimeRanges.length > 0 && !filters.selectedTimeRanges.includes('all')) {
      params.years = filters.selectedTimeRanges.map(Number)
    }
    
    params.isCN = filters.isCN
    
    params.sortFun = filters.sortBy === 'latestMotionTimeAsc'
    
    return params
  }

  // 获取阶段字典（仅初始化时调用一次）
  async function loadStageConfig() {
    try {
      const res = await getBillStageConfig()
      if (res.code === 200 && res.data) {
        stageConfig.value = res.data
      }
    } catch (error) {
      console.error('加载阶段字典失败:', error)
    }
  }

  // 根据当前筛选条件和分页参数加载法案列表
  async function loadBills() {
    if (!personId.value) return
    loading.value = true
    try {
      const params = buildParams()
      params.currentPage = currentPage.value - 1
      params.pageSize = pageSize.value
      
      const res = await getHistoryBillList(personId.value, params)
      if (res.code === 200 && res.data) {
        bills.value = res.data.content || []
        total.value = res.data.totalElements || 0
      } else {
        // 接口返回错误时清空数据
        bills.value = []
        total.value = 0
      }
    } catch (error) {
      console.error('加载法案列表失败:', error)
      bills.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 更新搜索关键词
  function updateKeyword(keyword) {
    filters.searchText = keyword
  }

  // 切换领域筛选项
  function toggleDomain(domainId) {
    if (domainId === 'all') {
      filters.selectedDomains = ['all']
    } else {
      // 去掉 all，切换具体项
      const withoutAll = filters.selectedDomains.filter(d => d !== 'all')
      const idx = withoutAll.indexOf(domainId)
      if (idx > -1) {
        withoutAll.splice(idx, 1)
      } else {
        withoutAll.push(domainId)
      }
      // 没有选中任何具体项时回到全部
      filters.selectedDomains = withoutAll.length > 0 ? withoutAll : ['all']
    }
  }

  // 切换时间范围筛选项
  function toggleTimeRange(timeId) {
    if (timeId === 'all') {
      filters.selectedTimeRanges = ['all']
    } else {
      const withoutAll = filters.selectedTimeRanges.filter(d => d !== 'all')
      const idx = withoutAll.indexOf(timeId)
      if (idx > -1) {
        withoutAll.splice(idx, 1)
      } else {
        withoutAll.push(timeId)
      }
      filters.selectedTimeRanges = withoutAll.length > 0 ? withoutAll : ['all']
    }
  }

  // 更新排序方式
  function updateSort(sortBy) {
    filters.sortBy = sortBy
  }

  function updateChinaRelated(isCN) {
    filters.isCN = isCN
  }

  // 翻页处理
  async function handlePageChange(page) {
    currentPage.value = page
    await loadBills()
  }

  // 初始化（阶段字典只在这里获取一次）
  async function init() {
    await Promise.all([loadFilterOptions(), loadSortOptions(), loadStageConfig()])
    await loadBills()
  }

  // 监听筛选变化自动重新获取
  watch(
    () => ({
      searchText: filters.searchText,
      domains: [...filters.selectedDomains],
      timeRanges: [...filters.selectedTimeRanges],
      sortBy: filters.sortBy,
      isCN: filters.isCN,
    }),
    () => {
      currentPage.value = 1
      loadBills()
    },
    { deep: true }
  )

  return {
    bills,
    stageConfig,
    total,
    loading,
    currentPage,
    pageSize,
    filters,
    filterOptions,
    sortOptions,
    init,
    loadBills,
    updateKeyword,
    toggleDomain,
    toggleTimeRange,
    updateSort,
    updateChinaRelated,
    handlePageChange,
  }
}
