const express = require('express');
const router = express.Router();
const { get, run, all, transaction } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');
const { demoSafeGuard } = require("./admin-auth");

// ========== 会员管理 ==========
router.get('/users', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 20, keyword, level_id } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));
  let where = "WHERE phone != 'admin'";
  const params = [];
  if (keyword) { where += ' AND (nickname LIKE ? OR phone LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`); }
  if (level_id) { where += ' AND level_id=?'; params.push(level_id); }

  const total = get(`SELECT COUNT(*) as c FROM users ${where}`, params).c;
  const list = all(`SELECT u.*, l.name as level_name FROM users u LEFT JOIN user_levels l ON u.level_id=l.id ${where} ORDER BY u.id DESC LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]);
  list.forEach(u => delete u.password);
  return res.json(page(list, total, pageNum, size));
});

router.get('/users/:id', authAdmin, (req, res) => {
  const user = get('SELECT u.*, l.name as level_name FROM users u LEFT JOIN user_levels l ON u.level_id=l.id WHERE u.id=?', [req.params.id]);
  if (!user) return res.json(fail('用户不存在'));
  delete user.password;
  return res.json(success(user));
});

router.put('/users/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { nickname, phone, level_id, status, balance } = req.body;
  run('UPDATE users SET nickname=?,phone=?,level_id=?,status=?,balance=? WHERE id=?',
    [nickname, phone, level_id, status||1, balance||0, req.params.id]);
  return res.json(success(null, '更新成功'));
});

// 用户等级管理
router.get('/levels', authAdmin, (req, res) => {
  const list = all('SELECT * FROM user_levels ORDER BY level ASC');
  return res.json(success(list));
});

router.post('/levels', authAdmin, demoSafeGuard, (req, res) => {
  const { name, level, min_experience, discount, icon, description } = req.body;
  const r = run('INSERT INTO user_levels(name,level,min_experience,discount,icon,description) VALUES(?,?,?,?,?,?)',
    [name, level, min_experience||0, discount||1.00, icon||'', description||'']);
  const levelId = r.lastInsertRowid;
  // 自动生成4种套餐类型
  const plans = [
    { type:'monthly', suffix:'月卡', months:1 },
    { type:'quarterly', suffix:'季卡', months:3 },
    { type:'yearly', suffix:'年卡', months:12 },
    { type:'permanent', suffix:'终身卡', months:0 },
  ];
  for (const p of plans) {
    run('INSERT INTO membership_plans(name,type,price,original_price,level_id,description,sort) VALUES(?,?,?,?,?,?,?)',
      [`${name}${p.suffix}`, p.type, 0, 0, levelId, `${name}${p.suffix}，享${Math.round((1-(discount||1))*100)}%折扣`, plans.indexOf(p)]);
  }
  return res.json(success({ id: levelId }, '添加成功，已自动生成4种套餐'));
});

router.put('/levels/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { name, min_experience, discount, icon, description } = req.body;
  run('UPDATE user_levels SET name=?,min_experience=?,discount=?,icon=?,description=? WHERE id=?',
    [name, min_experience||0, discount||1.00, icon||'', description||'', req.params.id]);
  return res.json(success(null, '更新成功'));
});

router.delete('/levels/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM user_levels WHERE id=?', [req.params.id]);
  return res.json(success(null, '删除成功'));
});

// 会员套餐
router.get('/plans', authAdmin, (req, res) => {
  const list = all('SELECT mp.*, l.name as level_name FROM membership_plans mp LEFT JOIN user_levels l ON mp.level_id=l.id ORDER BY mp.sort ASC');
  return res.json(success(list));
});

router.post('/plans', authAdmin, demoSafeGuard, (req, res) => {
  const { name, type, price, original_price, level_id, give_experience, give_coupon_ids, description, sort } = req.body;
  run('INSERT INTO membership_plans(name,type,price,original_price,level_id,give_experience,give_coupon_ids,description,sort) VALUES(?,?,?,?,?,?,?,?,?)',
    [name, type, price, original_price||0, level_id||null, give_experience||0, give_coupon_ids||'', description||'', sort||0]);
  return res.json(success(null, '添加成功'));
});

router.put('/plans/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { name, type, price, original_price, level_id, give_experience, give_coupon_ids, description, sort, status } = req.body;
  run('UPDATE membership_plans SET name=?,type=?,price=?,original_price=?,level_id=?,give_experience=?,give_coupon_ids=?,description=?,sort=?,status=? WHERE id=?',
    [name, type, price, original_price||0, level_id||null, give_experience||0, give_coupon_ids||'', description||'', sort||0, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

router.delete('/plans/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM membership_plans WHERE id=?', [req.params.id]);
  return res.json(success(null, '删除成功'));
});


module.exports = { router };
