<template>
  <div>
    <div class="mb-16"><el-button type="primary" @click="goAdd">+ 新增品牌</el-button></div>
    <el-table :data="tableData" border stripe v-loading="loading">
      <el-table-column prop="brandName" label="品牌名称"/>
      <el-table-column prop="deviceField" label="device字段"/>
      <el-table-column prop="tagsPath" label="tags路径"/>
      <el-table-column label="状态" align="center"><template #default="{row}"><el-tag :type="row.isEnabled?'success':'danger'" size="small">{{row.isEnabled?'启用':'停用'}}</el-tag></template></el-table-column>
      <el-table-column prop="fieldCount" label="字段数" align="center"/>
      <el-table-column label="操作" width="180" align="center"><template #default="{row}">
        <div style="white-space:nowrap">
          <el-button link type="primary" @click="goEdit(row.id)">编辑</el-button>
          <el-button link type="primary" @click="handleCopy(row)">复制</el-button>
          <el-button link type="primary" @click="handleToggle(row)">{{row.isEnabled?'禁用':'启用'}}</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </div>
      </template></el-table-column>
      </el-table>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useMockMode } from '@/composables/useMockMode'
import { CopyDocument } from '@element-plus/icons-vue'
import type { Brand, ApiResponse } from '@/types'
const router = useRouter()
const { isMock } = useMockMode()
const loading = ref(false)
const tableData = ref<Brand[]>([])
function goAdd() { router.push(isMock.value ? '/mock/brand/create' : '/brand/create') }
function goEdit(id: number) { router.push((isMock.value ? '/mock/brand/' : '/brand/') + id + '/edit') }
async function loadData() { loading.value = true; try { const r: ApiResponse<{ items: Brand[] }> = await request.get('/admin/brand'); tableData.value = r.data?.items ?? [] } finally { loading.value = false } }
async function handleToggle(row: Brand) { await ElMessageBox.confirm('确定' + (row.isEnabled ? '禁用' : '启用') + '？', '提示', { type: 'warning' }); await request.put(`/admin/brand/${row.id}/toggle`); ElMessage.success('操作成功'); loadData() }
async function handleDelete(row: Brand) { await ElMessageBox.confirm('确定删除【' + row.brandName + '】？此操作不可恢复。', '提示', { type: 'warning' }); await request.delete(`/admin/brand/${row.id}`); ElMessage.success('已删除'); loadData() }
// 复制品牌
async function handleCopy(row: Brand) {
  try {
    await ElMessageBox.confirm(`确定复制品牌【${row.brandName}】？`, '提示', { type: 'warning' })
    await request.post(`/admin/brand/${row.id}/copy`)
    ElMessage.success('复制成功')
    loadData()
  } catch {
    // 用户取消或失败不处理
  }
}
 onMounted(loadData)
</script>
