import { api } from '@/utils/request'
import type { PaginatedData, OrderItemFilters } from '@/types/api'
import type { OrderItemRecord } from '@/stores/order'

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

export const useOrderItemStore = defineStore('orderItem', () => {
  const orderItems = ref<OrderItemRecord[]>([])
  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<OrderItemFilters>({
    platform_order_id: '',
    platform_product_id: '',
    product_sku: '',
    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 fetchOrderItems() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<OrderItemRecord>>('/api/v1/order-items', {
        page: pagination.page,
        per_page: pagination.per_page,
        company_id: cascadeValue.company_id,
        platform_id: cascadeValue.platform_id,
        store_id: cascadeValue.store_id,
        platform_order_id: filters.platform_order_id || undefined,
        platform_product_id: filters.platform_product_id || undefined,
        product_sku: filters.product_sku || undefined,
        created_date_from: filters.created_date_range?.[0] || undefined,
        created_date_to: filters.created_date_range?.[1] || undefined,
      })
      orderItems.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      orderItems.value = []
      pagination.total = 0
      const msg = err instanceof Error ? err.message : '获取订单项列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

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

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