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

/** 订单列表记录（12 字段，与 getListFields 对应） */
export interface OrderRecord {
  id: number
  company_id: number
  platform_id: number
  store_id: number
  order_status_id: number
  platform_order_id: string
  total_amount: string
  total_paid: string
  total_discount: string
  created_date: string | null
  paid_date: string | null
  shipping_date: string | null
}

/** 订单子项记录 */
export interface OrderItemRecord {
  id: number
  company_id: number
  platform_id: number
  store_id: number
  order_id: number
  platform_order_id: string
  sub_order_id: string | null
  sub_order_type_id: number
  product_id: number
  platform_product_id: string
  product_sku: string | null
  product_barcode: string | null
  unit_price: string
  quantity: number
  discount: string
  total: string
  created_date: string | null
  ext: Record<string, unknown> | null
  created_at: string
  updated_at: string
}

/** 订单详情（含 order_items） */
export interface OrderDetail {
  id: number
  company_id: number
  platform_id: number
  store_id: number
  order_status_id: number
  platform_order_id: string
  buyer_user_id: string | null
  payment_method_id: number
  presale: boolean
  total_amount: string
  total_paid: string
  total_discount: string
  total_received: string
  freight_fee: string
  tax_fee: string
  discount_fee: string
  commission_fee: string
  coupon_amount: string
  voucher_amount: string
  order_type_id: number
  created_date: string | null
  updated_date: string | null
  paid_date: string | null
  shipping_date: string | null
  zipcode: string
  city: string
  province: string
  country: string
  ext: Record<string, unknown> | null
  created_at: string
  updated_at: string
  order_items: OrderItemRecord[]
}

/** Raw 订单详情 */
export interface RawOrderDetail {
  id: number
  platform_order_id: string
  store_id: number
  company_id: number
  platform_id: number
  order_status_id: number
  raw: Record<string, unknown> | null
  hash: string
  ext: Record<string, unknown> | null
  created_date: string | null
}

export interface OrderFilters {
  order_status_id: number | undefined
  platform_order_id: string
  created_date_range: [string, string] | null
  paid_date_range: [string, string] | null
}

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

export const useOrderStore = defineStore('order', () => {
  const orders = ref<OrderRecord[]>([])
  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<OrderFilters>({
    order_status_id: undefined,
    platform_order_id: '',
    created_date_range: null,
    paid_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 fetchOrders() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<OrderRecord>>('/api/v1/orders', {
        page: pagination.page,
        per_page: pagination.per_page,
        company_id: cascadeValue.company_id,
        platform_id: cascadeValue.platform_id,
        store_id: cascadeValue.store_id,
        order_status_id: filters.order_status_id,
        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,
        paid_date_from: filters.paid_date_range?.[0] || undefined,
        paid_date_to: filters.paid_date_range?.[1] || undefined,
      })
      orders.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      orders.value = []
      pagination.total = 0
      const msg = err instanceof Error ? err.message : '获取订单列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

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

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