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

/** 产品列表记录（13 字段） */
export interface ProductRecord {
  id: number
  company_id: number
  platform_id: number
  store_id: number
  status_id: number
  platform_item_id: string
  platform_model_id: string | null
  name: string | null
  price: string
  currency: string
  num: number
  created_date: string | null
  updated_date: string | null
}

/** Normal 产品详情（完整字段） */
export interface ProductDetail extends ProductRecord {
  type_id: number
  warehouse_id: number | null
  sub_warehouse_id: number | null
  origin_sku_id: string | null
  mapped_sku_id: string | null
  barcode: string | null
  hscode: string | null
  bundled: unknown | null
  url: string | null
  picture: string | null
  ext: Record<string, unknown> | null
  created_at: string
  updated_at: string
}

/** Raw 产品详情 */
export interface RawProductDetail {
  id: number
  platform_item_id: string
  platform_model_id: string | null
  name: string | null
  store_id: number
  company_id: number
  platform_id: number
  raw: Record<string, unknown> | null
  hash: string
  ext: Record<string, unknown> | null
  created_date: string | null
  updated_date: string | null
}

export interface ProductFilters {
  name: string
  platform_item_id: string
  status_id: number | undefined
}

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

export const useProductStore = defineStore('product', () => {
  const products = ref<ProductRecord[]>([])
  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<ProductFilters>({
    name: '',
    platform_item_id: '',
    status_id: undefined,
  })

  // 名称映射数据
  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 fetchProducts() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<ProductRecord>>('/api/v1/products', {
        page: pagination.page,
        per_page: pagination.per_page,
        company_id: cascadeValue.company_id,
        platform_id: cascadeValue.platform_id,
        store_id: cascadeValue.store_id,
        name: filters.name || undefined,
        platform_item_id: filters.platform_item_id || undefined,
        status_id: filters.status_id,
      })
      products.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      products.value = []
      pagination.total = 0
      const msg = err instanceof Error ? err.message : '获取产品列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  function resetFilters() {
    filters.name = ''
    filters.platform_item_id = ''
    filters.status_id = undefined
    cascadeValue.company_id = undefined
    cascadeValue.platform_id = undefined
    cascadeValue.store_id = undefined
    pagination.page = 1
  }

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