<template>
  <div class="page-container">
    <el-tabs v-model="activeTab" type="card" class="level-tabs">
      <el-tab-pane label="等级配置" name="levels" v-if="checkPermi(['fulfiller:levelConfig:list'])">
        <el-card shadow="never" class="content-card">
          <template v-slot:header>
            <div class="card-header">
              <span class="title">等级体系列表</span>
              <el-button type="primary" icon="Plus" @click="handleEditLevel(null)" v-hasPermi="['fulfiller:levelConfig:add']">新增等级</el-button>
            </div>
          </template>

          <el-table :data="levelList" style="width: 100%" stripe>
            <el-table-column prop="lvNo" label="等级" width="100">
              <template #default="{ row }">Lv.{{ row.lvNo }}</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.iconUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                  <span>{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="升级积分" width="150">
              <template #default="{ row }"> {{ row.upgradePoints }} </template>
            </el-table-column>
            <el-table-column label="节假日加成" width="150">
              <template #default="{ row }">
                <span style="color: #ff9900; font-weight: bold">{{ (row.holidayBonus || 0) / 100 }}倍</span>
              </template>
            </el-table-column>
            <el-table-column label="包含权益" min-width="300">
              <template #default="{ row }">
                <template v-if="row.rights && row.rights.length">
                  <el-tag v-for="rightId in row.rights" :key="rightId" size="small" class="right-tag" type="info">
                    {{ getRightName(rightId) }}
                  </el-tag>
                </template>
                <span v-else style="color: #999; font-size: 12px">暂无权益</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditLevel(row)" v-hasPermi="['fulfiller:levelConfig:config']">配置</el-button>
                <el-button link type="danger" @click="handleDeleteLevel(row)" v-hasPermi="['fulfiller:levelConfig:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="权益库管理" name="rights" v-if="checkPermi(['fulfiller:levelRights:list'])">
        <el-card shadow="never" class="content-card">
          <template v-slot:header>
            <div class="card-header">
              <span class="title">等级权益库</span>
              <el-button type="primary" icon="Plus" @click="handleEditRight(null)" v-hasPermi="['fulfiller:levelRights:add']">新增权益</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.iconUrl || '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)" v-hasPermi="['fulfiller:levelRights:edit']" />
              </template>
            </el-table-column>
            <el-table-column prop="statement" label="权益说明" show-overflow-tooltip />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditRight(row)" v-hasPermi="['fulfiller:levelRights:edit']">编辑</el-button>
                <el-button link type="danger" @click="handleDeleteRight(row)" v-hasPermi="['fulfiller:levelRights:remove']">删除</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)">
              <el-input-number v-model="levelDialog.form.lvNo" :min="1" />
            </el-form-item>
            <el-form-item label="等级名称">
              <el-input v-model="levelDialog.form.name" placeholder="请输入等级名称" />
            </el-form-item>
            <el-form-item label="等级图标">
              <image-upload v-model="levelDialog.form.icon" :limit="1" :is-delete="false" />
            </el-form-item>
            <el-form-item label="背景图片">
              <image-upload v-model="levelDialog.form.background" :limit="1" :is-delete="false" />
            </el-form-item>
            <el-form-item label="节假日加成">
              <el-input-number v-model="levelDialog.form.holidayBonus" :min="0" :precision="2" :step="0.1" />
            </el-form-item>
            <el-form-item label="权益配置">
              <el-checkbox-group v-model="levelDialog.form.rights">
                <el-checkbox v-for="r in rightsList" :key="r.id" :label="r.id" :disabled="!r.status">
                  {{ r.name }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="升级规则(自然月内)">
            <div class="rule-group">
              <div style="margin-bottom: 20px">
                到达 <el-input-number v-model="levelDialog.form.upgradePoints" :min="0" /> 积分
              </div>
              <div style="margin-bottom: 20px">
                完成 <el-input-number v-model="levelDialog.form.upgradeCompleteOrderQuality" :min="0" /> 单量
              </div>
              <div style="margin-bottom: 20px">
                达到 <el-input-number v-model="levelDialog.form.upgradeOntimeRate" :min="0" :max="100" :precision="2"
                  :step="0.01" /> 准时率
              </div>
              <div style="margin-bottom: 20px">
                达到 <el-input-number v-model="levelDialog.form.upgradeComplaintRate" :min="0" :max="100" :precision="2"
                  :step="0.01" /> 投诉率
              </div>
              <div style="margin-bottom: 20px">
                低于 <el-input-number v-model="levelDialog.form.upgradeViolationsCount" :min="0" /> 违规次数
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="扣分规则(自然月内)">
            <div class="rule-group">
              <div style="margin-bottom: 20px">
                上门准时率低于 <el-input-number v-model="levelDialog.form.degradeOntimeRate" :min="0" :max="100" :precision="2"
                  :step="0.01" /> %，自动扣罚积分 <el-input-number v-model="levelDialog.form.degradeOntimeRateScore"
                  :min="0" />
              </div>
              <div style="margin-bottom: 20px">
                完成订单为 <el-input-number v-model="levelDialog.form.degradeCompleteOrderQuality" :min="0" />，自动扣罚积分
                <el-input-number v-model="levelDialog.form.degradeCompleteOrderQualityScore" :min="0" />
              </div>
              <div style="margin-bottom: 20px">
                违规一次，人工扣罚积分 <el-input-number v-model="levelDialog.form.degradeViolationsScore" :min="0" />
              </div>
              <div style="margin-bottom: 20px">
                投诉率达到 <el-input-number v-model="levelDialog.form.degradeComplaintCount" :min="0" :max="100"
                  :precision="2" :step="0.01" /> %，自动扣罚积分 <el-input-number
                  v-model="levelDialog.form.degradeComplaintCountScore" :min="0" />
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="降级规则">
            <div class="rule-group">
              <div style="margin-bottom: 20px">
                积分低于 <el-input-number v-model="levelDialog.form.degradePoints" :min="0" /> 时自动降级
              </div>
            </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 prop="name">
          <el-input v-model="rightDialog.form.name" placeholder="请输入权益名称" />
        </el-form-item>
        <el-form-item label="权益图标" required prop="icon">
          <image-upload v-model="rightDialog.form.icon" :limit="1" :is-delete="false" />
        </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.statement" 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 lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { checkPermi } from '@/utils/permission';
import { listAllLevelRights, addLevelRights, updateLevelRights, delLevelRights, changeLevelRightsStatus } from '@/api/fulfiller/levelRights';
import { listAllLevelConfig, addLevelConfig, updateLevelConfig, delLevelConfig } from '@/api/fulfiller/levelConfig';
import { FlfLevelConfigVO, FlfLevelConfigForm } from '@/api/fulfiller/levelConfig/types';
import { FlfLevelRightsForm, FlfLevelRightsVO } from '@/api/fulfiller/levelRights/types';
import ImageUpload from '@/components/ImageUpload/index.vue';

const activeTab = ref(checkPermi(['fulfiller:levelConfig:list']) ? 'levels' : 'rights');

// Data: Rights
// Data: Rights
// 权益数据列表
const rightsList = ref<FlfLevelRightsVO[]>([]);

const getRightsList = async () => {
  try {
    const res = await listAllLevelRights();
    rightsList.value = res.data || [];
  } catch (error) {
    console.error('Failed to fetch rights list:', error);
  }
};

const getLevelList = async () => {
  try {
    const res = await listAllLevelConfig();
    levelList.value = res.data || [];
  } catch (error) {
    console.error('Failed to fetch level list:', error);
  }
};

const getRightName = (id: number | string) => {
  const right = rightsList.value.find((r) => r.id === id);
  return right ? right.name : `未知权益(${id})`;
};

// Data: Levels
const levelList = ref<FlfLevelConfigVO[]>([]);

// Dialogs
const levelDialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    id: undefined,
    lvNo: 1,
    name: '',
    icon: '',
    background: '',
    holidayBonus: 1,
    rights: [],
    // 升级规则
    upgradePoints: 0,
    upgradeCompleteOrderQuality: 0,
    upgradeOntimeRate: 1,
    upgradeComplaintRate: 1,
    upgradeViolationsCount: 0,
    // 降级规则
    degradePoints: 0,
    degradeOntimeRate: 1,
    degradeOntimeRateScore: 0,
    degradeCompleteOrderQuality: 0,
    degradeCompleteOrderQualityScore: 0,
    degradeViolationsScore: 0,
    degradeComplaintCount: 1,
    degradeComplaintCountScore: 0
  } as FlfLevelConfigForm
});

const rightDialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    id: undefined,
    name: '',
    icon: '',
    status: true,
    statement: ''
  } as FlfLevelRightsForm
});

// Methods
const handleEditLevel = async (row) => {
  levelDialog.isEdit = !!row;
  // 打开弹窗前同步刷新一次权益列表，确保数据最新
  await getRightsList();
  levelDialog.visible = true;
  if (row) {
    // 处理回显数据，特别是需要从 *100 的整数转换回小数的部分
    const formData = JSON.parse(JSON.stringify(row));
    // 转换比例值：后端是整数 (*100)，前端展示是小数
    formData.holidayBonus = (formData.holidayBonus || 100) / 100;
    formData.upgradeOntimeRate = (formData.upgradeOntimeRate || 100) / 100;
    formData.upgradeComplaintRate = (formData.upgradeComplaintRate || 100) / 100;
    formData.degradeOntimeRate = (formData.degradeOntimeRate || 100) / 100;
    formData.degradeComplaintCount = (formData.degradeComplaintCount || 100) / 100;

    // 图片 ID 转换回字符串，以便 ImageUpload 回显
    formData.icon = formData.icon ? String(formData.icon) : '';
    formData.background = formData.background ? String(formData.background) : '';

    levelDialog.form = formData;
  } else {
    // Reset
    levelDialog.form = {
      id: undefined,
      lvNo: levelList.value.length + 1,
      name: '',
      icon: '',
      background: '',
      holidayBonus: 1,
      rights: [],
      upgradePoints: 0,
      upgradeCompleteOrderQuality: 0,
      upgradeOntimeRate: 1,
      upgradeComplaintRate: 1,
      upgradeViolationsCount: 0,
      degradePoints: 0,
      degradeOntimeRate: 1,
      degradeOntimeRateScore: 0,
      degradeCompleteOrderQuality: 0,
      degradeCompleteOrderQualityScore: 0,
      degradeViolationsScore: 0,
      degradeComplaintCount: 1,
      degradeComplaintCountScore: 0
    };
  }
};

const saveLevel = async () => {
  // 转换数据为后端需要的格式：小数 * 100 并取整
  const submitData = JSON.parse(JSON.stringify(levelDialog.form));

  submitData.holidayBonus = Math.round((submitData.holidayBonus || 0) * 100);
  submitData.upgradeOntimeRate = Math.round((submitData.upgradeOntimeRate || 0) * 100);
  submitData.upgradeComplaintRate = Math.round((submitData.upgradeComplaintRate || 0) * 100);
  submitData.degradeOntimeRate = Math.round((submitData.degradeOntimeRate || 0) * 100);
  submitData.degradeComplaintCount = Math.round((submitData.degradeComplaintCount || 0) * 100);

  // 图片处理：ImageUpload 返回的是逗号分隔的 ID 字符串，后端需要数字
  if (submitData.icon && typeof submitData.icon === 'string') {
    submitData.icon = submitData.icon.split(',')[0];
  }
  if (submitData.background && typeof submitData.background === 'string') {
    submitData.background = submitData.background.split(',')[0];
  }

  try {
    if (levelDialog.isEdit) {
      await updateLevelConfig(submitData);
      ElMessage.success('等级配置修改成功');
    } else {
      await addLevelConfig(submitData);
      ElMessage.success('等级配置新增成功');
    }
    levelDialog.visible = false;
    getLevelList();
  } catch (error) {
    console.error('Save level failed:', error);
  }
};

const handleDeleteLevel = (row) => {
  ElMessageBox.confirm(`确定要删除等级 "Lv.${row.lvNo}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await delLevelConfig(row.id);
      ElMessage.success('删除成功');
      getLevelList();
    } catch (error) {
      console.error('Delete level failed:', error);
    }
  }).catch(() => { });
};

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

const saveRight = async () => {
  if (!rightDialog.form.name) return ElMessage.warning('请输入权益名称');
  if (!rightDialog.form.icon) return ElMessage.warning('请选择权益图标');

  try {
    if (rightDialog.isEdit) {
      await updateLevelRights(rightDialog.form);
      ElMessage.success('权益编辑成功');
    } else {
      await addLevelRights(rightDialog.form);
      ElMessage.success('权益新增成功');
    }
    rightDialog.visible = false;
    getRightsList();
  } catch (error) {
    console.error('Save right failed:', error);
  }
};

const handleDeleteRight = (row) => {
  ElMessageBox.confirm(`确定要删除权益 "${row.name}" 吗？此操作不可撤销。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await delLevelRights(row.id);
      ElMessage.success('删除成功');
      getRightsList();
    } catch (error) {
      console.error('Delete right failed:', error);
    }
  }).catch(() => { });
};

const handleRightStatusChange = async (row) => {
  try {
    await changeLevelRightsStatus({ id: row.id, status: row.status });
    ElMessage.success(`权益 "${row.name}" 已${row.status ? '启用' : '停用'}`);
  } catch (error) {
    row.status = !row.status; // 切换失败恢复状态
    console.error('Update right status failed:', error);
  }
};

onMounted(() => {
  getRightsList();
  getLevelList();
});
</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>
