<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, MagicStick, Plus, Refresh } from '@element-plus/icons-vue'
import type { ProductFamily } from '@/types'
import { productFamiliesApi } from '@/api/product-families'
import FamilyDetailDrawer from './FamilyDetailDrawer.vue'
import AutoGroupDialog from './AutoGroupDialog.vue'

const loading = ref(false)
const items = ref<ProductFamily[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const keyword = ref('')

const drawerVisible = ref(false)
const currentId = ref<string | null>(null)
const autoGroupVisible = ref(false)

const createVisible = ref(false)
const createLoading = ref(false)
const createForm = ref({ familyName: '', familyCode: '' })

async function load() {
  loading.value = true
  try {
    const res = await productFamiliesApi.list({
      keyword: keyword.value || undefined,
      page: page.value,
      pageSize: pageSize.value,
    })
    items.value = res.items
    total.value = Number(res.total)
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message ?? '加载产品族失败')
  } finally {
    loading.value = false
  }
}

function onSearch() {
  page.value = 1
  load()
}

function openDetail(row: ProductFamily) {
  currentId.value = row.id
  drawerVisible.value = true
}

async function submitCreate() {
  if (!createForm.value.familyName.trim()) {
    ElMessage.warning('请填写族名称')
    return
  }
  createLoading.value = true
  try {
    await productFamiliesApi.create({
      familyName: createForm.value.familyName.trim(),
      familyCode: createForm.value.familyCode.trim() || undefined,
    })
    ElMessage.success('族已创建')
    createVisible.value = false
    createForm.value = { familyName: '', familyCode: '' }
    load()
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message ?? '创建失败')
  } finally {
    createLoading.value = false
  }
}

onMounted(load)
</script>

<template>
  <div class="family-view">
    <div class="family-toolbar">
      <el-input
        v-model="keyword"
        placeholder="搜索族名称 / 编码"
        clearable
        style="width: 260px"
        :prefix-icon="Search"
        @keyup.enter="onSearch"
        @clear="onSearch"
      />
      <el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
      <el-button :icon="MagicStick" @click="autoGroupVisible = true">自动成族</el-button>
      <el-button type="primary" plain :icon="Plus" @click="createVisible = true">新建族</el-button>
      <el-button :icon="Refresh" circle @click="load" />
    </div>

    <el-table
      v-loading="loading"
      :data="items"
      height="100%"
      class="family-table"
      @row-click="openDetail"
    >
      <el-table-column prop="familyCode" label="编码" width="120">
        <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="220" show-overflow-tooltip />
      <el-table-column label="成员" width="80" align="center">
        <template #default="{ row }">
          <el-badge
            v-if="row.stale"
            is-dot
            type="warning"
            class="family-stale-dot"
          >
            <span>{{ row._count.originGoods }}</span>
          </el-badge>
          <span v-else>{{ row._count.originGoods }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人工改价" width="90" align="center">
        <template #default="{ row }">{{ row._count.priceOverrides }}</template>
      </el-table-column>
      <el-table-column label="托管" width="90" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.autoManaged" size="small" type="success">自动</el-tag>
          <el-tag v-else size="small" type="warning">锁定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.stale" size="small" type="danger">待处理(上游已变)</el-tag>
          <el-tag v-else size="small" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="更新时间" width="170">
        <template #default="{ row }">{{ new Date(row.updatedAt).toLocaleString() }}</template>
      </el-table-column>
      <el-table-column label="操作" width="80" fixed="right">
        <template #default="{ row }: any">
          <el-button link type="primary" @click.stop="openDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="family-pagination">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, sizes"
        :page-sizes="[20, 50, 100]"
        @current-change="load"
        @size-change="onSearch"
      />
    </div>

    <FamilyDetailDrawer
      v-model="drawerVisible"
      :family-id="currentId"
      @reload="load"
    />
    <AutoGroupDialog v-model="autoGroupVisible" @done="load" />

    <el-dialog v-model="createVisible" title="新建产品族" width="440px">
      <el-form label-width="80px">
        <el-form-item label="族名称" required>
          <el-input v-model="createForm.familyName" placeholder="如 180G纯棉T恤（成人款）" />
        </el-form-item>
        <el-form-item label="族编码">
          <el-input v-model="createForm.familyCode" placeholder="如 DG001（可留空）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button type="primary" :loading="createLoading" @click="submitCreate">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.family-view { height: 100%; display: flex; flex-direction: column; padding: 12px; gap: 12px; }
.family-toolbar { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
.family-table { flex: 1; min-height: 0; cursor: pointer; }
.family-pagination { flex-shrink: 0; display: flex; justify-content: flex-end; }
.family-stale-dot { padding-right: 6px; }
</style>
