<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>VIP等级管理</span>
        </div>
      </template>

      <!-- VIP等级列表表格 -->
      <el-table :data="vipList" v-loading="loading" border stripe>
        <el-table-column label="等级" align="center" width="80">
          <template #default="{ row }">
            <el-tag type="warning">VIP{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="等级名称" prop="title" min-width="150" />
        <el-table-column label="升级所需积分" align="right" width="150">
          <template #default="{ row }">
            <span class="number-text">{{ row.number?.toLocaleString() || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`编辑VIP${editForm.level}等级`"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="editForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="等级" prop="level">
          <el-input v-model="editForm.level" disabled />
        </el-form-item>
        <el-form-item label="等级名称" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入等级名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="升级所需积分" prop="number">
          <el-input-number
            v-model="editForm.number"
            :min="0"
            :max="999999999"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { getVipLevels, updateVipLevel, type VipLevel } from '@/api/business/user'

// 列表数据
const loading = ref(false)
const vipList = ref<VipLevel[]>([])

// 对话框
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 编辑表单
const editForm = reactive({
  id: 0,
  level: 0,
  title: '',
  number: 0
})

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入等级名称', trigger: 'blur' },
    { max: 50, message: '等级名称不能超过50个字符', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入升级所需积分', trigger: 'blur' },
    { type: 'number', min: 0, message: '积分不能为负数', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateStr: string | null) => {
  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'
  })
}

// 获取VIP等级列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getVipLevels()
    vipList.value = res.data || []
  } catch (error) {
    console.error('获取VIP等级列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 编辑
const handleEdit = (row: VipLevel) => {
  editForm.id = row.id
  editForm.level = row.level
  editForm.title = row.title
  editForm.number = row.number
  dialogVisible.value = true
}

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

  try {
    await formRef.value.validate()
    submitLoading.value = true

    await updateVipLevel(editForm.id, {
      title: editForm.title,
      number: editForm.number
    })

    ElMessage.success('更新成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('更新VIP等级失败:', error)
  } finally {
    submitLoading.value = false
  }
}

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

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

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

.number-text {
  font-family: 'Roboto Mono', monospace;
  font-weight: 500;
}
</style>
