<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>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="等级名称">
          <el-input v-model="queryParams.title" placeholder="请输入等级名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 概率统计 -->
      <div class="stats-bar">
        <el-tag type="info" size="large">
          概率总和: <span class="stats-value">{{ stats.totalProbability?.toFixed(2) || '0.00' }}%</span>
        </el-tag>
      </div>

      <!-- 等级列表 -->
      <el-table :data="levelList" v-loading="loading" border stripe>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="等级名称" min-width="120">
          <template #default="{ row }">
            <el-tag :color="row.color" :style="{ color: getTextColor(row.color) }">
              {{ row.title }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pro" label="概率" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.pro }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="等级图标" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.imgUrl"
              :src="row.imgUrl"
              :preview-src-list="[row.imgUrl]"
              fit="cover"
              style="width: 40px; height: 40px"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="100" align="center">
          <template #default="{ row }">
            <div v-if="row.color" class="color-preview" :style="{ backgroundColor: row.color }"></div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="prizeCount" label="关联奖品" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="info">{{ row.prizeCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <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>

      <!-- 分页 -->
      <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>

    <!-- 添加/编辑弹窗 -->
    <PrizeLevelFormDialog
      v-model="dialogVisible"
      :level-id="currentLevelId"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import PrizeLevelFormDialog from './components/PrizeLevelFormDialog.vue'
import {
  getPrizeLevels,
  getPrizeLevelStats,
  deletePrizeLevel,
  type PrizeLevelListRequest,
  type PrizeLevelResponse,
  type PrizeLevelStatsResponse
} from '@/api/business/prizelevel'

const loading = ref(false)
const levelList = ref<PrizeLevelResponse[]>([])
const total = ref(0)
const stats = ref<PrizeLevelStatsResponse>({ totalProbability: 0 })

const queryParams = reactive<PrizeLevelListRequest>({
  page: 1,
  pageSize: 20,
  title: ''
})

const dialogVisible = ref(false)
const currentLevelId = ref<number | null>(null)

// 获取文字颜色（根据背景色自动计算）
const getTextColor = (bgColor?: string): string => {
  if (!bgColor) return '#333'
  const hex = bgColor.replace('#', '')
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  const brightness = (r * 299 + g * 587 + b * 114) / 1000
  return brightness > 128 ? '#333' : '#fff'
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const [listRes, statsRes] = await Promise.all([
      getPrizeLevels(queryParams),
      getPrizeLevelStats()
    ])
    levelList.value = listRes.data.list
    total.value = listRes.data.total
    stats.value = statsRes.data
  } catch (error) {
    console.error('获取奖品等级列表失败:', error)
    ElMessage.error('获取奖品等级列表失败')
  } finally {
    loading.value = false
  }
}

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

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

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

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

// 添加
const handleAdd = () => {
  currentLevelId.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: PrizeLevelResponse) => {
  currentLevelId.value = row.id
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: PrizeLevelResponse) => {
  if (row.prizeCount > 0) {
    ElMessage.warning('当前等级关联有奖品，不可删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除等级"${row.title}"吗？`,
      '删除确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    await deletePrizeLevel(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 成功回调
const handleSuccess = () => {
  fetchData()
}

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;
}

.stats-bar {
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.stats-value {
  font-weight: 600;
  margin-left: 4px;
}

.color-preview {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: inline-block;
  border: 1px solid #ddd;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
