<script setup lang="ts">
import { api } from '@/utils/request'

export interface CascadeValue {
  company_id: number | undefined
  platform_id: number | undefined
  store_id: number | undefined
}

const model = defineModel<CascadeValue>({ default: () => ({ company_id: undefined, platform_id: undefined, store_id: undefined }) })

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

/** 清洗 label：过滤 "null" 字符串，优先 label 其次 name */
function cleanLabel(label: string | null | undefined, name: string | undefined, fallback: string): string {
  if (label && label !== 'null') return label
  if (name) return name
  return fallback
}

const loadingCompanies = ref(false)
const loadingStores = ref(false)

const companyOptions = computed(() =>
  companies.value.map((c) => ({ value: c.id, label: cleanLabel(c.label, c.name, `公司 #${c.id}`) })),
)

const platformOptions = computed(() =>
  platforms.value.map((p) => ({ value: p.id, label: cleanLabel(p.label, p.name, `平台 #${p.id}`) })),
)

const storeOptions = computed(() => {
  let filtered = stores.value
  if (model.value.company_id) {
    filtered = filtered.filter((s) => s.company_id === model.value.company_id)
  }
  if (model.value.platform_id) {
    filtered = filtered.filter((s) => s.platform_id === model.value.platform_id)
  }
  return filtered.map((s) => ({ value: s.id, label: cleanLabel(s.label, s.name, `店铺 #${s.id}`) }))
})

function handleCompanyChange(val: unknown) {
  model.value = {
    company_id: (val as number) ?? undefined,
    platform_id: undefined,
    store_id: undefined,
  }
}

function handlePlatformChange(val: unknown) {
  model.value = {
    ...model.value,
    platform_id: (val as number) ?? undefined,
    store_id: undefined,
  }
}

function handleStoreChange(val: unknown) {
  model.value = {
    ...model.value,
    store_id: (val as number) ?? undefined,
  }
}

async function loadData() {
  loadingCompanies.value = true
  loadingStores.value = true
  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: unknown) {
    const msg = err instanceof Error ? err.message : '加载筛选数据失败'
    message.error(msg)
  } finally {
    loadingCompanies.value = false
    loadingStores.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<template>
  <div class="flex gap-4 items-center">
    <div class="flex items-center gap-1">
      <span class="text-gray-600 text-sm whitespace-nowrap">公司 :</span>
      <a-select
        :value="model.company_id"
        :options="companyOptions"
        placeholder="选择公司"
        allow-clear
        show-search
        :filter-option="(input: string, option: unknown) =>
          ((option as { label: string }).label ?? '').toLowerCase().includes(input.toLowerCase())
        "
        :loading="loadingCompanies"
        style="min-width: 160px"
        @change="handleCompanyChange"
      />
    </div>
    <div class="flex items-center gap-1">
      <span class="text-gray-600 text-sm whitespace-nowrap">平台 :</span>
      <a-select
        :value="model.platform_id"
        :options="platformOptions"
        placeholder="选择平台"
        allow-clear
        show-search
        :filter-option="(input: string, option: unknown) =>
          ((option as { label: string }).label ?? '').toLowerCase().includes(input.toLowerCase())
        "
        style="min-width: 160px"
        @change="handlePlatformChange"
      />
    </div>
    <div class="flex items-center gap-1">
      <span class="text-gray-600 text-sm whitespace-nowrap">店铺 :</span>
      <a-select
        :value="model.store_id"
        :options="storeOptions"
        placeholder="选择店铺"
        allow-clear
        show-search
        :filter-option="(input: string, option: unknown) =>
          ((option as { label: string }).label ?? '').toLowerCase().includes(input.toLowerCase())
        "
        :loading="loadingStores"
        style="min-width: 160px"
        @change="handleStoreChange"
      />
    </div>
  </div>
</template>
