<script setup lang="ts">
import { api } from '@/utils/request'
import {
  useProductStore,
  type ProductRecord,
  type ProductDetail,
  type RawProductDetail,
} from '@/stores/product'
import CascadeFilter from '@/components/CascadeFilter.vue'
import { SearchOutlined, ReloadOutlined, EyeOutlined } from '@ant-design/icons-vue'

const store = useProductStore()

// Detail drawer
const drawerVisible = ref(false)
const drawerLoading = ref(false)
const productDetail = ref<ProductDetail | null>(null)
const rawDetail = ref<RawProductDetail | null>(null)
let detailRequestId = 0

const statusMap: Record<number, { text: string; color: string }> = {
  1: { text: '草稿', color: 'default' },
  2: { text: '在售', color: 'green' },
  3: { text: '下架', color: 'orange' },
  4: { text: '封禁', color: 'red' },
  5: { text: '审核中', color: 'blue' },
  6: { text: '卖家删除', color: 'volcano' },
  7: { text: '平台删除', color: 'volcano' },
}

const columns = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '公司', key: 'company', width: 120 },
  { title: '平台', key: 'platform', width: 100 },
  { title: '店铺', key: 'store', width: 140 },
  { title: '商品名称', dataIndex: 'name', ellipsis: true },
  { title: '价格', key: 'price', width: 120 },
  { title: '库存', dataIndex: 'num', width: 80 },
  { title: '状态', key: 'status', width: 100 },
  { title: '更新时间', key: 'updated_date', width: 160 },
  { title: '操作', key: 'action', width: 100 },
]

onMounted(() => {
  store.loadLookups()
  store.fetchProducts()
})

function handleSearch() {
  store.pagination.page = 1
  store.fetchProducts()
}

function handleReset() {
  store.resetFilters()
  store.fetchProducts()
}

function handlePageChange(page: number, pageSize: number) {
  store.pagination.page = page
  store.pagination.per_page = pageSize
  store.fetchProducts()
}

function formatPrice(record: { price: string; currency: string }) {
  if (!record.price || isNaN(Number(record.price))) return '-'
  const symbols: Record<string, string> = {
    CNY: '¥',
    USD: '$',
    EUR: '€',
    GBP: '£',
    JPY: '¥',
  }
  const symbol = symbols[record.currency] || record.currency + ' '
  return `${symbol}${record.price}`
}

function isSafeUrl(url: string | null): boolean {
  if (!url) return false
  try {
    const parsed = new URL(url)
    return ['http:', 'https:'].includes(parsed.protocol)
  } catch {
    return false
  }
}

function formatTime(time: string | null) {
  if (!time) return '-'
  return time.replace('T', ' ').substring(0, 16)
}

async function handleViewDetail(record: { id: number }) {
  const currentRequestId = ++detailRequestId
  drawerVisible.value = true
  drawerLoading.value = true
  productDetail.value = null
  rawDetail.value = null

  const [normalResult, rawResult] = await Promise.allSettled([
    api.get<ProductDetail>(`/api/v1/products/${record.id}`),
    api.get<RawProductDetail>(`/api/v1/raw/products/${record.id}`),
  ])

  // 竞态保护：若用户已切换到另一商品详情，丢弃过期响应
  if (currentRequestId !== detailRequestId) return

  if (normalResult.status === 'fulfilled') {
    productDetail.value = normalResult.value
  } else {
    message.error('获取产品详情失败')
  }

  if (rawResult.status === 'fulfilled') {
    rawDetail.value = rawResult.value
  } else {
    console.warn('加载原始数据(raw)失败', rawResult.reason)
  }

  drawerLoading.value = false
}
</script>

<template>
  <div>
    <h2 class="text-xl font-semibold mb-4">产品管理</h2>

    <!-- Filter area -->
    <a-card style="margin-bottom: 24px">
      <a-form layout="inline" class="filter-form" @submit.prevent="handleSearch">
        <a-form-item>
          <CascadeFilter v-model="store.cascadeValue" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="store.filters.status_id"
            placeholder="全部"
            allow-clear
            style="width: 120px"
          >
            <a-select-option :value="1">草稿</a-select-option>
            <a-select-option :value="2">在售</a-select-option>
            <a-select-option :value="3">下架</a-select-option>
            <a-select-option :value="4">封禁</a-select-option>
            <a-select-option :value="5">审核中</a-select-option>
            <a-select-option :value="6">卖家删除</a-select-option>
            <a-select-option :value="7">平台删除</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="商品名称">
          <a-input
            v-model:value="store.filters.name"
            placeholder="模糊搜索"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="平台商品ID">
          <a-input
            v-model:value="store.filters.platform_item_id"
            placeholder="精确搜索"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- Table -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="store.products"
        :loading="store.loading"
        :pagination="false"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'company'">
            {{ store.companyMap.get(record.company_id) || record.company_id }}
          </template>
          <template v-else-if="column.key === 'platform'">
            {{ store.platformMap.get(record.platform_id) || record.platform_id }}
          </template>
          <template v-else-if="column.key === 'store'">
            {{ store.storeMap.get(record.store_id) || record.store_id }}
          </template>
          <template v-else-if="column.dataIndex === 'name'">
            <a-tooltip :title="record.name">
              {{ record.name || '-' }}
            </a-tooltip>
          </template>
          <template v-else-if="column.key === 'price'">
            {{ formatPrice(record as ProductRecord) }}
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="statusMap[record.status_id]?.color || 'default'">
              {{ statusMap[record.status_id]?.text || `状态 ${record.status_id}` }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'updated_date'">
            {{ formatTime(record.updated_date) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="handleViewDetail(record as ProductRecord)">
              <template #icon><EyeOutlined /></template>
              查看
            </a-button>
          </template>
        </template>
      </a-table>

      <div class="mt-4 flex justify-end">
        <a-pagination
          :current="store.pagination.page"
          :page-size="store.pagination.per_page"
          :total="store.pagination.total"
          show-size-changer
          show-quick-jumper
          :show-total="(total: number) => `共 ${total} 条`"
          @change="handlePageChange"
        />
      </div>
    </a-card>

    <!-- Detail drawer -->
    <a-drawer
      title="产品详情"
      :open="drawerVisible"
      :width="640"
      @close="drawerVisible = false"
    >
      <a-spin :spinning="drawerLoading">
        <template v-if="productDetail">
          <a-descriptions title="基本信息" :column="2" bordered class="mb-4">
            <a-descriptions-item label="ID">{{ productDetail.id }}</a-descriptions-item>
            <a-descriptions-item label="状态">
              <a-tag :color="statusMap[productDetail.status_id]?.color || 'default'">
                {{ statusMap[productDetail.status_id]?.text || `状态 ${productDetail.status_id}` }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="商品名称" :span="2">
              {{ productDetail.name || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="平台商品ID">
              {{ productDetail.platform_item_id }}
            </a-descriptions-item>
            <a-descriptions-item label="平台规格ID">
              {{ productDetail.platform_model_id || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="价格">
              {{ formatPrice(productDetail) }}
            </a-descriptions-item>
            <a-descriptions-item label="库存">
              {{ productDetail.num }}
            </a-descriptions-item>
            <a-descriptions-item label="公司">
              {{ store.companyMap.get(productDetail.company_id) || productDetail.company_id }}
            </a-descriptions-item>
            <a-descriptions-item label="平台">
              {{ store.platformMap.get(productDetail.platform_id) || productDetail.platform_id }}
            </a-descriptions-item>
            <a-descriptions-item label="店铺" :span="2">
              {{ store.storeMap.get(productDetail.store_id) || productDetail.store_id }}
            </a-descriptions-item>
            <a-descriptions-item label="原始SKU">
              {{ productDetail.origin_sku_id || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="映射SKU">
              {{ productDetail.mapped_sku_id || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="条形码">
              {{ productDetail.barcode || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="HS编码">
              {{ productDetail.hscode || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="商品链接" :span="2">
              <a v-if="isSafeUrl(productDetail.url)" :href="productDetail.url!" target="_blank" rel="noopener noreferrer">
                {{ productDetail.url }}
              </a>
              <span v-else>{{ productDetail.url || '-' }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="平台创建时间">
              {{ formatTime(productDetail.created_date) }}
            </a-descriptions-item>
            <a-descriptions-item label="平台更新时间">
              {{ formatTime(productDetail.updated_date) }}
            </a-descriptions-item>
            <a-descriptions-item label="系统创建时间">
              {{ formatTime(productDetail.created_at) }}
            </a-descriptions-item>
            <a-descriptions-item label="系统更新时间">
              {{ formatTime(productDetail.updated_at) }}
            </a-descriptions-item>
          </a-descriptions>

          <!-- ext JSON -->
          <a-descriptions title="扩展数据 (ext)" :column="1" bordered class="mb-4">
            <a-descriptions-item>
              <pre v-if="productDetail.ext" class="m-0 text-xs max-h-80 overflow-auto">{{
                JSON.stringify(productDetail.ext, null, 2)
              }}</pre>
              <span v-else class="text-gray-400">暂无数据</span>
            </a-descriptions-item>
          </a-descriptions>

          <!-- raw JSON -->
          <a-descriptions title="原始数据 (raw)" :column="1" bordered>
            <a-descriptions-item>
              <pre v-if="rawDetail?.raw" class="m-0 text-xs max-h-80 overflow-auto">{{
                JSON.stringify(rawDetail.raw, null, 2)
              }}</pre>
              <span v-else class="text-gray-400">暂无数据</span>
            </a-descriptions-item>
          </a-descriptions>
        </template>
      </a-spin>
    </a-drawer>
  </div>
</template>
