<template>
  <AdminLayout 
    title="标签管理" 
    subtitle="各类标签信息"
  >
    <div class="tag-management">
      <!-- 顶部操作栏 -->
      <div class="header">
        <h2 class="title">数据标签管理</h2>
        <button class="add-button" @click="showCreateDialog">
          <img src="@/assets/imgs/plus.svg" alt="添加" />
          <span>添加标签</span>
        </button>
      </div>

      <!-- 按类型分类展示 -->
      <div class="tag-categories" v-loading="loading">
        <!-- 文章分类标签 -->
        <div class="tag-category-section">
          <div class="category-header">
            <h3 class="category-title">文章分类标签</h3>
            <span class="category-count">（{{ articleTags.length }}）</span>
          </div>
          <div class="tag-grid">
            <div 
              v-for="tag in articleTags" 
              :key="tag.tagID"
              class="tag-card"
            >
              <div class="tag-content">
                <div class="tag-info">
                  <div class="tag-dot" :style="{ background: tag.color }"></div>
                  <span class="tag-name">{{ tag.name }}</span>
                </div>
              </div>
              <div class="tag-actions">
                <button class="edit-button" @click="editTag(tag)">
                  <img src="@/assets/imgs/edit.svg" alt="编辑" />
                  <span>编辑</span>
                </button>
                <button class="delete-button" @click="deleteTag(tag)">
                  <img src="@/assets/imgs/trashbin.svg" alt="删除" />
                </button>
              </div>
            </div>
            <!-- 空状态 -->
            <div v-if="!loading && articleTags.length === 0" class="empty-state">
              暂无文章分类标签
            </div>
          </div>
        </div>

        <!-- 课程分类标签 -->
        <div class="tag-category-section">
          <div class="category-header">
            <h3 class="category-title">课程分类标签</h3>
            <span class="category-count">（{{ courseTags.length }}）</span>
          </div>
          <div class="tag-grid">
            <div 
              v-for="tag in courseTags" 
              :key="tag.tagID"
              class="tag-card"
            >
              <div class="tag-content">
                <div class="tag-info">
                  <div class="tag-dot" :style="{ background: tag.color }"></div>
                  <span class="tag-name">{{ tag.name }}</span>
                </div>
              </div>
              <div class="tag-actions">
                <button class="edit-button" @click="editTag(tag)">
                  <img src="@/assets/imgs/edit.svg" alt="编辑" />
                  <span>编辑</span>
                </button>
                <button class="delete-button" @click="deleteTag(tag)">
                  <img src="@/assets/imgs/trashbin.svg" alt="删除" />
                </button>
              </div>
            </div>
            <!-- 空状态 -->
            <div v-if="!loading && courseTags.length === 0" class="empty-state">
              暂无课程分类标签
            </div>
          </div>
        </div>

        <!-- 学习任务分类标签 -->
        <div class="tag-category-section">
          <div class="category-header">
            <h3 class="category-title">学习任务分类标签</h3>
            <span class="category-count">（{{ taskTags.length }}）</span>
          </div>
          <div class="tag-grid">
            <div 
              v-for="tag in taskTags" 
              :key="tag.tagID"
              class="tag-card"
            >
              <div class="tag-content">
                <div class="tag-info">
                  <div class="tag-dot" :style="{ background: tag.color }"></div>
                  <span class="tag-name">{{ tag.name }}</span>
                </div>
              </div>
              <div class="tag-actions">
                <button class="edit-button" @click="editTag(tag)">
                  <img src="@/assets/imgs/edit.svg" alt="编辑" />
                  <span>编辑</span>
                </button>
                <button class="delete-button" @click="deleteTag(tag)">
                  <img src="@/assets/imgs/trashbin.svg" alt="删除" />
                </button>
              </div>
            </div>
            <!-- 空状态 -->
            <div v-if="!loading && taskTags.length === 0" class="empty-state">
              暂无学习任务分类标签
            </div>
          </div>
        </div>

        <!-- 全局空状态 -->
        <div v-if="!loading && tags.length === 0" class="global-empty-state">
          暂无标签数据
        </div>
      </div>

      <!-- 创建/编辑标签对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑标签' : '新增标签'"
        width="500px"
        @close="handleDialogClose"
      >
        <el-form :model="currentTag" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="标签名称" prop="name">
            <el-input v-model="currentTag.name" placeholder="请输入标签名称" />
          </el-form-item>
          
          <el-form-item label="标签类型" prop="tagType">
            <el-select v-model="currentTag.tagType" placeholder="请选择标签类型" style="width: 100%">
              <el-option label="文章分类标签" :value="1" />
              <el-option label="课程分类标签" :value="2" />
              <el-option label="学习任务分类标签" :value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="标签颜色" prop="color">
            <div class="color-picker-wrapper">
              <el-color-picker v-model="currentTag.color" />
              <el-input v-model="currentTag.color" placeholder="#000000" style="width: 150px; margin-left: 10px" />
            </div>
          </el-form-item>

          <el-form-item label="标签描述">
            <el-input 
              v-model="currentTag.description" 
              type="textarea"
              :rows="3"
              placeholder="请输入标签描述"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { resourceTagApi } from '@/apis/resource';
import type { Tag } from '@/types/resource';
import { TagType } from '@/types/resource';
import {AdminLayout} from '@/views/admin';

defineOptions({
  name: 'TagManagementView'
});

const tags = ref<Tag[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const submitting = ref(false);
const formRef = ref<FormInstance>();

const currentTag = ref<Partial<Tag>>({
  name: '',
  tagType: 1,
  color: '#409EFF',
  description: ''
});

// 按类型分类的标签
const articleTags = computed(() => {
  return tags.value.filter(tag => tag.tagType === TagType.ARTICLE_CATEGORY);
});

const courseTags = computed(() => {
  return tags.value.filter(tag => tag.tagType === TagType.COURSE_CATEGORY);
});

const taskTags = computed(() => {
  return tags.value.filter(tag => tag.tagType === TagType.LEARNING_TASK_CATEGORY);
});

const rules: FormRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' }
  ],
  tagType: [
    { required: true, message: '请选择标签类型', trigger: 'change' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'change' }
  ]
};

onMounted(() => {
  loadTags();
});

// 加载标签列表
async function loadTags() {
  try {
    loading.value = true;
    const result = await resourceTagApi.getTagList({});
    if (result.success) {
      tags.value = result.dataList || [];
      // TODO: 加载每个标签的使用计数
      // 这里可以调用 API 获取每个标签被使用的资源数量
    } else {
      ElMessage.error(result.message || '加载标签列表失败');
    }
  } catch (error) {
    console.error('加载标签列表失败:', error);
    ElMessage.error('加载标签列表失败');
  } finally {
    loading.value = false;
  }
}

// 显示创建对话框
function showCreateDialog() {
  isEdit.value = false;
  currentTag.value = {
    name: '',
    tagType: 1,
    color: '#409EFF',
    description: ''
  };
  dialogVisible.value = true;
}

// 编辑标签
function editTag(row: Tag) {
  isEdit.value = true;
  currentTag.value = { ...row };
  dialogVisible.value = true;
}

// 删除标签
async function deleteTag(row: Tag) {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签"${row.name}"吗？删除后不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const result = await resourceTagApi.deleteTag(row.tagID!);
    if (result.success) {
      ElMessage.success('删除成功');
      loadTags();
    } else {
      ElMessage.error(result.message || '删除失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    let result;
    if (isEdit.value) {
      result = await resourceTagApi.updateTag(currentTag.value as Tag);
    } else {
      result = await resourceTagApi.createTag(currentTag.value as Tag);
    }

    if (result.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功');
      dialogVisible.value = false;
      loadTags();
    } else {
      ElMessage.error(result.message || (isEdit.value ? '更新失败' : '创建失败'));
    }
  } catch (error) {
    console.error('提交失败:', error);
  } finally {
    submitting.value = false;
  }
}

// 对话框关闭处理
function handleDialogClose() {
  formRef.value?.resetFields();
}
</script>

<style lang="scss" scoped>
.tag-management {
  display: flex;
  flex-direction: column;
  gap: 48px;
  box-sizing: border-box;
  background: white;
  padding: 24px;
  border-radius: 14px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  margin: 0;
  font-family: 'Inter', 'PingFang SC', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 1.5em;
  letter-spacing: -0.02em;
  color: #101828;
}

.add-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 8px 16px;
  background: #E7000B;
  border: none;
  border-radius: 8px;
  color: #FFFFFF;
  font-family: 'Inter', 'PingFang SC', sans-serif;
  font-weight: 500;
  font-size: 14px;
  line-height: 1.43em;
  letter-spacing: -0.01em;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: #c50009;
  }

  &:active {
    background: #a80008;
  }

  svg {
    flex-shrink: 0;
  }
}

.tag-categories {
  display: flex;
  flex-direction: column;
  gap: 40px;
}

.tag-category-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.category-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 12px;
  border-bottom: 2px solid #F0F0F0;
}

.category-title {
  margin: 0;
  font-family: 'Inter', 'PingFang SC', sans-serif;
  font-weight: 500;
  font-size: 18px;
  line-height: 1.5em;
  color: #101828;
}

.category-count {
  font-family: 'Inter', 'PingFang SC', sans-serif;
  font-weight: 400;
  font-size: 14px;
  line-height: 1.5em;
  color: #909399;
}

.tag-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
  min-height: 100px;
}

.tag-card {
  display: flex;
  flex-direction: column;
  gap: 36px;
  padding: 16px;
  background: #F9FAFB;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 14px;
  box-sizing: border-box;
}

.tag-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tag-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tag-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex-shrink: 0;
}

.tag-name {
  font-family: 'Inter', 'PingFang SC', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 1.5em;
  letter-spacing: -0.02em;
  color: #101828;
}

.tag-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2px 8px;
  background: #ECEEF2;
  border: 1px solid transparent;
  border-radius: 8px;
  font-family: 'Inter', 'PingFang SC', sans-serif;
  font-weight: 500;
  font-size: 12px;
  line-height: 1.33em;
  color: #030213;
}

.tag-actions {
  display: flex;
  gap: 8px;
}

.edit-button {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  height: 32px;
  padding: 0 16px;
  background: #FFFFFF;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  font-family: 'Inter', 'PingFang SC', sans-serif;
  font-weight: 500;
  font-size: 14px;
  line-height: 1.43em;
  letter-spacing: -0.01em;
  color: #0A0A0A;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: #f5f5f5;
  }

  svg {
    flex-shrink: 0;
  }
}

.delete-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 38px;
  height: 32px;
  background: #FFFFFF;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: #fff5f5;
    border-color: rgba(231, 0, 11, 0.2);
  }

  svg {
    flex-shrink: 0;
  }
}

.empty-state {
  grid-column: 1 / -1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  font-size: 14px;
  color: #909399;
}

.global-empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
  font-size: 16px;
  color: #909399;
}

.color-picker-wrapper {
  display: flex;
  align-items: center;
}

// 响应式调整
@media (max-width: 1400px) {
  .tag-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 900px) {
  .tag-grid {
    grid-template-columns: 1fr;
  }
}
</style>
