<template>
  <div>
    <div class="filter-section">
      <div class="filter-content">
        <el-form :inline="true" :model="tagQueryParams" class="search-form">
          <el-form-item label="关键词">
            <el-input v-model="tagQueryParams.key" placeholder="搜索标签名称" clearable style="width: 180px" @keyup.enter="fetchTagList" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchTagList">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetTagQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="action-bar">
          <el-button type="primary" @click="handleAddTag">
            <el-icon><Plus /></el-icon>新增标签
          </el-button>
          <el-button type="success" @click="fetchTagList">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </div>
      </div>
    </div>
    <div class="table-section">
      <el-table
        v-loading="tagLoading"
        :data="tagList"
        style="width: 100%"
        :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
      >
        <el-table-column prop="id" label="标签ID" width="100" />
        <el-table-column prop="name" label="标签名称" min-width="200" />
        <el-table-column prop="index" label="排序" width="100" sortable />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" link @click="handleEditTag(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDeleteTag(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无标签数据" :image-size="80" />
        </template>
      </el-table>
      <el-pagination
        v-model:current-page="tagQueryParams.page"
        v-model:page-size="tagQueryParams.count"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tagTotal"
        @size-change="handleTagSizeChange"
        @current-change="handleTagCurrentChange"
        background
        class="pagination"
      />
    </div>

    <!-- 分组标签表单对话框 -->
    <el-dialog
      v-model="tagDialogVisible"
      :title="tagDialogType === 'add' ? '新增分组标签' : '编辑分组标签'"
      width="500px"
      append-to-body
    >
      <el-form
        ref="tagFormRef"
        :model="tagForm"
        :rules="tagRules"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="排序索引" prop="index">
          <el-input-number v-model="tagForm.index" :min="0" :max="9999" placeholder="数值越小越靠前" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTagForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import {
  getProductGroupTagList,
  createProductGroupTag,
  updateProductGroupTag,
  deleteProductGroupTag
} from '@/api/admin/product'

const tagQueryParams = reactive({ page: 1, count: 10, key: '' })
const tagLoading = ref(false)
const tagList = ref([])
const tagTotal = ref(0)
const tagDialogVisible = ref(false)
const tagDialogType = ref('add')
const tagFormRef = ref(null)
const tagForm = reactive({ id: undefined, name: '', index: 0 })
const tagRules = { name: [{ required: true, message: '请输入标签名称', trigger: 'blur' }] }

const fetchTagList = async () => {
  tagLoading.value = true
  try {
    const params = { ...tagQueryParams }
    if (!params.key) delete params.key
    const res = await getProductGroupTagList(params)
    if (res.data.code === 200) {
      const data = res.data.data
      if (Array.isArray(data)) {
        tagList.value = data
        tagTotal.value = data.length
      } else if (data && data.list) {
        tagList.value = data.list
        tagTotal.value = data.all_count || data.total || data.list.length
      } else if (data && data.data) {
        tagList.value = data.data
        tagTotal.value = data.total || data.data.length
      } else {
        tagList.value = []
        tagTotal.value = 0
      }
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  } finally {
    tagLoading.value = false
  }
}

const resetTagQuery = () => { tagQueryParams.key = ''; tagQueryParams.page = 1; fetchTagList() }
const handleTagSizeChange = (size) => { tagQueryParams.count = size; fetchTagList() }
const handleTagCurrentChange = (page) => { tagQueryParams.page = page; fetchTagList() }

const handleAddTag = () => {
  tagDialogType.value = 'add'
  tagDialogVisible.value = true
  Object.assign(tagForm, { id: undefined, name: '', index: 0 })
  tagFormRef.value?.resetFields()
}

const handleEditTag = (row) => {
  tagDialogType.value = 'edit'
  tagDialogVisible.value = true
  Object.assign(tagForm, { id: row.id, name: row.name, index: row.index || 0 })
}

const handleDeleteTag = (row) => {
  ElMessageBox.confirm(`确认删除标签 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteProductGroupTag({ id: row.id })
      if (res.data.code === 200) { ElMessage.success('删除成功'); fetchTagList() }
    } catch (error) { ElMessage.error('删除失败') }
  }).catch(() => {})
}

const submitTagForm = () => {
  tagFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (tagDialogType.value === 'add') {
          res = await createProductGroupTag({ name: tagForm.name, index: tagForm.index })
        } else {
          res = await updateProductGroupTag({ id: tagForm.id, name: tagForm.name, index: tagForm.index })
        }
        if (res.data.code === 200) {
          ElMessage.success(tagDialogType.value === 'add' ? '新增成功' : '修改成功')
          tagDialogVisible.value = false
          fetchTagList()
        }
      } catch (error) { ElMessage.error('操作失败') }
    }
  })
}

defineExpose({ fetchTagList })
</script>

<style scoped>
.filter-section { padding: 0; border-bottom: 1px solid #e1e8ed; background: #fafbfc; }
.filter-content { display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; gap: 20px; flex-wrap: wrap; }
.search-form { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 0; }
.search-form :deep(.el-form-item) { margin-bottom: 0; margin-right: 0; }
.action-bar { display: flex; gap: 12px; flex-shrink: 0; flex-wrap: wrap; align-items: center; }
.table-section { padding: 0; }
.action-buttons { display: flex; gap: 4px; align-items: center; flex-wrap: nowrap; }
.action-buttons .el-button { padding: 4px 8px; }
.pagination { margin-top: 20px; padding: 16px 20px; border-top: 1px solid #e1e8ed; background: #fafbfc; justify-content: flex-end; }
.dialog-footer { display: flex; justify-content: flex-end; gap: 12px; padding: 0; }
</style>
