import { api } from '@/utils/request'
import type { PaginatedData, RefundRecord, RefundFilters } from '@/types/api'

export type { RefundRecord }

/** 名称映射用的查找表 */
interface LookupItem {
  id: number
  name: string
  label?: string
}

export const useRefundStore = defineStore('refund', () => {
  const refunds = ref<RefundRecord[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    per_page: 15,
    total: 0,
  })
  const cascadeValue = reactive({
    company_id: undefined as number | undefined,
    platform_id: undefined as number | undefined,
    store_id: undefined as number | undefined,
  })
  const filters = reactive<RefundFilters>({
    refund_status_id: undefined,
    refund_type_id: undefined,
    platform_refund_id: '',
    platform_order_id: '',
    created_date_range: null,
  })

  // 名称映射数据
  const companies = ref<LookupItem[]>([])
  const platforms = ref<{ id: number; name: string; label?: string; developer_id: number }[]>([])
  const stores = ref<(LookupItem & { company_id: number; platform_id: number })[]>([])

  const companyMap = computed(
    () => new Map(companies.value.map((c) => [c.id, (c.label && c.label !== 'null') ? c.label : c.name])),
  )
  const platformMap = computed(
    () => new Map(platforms.value.map((p) => [p.id, (p.label && p.label !== 'null') ? p.label : (p.name || `平台 #${p.id}`)])),
  )
  const storeMap = computed(
    () => new Map(stores.value.map((s) => [s.id, (s.label && s.label !== 'null') ? s.label : s.name])),
  )

  async function loadLookups() {
    try {
      const [c, p, s] = await Promise.all([
        api.get<LookupItem[]>('/api/v1/companies'),
        api.get<{ id: number; name: string; label?: string; developer_id: number }[]>('/api/v1/platforms'),
        api.get<(LookupItem & { company_id: number; platform_id: number })[]>(
          '/api/v1/stores',
        ),
      ])
      companies.value = c
      platforms.value = p
      stores.value = s
    } catch (err: unknown) {
      console.warn('加载查找表数据失败', err)
    }
  }

  async function fetchRefunds() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<RefundRecord>>('/api/v1/refunds', {
        page: pagination.page,
        per_page: pagination.per_page,
        company_id: cascadeValue.company_id,
        platform_id: cascadeValue.platform_id,
        store_id: cascadeValue.store_id,
        refund_status_id: filters.refund_status_id,
        refund_type_id: filters.refund_type_id,
        platform_refund_id: filters.platform_refund_id || undefined,
        platform_order_id: filters.platform_order_id || undefined,
        created_date_from: filters.created_date_range?.[0] || undefined,
        created_date_to: filters.created_date_range?.[1] || undefined,
      })
      refunds.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      refunds.value = []
      pagination.total = 0
      const msg = err instanceof Error ? err.message : '获取退款列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  function resetFilters() {
    filters.refund_status_id = undefined
    filters.refund_type_id = undefined
    filters.platform_refund_id = ''
    filters.platform_order_id = ''
    filters.created_date_range = null
    cascadeValue.company_id = undefined
    cascadeValue.platform_id = undefined
    cascadeValue.store_id = undefined
    pagination.page = 1
  }

  return {
    refunds,
    loading,
    pagination,
    cascadeValue,
    filters,
    companies,
    platforms,
    stores,
    companyMap,
    platformMap,
    storeMap,
    loadLookups,
    fetchRefunds,
    resetFilters,
  }
})
