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

// ─── Types ───

export interface SkuMappingRecord {
  id: number
  company_id: number
  platform_id: number
  store_id: number | null
  origin_sku: string
  origin_sku_id: number
  platform_outer_sku: string
  platform_product_id: string
  enabled: boolean
  bundled: boolean
  note: string | null
  created_at: string
  updated_at: string
}

export interface SkuMappingFilters {
  origin_sku: string
  platform_outer_sku: string
  enabled: boolean | undefined
  bundled: boolean | undefined
}

export interface SkuMappingForm {
  company_id: number | undefined
  platform_id: number | undefined
  store_id: number | undefined
  origin_sku: string
  origin_sku_id: number | undefined
  platform_product_id: string
  platform_outer_sku: string
  generation_strategy: string
  warehouse_id: number | undefined
  enabled: boolean
  bundled?: boolean
  note: string
}

export interface GenerateSkuParams {
  origin_sku_id: number
  platform_id: number
  strategy: 'prefix' | 'prefix_random' | 'manual'
  prefix: string
  random_length: number
  manual_value: string
}

export interface GenerateSkuResult {
  generated_sku: string
  strategy_record: string
  has_duplicate: boolean
  existing_mappings: Array<{
    id: number
    store_id: number | null
    platform_outer_sku: string | null
    note: string | null
  }>
  message: string
}

export interface DuplicateCheckResult {
  has_duplicate: boolean
  existing_mappings: Array<{
    id: number
    store_id: number | null
    platform_outer_sku: string | null
    note: string | null
  }>
  message: string
}

// ─── Store ───

export const useSkuMappingStore = defineStore('skuMapping', () => {
  const items = ref<SkuMappingRecord[]>([])
  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<SkuMappingFilters>({
    origin_sku: '',
    platform_outer_sku: '',
    enabled: undefined,
    bundled: undefined,
  })

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

  // SKU Origin lookups for select
  const skuOrigins = ref<{ id: number; company_id: number; sku: string; name: string }[]>([])

  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 loadSkuOrigins(company_id?: number) {
    try {
      const data = await api.get<PaginatedData<{ id: number; company_id: number; sku: string; name: string }>>('/api/v1/sku-origins', {
        company_id,
        per_page: 100,
      })
      skuOrigins.value = data.items
    } catch (err) {
      console.warn('加载 SKU Origin 列表失败', err)
    }
  }

  async function searchSkuOrigins(company_id: number, sku: string) {
    const data = await api.get<PaginatedData<{ id: number; company_id: number; sku: string; name: string }>>('/api/v1/sku-origins', {
      company_id,
      sku,
      per_page: 20,
    })
    return data.items
  }

  async function fetchItems() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<SkuMappingRecord>>('/api/v1/sku-mappings', {
        page: pagination.page,
        per_page: pagination.per_page,
        company_id: cascadeValue.company_id,
        platform_id: cascadeValue.platform_id,
        store_id: cascadeValue.store_id,
        origin_sku: filters.origin_sku || undefined,
        platform_outer_sku: filters.platform_outer_sku || undefined,
        enabled: filters.enabled,
        bundled: filters.bundled,
      })
      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 : '获取映射列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  function resetFilters() {
    filters.origin_sku = ''
    filters.platform_outer_sku = ''
    filters.enabled = undefined
    filters.bundled = undefined
    cascadeValue.company_id = undefined
    cascadeValue.platform_id = undefined
    cascadeValue.store_id = undefined
    pagination.page = 1
  }

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

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

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

  async function generateSku(params: GenerateSkuParams): Promise<GenerateSkuResult> {
    return await api.post<GenerateSkuResult>('/api/v1/sku-mappings/generate-sku', params)
  }

  async function checkDuplicate(
    origin_sku_id: number,
    platform_id: number,
  ): Promise<DuplicateCheckResult> {
    return await api.get<DuplicateCheckResult>('/api/v1/sku-mappings/check-duplicate', {
      origin_sku_id,
      platform_id,
    })
  }

  return {
    items,
    loading,
    pagination,
    cascadeValue,
    filters,
    companies,
    platforms,
    stores,
    companyMap,
    platformMap,
    storeMap,
    skuOrigins,
    loadLookups,
    loadSkuOrigins,
    searchSkuOrigins,
    fetchItems,
    resetFilters,
    createItem,
    updateItem,
    deleteItem,
    generateSku,
    checkDuplicate,
  }
})
