<!-- views/backend/topic-target/index.vue -->
<template>
  <div class="topic-target-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchForm.name"
        placeholder="请输入栏目板块"
        class="search-input"
        clearable
      />

      <el-select v-model="searchForm.status" placeholder="请选择" class="search-select" clearable>
        <el-option label="全部" value="" />
        <el-option label="已发布" value="published" />
        <el-option label="未发布" value="unpublished" />
      </el-select>

      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button @click="handleBatchPublish">批量发布/隐藏</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <!-- 表格 -->
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="tableData"
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="order" label="栏目顺序" width="100" />
          <el-table-column prop="name" label="栏目名称" min-width="150" />

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

          <el-table-column prop="count" label="栏目标签数量" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="creator" label="创建人" width="180" />

          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.published"
                active-text="发布"
                inactive-text="隐藏"
                @change="handleStatusChange(row)"
              />
            </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="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="栏目名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入栏目名称" />
        </el-form-item>

        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="formData.color" />
        </el-form-item>

        <el-form-item label="顺序" prop="order">
          <el-input-number v-model="formData.order" :min="0" />
        </el-form-item>
      </el-form>

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

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'

interface SearchForm {
  name: string
  status: string
}

interface TableRow {
  id: number
  order: number
  name: string
  color: string
  count: number
  createTime: string
  creator: string
  published: boolean
}

interface FormData {
  id?: number
  name: string
  color: string
  order: number
}

interface Pagination {
  page: number
  size: number
  total: number
}

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  status: '',
})

// 表格数据
const loading = ref(false)
const tableData = ref<TableRow[]>([])
const selectedRows = ref<TableRow[]>([])

// 分页
const pagination = reactive<Pagination>({
  page: 1,
  size: 20,
  total: 0,
})

// 对话框
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const formData = reactive<FormData>({
  name: '',
  color: '#88FFCB',
  order: 0,
})

const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增栏目' : '编辑栏目'
})

const formRules: FormRules = {
  name: [{ required: true, message: '请输入栏目名称', trigger: 'blur' }],
  color: [{ required: true, message: '请选择颜色', trigger: 'change' }],
  order: [{ required: true, message: '请输入顺序', trigger: 'blur' }],
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(formData, {
    name: '',
    color: '#88FFCB',
    order: 0,
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: TableRow) => {
  dialogType.value = 'edit'
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    color: row.color,
    order: row.order,
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: TableRow) => {
  try {
    await ElMessageBox.confirm('确定要删除该栏目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // TODO: 调用删除接口
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消删除
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条数据吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // TODO: 调用批量删除接口
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消删除
  }
}

// 批量发布/隐藏
const handleBatchPublish = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要操作的数据')
    return
  }

  // TODO: 调用批量发布接口
  ElMessage.success('操作成功')
  fetchData()
}

// 状态切换
const handleStatusChange = (row: TableRow) => {
  // TODO: 调用状态更新接口
  ElMessage.success(row.published ? '已发布' : '已隐藏')
}

// 表格选择
const handleSelectionChange = (rows: TableRow[]) => {
  selectedRows.value = rows
}

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

  await formRef.value.validate((valid) => {
    if (valid) {
      // TODO: 调用新增/编辑接口
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
      dialogVisible.value = false
      fetchData()
    }
  })
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  fetchData()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true

  try {
    // TODO: 调用接口获取数据
    // 模拟数据
    tableData.value = [
      {
        id: 123,
        order: 123,
        name: '专栏标签5',
        color: '#88FFCB',
        count: 1,
        createTime: '2025-11-20 14:15:07',
        creator: '178126911664085000',
        published: true,
      },
      {
        id: 8,
        order: 8,
        name: '专栏标签4',
        color: '#9878FF',
        count: 1,
        createTime: '2025-11-20 14:14:49',
        creator: '178126911664085000',
        published: true,
      },
      {
        id: 0,
        order: 0,
        name: '专栏标签3',
        color: '#f0fdf4',
        count: 4,
        createTime: '2025-11-10 18:05:37',
        creator: '178126911664085000',
        published: true,
      },
      {
        id: 11,
        order: 11,
        name: '专栏标签2',
        color: '#fdf2f8',
        count: 0,
        createTime: '2025-11-10 17:46:40',
        creator: '178126911664085000',
        published: true,
      },
      {
        id: 3,
        order: 3,
        name: '专栏标签1',
        color: '#eff6ff',
        count: 3,
        createTime: '2025-11-10 17:46:30',
        creator: '178126911664085000',
        published: true,
      },
    ]

    pagination.total = 5
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

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

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

  .search-input {
    width: 240px;
  }

  .search-select {
    width: 160px;
  }
}

// 表格区域 - 占满剩余高度
.table-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-height: 0; // 重要:允许flex子元素收缩
}

.action-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  flex-shrink: 0;
}

// 表格包裹器 - 自适应高度
.table-wrapper {
  flex: 1;
  min-height: 0; // 重要:允许flex子元素收缩

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

    .color-block {
      width: 24px;
      height: 24px;
      border-radius: 4px;
      border: 1px solid #e5e7eb;
    }
  }
}

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