import { api } from '@/utils/request'
import type { PaginatedData, RefundItemRecord, RefundItemFilters } from '@/types/api'

export type { RefundItemRecord }

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

export const useRefundItemStore = defineStore('refundItem', () => {
  const refundItems = ref<RefundItemRecord[]>([])
  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<RefundItemFilters>({
    refund_id: undefined,
    refund_status_id: undefined,
    refund_type_id: undefined,
    platform_refund_id: '',
    platform_order_id: '',
    platform_product_id: '',
    created_date_range: null,
  })

  // 名称映射数据
  const companies = ref<LookupItem[]>([])
  const platforms = ref<{ id: number; 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.name])),
  )
  const platformMap = computed(
    () => new Map(platforms.value.map((p) => [p.id, `平台 #${p.id}`])),
  )
  const storeMap = computed(
    () => new Map(stores.value.map((s) => [s.id, 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; 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 fetchRefundItems() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<RefundItemRecord>>('/api/v1/refund-items', {
        page: pagination.page,
        per_page: pagination.per_page,
        company_id: cascadeValue.company_id,
        platform_id: cascadeValue.platform_id,
        store_id: cascadeValue.store_id,
        refund_id: filters.refund_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,
        platform_product_id: filters.platform_product_id || undefined,
        created_date_from: filters.created_date_range?.[0] || undefined,
        created_date_to: filters.created_date_range?.[1] || undefined,
      })
      refundItems.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      refundItems.value = []
      pagination.total = 0
      const msg = err instanceof Error ? err.message : '获取退款项列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

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

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