import { api } from '@/utils/request'
import type { PaginatedData } from '@/types/api'
import type { SkuMappingRecord } from '@/stores/sku-mapping'

// ─── Types ───

export interface SkuOriginRecord {
  id: number
  company_id: number
  sku: string
  barcode: string
  name: string
  label: string | null
  hs: string | null
  created_at: string
  updated_at: string
}

export interface SkuOriginDetail extends SkuOriginRecord {
  ledger: string | null
  ext: Record<string, unknown> | null
}

export interface SkuOriginFilters {
  sku: string
  name: string
  barcode: string
}

export interface SkuOriginForm {
  company_id: number | undefined
  sku: string
  barcode: string
  name: string
  label: string
  hs: string
  ledger: string
}

// ─── Store ───

export const useSkuOriginStore = defineStore('skuOrigin', () => {
  const items = ref<SkuOriginRecord[]>([])
  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<SkuOriginFilters>({
    sku: '',
    name: '',
    barcode: '',
  })

  // Lookup maps
  const companies = ref<{ id: number; name: string; label: string | null }[]>([])
  const platforms = ref<{ id: number; name: string; label: string | null }[]>([])
  const stores = ref<
    { id: number; company_id: number; platform_id: number; name: string; label: string | null }[]
  >([])

  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,
        ]),
      ),
  )

  // Mappings expand cache
  const mappingsCache = ref<Map<number, SkuMappingRecord[]>>(new Map())
  const mappingsLoading = ref<Set<number>>(new Set())

  async function loadLookups() {
    try {
      const [c, p, s] = await Promise.all([
        api.get<typeof companies.value>('/api/v1/companies'),
        api.get<typeof platforms.value>('/api/v1/platforms'),
        api.get<typeof stores.value>('/api/v1/stores'),
      ])
      companies.value = c
      platforms.value = p
      stores.value = s
    } catch (err) {
      console.warn('加载查找表数据失败', err)
    }
  }

  async function fetchMappings(originSkuId: number) {
    if (mappingsLoading.value.has(originSkuId)) return
    mappingsLoading.value.add(originSkuId)
    try {
      const data = await api.get<PaginatedData<SkuMappingRecord>>('/api/v1/sku-mappings', {
        origin_sku_id: originSkuId,
        per_page: 50,
      })
      mappingsCache.value.set(originSkuId, data.items)
    } catch (err) {
      console.warn('加载关联链接数据失败', err)
      mappingsCache.value.set(originSkuId, [])
    } finally {
      mappingsLoading.value.delete(originSkuId)
    }
  }

  async function fetchItems() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<SkuOriginRecord>>('/api/v1/sku-origins', {
        page: pagination.page,
        per_page: pagination.per_page,
        company_id: cascadeValue.company_id,
        sku: filters.sku || undefined,
        name: filters.name || undefined,
        barcode: filters.barcode || undefined,
      })
      items.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      items.value = []
      pagination.total = 0
      const msg = err instanceof Error ? err.message : '获取 SKU 列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

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

  async function createItem(form: SkuOriginForm) {
    await api.post('/api/v1/sku-origins', form)
    message.success('创建成功')
    await fetchItems()
  }

  async function updateItem(id: number, form: Partial<SkuOriginForm>) {
    await api.put(`/api/v1/sku-origins/${id}`, form)
    message.success('更新成功')
    await fetchItems()
  }

  async function deleteItem(id: number) {
    await api.delete(`/api/v1/sku-origins/${id}`)
    message.success('删除成功')
    await fetchItems()
  }

  return {
    items,
    loading,
    pagination,
    cascadeValue,
    filters,
    companies,
    platforms,
    stores,
    companyMap,
    platformMap,
    storeMap,
    mappingsCache,
    mappingsLoading,
    loadLookups,
    fetchItems,
    fetchMappings,
    resetFilters,
    createItem,
    updateItem,
    deleteItem,
  }
})
