<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { AutoGroupPreviewGroup } from '@/types'
import { productFamiliesApi } from '@/api/product-families'

const props = defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'done'): void }>()

const visible = computed({
  get: () => props.modelValue,
  set: (v) => emit('update:modelValue', v),
})

const loading = ref(false)
const applying = ref(false)
const groups = ref<AutoGroupPreviewGroup[]>([])

async function loadPreview() {
  loading.value = true
  try {
    const res = await productFamiliesApi.autoGroup(false)
    groups.value = res.groups
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message ?? '预览失败')
  } finally {
    loading.value = false
  }
}

watch(
  () => props.modelValue,
  (open) => {
    if (open) loadPreview()
  },
)

const totalLinks = computed(() => groups.value.reduce((s, g) => s + g.memberCount, 0))

async function apply() {
  applying.value = true
  try {
    const res = await productFamiliesApi.autoGroup(true)
    ElMessage.success(`已创建 ${res.applied} 个族`)
    visible.value = false
    emit('done')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message ?? '成族失败')
  } finally {
    applying.value = false
  }
}
</script>

<template>
  <el-dialog v-model="visible" title="自动成族（按 SDS 分类 = 产品模型）" width="760px">
    <div v-loading="loading">
      <el-alert
        type="info"
        :closable="false"
        show-icon
        :title="`共发现 ${groups.length} 个候选分组、${totalLinks} 条未归属链接`"
        description="同 SDS 分类的链接将合并为一个族（跨工艺/物流/仓库/编码）；应用后自动重算每个族的并集与价格矩阵，操作幂等。"
      />
      <el-table :data="groups" size="small" border max-height="420" style="margin-top: 12px">
        <el-table-column prop="familyCode" label="编码" width="110">
          <template #default="{ row }">
            <el-tag size="small" type="info">{{ row.familyCode ?? '—' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="familyName" label="族名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="memberCount" label="成员数" width="80" align="center" />
        <el-table-column label="示例链接" min-width="260">
          <template #default="{ row }">
            <div v-for="n in row.sampleNames" :key="n" class="ag-sample">{{ n }}</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="applying" :disabled="!groups.length" @click="apply">
        确认建族（{{ groups.length }}）
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.ag-sample { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; }
</style>
