<!-- views/backend/official/index.vue -->
<template>
  <div class="official-tag-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="flex-1 flex gap-2">
        <el-input
          v-model="searchParams.title"
          placeholder="请输入栏目标题"
          class="w-200px"
          clearable
        ></el-input>

        <el-select
          v-model="searchParams.status"
          placeholder="请选择发布状态"
          class="search-select"
          clearable
        >
          <el-option label="发布" :value="1" />
          <el-option label="隐藏" :value="0" />
        </el-select>
        <el-button type="primary" :icon="Search" @click="refresh">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </div>

      <div class="flex justify-end">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button type="primary" @click="handleBatchPublish"> 批量发布/隐藏 </el-button>
        <el-button type="danger" @click="handleBatchDelete"> 批量删除 </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <!-- 表格 -->
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="list"
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="sort" label="栏目顺序" width="180"> </el-table-column>
          <el-table-column prop="title" label="栏目名称" min-width="200" />
          <el-table-column prop="postCount" 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 prop="createUserId" label="创建人" min-width="200" />

          <el-table-column prop="createTime" label="创建时间" min-width="200">
            <template #default="{ row }">
              {{ dayjs(row.createTime * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" min-width="200">
            <template #default="{ row }">
              <el-switch
                :model-value="row.status"
                :active-value="1"
                :inactive-value="0"
                @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="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="title">
          <el-input v-model="form.title" 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-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="100" />
        </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"><Upload /></el-icon>
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Search, Plus, Upload } from '@element-plus/icons-vue'
import { usePageSearch, useResetData } from '@/hooks'
import { listOfCultureColumn, addOrUpdateColumn, deleteColumn, hideColumn } from '@/api/backend'
import type { FormInstance, FormRules } from 'element-plus'
import type { BackendColumnListItemDto, AddOrUpdateColumnDto } from '@/api/backend'
import dayjs from 'dayjs'

const { loading, list, total, reset, goToPage, changePageSize, refresh, searchParams, search } =
  usePageSearch(listOfCultureColumn, {
    defaultParams: {
      type: 'column',
    },
  })

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

// 表单数据

const [form, resetForm] = useResetData<AddOrUpdateColumnDto>({
  title: '',
  color: '#000000',
  id: undefined,
  sort: 0,
  type: 'column',
})
// 表单验证规则
const formRules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  color: [{ required: true, message: '请选择颜色', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}

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

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

// 状态改变
const handleStatusChange = async (row: BackendColumnListItemDto) => {
  await hideColumn([row.id])
  refresh()
}

// 删除
const handleDelete = async (row: BackendColumnListItemDto) => {
  try {
    await ElMessageBox.confirm(`确定要删除标签"${row.title}"吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await deleteColumn([row.id])

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

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

  try {
    await formRef.value.validate()

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

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

const selectedRows = ref<BackendColumnListItemDto[]>([])
// 选择
const handleSelectionChange = (selection: BackendColumnListItemDto[]) => {
  selectedRows.value = selection
}

// 批量发布/隐藏
const handleBatchPublish = async () => {
  await hideColumn(selectedRows.value.map((item) => item.id))
  refresh()
  selectedRows.value = []
  ElMessage.success('发布/隐藏成功')
}

// 批量删除
const handleBatchDelete = async () => {
  await deleteColumn(selectedRows.value.map((item) => item.id))
  refresh()
  selectedRows.value = []
  ElMessage.success('删除成功')
}
</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;
  gap: 12px;
  flex-shrink: 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>
