<template>
  <div class="page-container">
    <el-tabs v-model="activeTab" type="card" class="level-tabs">
      <el-tab-pane label="等级配置" name="levels">
        <el-card shadow="never" class="content-card">
          <template #header>
            <div class="card-header">
              <span class="title">等级体系列表</span>
              <el-button type="primary" icon="Plus" @click="handleEditLevel(null)">新增等级</el-button>
            </div>
          </template>

          <el-table :data="levelList" style="width: 100%" stripe>
            <el-table-column prop="level" label="等级" width="100">
              <template #default="{ row }">Lv.{{ row.level }}</template>
            </el-table-column>
            <el-table-column label="等级名称" width="150">
              <template #default="{ row }">
                <div class="level-name-col">
                  <el-avatar shape="square" :size="30" :src="row.icon || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                  <span>{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="积分区间" width="200">
              <template #default="{ row }"> {{ row.minPoints }} - {{ row.maxPoints === -1 ? '无限' : row.maxPoints }} </template>
            </el-table-column>
            <el-table-column label="节假日加成" width="150">
              <template #default="{ row }">
                <span style="color: #ff9900; font-weight: bold">{{ row.holidayMultiplier }}倍</span> 积分
              </template>
            </el-table-column>
            <el-table-column label="包含权益" min-width="300">
              <template #default="{ row }">
                <el-tag v-for="right in row.rights" :key="right.id" size="small" class="right-tag" type="info">{{ right.name }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ scope }">
                <el-button link type="primary" @click="handleEditLevel(scope.row)">配置</el-button>
                <el-button link type="danger" @click="handleDeleteLevel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="权益库管理" name="rights">
        <el-card shadow="never" class="content-card">
          <template #header>
            <div class="card-header">
              <span class="title">等级权益库</span>
              <el-button type="primary" icon="Plus" @click="handleEditRight(null)">新增权益</el-button>
            </div>
          </template>
          <el-table :data="rightsList" style="width: 100%">
            <el-table-column prop="name" label="权益名称" width="200">
              <template #default="{ row }">
                <div class="level-name-col">
                  <el-image
                    style="width: 30px; height: 30px; border-radius: 4px"
                    :src="row.icon || 'https://cube.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'"
                    fit="cover"
                  />
                  <span>{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-switch v-model="row.status" size="small" @change="handleRightStatusChange(row)" />
              </template>
            </el-table-column>
            <el-table-column prop="desc" label="权益说明" show-overflow-tooltip />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditRight(row)">编辑</el-button>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 等级编辑弹窗 -->
    <el-dialog v-model="levelDialog.visible" :title="levelDialog.isEdit ? '编辑等级' : '新增等级'" width="800px" top="5vh">
      <el-form :model="levelDialog.form" label-width="120px">
        <el-tabs type="border-card">
          <el-tab-pane label="基础设置">
            <el-form-item label="等级数值(Lv)" required>
              <el-input-number v-model="levelDialog.form.level" :min="1" />
            </el-form-item>
            <el-form-item label="等级名称" required>
              <el-input v-model="levelDialog.form.name" placeholder="如：青铜骑士" />
            </el-form-item>
            <el-form-item label="等级图标">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="(file) => handleLevelIconChange(file, 'icon')"
              >
                <img v-if="levelDialog.form.icon" :src="levelDialog.form.icon" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="tips">建议尺寸 100x100px</div>
            </el-form-item>
            <el-form-item label="背景图片">
              <el-upload
                class="bg-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="(file) => handleLevelIconChange(file, 'bg')"
              >
                <img v-if="levelDialog.form.bg" :src="levelDialog.form.bg" class="bg-img" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="tips">建议尺寸 600x300px</div>
            </el-form-item>

            <el-divider content-position="left">积分规则</el-divider>

            <el-row>
              <el-col :span="12">
                <el-form-item label="最低积分" required>
                  <el-input-number v-model="levelDialog.form.minPoints" :min="0" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最高积分">
                  <el-input-number v-model="levelDialog.form.maxPoints" :min="-1" placeholder="-1为无限" />
                  <div class="tips">设置-1代表无上限</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="节假日倍数" required>
              <el-input-number v-model="levelDialog.form.holidayMultiplier" :min="1" :precision="1" :step="0.1" />
              <div class="tips">法定节假日接单获得的积分倍率</div>
            </el-form-item>

            <el-divider content-position="left">权益配置</el-divider>

            <el-form-item label="权益关联">
              <el-checkbox-group v-model="levelDialog.form.rightsIds">
                <el-checkbox v-for="r in rightsList" :key="r.id" :label="r.id" :disabled="!r.status">
                  {{ r.name }}
                  <span v-if="!r.status" style="color: #999; font-size: 12px">(已停用)</span>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="升级规则">
            <div class="rule-group">
              <div class="rule-title">自动升级条件 (需全部满足)</div>
              <el-form-item label="考核周期">
                最近 <el-input-number v-model="levelDialog.form.rules.periodDays" :min="1" size="small" style="width: 100px" /> 天
              </el-form-item>
              <el-form-item label="完成单量">
                ≥ <el-input-number v-model="levelDialog.form.rules.minOrders" :min="0" size="small" style="width: 100px" /> 单
              </el-form-item>
              <el-form-item label="上门准时率">
                ≥ <el-input-number v-model="levelDialog.form.rules.onTimeRate" :min="0" :max="100" size="small" style="width: 100px" /> %
              </el-form-item>
              <el-form-item label="投诉率">
                ≤ <el-input-number v-model="levelDialog.form.rules.complaintRate" :min="0" :max="100" size="small" style="width: 100px" /> %
              </el-form-item>
              <el-form-item label="违规次数">
                ≤ <el-input-number v-model="levelDialog.form.rules.maxViolations" :min="0" size="small" style="width: 100px" /> 次
              </el-form-item>
              <el-form-item label="积分门槛">
                累计获得积分 ≥ <el-input-number v-model="levelDialog.form.rules.accumulatedPoints" :min="0" size="small" style="width: 120px" />
              </el-form-item>
            </div>
          </el-tab-pane>

          <el-tab-pane label="惩罚/降级">
            <el-form-item label="降级规则">
              <el-radio-group v-model="levelDialog.form.downgradeType">
                <el-radio label="points">仅积分不足时降级</el-radio>
                <el-radio label="strict">不满足升级条件即降级</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="rule-group" style="margin-top: 10px">
              <div class="rule-title">扣分配置</div>
              <el-form-item label="准时率过低">
                每低于1% 扣 <el-input-number v-model="levelDialog.form.deductions.late" :min="0" size="small" /> 分
              </el-form-item>
              <el-form-item label="一般违规">
                每次 扣 <el-input-number v-model="levelDialog.form.deductions.violation" :min="0" size="small" /> 分
              </el-form-item>
              <el-form-item label="严重投诉">
                每次 扣 <el-input-number v-model="levelDialog.form.deductions.complaint" :min="0" size="small" /> 分
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <el-button @click="levelDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveLevel">保存配置</el-button>
      </template>
    </el-dialog>

    <!-- 权益编辑弹窗 -->
    <el-dialog v-model="rightDialog.visible" :title="rightDialog.isEdit ? '编辑权益' : '新增权益'" width="500px">
      <el-form :model="rightDialog.form" label-width="100px">
        <el-form-item label="权益名称" required>
          <el-input v-model="rightDialog.form.name" />
        </el-form-item>
        <el-form-item label="权益图标">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false" :on-change="handleRightIconChange">
            <img v-if="rightDialog.form.icon" :src="rightDialog.form.icon" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="权益状态">
          <el-switch v-model="rightDialog.form.status" active-text="启用" inactive-text="停用" />
        </el-form-item>
        <el-form-item label="权益描述">
          <el-input v-model="rightDialog.form.desc" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rightDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveRight">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';

const activeTab = ref('levels');

// Data: Rights
const rightsList = ref([
  {
    id: 1,
    name: '节假日双倍积分',
    icon: 'https://cube.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
    status: true,
    desc: '在法定节假日接单，获得积分翻倍'
  },
  {
    id: 2,
    name: '专属人工客服',
    icon: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
    status: true,
    desc: '拥有专属客服经理，问题优先处理'
  },
  {
    id: 3,
    name: '提现免手续费',
    icon: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    status: true,
    desc: '每月前3笔提现免除平台手续费'
  }
]);

// Data: Levels
const levelList = ref([
  {
    id: 1,
    level: 1,
    name: '青铜骑士',
    icon: '',
    minPoints: 0,
    maxPoints: 1000,
    holidayMultiplier: 1.0,
    rights: [rightsList.value[1]],
    rules: { periodDays: 30, minOrders: 10, onTimeRate: 90, complaintRate: 5, maxViolations: 0, accumulatedPoints: 100 },
    deductions: { late: 5, violation: 20, complaint: 50 },
    downgradeType: 'points'
  },
  {
    id: 2,
    level: 2,
    name: '白银卫士',
    icon: '',
    minPoints: 1001,
    maxPoints: 5000,
    holidayMultiplier: 1.2,
    rights: [rightsList.value[1], rightsList.value[2]],
    rules: { periodDays: 30, minOrders: 30, onTimeRate: 95, complaintRate: 2, maxViolations: 0, accumulatedPoints: 1000 },
    deductions: { late: 10, violation: 50, complaint: 100 },
    downgradeType: 'points'
  },
  {
    id: 3,
    level: 3,
    name: '黄金领主',
    icon: '',
    minPoints: 5001,
    maxPoints: -1,
    holidayMultiplier: 1.5,
    rights: [rightsList.value[0], rightsList.value[1], rightsList.value[2]],
    rules: { periodDays: 30, minOrders: 100, onTimeRate: 98, complaintRate: 0, maxViolations: 0, accumulatedPoints: 5000 },
    deductions: { late: 20, violation: 100, complaint: 200 },
    downgradeType: 'points'
  }
]);

// Dialogs
const levelDialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    level: 1,
    name: '',
    icon: '',
    bg: '',
    minPoints: 0,
    maxPoints: -1,
    holidayMultiplier: 1.0,
    rightsIds: [],
    rules: { periodDays: 30, minOrders: 0, onTimeRate: 95, complaintRate: 0, maxViolations: 0, accumulatedPoints: 0 },
    deductions: { late: 10, violation: 50, complaint: 100 },
    downgradeType: 'points'
  }
});

const rightDialog = reactive({
  visible: false,
  isEdit: false,
  form: { name: '', icon: '', status: true, desc: '' }
});

// Methods
const handleEditLevel = (row) => {
  levelDialog.isEdit = !!row;
  levelDialog.visible = true;
  if (row) {
    // Deep copy to break ref
    const rightsIds = row.rights.map((r) => r.id);
    levelDialog.form = JSON.parse(JSON.stringify({ ...row, rightsIds }));
  } else {
    // Reset
    levelDialog.form = {
      level: levelList.value.length + 1,
      name: '',
      icon: '',
      bg: '',
      minPoints: 0,
      maxPoints: -1,
      holidayMultiplier: 1.0,
      rightsIds: [],
      rules: { periodDays: 30, minOrders: 0, onTimeRate: 95, complaintRate: 0, maxViolations: 0, accumulatedPoints: 0 },
      deductions: { late: 10, violation: 50, complaint: 100 },
      downgradeType: 'points'
    };
  }
};

const handleLevelIconChange = (file, type) => {
  // 模拟上传，实际应调用后端接口，这里直接读取本地文件展示
  const url = URL.createObjectURL(file.raw);
  if (type === 'icon') {
    levelDialog.form.icon = url;
  } else {
    levelDialog.form.bg = url;
  }
};

const saveLevel = () => {
  // Map rightsIds back to objects
  const selectedRights = rightsList.value.filter((r) => levelDialog.form.rightsIds.includes(r.id));
  const newLevel = { ...levelDialog.form, rights: selectedRights };

  if (levelDialog.isEdit) {
    const idx = levelList.value.findIndex((l) => l.id === newLevel.id);
    if (idx !== -1) levelList.value[idx] = newLevel;
  } else {
    newLevel.id = Date.now();
    levelList.value.push(newLevel);
  }

  levelList.value.sort((a, b) => a.level - b.level);
  levelDialog.visible = false;
  ElMessage.success('等级配置保存成功');
};

const handleDeleteLevel = () => {
  ElMessage.warning('演示模式：暂不执行删除');
};

const handleEditRight = (row) => {
  rightDialog.isEdit = !!row;
  rightDialog.visible = true;
  if (row) {
    rightDialog.form = { ...row };
  } else {
    rightDialog.form = { name: '', icon: '', status: true, desc: '' };
  }
};

const handleRightIconChange = (file) => {
  rightDialog.form.icon = URL.createObjectURL(file.raw);
};

const saveRight = () => {
  if (rightDialog.isEdit) {
    const idx = rightsList.value.findIndex((r) => r.id === rightDialog.form.id);
    if (idx !== -1) rightsList.value[idx] = { ...rightsList.value[idx], ...rightDialog.form };
  } else {
    // Default icon if empty for demo
    if (!rightDialog.form.icon) rightDialog.form.icon = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
    rightsList.value.push({ ...rightDialog.form, id: Date.now() });
  }
  rightDialog.visible = false;
  ElMessage.success('权益保存成功');
};

const handleRightStatusChange = (row) => {
  ElMessage.success(`权益 "${row.name}" 已${row.status ? '启用' : '停用'}`);
};
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title {
  font-weight: bold;
  font-size: 16px;
}

.level-name-col {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}
.right-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.avatar-uploader,
.bg-uploader {
  width: 80px;
  height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}
.bg-uploader {
  width: 160px;
  height: 80px;
}
.avatar-uploader:hover,
.bg-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: cover;
}
.bg-img {
  width: 160px;
  height: 80px;
  display: block;
  object-fit: cover;
}

.tips {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
  display: inline-block;
}

.rule-group {
  background: #f8fcfb;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #ebf5f2;
}
.rule-title {
  font-weight: bold;
  margin-bottom: 12px;
  font-size: 14px;
  color: #333;
}
</style>
