<script setup lang="ts">
import { useSkuOriginStore, type SkuOriginForm } from '@/stores/sku-origin'
import { useSkuMappingStore, type SkuMappingForm } from '@/stores/sku-mapping'
import CascadeFilter from '@/components/CascadeFilter.vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LinkOutlined,
} from '@ant-design/icons-vue'
import type { Rule } from 'ant-design-vue/es/form'

const store = useSkuOriginStore()
const mappingStore = useSkuMappingStore()

const columns = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '公司', key: 'company', width: 140 },
  { title: 'SKU', dataIndex: 'sku', width: 160 },
  { title: '名称', dataIndex: 'name', ellipsis: true, customCell: () => ({ class: 'min-w-40' }) },
  { title: '条形码', dataIndex: 'barcode', width: 160 },
  { title: '标签', dataIndex: 'label', width: 120 },
  { title: 'HS 编码', dataIndex: 'hs', width: 120 },
  { title: '更新时间', key: 'updated_at', width: 170 },
  { title: '操作', key: 'action', width: 320, fixed: 'right' as const },
]

// Expand row
const expandedRowKeys = ref<number[]>([])

const mappingColumns = [
  { title: '平台', key: 'platform', width: 100 },
  { title: '店铺', key: 'store', width: 140 },
  { title: '平台 SKU', dataIndex: 'platform_outer_sku', width: 160 },
  { title: '平台商品 ID', dataIndex: 'platform_product_id', width: 160, ellipsis: true },
  { title: '状态', key: 'enabled', width: 80 },
]

function onExpand(expanded: boolean, record: { id: number }) {
  if (expanded) {
    store.fetchMappings(record.id)
  }
}

// Create mapping modal
const mappingModalVisible = ref(false)
const mappingSaving = ref(false)
const mappingFormRef = ref()
const mappingOriginRecord = ref<{ id: number; company_id: number; sku: string } | null>(null)

const defaultMappingForm = () => ({
  platform_id: undefined as number | undefined,
  store_id: undefined as number | undefined,
  platform_outer_sku: '',
  platform_product_id: '',
})

const mappingForm = reactive(defaultMappingForm())

const mappingRules: Record<string, Rule[]> = {
  platform_id: [{ required: true, message: '请选择平台', trigger: 'change' }],
  platform_outer_sku: [{ required: true, message: '请输入平台 SKU', trigger: 'blur' }],
}

const filteredMappingStores = computed(() => {
  let filtered = store.stores
  if (mappingOriginRecord.value?.company_id) {
    filtered = filtered.filter((s) => s.company_id === mappingOriginRecord.value!.company_id)
  }
  if (mappingForm.platform_id) {
    filtered = filtered.filter((s) => s.platform_id === mappingForm.platform_id)
  }
  return filtered.map((s) => ({
    value: s.id,
    label: s.label && s.label !== 'null' ? s.label : s.name,
  }))
})

function openCreateMapping(record: { id: number; company_id: number; sku: string }) {
  mappingOriginRecord.value = record
  Object.assign(mappingForm, defaultMappingForm())
  mappingModalVisible.value = true
}

async function handleMappingSubmit() {
  try {
    await mappingFormRef.value.validate()
  } catch {
    return
  }
  if (!mappingOriginRecord.value) return
  mappingSaving.value = true
  try {
    const payload: SkuMappingForm = {
      company_id: mappingOriginRecord.value.company_id,
      platform_id: mappingForm.platform_id,
      store_id: mappingForm.store_id,
      origin_sku: mappingOriginRecord.value.sku,
      origin_sku_id: mappingOriginRecord.value.id,
      platform_product_id: mappingForm.platform_product_id,
      platform_outer_sku: mappingForm.platform_outer_sku,
      generation_strategy: 'manual',
      warehouse_id: undefined,
      enabled: true,
      note: '',
    }
    await mappingStore.createItem(payload)
    mappingModalVisible.value = false
    // 刷新展开行缓存
    store.mappingsCache.delete(mappingOriginRecord.value.id)
    store.fetchMappings(mappingOriginRecord.value.id)
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '创建失败'
    message.error(msg)
  } finally {
    mappingSaving.value = false
  }
}

// Modal state
const modalVisible = ref(false)
const modalTitle = ref('新建内部 SKU')
const editingId = ref<number | null>(null)
const formRef = ref()
const saving = ref(false)

const defaultForm = (): SkuOriginForm => ({
  company_id: undefined,
  sku: '',
  barcode: '',
  name: '',
  label: '',
  hs: '',
  ledger: '',
})

const form = reactive<SkuOriginForm>(defaultForm())

const rules: Record<string, Rule[]> = {
  company_id: [{ required: true, message: '请选择公司', trigger: 'change' }],
  sku: [{ required: true, message: '请输入 SKU 编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  barcode: [{ required: true, message: '请输入条形码', trigger: 'blur' }],
}

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

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

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

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

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

function openCreate() {
  Object.assign(form, defaultForm())
  editingId.value = null
  modalTitle.value = '新建内部 SKU'
  modalVisible.value = true
}

function openEdit(record: { id: number; company_id: number; sku: string; barcode: string; name: string; label: string | null; hs: string | null }) {
  editingId.value = record.id
  modalTitle.value = '编辑内部 SKU'
  Object.assign(form, {
    company_id: record.company_id,
    sku: record.sku,
    barcode: record.barcode || '',
    name: record.name || '',
    label: record.label || '',
    hs: record.hs || '',
    ledger: '',
  })
  modalVisible.value = true
}

async function handleSubmit() {
  try {
    await formRef.value.validate()
  } catch {
    return
  }
  saving.value = true
  try {
    if (editingId.value) {
      await store.updateItem(editingId.value, { ...form })
    } else {
      await store.createItem({ ...form })
    }
    modalVisible.value = false
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '操作失败'
    message.error(msg)
  } finally {
    saving.value = false
  }
}

function handleDelete(record: { id: number; sku: string }) {
  Modal.confirm({
    title: '确认删除',
    content: `确定删除 SKU「${record.sku}」？如果该 SKU 已被链接引用将无法删除。`,
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await store.deleteItem(record.id)
      } catch (err: unknown) {
        const msg = err instanceof Error ? err.message : '删除失败'
        message.error(msg)
      }
    },
  })
}
</script>

<template>
  <div>
    <h2 class="text-xl font-semibold mb-4">内部 SKU 管理</h2>

    <!-- Filter area -->
    <a-card class="mb-6">
      <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="SKU">
          <a-input
            v-model:value="store.filters.sku"
            placeholder="SKU 编码"
            allow-clear
            @press-enter="handleSearch"
          />
        </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="条形码">
          <a-input
            v-model:value="store.filters.barcode"
            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>
      <div class="mb-4 flex justify-between items-center">
        <span class="text-gray-500">共 {{ store.pagination.total }} 条记录</span>
        <a-button type="primary" @click="openCreate">
          <template #icon><PlusOutlined /></template>
          新建 SKU
        </a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="store.items"
        :loading="store.loading"
        :pagination="false"
        row-key="id"
        :scroll="{ x: 1200 }"
        :expand-column-width="48"
        v-model:expandedRowKeys="expandedRowKeys"
        @expand="onExpand"
      >
        <template #expandedRowRender="{ record }">
          <a-spin v-if="store.mappingsLoading.has(record.id)" />
          <a-empty v-else-if="!store.mappingsCache.get(record.id)?.length" description="暂无平台链接" />
          <a-table
            v-else
            :columns="mappingColumns"
            :data-source="store.mappingsCache.get(record.id) || []"
            :pagination="false"
            size="small"
            row-key="id"
          >
            <template #bodyCell="{ column, record: mapping }">
              <template v-if="column.key === 'platform'">
                {{ store.platformMap.get(mapping.platform_id) || mapping.platform_id }}
              </template>
              <template v-else-if="column.key === 'store'">
                <template v-if="mapping.store_id">
                  {{ store.storeMap.get(mapping.store_id) || mapping.store_id }}
                </template>
                <span v-else class="text-gray-400">平台默认</span>
              </template>
              <template v-else-if="column.key === 'enabled'">
                <a-tag :color="mapping.enabled ? 'green' : 'default'">
                  {{ mapping.enabled ? '启用' : '禁用' }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </template>
        <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 === 'updated_at'">
            {{ formatTime(record.updated_at) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="openCreateMapping(record as any)">
                <template #icon><LinkOutlined /></template>
                新建链接
              </a-button>
              <a-button type="link" size="small" @click="openEdit(record as any)">
                <template #icon><EditOutlined /></template>
                编辑
              </a-button>
              <a-button type="link" danger size="small" @click="handleDelete(record as any)">
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-space>
          </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>

    <!-- Create/Edit Modal -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="saving"
      @ok="handleSubmit"
      @cancel="modalVisible = false"
      :width="560"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
        class="mt-4"
      >
        <a-form-item label="公司" name="company_id">
          <a-select
            v-model:value="form.company_id"
            placeholder="请选择公司"
            :options="store.companies.map(c => ({
              value: c.id,
              label: (c.label && c.label !== 'null') ? c.label : c.name
            }))"
            show-search
            :filter-option="(input: string, option: { label?: string } | undefined) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())"
          />
        </a-form-item>
        <a-form-item label="SKU 编码" name="sku">
          <a-input v-model:value="form.sku" placeholder="客户内部 SKU 编码" />
        </a-form-item>
        <a-form-item label="名称" name="name">
          <a-input v-model:value="form.name" placeholder="SKU 名称/描述" />
        </a-form-item>
        <a-form-item label="条形码" name="barcode">
          <a-input v-model:value="form.barcode" placeholder="条形码 / GTIN 编码" />
        </a-form-item>
        <a-form-item label="标签" name="label">
          <a-input v-model:value="form.label" placeholder="可选别名" />
        </a-form-item>
        <a-form-item label="HS 编码" name="hs">
          <a-input v-model:value="form.hs" placeholder="可选" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- Create Mapping Modal -->
    <a-modal
      v-model:open="mappingModalVisible"
      title="新建平台 SKU 链接"
      :confirm-loading="mappingSaving"
      @ok="handleMappingSubmit"
      @cancel="mappingModalVisible = false"
      :width="520"
    >
      <a-form
        ref="mappingFormRef"
        :model="mappingForm"
        :rules="mappingRules"
        layout="vertical"
        class="mt-4"
      >
        <a-form-item label="内部 SKU">
          <a-input :value="mappingOriginRecord?.sku" disabled />
        </a-form-item>
        <a-form-item label="平台" name="platform_id">
          <a-select
            v-model:value="mappingForm.platform_id"
            placeholder="请选择平台"
            :options="store.platforms.map(p => ({
              value: p.id,
              label: (p.label && p.label !== 'null') ? p.label : (p.name || `平台 #${p.id}`)
            }))"
            show-search
            :filter-option="(input: string, option: { label?: string } | undefined) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())"
          />
        </a-form-item>
        <a-form-item label="店铺" name="store_id">
          <a-select
            v-model:value="mappingForm.store_id"
            placeholder="留空表示平台默认"
            :options="filteredMappingStores"
            allow-clear
            show-search
            :filter-option="(input: string, option: { label?: string } | undefined) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())"
          />
        </a-form-item>
        <a-form-item label="平台 SKU" name="platform_outer_sku">
          <a-input v-model:value="mappingForm.platform_outer_sku" placeholder="平台侧 SKU 编码" />
        </a-form-item>
        <a-form-item label="平台商品 ID" name="platform_product_id">
          <a-input v-model:value="mappingForm.platform_product_id" placeholder="可选" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.filter-form :deep(.ant-form-item) {
  margin-bottom: 12px;
}
</style>
