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

const store = useSkuMappingStore()

const columns = [
  { title: 'ID', dataIndex: 'id', width: 70 },
  { title: '公司', key: 'company', width: 120 },
  { title: '平台', key: 'platform', width: 100 },
  { title: '店铺', key: 'store', width: 140 },
  { title: '内部 SKU', dataIndex: 'origin_sku', width: 140 },
  { title: '平台 SKU', dataIndex: 'platform_outer_sku', width: 160 },
  { title: '平台商品ID', dataIndex: 'platform_product_id', width: 160, ellipsis: true },
  { title: '组合商品', key: 'bundled', width: 100 },
  { title: '状态', key: 'enabled', width: 80 },
  { title: '更新时间', key: 'updated_at', width: 170 },
  { title: '操作', key: 'action', width: 200, fixed: 'right' as const },
]

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

const defaultForm = (): SkuMappingForm => ({
  company_id: undefined,
  platform_id: undefined,
  store_id: undefined,
  origin_sku: '',
  origin_sku_id: undefined,
  platform_product_id: '',
  platform_outer_sku: '',
  generation_strategy: 'prefix',
  warehouse_id: undefined,
  enabled: true,
  bundled: false,
  note: '',
})

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

const rules: Record<string, Rule[]> = {
  company_id: [{ required: true, message: '请选择公司', trigger: 'change' }],
  platform_id: [{ required: true, message: '请选择平台', trigger: 'change' }],
  origin_sku_id: [
    { required: true, message: '请选择内部 SKU', trigger: 'change', type: 'number' },
  ],
  platform_outer_sku: [{ required: true, message: '请输入或生成平台 SKU', trigger: 'blur' }],
}

// Generation modal
const genModalVisible = ref(false)
const genLoading = ref(false)
const genForm = reactive({
  strategy: 'prefix' as 'prefix' | 'prefix_random' | 'manual',
  prefix: '',
  random_length: 4,
  manual_value: '',
})
const genResult = ref('')

// Filtered store options based on cascade
const filteredStoreOptions = computed(() => {
  let filtered = store.stores
  if (form.company_id) {
    filtered = filtered.filter((s) => s.company_id === form.company_id)
  }
  if (form.platform_id) {
    filtered = filtered.filter((s) => s.platform_id === form.platform_id)
  }
  return filtered.map((s) => ({
    value: s.id,
    label: s.label && s.label !== 'null' ? s.label : s.name,
  }))
})

// Remote search for SKU origins
let skipCompanyWatch = false
const skuSearchOptions = ref<{ value: number; label: string }[]>([])
const skuSearching = ref(false)
let skuSearchTimer: ReturnType<typeof setTimeout> | null = null

function handleSkuSearch(keyword: string) {
  if (skuSearchTimer) clearTimeout(skuSearchTimer)

  if (!form.company_id) {
    skuSearchOptions.value = []
    return
  }
  if (keyword.length < 3) {
    skuSearchOptions.value = []
    return
  }

  skuSearching.value = true
  skuSearchTimer = setTimeout(async () => {
    try {
      const items = await store.searchSkuOrigins(form.company_id!, keyword)
      skuSearchOptions.value = items.map((s) => ({
        value: s.id,
        label: `${s.sku} - ${s.name}`,
      }))
    } catch {
      skuSearchOptions.value = []
    } finally {
      skuSearching.value = false
    }
  }, 300)
}

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 = '新建连接'
  skuSearchOptions.value = []
  modalVisible.value = true
}

function openEdit(record: SkuMappingForm & { id: number }) {
  editingId.value = record.id
  modalTitle.value = '编辑连接'
  // 先预填 options，再赋值 form（避免 watch 清空后丢失）
  skuSearchOptions.value = record.origin_sku_id
    ? [{ value: record.origin_sku_id as number, label: record.origin_sku || '' }]
    : []
  // 暂停 watch 重置逻辑
  skipCompanyWatch = true
  Object.assign(form, {
    company_id: record.company_id,
    platform_id: record.platform_id,
    store_id: record.store_id || undefined,
    origin_sku: record.origin_sku || '',
    origin_sku_id: record.origin_sku_id || undefined,
    platform_product_id: record.platform_product_id || '',
    platform_outer_sku: record.platform_outer_sku || '',
    generation_strategy: record.generation_strategy || 'prefix',
    warehouse_id: record.warehouse_id || undefined,
    enabled: record.enabled ?? true,
    bundled: record.bundled ?? false,
    note: record.note || '',
  })
  nextTick(() => { skipCompanyWatch = false })
  modalVisible.value = true
}

function handleModalClose() {
  skuSearchOptions.value = []
}

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
    handleModalClose()
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '操作失败'
    message.error(msg)
  } finally {
    saving.value = false
  }
}

function handleDelete(record: {
  id: number
  origin_sku: string
  platform_outer_sku: string | null
}) {
  Modal.confirm({
    title: '确认删除',
    content: `确定删除连接「${record.origin_sku} → ${record.platform_outer_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)
      }
    },
  })
}

function openGenerate() {
  if (!form.origin_sku_id) {
    message.warning('请先选择内部 SKU')
    return
  }
  if (!form.platform_id) {
    message.warning('请先选择平台')
    return
  }
  genForm.strategy = 'prefix'
  genForm.prefix = form.company_id ? `C${String(form.company_id).padStart(4, '0')}` : ''
  genForm.random_length = 4
  genForm.manual_value = ''
  genResult.value = ''
  genModalVisible.value = true
}

async function handleGenerate() {
  if (genForm.strategy === 'manual' && !genForm.manual_value) {
    message.warning('请输入手动 SKU 值')
    return
  }
  if ((genForm.strategy === 'prefix' || genForm.strategy === 'prefix_random') && !genForm.prefix) {
    message.warning('请输入前缀')
    return
  }
  genLoading.value = true
  try {
    const params: GenerateSkuParams = {
      origin_sku_id: form.origin_sku_id!,
      platform_id: form.platform_id!,
      strategy: genForm.strategy,
      prefix: genForm.prefix,
      random_length: genForm.random_length,
      manual_value: genForm.manual_value,
    }
    const result = await store.generateSku(params)
    genResult.value = result.generated_sku
    if (result.has_duplicate) {
      message.warning(result.message || '该平台已存在相同 SKU 映射')
    }
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '生成失败'
    message.error(msg)
  } finally {
    genLoading.value = false
  }
}

function applyGenerated() {
  if (genResult.value) {
    form.platform_outer_sku = genResult.value
    form.generation_strategy = genForm.strategy
    genModalVisible.value = false
    message.success('已填入生成的平台 SKU')
  }
}

// Watch company change to reset SKU search (skip during openEdit)
watch(
  () => form.company_id,
  () => {
    if (skipCompanyWatch) return
    form.origin_sku_id = undefined
    form.origin_sku = ''
    skuSearchOptions.value = []
  },
)
</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.origin_sku"
            placeholder="内部 SKU"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="平台 SKU">
          <a-input
            v-model:value="store.filters.platform_outer_sku"
            placeholder="平台侧 SKU"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            :value="(store.filters.enabled as any)"
            @update:value="(v: any) => { store.filters.enabled = v }"
            placeholder="全部"
            allow-clear
            style="width: 100px"
          >
            <a-select-option :value="true">启用</a-select-option>
            <a-select-option :value="false">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="组合商品">
          <a-select
            :value="(store.filters.bundled as any)"
            @update:value="(v: any) => { store.filters.bundled = v }"
            placeholder="全部"
            allow-clear
            style="width: 100px"
          >
            <a-select-option :value="true">是</a-select-option>
            <a-select-option :value="false">否</a-select-option>
          </a-select>
        </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>
          新建连接
        </a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="store.items"
        :loading="store.loading"
        :pagination="false"
        row-key="id"
        :scroll="{ x: 1400 }"
      >
        <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'">
            <template v-if="record.store_id">
              {{ store.storeMap.get(record.store_id) || record.store_id }}
            </template>
            <span v-else class="text-gray-400">平台默认</span>
          </template>
          <template v-else-if="column.key === 'bundled'">
            <a-tag :color="record.bundled ? 'blue' : 'default'">
              {{ record.bundled ? '是' : '否' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'enabled'">
            <a-tag :color="record.enabled ? 'green' : 'default'">
              {{ record.enabled ? '启用' : '禁用' }}
            </a-tag>
          </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="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; handleModalClose()"
      :width="640"
    >
      <a-form ref="formRef" :model="form" :rules="rules" layout="vertical" class="mt-4">
        <a-row :gutter="16">
          <a-col :span="12">
            <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-col>
          <a-col :span="12">
            <a-form-item label="平台" name="platform_id">
              <a-select
                v-model:value="form.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-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="店铺" name="store_id">
              <a-select
                v-model:value="form.store_id"
                placeholder="留空表示平台默认"
                :options="filteredStoreOptions"
                allow-clear
                show-search
                :filter-option="
                  (input: string, option: { label?: string } | undefined) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="内部 SKU" name="origin_sku_id">
              <a-select
                v-model:value="form.origin_sku_id"
                :placeholder="!form.company_id ? '请先选择公司' : '搜索(最少3个字)或输入SKU'"
                :options="skuSearchOptions"
                :loading="skuSearching"
                :disabled="!form.company_id"
                allow-clear
                show-search
                :filter-option="false"
                :not-found-content="skuSearching ? '搜索中...' : '无匹配结果'"
                @search="handleSkuSearch"
                @change="
                  (val: unknown) => {
                    const found = skuSearchOptions.find((s) => s.value === val)
                    form.origin_sku = found ? found.label.split(' - ')[0] ?? '' : ''
                  }
                "
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="platform_outer_sku">
              <template #label>
                <span>
                  平台 SKU
                  <a-tooltip
                    title="电商平台侧使用的 SKU 编码，需符合平台填写规则（如不能以 0 开头、不能含特殊字符等）"
                  >
                    <QuestionCircleOutlined class="ml-1 text-gray-400" />
                  </a-tooltip>
                </span>
              </template>
              <a-input v-model:value="form.platform_outer_sku" placeholder="平台侧 SKU 编码">
                <template #addonAfter>
                  <a-button type="link" size="small" @click="openGenerate" :style="{ padding: 0 }">
                    <ThunderboltOutlined /> 自动生成
                  </a-button>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="平台商品 ID" name="platform_product_id">
              <a-input v-model:value="form.platform_product_id" placeholder="可选" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="备注" name="note">
          <a-textarea v-model:value="form.note" placeholder="可选备注" :rows="2" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="状态">
              <a-switch
                v-model:checked="form.enabled"
                checked-children="启用"
                un-checked-children="禁用"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="组合商品" name="bundled">
              <a-switch
                v-model:checked="form.bundled"
                checked-children="是"
                un-checked-children="否"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- SKU Generation Modal -->
    <a-modal
      v-model:open="genModalVisible"
      title="自动生成平台 SKU"
      :width="480"
      @cancel="genModalVisible = false"
    >
      <div class="mt-4">
        <a-form layout="vertical">
          <a-form-item label="生成策略">
            <a-radio-group v-model:value="genForm.strategy">
              <a-radio-button value="prefix">前缀模式</a-radio-button>
              <a-radio-button value="prefix_random">前缀+随机</a-radio-button>
              <a-radio-button value="manual">手动输入</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <template v-if="genForm.strategy === 'prefix' || genForm.strategy === 'prefix_random'">
            <a-form-item label="前缀">
              <a-input v-model:value="genForm.prefix" placeholder="如 C03" />
              <div class="text-xs text-gray-400 mt-1">
                前缀模式：生成 {前缀}_{内部SKU}，如 C03_0032
              </div>
            </a-form-item>
          </template>

          <template v-if="genForm.strategy === 'prefix_random'">
            <a-form-item label="随机部分长度">
              <a-input-number v-model:value="genForm.random_length" :min="2" :max="8" />
              <div class="text-xs text-gray-400 mt-1">
                前缀+随机模式：生成 {前缀}_{随机字母数字}，如 C03_A7K2
              </div>
            </a-form-item>
          </template>

          <template v-if="genForm.strategy === 'manual'">
            <a-form-item label="手动输入">
              <a-input v-model:value="genForm.manual_value" placeholder="手动输入 SKU 值" />
            </a-form-item>
          </template>

          <a-form-item>
            <a-button type="primary" :loading="genLoading" @click="handleGenerate">
              <ThunderboltOutlined /> 生成预览
            </a-button>
          </a-form-item>

          <a-form-item v-if="genResult" label="生成结果">
            <a-alert type="success" show-icon>
              <template #message>
                <span class="font-mono text-base">{{ genResult }}</span>
              </template>
            </a-alert>
          </a-form-item>
        </a-form>
      </div>

      <template #footer>
        <a-button @click="genModalVisible = false">取消</a-button>
        <a-button type="primary" :disabled="!genResult" @click="applyGenerated">
          使用此 SKU
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

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