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('/coupons', authAdmin, (req, res) => {
  const list = all('SELECT * FROM coupons ORDER BY id DESC');
  return res.json(success(list));
});

router.post('/coupons', authAdmin, demoSafeGuard, (req, res) => {
  const { name, type, value, min_amount, max_amount, total_count, per_limit, valid_days, start_time, end_time } = req.body;
  run('INSERT INTO coupons(name,type,value,min_amount,max_amount,total_count,per_limit,valid_days,start_time,end_time) VALUES(?,?,?,?,?,?,?,?,?,?)',
    [name, type, value, min_amount||0, max_amount||0, total_count||0, per_limit||1, valid_days||30, start_time||null, end_time||null]);
  return res.json(success(null, '添加成功'));
});

router.put('/coupons/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { name, type, value, min_amount, max_amount, total_count, per_limit, valid_days, start_time, end_time, status } = req.body;
  run('UPDATE coupons SET name=?,type=?,value=?,min_amount=?,max_amount=?,total_count=?,per_limit=?,valid_days=?,start_time=?,end_time=?,status=? WHERE id=?',
    [name, type, value, min_amount||0, max_amount||0, total_count||0, per_limit||1, valid_days||30, start_time||null, end_time||null, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

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

router.get('/seckill', authAdmin, (req, res) => {
  const list = all('SELECT sp.*, p.name,p.image FROM seckill_products sp JOIN products p ON sp.product_id=p.id ORDER BY sp.id DESC');
  return res.json(success(list));
});

router.post('/seckill', authAdmin, demoSafeGuard, (req, res) => {
  const { product_id, seckill_price, stock, per_limit, start_time, end_time } = req.body;
  run('INSERT INTO seckill_products(product_id,seckill_price,stock,per_limit,start_time,end_time) VALUES(?,?,?,?,?,?)',
    [product_id, seckill_price, stock||0, per_limit||1, start_time, end_time]);
  return res.json(success(null, '添加成功'));
});

router.put('/seckill/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { seckill_price, stock, per_limit, start_time, end_time, status } = req.body;
  run('UPDATE seckill_products SET seckill_price=?,stock=?,per_limit=?,start_time=?,end_time=?,status=? WHERE id=?',
    [seckill_price, stock||0, per_limit||1, start_time, end_time, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

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

router.get('/group-buy', authAdmin, (req, res) => {
  const list = all('SELECT gb.*, p.name,p.image FROM group_buy_products gb JOIN products p ON gb.product_id=p.id ORDER BY gb.id DESC');
  return res.json(success(list));
});

router.post('/group-buy', authAdmin, demoSafeGuard, (req, res) => {
  const { product_id, group_price, min_people, stock, start_time, end_time } = req.body;
  run('INSERT INTO group_buy_products(product_id,group_price,min_people,stock,start_time,end_time) VALUES(?,?,?,?,?,?)',
    [product_id, group_price, min_people||2, stock||0, start_time, end_time]);
  return res.json(success(null, '添加成功'));
});

router.put('/group-buy/:id', authAdmin, demoSafeGuard, (req, res) => {
  const { group_price, min_people, stock, start_time, end_time, status } = req.body;
  run('UPDATE group_buy_products SET group_price=?,min_people=?,stock=?,start_time=?,end_time=?,status=? WHERE id=?',
    [group_price, min_people||2, stock||0, start_time, end_time, status||1, req.params.id]);
  return res.json(success(null, '更新成功'));
});

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

// ========== 轮播图
router.get('/banners', authAdmin, (req, res) => {
  const list = all('SELECT * FROM banners ORDER BY sort ASC');
  return res.json(success(list));
});

router.post('/banners', authAdmin, demoSafeGuard, (req, res) => {
  const { title, image, url, sort } = req.body;
  run('INSERT INTO banners(title,image,url,sort) VALUES(?,?,?,?)', [title||'', image, url||'', sort||0]);
  return res.json(success(null, '添加成功'));
});

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

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

// ========== 满减满送活动管理 ==========
router.get('/promotions', authAdmin, (req, res) => {
  const {page:p=1,pageSize=15,keyword,type,status}=req.query;
  const pageNum=Math.max(1,+p);const size=Math.min(50,Math.max(1,+pageSize));
  let where='WHERE 1=1';const params=[];
  if(keyword){where+=' AND name LIKE ?';params.push('%'+keyword+'%')}
  if(type){where+=' AND type=?';params.push(type)}
  if(status!==undefined&&status!==''){where+=' AND status=?';params.push(+status)}
  const total=get(`SELECT COUNT(*) as c FROM promotions ${where}`,params).c;
  const list=all(`SELECT * FROM promotions ${where} ORDER BY id DESC LIMIT ? OFFSET ?`,[...params,size,(pageNum-1)*size]);
  res.json(page(list,total,pageNum,size));
});
router.get('/promotions/:id', authAdmin, (req, res) => {
  const p=get('SELECT * FROM promotions WHERE id=?',[req.params.id]);
  if(!p)return res.json(fail('活动不存在'));
  p.rules=JSON.parse(p.rules||'[]');p.scope_values=JSON.parse(p.scope_values||'[]');
  const logs=all('SELECT pl.*,u.nickname,o.order_no FROM promotion_logs pl LEFT JOIN users u ON pl.user_id=u.id LEFT JOIN orders o ON pl.order_id=o.id WHERE pl.promotion_id=? ORDER BY pl.id DESC LIMIT 20',[p.id]);
  const stats=get(`SELECT COUNT(DISTINCT user_id) as participants,COUNT(*) as orders,COALESCE(SUM(benefit_amount),0) as total_benefit FROM promotion_logs WHERE promotion_id=?`,[p.id]);
  res.json(success({...p,logs,...stats}));
});
router.post('/promotions', authAdmin, demoSafeGuard, (req, res) => {
  const {name,type,start_time,end_time,is_forever,scope_type,scope_values,rules,limit_type,limit_count,description,sort}=req.body;
  if(!name)return res.json(fail('请输入活动名称'));
  const r=run('INSERT INTO promotions(name,type,start_time,end_time,is_forever,scope_type,scope_values,rules,limit_type,limit_count,description,sort) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',
    [name,type||'full_reduce',start_time||null,end_time||null,is_forever||0,scope_type||'all',JSON.stringify(scope_values||[]),JSON.stringify(rules||[]),limit_type||'none',limit_count||0,description||'',sort||0]);
  res.json(success({id:r.lastInsertRowid},'创建成功'));
});
router.put('/promotions/:id', authAdmin, demoSafeGuard, (req, res) => {
  const {name,type,start_time,end_time,is_forever,scope_type,scope_values,rules,limit_type,limit_count,description,sort,status}=req.body;
  run("UPDATE promotions SET name=?,type=?,start_time=?,end_time=?,is_forever=?,scope_type=?,scope_values=?,rules=?,limit_type=?,limit_count=?,description=?,sort=?,status=?,updated_at=datetime('now','localtime') WHERE id=?",
    [name,type||'full_reduce',start_time||null,end_time||null,is_forever||0,scope_type||'all',JSON.stringify(scope_values||[]),JSON.stringify(rules||[]),limit_type||'none',limit_count||0,description||'',sort||0,status||1,req.params.id]);
  res.json(success(null,'更新成功'));
});
router.post('/promotions/:id/toggle', authAdmin, demoSafeGuard, (req, res) => {
  const p=get('SELECT status FROM promotions WHERE id=?',[req.params.id]);
  if(!p)return res.json(fail('活动不存在'));
  const newStatus=p.status===1?0:1;
  run('UPDATE promotions SET status=? WHERE id=?',[newStatus,req.params.id]);
  res.json(success({status:newStatus},newStatus?'已上架':'已下架'));
});
router.delete('/promotions/:id', authAdmin, demoSafeGuard, (req, res) => {
  run('DELETE FROM promotions WHERE id=?',[req.params.id]);
  run('DELETE FROM promotion_logs WHERE promotion_id=?',[req.params.id]);
  res.json(success(null,'已删除'));
});
router.get('/promotions/stats/overview', authAdmin, (req, res) => {
  const total=get('SELECT COUNT(*) as c FROM promotions').c;
  const active=get("SELECT COUNT(*) as c FROM promotions WHERE status=1").c;
  const totalBenefit=get('SELECT COALESCE(SUM(benefit_amount),0) as s FROM promotion_logs').s;
  const participants=get('SELECT COUNT(DISTINCT user_id) as c FROM promotion_logs').c;
  res.json(success({total,active,totalBenefit,participants}));
});


// ========== 营销数据统计 ==========
router.get('/marketing-stats', authAdmin, (req, res) => {
  const {range='7d'}=req.query;
  let days=7; if(range==='30d')days=30; else if(range==='3m')days=90; else if(range==='1y')days=365;
  const start=new Date(Date.now()-days*86400000).toISOString().split('T')[0];
  
  // 优惠券统计
  const couponTotal=get('SELECT COUNT(*) as c FROM coupons').c;
  const couponUsed=get('SELECT COALESCE(SUM(used_count),0) as c FROM coupons').c;
  const couponRate=couponTotal>0?Math.round(couponUsed/couponTotal*100):0;
  
  // 秒杀统计
  const seckillCount=get('SELECT COUNT(*) as c FROM seckill_products').c;
  const seckillOrders=get("SELECT COUNT(*) as c FROM orders WHERE created_at>=? AND status NOT IN ('pending_pay')",[start]).c||0;
  
  // 拼团统计
  const groupBuyCount=get('SELECT COUNT(*) as c FROM group_buy_products').c;
  const groupOrders=get('SELECT COUNT(*) as c FROM group_buy_orders').c;
  
  // 满减统计
  const promoOrders=get("SELECT COALESCE(SUM(order_count),0) as c FROM promotions").c;
  const promoDiscount=get("SELECT COALESCE(SUM(discount_total),0) as s FROM promotions").s;
  
  // 会员营收
  const memberRevenue=get("SELECT COALESCE(SUM(amount),0) as s FROM membership_renew_logs").s;
  const memberCount=get("SELECT COUNT(*) as c FROM user_memberships WHERE status='active'").c;
  
  // 趋势（按天）
  const trend=all(`SELECT date(created_at) as d,COUNT(*) as cnt FROM order_logs WHERE action='pay' AND created_at>=? GROUP BY d ORDER BY d`,[start]);
  
  res.json(success({couponTotal,couponUsed,couponRate:couponRate+'%',seckillCount,seckillOrders,groupBuyCount,groupOrders,promoOrders,promoDiscount,memberRevenue,memberCount,trend}));
});



module.exports = { router };
