const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { nanoid } = require('nanoid');
const config = require('../../config');
const { get, run, all } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authUser } = require('../middleware/auth');

// 注册
router.post('/register', async (req, res) => {
  try {
    const { phone, password, nickname, parent_id } = req.body;
    if (!phone || !password) return res.json(fail('手机号和密码不能为空'));
    if (!/^1\d{10}$/.test(phone)) return res.json(fail('手机号格式不正确'));
    if (password.length < 6) return res.json(fail('密码长度不能少于6位'));

    const exist = get('SELECT id FROM users WHERE phone = ?', [phone]);
    if (exist) return res.json(fail('该手机号已注册'));

    const hash = await bcrypt.hash(password, 10);
    const name = nickname || `用户${phone.slice(-4)}`;

    const result = run(
      'INSERT INTO users (phone, password, nickname, parent_id, created_at) VALUES (?,?,?,?,datetime(\'now\',\'localtime\'))',
      [phone, hash, name, parent_id || null]
    );

    return res.json(success({ id: result.lastInsertRowid }, '注册成功'));
  } catch (e) {
    console.error('注册失败:', e);
    return res.json(fail('注册失败'));
  }
});

// 登录
router.post('/login', async (req, res) => {
  try {
    const { phone, password } = req.body;
    if (!phone || !password) return res.json(fail('手机号和密码不能为空'));
    const ip = req.ip || req.headers['x-forwarded-for'] || '';

    const user = get('SELECT * FROM users WHERE phone = ?', [phone]);
    if (!user) {
      run('INSERT INTO login_logs(user_id,phone,ip,user_agent,result,reason) VALUES(?,?,?,?,?,?)',
        [null, phone, ip, (req.headers['user-agent']||'').slice(0,200), 'fail', '用户不存在']);
      return res.json(fail('用户不存在'));
    }
    if (user.status === 0) {
      run('INSERT INTO login_logs(user_id,phone,ip,user_agent,result,reason) VALUES(?,?,?,?,?,?)',
        [user.id, phone, ip, (req.headers['user-agent']||'').slice(0,200), 'fail', '账号被禁用']);
      return res.json(fail('账号已被禁用'));
    }

    const valid = await bcrypt.compare(password, user.password);
    if (!valid) {
      run('INSERT INTO login_logs(user_id,phone,ip,user_agent,result,reason) VALUES(?,?,?,?,?,?)',
        [user.id, phone, ip, (req.headers['user-agent']||'').slice(0,200), 'fail', '密码错误']);
      return res.json(fail('密码错误'));
    }

    const token = jwt.sign({ userId: user.id }, config.jwtSecret, { expiresIn: config.jwtExpiresIn });
    run('INSERT INTO login_logs(user_id,phone,ip,user_agent,result,reason) VALUES(?,?,?,?,?,?)',
      [user.id, phone, ip, (req.headers['user-agent']||'').slice(0,200), 'success', '']);

    return res.json(success({
      token,
      user: { id: user.id, phone: user.phone, nickname: user.nickname, avatar: user.avatar, level_id: user.level_id }
    }, '登录成功'));
  } catch (e) {
    console.error('登录失败:', e);
    return res.json(fail('登录失败'));
  }
});

// 获取用户信息（显式指定字段，避免泄露password/salt等敏感字段）
router.get('/info', authUser, (req, res) => {
  const user = get('SELECT id,phone,nickname,avatar,level_id,experience,balance,parent_id,created_at FROM users WHERE id=?', [req.userId]);
  if (!user) return res.json(fail('用户不存在'));
  const level = get('SELECT id,name,min_experience,description FROM user_levels WHERE id=?', [user.level_id]);
  return res.json(success({ ...user, level: level || null }));
});

// 更新个人信息
router.put('/info', authUser, (req, res) => {
  try {
    const { nickname, avatar } = req.body;
    if (nickname) run('UPDATE users SET nickname=? WHERE id=?', [nickname, req.userId]);
    if (avatar) run('UPDATE users SET avatar=? WHERE id=?', [avatar, req.userId]);
    return res.json(success(null, '更新成功'));
  } catch (e) {
    return res.json(fail('更新失败'));
  }
});

// 地址列表
router.get('/address', authUser, (req, res) => {
  const list = all('SELECT * FROM user_addresses WHERE user_id=? ORDER BY is_default DESC, id DESC', [req.userId]);
  return res.json(success(list));
});

// 新增地址
router.post('/address', authUser, (req, res) => {
  try {
    const { name, phone, province, city, district, detail, zip_code, is_default } = req.body;
    if (!name || !phone) return res.json(fail('请填写完整信息'));
    
    if (is_default) run('UPDATE user_addresses SET is_default=0 WHERE user_id=?', [req.userId]);
    const count = get('SELECT COUNT(*) as c FROM user_addresses WHERE user_id=?', [req.userId]);
    const def = is_default || count.c === 0 ? 1 : 0;

    const r = run(
      'INSERT INTO user_addresses(user_id,name,phone,province,city,district,detail,zip_code,is_default) VALUES(?,?,?,?,?,?,?,?,?)',
      [req.userId, name, phone, province||'', city||'', district||'', detail||'', zip_code||'', def]
    );
    return res.json(success({ id: r.lastInsertRowid }, '新增成功'));
  } catch (e) {
    return res.json(fail('新增失败'));
  }
});

// 编辑地址
router.put('/address/:id', authUser, (req, res) => {
  try {
    const addr = get('SELECT id FROM user_addresses WHERE id=? AND user_id=?', [req.params.id, req.userId]);
    if (!addr) return res.json(fail('地址不存在'));
    const { name, phone, province, city, district, detail, zip_code, is_default } = req.body;
    
    if (is_default) run('UPDATE user_addresses SET is_default=0 WHERE user_id=?', [req.userId]);
    
    run(`UPDATE user_addresses SET name=?,phone=?,province=?,city=?,district=?,detail=?,zip_code=?,is_default=?
      WHERE id=?`, [name, phone, province||'', city||'', district||'', detail||'', zip_code||'', is_default?1:0, req.params.id]);
    return res.json(success(null, '更新成功'));
  } catch (e) {
    return res.json(fail('更新失败'));
  }
});

// 删除地址
router.delete('/address/:id', authUser, (req, res) => {
  run('DELETE FROM user_addresses WHERE id=? AND user_id=?', [req.params.id, req.userId]);
  return res.json(success(null, '删除成功'));
});

// 设为默认
router.put('/address/:id/default', authUser, (req, res) => {
  run('UPDATE user_addresses SET is_default=0 WHERE user_id=?', [req.userId]);
  run('UPDATE user_addresses SET is_default=1 WHERE id=? AND user_id=?', [req.params.id, req.userId]);
  return res.json(success(null, '设置成功'));
});

// 用户等级信息
router.get('/level', authUser, (req, res) => {
  const user = get('SELECT level_id, experience FROM users WHERE id=?', [req.userId]);
  const current = get('SELECT * FROM user_levels WHERE id=?', [user.level_id]);
  const next = get('SELECT * FROM user_levels WHERE min_experience>? ORDER BY min_experience ASC LIMIT 1', [user.experience]);
  return res.json(success({ experience: user.experience, current_level: current, next_level: next }));
});

// 修改密码
router.put('/password', authUser, async (req, res) => {
  try {
    const { old_password, new_password } = req.body;
    if (!old_password || !new_password) return res.json(fail('请填写完整'));
    if (new_password.length < 6) return res.json(fail('密码长度不能少于6位'));
    
    const user = get('SELECT password FROM users WHERE id=?', [req.userId]);
    if (!await bcrypt.compare(old_password, user.password)) return res.json(fail('旧密码错误'));
    
    run('UPDATE users SET password=? WHERE id=?', [await bcrypt.hash(new_password, 10), req.userId]);
    return res.json(success(null, '修改成功'));
  } catch (e) {
    return res.json(fail('修改失败'));
  }
});

// ========== 收藏 ==========
// 添加收藏
router.post('/favorite', authUser, (req, res) => {
  try {
    const { product_id } = req.body;
    if (!product_id) return res.json(fail('参数错误'));
    const exist = get('SELECT id FROM user_favorites WHERE user_id=? AND product_id=?', [req.userId, product_id]);
    if (exist) return res.json(fail('已收藏'));
    run('INSERT INTO user_favorites(user_id,product_id) VALUES(?,?)', [req.userId, product_id]);
    return res.json(success(null, '收藏成功'));
  } catch (e) { return res.json(fail('收藏失败')); }
});

// 取消收藏
router.delete('/favorite/:productId', authUser, (req, res) => {
  run('DELETE FROM user_favorites WHERE user_id=? AND product_id=?', [req.userId, req.params.productId]);
  return res.json(success(null, '已取消收藏'));
});

// 收藏列表（支持检查单个商品是否收藏）
router.get('/favorites', authUser, (req, res) => {
  const { product_id } = req.query;
  if (product_id) {
    const fav = get('SELECT id FROM user_favorites WHERE user_id=? AND product_id=?', [req.userId, +product_id]);
    return res.json(success({ some: !!fav }));
  }
  const list = all(`SELECT uf.product_id, uf.created_at, p.name, p.image, p.price 
    FROM user_favorites uf JOIN products p ON uf.product_id=p.id 
    WHERE uf.user_id=? ORDER BY uf.id DESC`, [req.userId]);
  return res.json(success(list));
});

// ========== 用户通知 ==========
router.get('/notifications', authUser, (req, res) => {
  const list = all('SELECT * FROM notifications WHERE user_id=? OR user_id=0 ORDER BY id DESC LIMIT 50', [req.userId]);
  return res.json(success(list));
});

// 标记通知已读
router.put('/notifications/read', authUser, (req, res) => {
  run('UPDATE notifications SET is_read=1 WHERE user_id=?', [req.userId]);
  return res.json(success(null, '已读'));
});

// ========== 用户统计（我的页面用） ==========
// 单SQL GROUP BY保证一致性，避免并发下多次COUNT结果不一致
router.get('/stats', authUser, (req, res) => {
  const user = get('SELECT id,phone,nickname,avatar,level_id,experience,balance,points,total_points,parent_id,distributor_status,distributor_level FROM users WHERE id=?', [req.userId]);
  if (!user) return res.json(fail('用户不存在'));
  const level = get('SELECT id,name,min_experience,description FROM user_levels WHERE id=?', [user.level_id]);
  // 单次查询聚合所有订单状态计数，原子一致
  const counts = all("SELECT status, COUNT(*) as cnt FROM orders WHERE user_id=? AND status IN ('pending_pay','pending_ship','shipped','completed','refunding') GROUP BY status", [req.userId]);
  const orderCounts = { pending_pay: 0, pending_ship: 0, shipped: 0, completed: 0, refund: 0 };
  counts.forEach(r => {
    const key = r.status === 'refunding' ? 'refund' : r.status;
    if (key in orderCounts) orderCounts[key] = r.cnt;
  });
  return res.json(success({
    user: { id: user.id, phone: user.phone, nickname: user.nickname, avatar: user.avatar, level_id: user.level_id, experience: user.experience, balance: user.balance, points: user.points || 0, total_points: user.total_points || 0 },
    level: level || null,
    order_counts: orderCounts,
    has_distribution: user.distributor_status === 'active',
    distributor_level: user.distributor_level || 0,
    parent_id: user.parent_id
  }));
});

// ========== 浏览足迹 ==========
// 限制每人最多50条，超限自动裁剪尾部
router.get('/browse-history', authUser, (req, res) => {
  const list = all(`SELECT bh.product_id, bh.created_at, p.name, p.image, p.price 
    FROM browse_history bh JOIN products p ON bh.product_id=p.id 
    WHERE bh.user_id=? ORDER BY bh.id DESC LIMIT 50`, [req.userId]);
  return res.json(success(list));
});

router.post('/browse-history', authUser, (req, res) => {
  const pid = parseInt(req.body.product_id, 10);
  if (!pid || pid < 1) return res.json(fail('参数错误'));
  // 同商品去重（旧记录先删）
  run('DELETE FROM browse_history WHERE user_id=? AND product_id=?', [req.userId, pid]);
  run('INSERT INTO browse_history(user_id,product_id) VALUES(?,?)', [req.userId, pid]);
  // 裁剪超出50条的旧记录
  run(`DELETE FROM browse_history WHERE id NOT IN (
    SELECT id FROM browse_history WHERE user_id=? ORDER BY id DESC LIMIT 50
  ) AND user_id=?`, [req.userId, req.userId]);
  return res.json(success(null));
});

// ========== 短信验证码登录 ==========
// 接收 captchaStore（在 captcha.js 中定义的内存存储）
const smsLoginRouter = express.Router();

router.post('/sms-login', async (req, res) => {
  try {
    const { phone, sms_code } = req.body;
    if (!phone || !sms_code) return res.json(fail('手机号和验证码不能为空'));
    
    // 🔒 [安全] 服务端校验短信验证码：仅当该验证码确为该手机号下发且未过期（一次性）时放行，
    // 防止仅凭任意验证码绕过登录（原实现完全信任前端，可被直接伪造成登录/注册）。
    const { verifySms } = require('./captcha');
    if (!verifySms(phone, sms_code)) return res.json(fail('验证码错误或已过期'));

    // 查找或创建用户
    let user = get('SELECT * FROM users WHERE phone = ?', [phone]);
    
    if (!user) {
      // 自动注册新用户
      // 🔒 [安全] 密码不落短信验证码（6位，可被密码登录暴力破解），改为随机强口令
      const randPass = 'sms_' + require('crypto').randomBytes(16).toString('hex');
      const hash = await bcrypt.hash(randPass, 10);
      const nick = '用户' + phone.slice(-4);
      run("INSERT INTO users (phone, password, nickname, status, created_at, updated_at) VALUES (?, ?, ?, 1, datetime('now','localtime'), datetime('now','localtime'))",
        [phone, hash, nick]);
      user = get('SELECT * FROM users WHERE phone = ?', [phone]);
    }
    
    if (!user) return res.json(fail('登录失败'));
    if (user.status === 0) return res.json(fail('账号已被禁用'));
    
    const token = jwt.sign({ userId: user.id }, config.jwtSecret, { expiresIn: config.jwtExpiresIn });
    
    const ip = req.ip || req.headers['x-forwarded-for'] || '';
    run('INSERT INTO login_logs(user_id,phone,ip,user_agent,result,reason) VALUES(?,?,?,?,?,?)',
      [user.id, phone, ip, (req.headers['user-agent']||'').slice(0,200), 'success', '短信登录']);
    
    return res.json(success({
      token,
      user: {
        id: user.id,
        nickname: user.nickname,
        avatar: user.avatar,
        phone: user.phone,
        balance: user.balance,
        level_id: user.level_id
      }
    }, '登录成功'));
  } catch (e) {
    console.error('短信登录异常:', e);
    return res.json(fail('登录失败'));
  }
});

// ===================================================================
// 微信小程序登录 - POST /api/user/wx-login
// 接收: { code, encryptedData, iv } 或只 { code } 静默登录
// 流程: code -> 微信API获取openid -> 查找/创建用户 -> 返回JWT token
// ===================================================================
router.post('/wx-login', async (req, res) => {
  try {
    const { code, encryptedData, iv } = req.body;
    if (!code) return res.json(fail('code不能为空'));

    // ===== 模拟环境：直接生成mock openid =====
    // 生产环境需替换为真实微信API调用:
    //   GET https://api.weixin.qq.com/sns/jscode2session
    //   ?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code
    const mockOpenid = 'mock_openid_' + code.slice(-8);
    const mockSessionKey = 'mock_session_' + require('crypto').randomBytes(8).toString('hex');

    // 尝试通过openid查找已有用户
    let user = get('SELECT * FROM users WHERE openid=?', [mockOpenid]);

    if (!user && encryptedData && iv) {
      // 有手机号授权时，创建新用户（模拟解密）
      const mockPhone = '1' + String(Math.floor(100000000 + Math.random() * 900000000));
      const nick = '微信用户' + mockOpenid.slice(-4);
      const hash = await bcrypt.hash(mockPhone.slice(-6), 10);

      run("INSERT INTO users(phone,password,nickname,openid,level_id,status,created_at) VALUES(?,?,?,?,1,1,datetime('now','localtime'))",
        [mockPhone, hash, nick, mockOpenid]);

      user = get('SELECT * FROM users WHERE openid=?', [mockOpenid]);
    }

    if (!user) {
      // 静默登录模式，没有phone授权时，创建一个临时用户
      const tmpPhone = '1' + String(Math.floor(100000000 + Math.random() * 900000000));
      const tmpNick = '微信用户_' + mockOpenid.slice(-4);
      const tmpHash = await bcrypt.hash(mockOpenid.slice(-6), 10);

      run("INSERT INTO users(phone,password,nickname,openid,level_id,status,created_at) VALUES(?,?,?,?,1,1,datetime('now','localtime'))",
        [tmpPhone, tmpHash, tmpNick, mockOpenid]);

      user = get('SELECT * FROM users WHERE openid=?', [mockOpenid]);
    }

    if (user.status === 0) return res.json(fail('账号已被禁用'));

    const token = jwt.sign({ userId: user.id }, config.jwtSecret, { expiresIn: config.jwtExpiresIn });

    run('INSERT INTO login_logs(user_id,phone,ip,user_agent,result,reason) VALUES(?,?,?,?,?,?)',
      [user.id, user.phone, req.ip || '', '微信小程序登录', 'success', 'wx-login']);

    return res.json(success({
      token,
      user: {
        id: user.id,
        nickname: user.nickname,
        avatar: user.avatar,
        phone: user.phone,
        balance: user.balance,
        level_id: user.level_id,
        openid: mockOpenid
      }
    }, '登录成功'));
  } catch (e) {
    console.error('微信登录异常:', e);
    return res.json(fail('登录失败: ' + e.message));
  }
});

// ========== 会员积分（独立积分，与经验值/等级解耦） ==========
// 积分余额
router.get('/points', authUser, (req, res) => {
  try {
    const pts = require('../lib/points');
    const bal = pts.getBalance(req.userId);
    return res.json(success(bal));
  } catch (e) { return res.json(fail('获取积分失败')); }
});
// 积分明细（分页）
router.get('/points/logs', authUser, (req, res) => {
  try {
    const pts = require('../lib/points');
    const page = Math.max(1, parseInt(req.query.page) || 1);
    const size = Math.min(50, Math.max(1, parseInt(req.query.pageSize) || 20));
    const r = pts.getLogs(req.userId, page, size);
    return res.json(success(r));
  } catch (e) { return res.json(fail('获取积分明细失败')); }
});

module.exports = router;
