<!-- views/backend/official/index.vue -->
<template>
  <div class="official-tag-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <el-select
        v-model="searchParams.type"
        placeholder="请选择类型"
        class="search-select"
        clearable
      >
        <el-option label="文化关键词" value="culture" />
        <el-option label="年度主推关键词" value="year_recommend" />
        <el-option label="关联场景" value="related_scenarios" />
      </el-select>
      <el-button type="primary" @click="refresh" class="ml-12px">
        <el-icon><IEpSearch /></el-icon>
        搜索
      </el-button>
      <el-button @click="reset">重置</el-button>

      <el-button type="primary" @click="handleAdd">
        <el-icon><IEpPlus /></el-icon>
        新增
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <!-- 表格 -->
      <div class="table-wrapper">
        <el-table v-loading="loading" :data="list" height="100%">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="type" label="类型" width="180">
            <template #default="{ row }">
              {{
                row.type === 'culture'
                  ? '文化关键词'
                  : row.type === 'year_recommend'
                    ? '年度主推关键词'
                    : '关联场景'
              }}
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200" />
          <el-table-column prop="description" label="描述" min-width="200" />

          <el-table-column prop="color" label="颜色" width="300">
            <template #default="{ row }">
              <div class="color-cell">
                <div class="color-block" :style="{ backgroundColor: row.color }" />
                <span class="color-text">{{ row.color }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="searchParams.current"
          v-model:page-size="searchParams.size"
          :total="total"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="changePageSize"
          @current-change="goToPage"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="文化关键词" value="culture" />
            <el-option label="年度主推关键词" value="year_recommend" />
            <el-option label="关联场景" value="related_scenarios" />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>

        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="form.color" />
          <span class="color-value">{{ form.color }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon class="btn-icon"
            ><el-icon><IEpUpload /></el-icon
          ></el-icon>
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { usePageSearch, useResetData } from '@/hooks'
import { getTagList, addOrUpdateTag, deleteTag } from '@/api/backend'
import type { FormInstance, FormRules } from 'element-plus'

import type { BackendTagListItemDto, AddOrUpdateTagDto } from '@/api/backend'
import { push } from 'notivue'
import { useMessageBox } from '@/hooks'

const { confirm } = useMessageBox()
const { loading, list, total, reset, goToPage, changePageSize, refresh, searchParams, search } =
  usePageSearch(getTagList)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = computed(() => (form.value.id ? '编辑' : '新增'))
const formRef = ref<FormInstance>()

// 表单数据

const [form, resetForm] = useResetData<AddOrUpdateTagDto>({
  type: '',
  title: '',
  description: '',
  color: '#000000',
  id: undefined,
})
// 表单验证规则
const formRules: FormRules = {
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  color: [{ required: true, message: '请选择颜色', trigger: 'change' }],
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: BackendTagListItemDto) => {
  resetForm()
  form.value = {
    type: row.type,
    title: row.title,
    description: row.description,
    color: row.color,
    id: row.id,
  }
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: BackendTagListItemDto) => {
  await confirm({
    title: '提示',
    message: `确定要删除标签"${row.title}"吗?`,
    type: 'danger',
  })

  try {
    await deleteTag(row.id)

    push.success('删除成功')
    refresh()
  } catch (error) {
    if (error !== 'cancel') {
      push.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    if (form.value.id) {
      await addOrUpdateTag(form.value)
    } else {
      await addOrUpdateTag(form.value)
    }

    push.success(form.value.id ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    if (form.value.id) {
      search()
    } else {
      refresh()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped lang="scss">
.official-tag-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

// 搜索区域
.search-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  flex-shrink: 0;
  gap: 12px 0;
  .search-select {
    width: 200px;
  }
}

// 表格区域
.table-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  min-height: 0;

  .color-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .color-block {
      width: 100%;
      height: 36px;
      border-radius: 4px;
      border: 1px solid #e5e7eb;
      flex: 1;
    }

    .color-text {
      color: #fff;
      font-size: 14px;
      font-weight: 500;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
    }
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  flex-shrink: 0;
}

// 对话框内的颜色显示
.color-value {
  margin-left: 12px;
  color: #606266;
  font-family: monospace;
}

.btn-icon {
  margin-right: 4px;
}
</style>
