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");
const { checkProductLimit } = require('../lib/limits');

// 辅助：记录操作日志
function logAction(adminId, action, module, targetId, detail, ip) {
  try {
    run('INSERT INTO operation_logs(admin_id,action,module,target_id,detail,ip) VALUES(?,?,?,?,?,?)',
      [adminId, action, module, targetId||null, detail||'', ip||'']);
  } catch(e) {}
}

// 复制商品
router.post('/products/:id/copy', authAdmin, demoSafeGuard, (req, res) => {
  try {
    // 免费版商品数量检查
    const limitCheck = checkProductLimit();
    if (!limitCheck.ok) {
      return res.json(fail(limitCheck.message, 403));
    }
    
    const p = get('SELECT * FROM products WHERE id=?', [req.params.id]);
    if (!p) return res.json(fail('商品不存在'));
    const r = run(`INSERT INTO products(name,subtitle,category_id,image,images,price,original_price,cost_price,stock,unit,spec_type,description,is_new,is_hot,is_recommend,sort,weight,seo_keywords,seo_description)
      VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
      [p.name+'(复制)', p.subtitle, p.category_id, p.image, p.images, p.price, p.original_price, p.cost_price, p.stock||0, p.unit||'件', p.spec_type||0, p.description, 0, 0, 0, 0, p.weight||0, p.seo_keywords||'', p.seo_description||'']);
    // 复制SKU
    const skus = all('SELECT * FROM product_skus WHERE product_id=?', [p.id]);
    for (const sku of skus) {
      run('INSERT INTO product_skus(product_id,sku_code,image,specs,price,original_price,cost_price,stock,weight,sort) VALUES(?,?,?,?,?,?,?,?,?,?)',
        [r.lastInsertRowid, sku.sku_code||'', sku.image||'', sku.specs||'[]', sku.price, sku.original_price||0, sku.cost_price||0, sku.stock||0, sku.weight||0, sku.sort||0]);
    }
    logAction(req.userId, 'copy', 'product', r.lastInsertRowid, '复制商品: '+p.name, req.ip);
    return res.json(success({id: r.lastInsertRowid}, '复制成功'));
  } catch(e) { return res.json(fail('复制失败')); }
});

// 批量更新库存
router.post('/products/batch-stock', authAdmin, demoSafeGuard, (req, res) => {
  try {
    const { items } = req.body; // [{product_id, stock}]
    if (!items || !items.length) return res.json(fail('请提供数据'));
    for (const item of items) {
      run('UPDATE products SET stock=?,updated_at=datetime(\'now\',\'localtime\') WHERE id=?', [item.stock, item.product_id]);
    }
    return res.json(success(null, '更新成功'));
  } catch(e) { return res.json(fail('更新失败')); }
});


// ========== 商品SKU/规格管理 ==========
router.post('/products/:id/skus', authAdmin, demoSafeGuard, (req, res) => {
  try {
    const { sku_code, image, specs, price, original_price, cost_price, stock, weight, bar_code, sort } = req.body;
    const p = get('SELECT id FROM products WHERE id=?', [req.params.id]);
    if (!p) return res.json(fail('商品不存在'));
    const r = run(`INSERT INTO product_skus(product_id,sku_code,image,specs,price,original_price,cost_price,stock,weight,bar_code,sort)
      VALUES(?,?,?,?,?,?,?,?,?,?,?)`,
      [req.params.id, sku_code||'', image||'', JSON.stringify(specs||[]), price, original_price||0, cost_price||0, stock||0, weight||0, bar_code||'', sort||0]);
    logAction(req.userId, 'add_sku', 'product', req.params.id, `添加SKU`, req.ip);
    return res.json(success({id: r.lastInsertRowid}, '添加成功'));
  } catch(e) { return res.json(fail('添加失败')); }
});

router.put('/products/:id/skus/:sid', authAdmin, demoSafeGuard, (req, res) => {
  try {
    const { sku_code, image, specs, price, original_price, cost_price, stock, weight, bar_code, sort } = req.body;
    run(`UPDATE product_skus SET sku_code=?,image=?,specs=?,price=?,original_price=?,cost_price=?,stock=?,weight=?,bar_code=?,sort=? WHERE id=? AND product_id=?`,
      [sku_code||'', image||'', JSON.stringify(specs||[]), price, original_price||0, cost_price||0, stock||0, weight||0, bar_code||'', sort||0, req.params.sid, req.params.id]);
    logAction(req.userId, 'update_sku', 'product', req.params.id, `更新SKU`, req.ip);
    return res.json(success(null, '更新成功'));
  } catch(e) { return res.json(fail('更新失败')); }
});

router.delete('/products/:id/skus/:sid', authAdmin, demoSafeGuard, (req, res) => {
});

router.post('/products/:id/specs', authAdmin, demoSafeGuard, (req, res) => {
  try {
    const { name, spec_values, sort } = req.body;
    const p = get('SELECT id FROM products WHERE id=?', [req.params.id]);
    if (!p) return res.json(fail('商品不存在'));
    const r = run('INSERT INTO product_specs(product_id,name,spec_values,sort) VALUES(?,?,?,?)',
      [req.params.id, name, JSON.stringify(spec_values||[]), sort||0]);
    logAction(req.userId, 'add_spec', 'product', req.params.id, `添加规格: ${name}`, req.ip);
    return res.json(success({id: r.lastInsertRowid}, '添加成功'));
  } catch(e) { return res.json(fail('添加失败')); }
});

router.delete('/products/:id/specs/:sid', authAdmin, demoSafeGuard, (req, res) => {
});

// ========== 商品管理 ==========
router.get('/products', authAdmin, (req, res) => {
  const { page: p = 1, pageSize = 20, keyword, category_id, status } = req.query;
  const pageNum = Math.max(1, +p);
  const size = Math.min(100, Math.max(1, +pageSize));
  let where = 'WHERE 1=1';
  const params = [];
  if (keyword) { where += ' AND name LIKE ?'; params.push(`%${keyword}%`); }
  if (category_id) { where += ' AND category_id=?'; params.push(category_id); }
  if (status !== undefined && status !== '') { where += ' AND status=?'; params.push(status); }

  const total = get(`SELECT COUNT(*) as c FROM products ${where}`, params).c;
  const list = all(`SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id=c.id ${where} ORDER BY p.id DESC LIMIT ? OFFSET ?`,
    [...params, size, (pageNum - 1) * size]);
  return res.json(page(list, total, pageNum, size));
});

// 免费版商品数量限制

router.post('/products', authAdmin, demoSafeGuard, (req, res) => {
  try {
    // 免费版商品数量检查
    const limitCheck = checkProductLimit();
    if (!limitCheck.ok) {
      return res.json(fail(limitCheck.message, 403));
    }
    
    const { name, subtitle, category_id, image, images, price, original_price, cost_price, stock, unit,
      spec_type, description, is_new, is_hot, is_recommend, sort, weight, shipping_template_id, seo_keywords, seo_description,
      member_rates, commission_rate, is_flash_sale, flash_sale_config, is_group_buy, group_buy_config,
      publish_time, stock_warning, is_hidden, bar_code, min_qty, max_qty,
      brief, command_code, service_guarantees, product_params, recommend_image,
      give_points, give_coupon_id, is_limited, is_pre_sale, pre_sale_time, is_premium, fake_sales } = req.body;
    if (!name || name.length > 200) return res.json(fail('请输入商品名称（200字以内）'));
    if (!price || price <= 0) return res.json(fail('价格必须大于0'));

    const r = run(`INSERT INTO products(name,subtitle,category_id,image,images,price,original_price,cost_price,stock,unit,
      spec_type,description,is_new,is_hot,is_recommend,sort,weight,shipping_template_id,seo_keywords,seo_description,
      member_rates,commission_rate,is_flash_sale,flash_sale_config,is_group_buy,group_buy_config,
      publish_time,stock_warning,is_hidden,bar_code,min_qty,max_qty,
      brief,command_code,service_guarantees,product_params,recommend_image,
      give_points,give_coupon_id,is_limited,is_pre_sale,pre_sale_time,is_premium,fake_sales)
      VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,
      ?,?,?,?,?,?,?,?,?,?,?,?,
      ?,?,?,?,?,
      ?,?,?,?,?,?,?)`,
      [name, subtitle||'', category_id||null, image||'', JSON.stringify(images||[]), price, original_price||0, cost_price||0, stock||0, unit||'件',
       spec_type||0, description||'', is_new||0, is_hot||0, is_recommend||0, sort||0, weight||0, shipping_template_id||null, seo_keywords||'', seo_description||'',
       JSON.stringify(member_rates||[]), commission_rate||0, is_flash_sale||0, JSON.stringify(flash_sale_config||{}), is_group_buy||0, JSON.stringify(group_buy_config||{}),
       publish_time||'', stock_warning||0, is_hidden||0, bar_code||'', min_qty||1, max_qty||999,
       brief||'', command_code||'', JSON.stringify(service_guarantees||[]), JSON.stringify(product_params||[]), recommend_image||'',
       give_points||0, give_coupon_id||0, is_limited||0, is_pre_sale||0, pre_sale_time||'', is_premium||0, fake_sales||0]);
    logAction(req.userId, 'add', 'product', r.lastInsertRowid, `添加商品: ${name}`, req.ip);
    return res.json(success({ id: r.lastInsertRowid }, '添加成功'));
  } catch (e) { return res.json(fail('添加失败')); }
});

router.get('/products/:id', authAdmin, (req, res) => {
  const product = get('SELECT * FROM products WHERE id=?', [req.params.id]);
  if (!product) return res.json(fail('商品不存在'));
  product.images = JSON.parse(product.images || '[]');
  product.member_rates = JSON.parse(product.member_rates || '[]');
  product.flash_sale_config = JSON.parse(product.flash_sale_config || '{}');
  product.group_buy_config = JSON.parse(product.group_buy_config || '{}');
  product.service_guarantees = JSON.parse(product.service_guarantees || '[]');
  product.product_params = JSON.parse(product.product_params || '[]');
  product.skus = all('SELECT * FROM product_skus WHERE product_id=? ORDER BY sort', [product.id]);
  product.specs = all('SELECT * FROM product_specs WHERE product_id=? ORDER BY sort', [product.id]);
  product.specs.forEach(s => s.values = JSON.parse(s.spec_values || '[]'));
  return res.json(success(product));
});

router.put('/products/:id', authAdmin, demoSafeGuard, (req, res) => {
  try {
    const { name, subtitle, category_id, image, images, price, original_price, cost_price, stock, unit,
      spec_type, description, is_new, is_hot, is_recommend, sort, weight, shipping_template_id, seo_keywords, seo_description, status, skus, specs,
      member_rates, commission_rate, is_flash_sale, flash_sale_config, is_group_buy, group_buy_config,
      publish_time, stock_warning, is_hidden, bar_code, min_qty, max_qty,
      brief, command_code, service_guarantees, product_params, recommend_image,
      give_points, give_coupon_id, is_limited, is_pre_sale, pre_sale_time, is_premium, fake_sales } = req.body;
    if (!name) return res.json(fail('商品名称不能为空'));
    
    run(`UPDATE products SET name=?,subtitle=?,category_id=?,image=?,images=?,price=?,original_price=?,cost_price=?,
      stock=?,unit=?,spec_type=?,description=?,is_new=?,is_hot=?,is_recommend=?,sort=?,weight=?,shipping_template_id=?,
      seo_keywords=?,seo_description=?,status=?,member_rates=?,commission_rate=?,is_flash_sale=?,flash_sale_config=?,
      is_group_buy=?,group_buy_config=?,publish_time=?,stock_warning=?,is_hidden=?,bar_code=?,min_qty=?,max_qty=?,
      brief=?,command_code=?,service_guarantees=?,product_params=?,recommend_image=?,
      give_points=?,give_coupon_id=?,is_limited=?,is_pre_sale=?,pre_sale_time=?,is_premium=?,fake_sales=?,
      updated_at=datetime('now','localtime') WHERE id=?`,
      [name, subtitle||'', category_id||null, image||'', JSON.stringify(images||[]), price, original_price||0, cost_price||0,
       stock||0, unit||'件', spec_type||0, description||'', is_new||0, is_hot||0, is_recommend||0, sort||0, weight||0,
       shipping_template_id||null, seo_keywords||'', seo_description||'', status||1,
       JSON.stringify(member_rates||[]), commission_rate||0, is_flash_sale||0, JSON.stringify(flash_sale_config||{}),
       is_group_buy||0, JSON.stringify(group_buy_config||{}), publish_time||'', stock_warning||0, is_hidden||0, bar_code||'',
       min_qty||1, max_qty||999,
       brief||'', command_code||'', JSON.stringify(service_guarantees||[]), JSON.stringify(product_params||[]), recommend_image||'',
       give_points||0, give_coupon_id||0, is_limited||0, is_pre_sale||0, pre_sale_time||'', is_premium||0, fake_sales||0,
       req.params.id]);

    // 更新SKU
    if (skus && Array.isArray(skus)) {
      run('DELETE FROM product_skus WHERE product_id=?', [req.params.id]);
      for (const sku of skus) {
        run('INSERT INTO product_skus(product_id,sku_code,image,specs,price,original_price,cost_price,stock,weight,sort) VALUES(?,?,?,?,?,?,?,?,?,?)',
          [req.params.id, sku.sku_code||'', sku.image||'', JSON.stringify(sku.specs||[]), sku.price, sku.original_price||0, sku.cost_price||0, sku.stock||0, sku.weight||0, sku.sort||0]);
      }
    }
    // 更新规格
    if (specs && Array.isArray(specs)) {
      run('DELETE FROM product_specs WHERE product_id=?', [req.params.id]);
      for (const spec of specs) {
        run('INSERT INTO product_specs(product_id,name,spec_values,sort) VALUES(?,?,?,?)',
          [req.params.id, spec.name, JSON.stringify(spec.values||[]), spec.sort||0]);
      }
    }

    logAction(req.userId, 'update', 'product', +req.params.id, `更新商品: ${name}`, req.ip);
    return res.json(success(null, '更新成功'));
  } catch (e) { return res.json(fail('更新失败')); }
});

router.delete('/products/:id', authAdmin, demoSafeGuard, (req, res) => {
  const p = get('SELECT name FROM products WHERE id=?', [req.params.id]);
  run('DELETE FROM product_skus WHERE product_id=?', [req.params.id]);
  run('DELETE FROM product_specs WHERE product_id=?', [req.params.id]);
  run('DELETE FROM product_images WHERE product_id=?', [req.params.id]);
  run('DELETE FROM products WHERE id=?', [req.params.id]);
  logAction(req.userId, 'delete', 'product', +req.params.id, `删除商品: ${p?.name||''}`, req.ip);
  return res.json(success(null, '删除成功'));
});

router.put('/products/:id/status', authAdmin, demoSafeGuard, (req, res) => {
  const { status } = req.body;
  const p = get('SELECT name FROM products WHERE id=?', [req.params.id]);
  run('UPDATE products SET status=?,updated_at=datetime(\'now\',\'localtime\') WHERE id=?', [status, req.params.id]);
  logAction(req.userId, status?'online':'offline', 'product', +req.params.id, `${status?'上架':'下架'}商品: ${p?.name||''}`, req.ip);
  return res.json(success(null, status ? '已上架' : '已下架'));
});

// ========== 分类管理 ==========
router.get('/categories', authAdmin, (req, res) => {
  const list = all('SELECT * FROM categories ORDER BY sort ASC');
  return res.json(success(list));
});

router.post('/categories', authAdmin, demoSafeGuard, (req, res) => {
  const { name, pid, icon, image, sort } = req.body;
  if (!name) return res.json(fail('分类名称不能为空'));
  const r = run('INSERT INTO categories(name,pid,icon,image,sort) VALUES(?,?,?,?,?)',
    [name, pid||0, icon||'', image||'', sort||0]);
  return res.json(success({ id: r.lastInsertRowid }, '添加成功'));
});

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

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

module.exports = { router };
