<template>
  <AdminLayout 
    title="成就管理" 
    subtitle="管理用户成就、徽章等激励内容"
  >
    <div class="achievement-management">
      <div class="header">
        <h2>成就管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增成就
        </el-button>
      </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <div class="filter-item">
        <span class="filter-label">成就类型</span>
        <el-select v-model="filter.type" placeholder="全部" clearable style="width: 150px">
          <el-option 
            v-for="option in achievementTypeOptions" 
            :key="option.value" 
            :label="option.label" 
            :value="option.value" 
          />
        </el-select>
      </div>
      <div class="filter-item">
        <span class="filter-label">成就等级</span>
        <el-input-number 
          v-model="filter.level" 
          :min="0" 
          :max="10" 
          placeholder="全部" 
          clearable 
          style="width: 120px"
        />
      </div>
      <div class="filter-item">
        <span class="filter-label">条件类型</span>
        <el-select v-model="filter.conditionType" placeholder="全部" clearable style="width: 180px">
          <el-option 
            v-for="option in conditionTypeOptions" 
            :key="option.value" 
            :label="option.label" 
            :value="option.value" 
          />
        </el-select>
      </div>
      <div class="filter-actions">
        <el-button type="primary" @click="loadAchievementList">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
    </div>

    <!-- 成就列表 -->
    <el-table 
      :data="achievementList" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
      row-key="achievementID"
    >
      <el-table-column prop="icon" label="图标" width="80" align="center">
        <template #default="{ row }">
          <el-image 
            :src="getIconUrl(row.icon)" 
            style="width: 48px; height: 48px" 
            fit="contain"
            :preview-src-list="[getIconUrl(row.icon)]"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="成就名称" min-width="150" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.type === 1 ? 'success' : 'primary'">
            {{ getAchievementTypeLabel(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="等级" width="80" align="center" />
      <el-table-column prop="conditionType" label="条件类型" width="150">
        <template #default="{ row }">
          {{ getConditionTypeLabel(row.conditionType) }}
        </template>
      </el-table-column>
      <el-table-column prop="conditionValue" label="条件值" width="100" align="center" />
      <el-table-column prop="points" label="积分奖励" width="100" align="center" />
      <el-table-column prop="orderNum" label="排序号" width="80" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleEdit(row)"
            link
          >
            编辑
          </el-button>
          <el-button 
            type="info" 
            size="small" 
            @click="handleViewUsers(row)"
            link
          >
            查看获得者
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(row)"
            link
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑成就对话框 -->
    <el-dialog
      v-model="achievementDialogVisible"
      :title="isEdit ? '编辑成就' : '新增成就'"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="achievementFormRef"
        :model="currentAchievement"
        :rules="achievementFormRules"
        label-width="120px"
      >
        <el-form-item label="成就名称" prop="name">
          <el-input v-model="currentAchievement.name" placeholder="请输入成就名称" />
        </el-form-item>
        <el-form-item label="成就描述" prop="description">
          <el-input 
            v-model="currentAchievement.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入成就描述" 
          />
        </el-form-item>
        <el-form-item label="成就图标" prop="icon">
          <el-input 
            v-model="currentAchievement.icon" 
            placeholder="请输入图标路径，如：/img/achievement/v1-icon.svg 或完整URL"
          >
            <template #append>
              <el-button @click="showIconUpload = true">上传</el-button>
            </template>
          </el-input>
          <div v-if="currentAchievement.icon" style="margin-top: 10px">
            <div style="display: flex; align-items: center; gap: 10px;">
              <el-image 
                :src="getIconUrl(currentAchievement.icon)" 
                style="width: 80px; height: 80px" 
                fit="contain"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div style="font-size: 12px; color: #909399;">
                <div>路径: {{ currentAchievement.icon }}</div>
                <div>完整URL: {{ getIconUrl(currentAchievement.icon) }}</div>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成就类型" prop="type">
              <el-select v-model="currentAchievement.type" placeholder="请选择成就类型" style="width: 100%">
                <el-option 
                  v-for="option in achievementTypeOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成就等级" prop="level">
              <el-input-number 
                v-model="currentAchievement.level" 
                :min="1" 
                :max="10" 
                placeholder="请输入等级" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="条件类型" prop="conditionType">
              <el-select 
                v-model="currentAchievement.conditionType" 
                placeholder="请选择条件类型" 
                style="width: 100%"
              >
                <el-option 
                  v-for="option in conditionTypeOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条件值" prop="conditionValue">
              <el-input-number 
                v-model="currentAchievement.conditionValue" 
                :min="1" 
                placeholder="请输入条件值" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="条件预览" v-if="currentAchievement.conditionType && currentAchievement.conditionValue">
          <el-alert 
            :title="formatConditionValue(currentAchievement.conditionType, currentAchievement.conditionValue)" 
            type="info" 
            :closable="false"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="积分奖励" prop="points">
              <el-input-number 
                v-model="currentAchievement.points" 
                :min="0" 
                placeholder="请输入积分奖励" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="orderNum">
              <el-input-number 
                v-model="currentAchievement.orderNum" 
                :min="0" 
                placeholder="请输入排序号" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="achievementDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAchievement" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看获得者对话框 -->
    <el-dialog
      v-model="usersDialogVisible"
      title="成就获得者列表"
      width="900px"
    >
      <div class="achievement-info-bar">
        <el-alert 
          :title="`成就：${currentAchievement.name} - ${currentAchievement.description}`" 
          type="info" 
          :closable="false"
          style="margin-bottom: 20px"
        />
      </div>

      <el-table 
        :data="achieverList" 
        v-loading="achieversLoading"
        border
        stripe
      >
        <el-table-column prop="userID" label="用户ID" width="200" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="realName" label="真实姓名" min-width="100" />
        <el-table-column prop="obtainTime" label="获得时间" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleRevokeAchievement(row)"
            >
              撤销成就
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    </div>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Picture } from '@element-plus/icons-vue';
import { achievementApi } from '@/apis/achievement';
import type { Achievement, UserAchievement } from '@/types';
import { AchievementEnumHelper } from '@/types/enums/achievement-enums';
import { getAchievementIconUrl } from '@/utils/iconUtils';
import { AdminLayout } from '@/views/admin';

defineOptions({
  name: 'AchievementManagementView'
});

// 响应式数据
const loading = ref(false);
const submitting = ref(false);
const achieversLoading = ref(false);
const achievementList = ref<Achievement[]>([]);
const achieverList = ref<UserAchievement[]>([]);

// 对话框控制
const achievementDialogVisible = ref(false);
const usersDialogVisible = ref(false);
const showIconUpload = ref(false);
const isEdit = ref(false);

// 筛选条件
const filter = ref<Partial<Achievement>>({});

// 当前操作的成就
const currentAchievement = ref<Achievement>({});

// 枚举选项
const achievementTypeOptions = AchievementEnumHelper.getAllAchievementTypeOptions();
const conditionTypeOptions = AchievementEnumHelper.getAllConditionTypeOptions();

// 表单引用
const achievementFormRef = ref();

// 表单验证规则
const achievementFormRules = {
  name: [
    { required: true, message: '请输入成就名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入成就描述', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请输入图标URL', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择成就类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请输入成就等级', trigger: 'blur' }
  ],
  conditionType: [
    { required: true, message: '请选择条件类型', trigger: 'change' }
  ],
  conditionValue: [
    { required: true, message: '请输入条件值', trigger: 'blur' }
  ],
  points: [
    { required: true, message: '请输入积分奖励', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
};

// 获取成就类型标签
function getAchievementTypeLabel(type?: number): string {
  if (type === undefined) return '未知';
  return AchievementEnumHelper.getAchievementTypeDescription(type);
}

// 获取条件类型标签
function getConditionTypeLabel(type?: number): string {
  if (type === undefined) return '未知';
  return AchievementEnumHelper.getConditionTypeDescription(type);
}

// 格式化条件值显示
function formatConditionValue(conditionType?: number, conditionValue?: number): string {
  if (conditionType === undefined || conditionValue === undefined) return '';
  return AchievementEnumHelper.formatConditionValue(conditionType, conditionValue);
}

// 获取图标完整路径
const getIconUrl = getAchievementIconUrl;

// 加载成就列表
async function loadAchievementList() {
  try {
    loading.value = true;
    const result = await achievementApi.getAllAchievements(filter.value);
    achievementList.value = result.dataList || [];
  } catch (error) {
    console.error('加载成就列表失败:', error);
    ElMessage.error('加载成就列表失败');
  } finally {
    loading.value = false;
  }
}

// 重置筛选条件
function resetFilter() {
  filter.value = {};
  loadAchievementList();
}

// 新增成就
function handleAdd() {
  isEdit.value = false;
  currentAchievement.value = {
    type: 1,
    level: 1,
    points: 0,
    orderNum: 0
  };
  achievementDialogVisible.value = true;
}

// 编辑成就
function handleEdit(row: Achievement) {
  isEdit.value = true;
  currentAchievement.value = { ...row };
  achievementDialogVisible.value = true;
}

// 删除成就
async function handleDelete(row: Achievement) {
  try {
    await ElMessageBox.confirm(
      `确定要删除成就 "${row.name}" 吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await achievementApi.deleteAchievement(row);
    ElMessage.success('删除成功');
    await loadAchievementList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除成就失败:', error);
      ElMessage.error('删除成就失败');
    }
  }
}

// 保存成就
async function saveAchievement() {
  try {
    await achievementFormRef.value?.validate();
    submitting.value = true;
    
    if (isEdit.value) {
      await achievementApi.updateAchievement(currentAchievement.value);
      ElMessage.success('更新成功');
    } else {
      await achievementApi.createAchievement(currentAchievement.value);
      ElMessage.success('创建成功');
    }
    
    achievementDialogVisible.value = false;
    await loadAchievementList();
  } catch (error) {
    console.error('保存成就失败:', error);
    if (error !== false) {
      ElMessage.error('保存成就失败');
    }
  } finally {
    submitting.value = false;
  }
}

// 查看获得者
async function handleViewUsers(row: Achievement) {
  currentAchievement.value = { ...row };
  usersDialogVisible.value = true;
  
  try {
    achieversLoading.value = true;
    const result = await achievementApi.getRecentAchievers(
      { pageNumber: 1, pageSize: 100 },
      { achievementID: row.achievementID }
    );
    achieverList.value = result.dataList || [];
  } catch (error) {
    console.error('加载获得者列表失败:', error);
    ElMessage.error('加载获得者列表失败');
  } finally {
    achieversLoading.value = false;
  }
}

// 撤销成就
async function handleRevokeAchievement(row: UserAchievement) {
  try {
    await ElMessageBox.confirm(
      '确定要撤销该用户的成就吗？',
      '确认撤销',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await achievementApi.revokeAchievement(row.userID || '', row.achievementID || '');
    ElMessage.success('撤销成功');
    
    // 刷新获得者列表
    await handleViewUsers(currentAchievement.value);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤销成就失败:', error);
      ElMessage.error('撤销成就失败');
    }
  }
}

// 重置表单
function resetForm() {
  currentAchievement.value = {};
  achievementFormRef.value?.clearValidate();
}

// 组件挂载时加载数据
onMounted(() => {
  loadAchievementList();
});
</script>

<style scoped lang="scss">
.achievement-management {
  background: #FFFFFF;
  padding: 24px;
  border-radius: 14px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #141F38;
  }
}

.filter-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;

  .filter-item {
    display: flex;
    align-items: center;
    gap: 8px;

    .filter-label {
      font-size: 14px;
      color: #606266;
      white-space: nowrap;
    }
  }

  .filter-actions {
    display: flex;
    gap: 8px;
    margin-left: auto;
  }
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #ccc;
  font-size: 24px;
}

.achievement-info-bar {
  margin-bottom: 20px;
}
</style>

