<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>中奖公告管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加公告
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="关键词">
            <el-input
              v-model="queryParams.keyword"
              placeholder="用户名/奖品名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 公告表格 -->
      <el-table :data="announcementList" v-loading="loading" border stripe>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        
        <el-table-column label="用户头像" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.userAvatar"
              :src="row.userAvatar"
              :preview-src-list="[row.userAvatar]"
              fit="cover"
              class="avatar-image"
              preview-teleported
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-avatar v-else :size="40" :icon="UserFilled" />
          </template>
        </el-table-column>
        
        <el-table-column prop="userName" label="用户名称" min-width="120" />
        
        <el-table-column label="奖品等级" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPrizeLevelType(row.prizeLevel)" size="small">
              {{ row.prizeLevel }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="prizeName" label="奖品名称" min-width="150" />
        
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.isEnabled"
              :loading="row.statusLoading"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        
        <el-table-column label="创建时间" width="160" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        class="pagination"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑公告' : '新增公告'"
      width="550px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户头像" prop="userAvatar">
          <ImageUpload
            v-model="formData.userAvatar"
            placeholder="点击上传头像"
            url-placeholder="或输入头像URL"
            tip="支持 jpg、png、gif、webp 格式"
          />
        </el-form-item>

        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="formData.userName"
            placeholder="请输入用户名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="奖品等级" prop="prizeLevel">
          <el-select v-model="formData.prizeLevel" placeholder="请选择奖品等级" style="width: 100%">
            <el-option label="无上" value="无上" />
            <el-option label="传说" value="传说" />
            <el-option label="史诗" value="史诗" />
            <el-option label="稀有" value="稀有" />
            <el-option label="普通" value="普通" />
          </el-select>
        </el-form-item>

        <el-form-item label="奖品名称" prop="prizeName">
          <el-input
            v-model="formData.prizeName"
            placeholder="请输入奖品名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="排序值" prop="sort">
          <el-input-number
            v-model="formData.sort"
            :min="0"
            :max="9999"
            placeholder="请输入排序值"
            style="width: 100%"
            controls-position="right"
          />
          <div class="form-tip">数值越小排序越靠前</div>
        </el-form-item>

        <el-form-item label="启用状态" prop="isEnabled">
          <el-switch v-model="formData.isEnabled" />
        </el-form-item>
      </el-form>

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

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh, Picture, UserFilled } from '@element-plus/icons-vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import {
  getAnnouncementList,
  createAnnouncement,
  updateAnnouncement,
  deleteAnnouncement,
  toggleAnnouncementStatus,
  type AnnouncementItem,
  type AnnouncementListQuery,
  type CreateAnnouncementRequest
} from '@/api/business/announcement'

// 列表数据
const loading = ref(false)
const announcementList = ref<(AnnouncementItem & { statusLoading?: boolean })[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<AnnouncementListQuery>({
  page: 1,
  pageSize: 20,
  keyword: ''
})

// 弹窗控制
const formDialogVisible = ref(false)
const isEdit = ref(false)
const currentId = ref<number | null>(null)
const submitLoading = ref(false)

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
interface FormDataType {
  userAvatar: string
  userName: string
  prizeLevel: string
  prizeName: string
  sort: number
  isEnabled: boolean
}

const formData = reactive<FormDataType>({
  userAvatar: '',
  userName: '',
  prizeLevel: '',
  prizeName: '',
  sort: 0,
  isEnabled: true
})

// 表单验证规则
const formRules: FormRules = {
  userName: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
    { max: 50, message: '用户名称不能超过50个字符', trigger: 'blur' }
  ],
  prizeLevel: [
    { required: true, message: '请选择奖品等级', trigger: 'change' }
  ],
  prizeName: [
    { required: true, message: '请输入奖品名称', trigger: 'blur' },
    { max: 100, message: '奖品名称不能超过100个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateStr: string): string => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取奖品等级标签类型
const getPrizeLevelType = (level: string): '' | 'success' | 'warning' | 'info' | 'danger' => {
  const typeMap: Record<string, '' | 'success' | 'warning' | 'info' | 'danger'> = {
    '无上': 'danger',
    '传说': 'warning',
    '史诗': '',
    '稀有': 'success',
    '普通': 'info'
  }
  return typeMap[level] || 'info'
}

// 获取公告列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getAnnouncementList(queryParams)
    announcementList.value = res.data.list.map(item => ({ ...item, statusLoading: false }))
    total.value = res.data.total
  } finally {
    loading.value = false
  }
}

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

// 重置
const handleReset = () => {
  queryParams.keyword = ''
  queryParams.page = 1
  fetchData()
}

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

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

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    userAvatar: '',
    userName: '',
    prizeLevel: '',
    prizeName: '',
    sort: 0,
    isEnabled: true
  })
  formRef.value?.resetFields()
}

// 新增公告
const handleAdd = () => {
  isEdit.value = false
  currentId.value = null
  resetForm()
  formDialogVisible.value = true
}

// 编辑公告
const handleEdit = (row: AnnouncementItem) => {
  isEdit.value = true
  currentId.value = row.id
  Object.assign(formData, {
    userAvatar: row.userAvatar || '',
    userName: row.userName,
    prizeLevel: row.prizeLevel,
    prizeName: row.prizeName,
    sort: row.sort,
    isEnabled: row.isEnabled
  })
  formDialogVisible.value = true
}

// 删除公告
const handleDelete = async (row: AnnouncementItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除公告 "${row.userName} - ${row.prizeName}" 吗？删除后不可恢复！`,
      '删除确认',
      { type: 'warning' }
    )
    await deleteAnnouncement(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

// 切换状态
const handleStatusChange = async (row: AnnouncementItem & { statusLoading?: boolean }) => {
  row.statusLoading = true
  try {
    await toggleAnnouncementStatus(row.id)
    ElMessage.success(row.isEnabled ? '已启用' : '已禁用')
  } catch {
    // 恢复原状态
    row.isEnabled = !row.isEnabled
  } finally {
    row.statusLoading = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  formDialogVisible.value = false
  resetForm()
}

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

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitLoading.value = true
  try {
    const submitData: CreateAnnouncementRequest = {
      userAvatar: formData.userAvatar || undefined,
      userName: formData.userName,
      prizeLevel: formData.prizeLevel,
      prizeName: formData.prizeName,
      sort: formData.sort,
      isEnabled: formData.isEnabled
    }

    if (isEdit.value && currentId.value) {
      await updateAnnouncement(currentId.value, submitData)
      ElMessage.success('更新成功')
    } else {
      await createAnnouncement(submitData)
      ElMessage.success('创建成功')
    }

    handleDialogClose()
    fetchData()
  } finally {
    submitLoading.value = false
  }
}

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

<style scoped>
.page-container {
  padding: 0;
}

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

.search-form {
  margin-bottom: 16px;
}

.avatar-image {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  background: #f5f7fa;
  color: #909399;
  font-size: 16px;
  border-radius: 50%;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
