import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  getcategoryTreeApi,
  getcraftListApi,
  getAllCurrencyApi,
} from '@/api/product'
import { warehouseInfoGetAll } from '@/api/warehouse'
interface ApiResponse {
  data: unknown
  code?: number
  message?: string
}

type OptionItem = Record<string, unknown>

export const getOptionsApi = (
  name: string,
  params?: Record<string, unknown>,
): Promise<ApiResponse> => {
  switch (name) {
    case 'category':
      return getcategoryTreeApi() as Promise<ApiResponse>
    case 'craft':
      return getcraftListApi() as Promise<ApiResponse>
    case 'currency':
      return getAllCurrencyApi() as Promise<ApiResponse>
    case 'warehouse':
      return warehouseInfoGetAll() as Promise<ApiResponse>
    default:
      throw new Error(`Unknown option name: ${name}:params${params}`)
  }
}

// 模块级共享状态
let _keyCode: string | null = null

export const useOptionsStore = defineStore('options', () => {
  // 使用 computed 与模块级 _keyCode 保持同步
  const keyCode = computed({
    get: () => _keyCode,
    set: (v: string | null) => {
      _keyCode = v
    },
  })

  const dataMap = ref<Partial<Record<string, OptionItem[]>>>({})
  const extractList = (response: ApiResponse): OptionItem[] => {
    const { data } = response
    if (Array.isArray(data)) {
      return data as OptionItem[]
    }
    if (
      data &&
      typeof data === 'object' &&
      'data' in data &&
      Array.isArray((data as { data: unknown }).data)
    ) {
      return (data as { data: OptionItem[] }).data
    }
    console.warn('Unexpected response structure:', response)
    return []
  }

  const fetchOption = async (
    name: string,
    params?: Record<string, unknown>,
  ): Promise<OptionItem[]> => {
    if (dataMap.value[name] && name !== 'canlogistics') {
      return dataMap.value[name]!
    }

    try {
      const response = await getOptionsApi(name, params)
      const list = extractList(response)
      dataMap.value[name] = list
      return list
    } catch (error) {
      console.error(`Failed to fetch ${name}:`, error)
      throw error
    }
  }

  const getOptions = async (
    names: string | string[],
    params?: Record<string, unknown>,
  ): Promise<Record<string, OptionItem[]>> => {
    const nameArray = Array.isArray(names) ? names : [names]
    const results = await Promise.all(
      nameArray.map(async (name) => {
        try {
          const list = await fetchOption(
            name,
            name === 'canlogistics' ? params : undefined,
          )
          return { name, list }
        } catch {
          return { name, list: [] }
        }
      }),
    )
    return Object.fromEntries(results.map(({ name, list }) => [name, list]))
  }

  const clearCache = (name?: string) => {
    if (name) {
      delete dataMap.value[name]
    } else {
      dataMap.value = {}
    }
  }

  const setKeyCode = (code: string | null) => {
    keyCode.value = code
  }

  return {
    keyCode,
    dataMap,
    getOptions,
    clearCache,
    setKeyCode,
  }
})

// 导出供直接导入使用（与 store 内部共享 _keyCode）
export const keyCode = {
  get value() {
    return _keyCode
  },
  set value(v: string | null) {
    _keyCode = v
  },
}
export const setKeyCode = (code: string | null) => {
  _keyCode = code
}
