const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { authAdmin } = require('../middleware/auth');
const { get, all, run } = require('../utils/db');
const { success, fail } = require('../utils/response');

const uploadDir = path.join(__dirname, '..', '..', 'uploads', 'banners');
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, uploadDir),
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    cb(null, 'banner_' + Date.now() + Math.random().toString(36).slice(2,6) + ext);
  }
});
const upload = multer({ storage, limits: { fileSize: 10 * 1024 * 1024 } });

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

// 添加轮播图
router.post('/add', authAdmin, upload.single("file"), (req, res) => {
  try {
    const { title, url, sort } = req.body;
    let imageUrl = req.body.image || '';
    if (req.file) imageUrl = '/uploads/banners/' + req.file.filename;
    if (!imageUrl) return res.json(fail('请上传图片'));
    
    const maxSort = get('SELECT MAX(sort) as max FROM banners');
    const newSort = sort || (maxSort?.max || 0) + 1;
    
    run('INSERT INTO banners (title, image, url, sort, status, created_at) VALUES (?,?,?,?,?,?)',
      [title || '', imageUrl, url || '', newSort, 1, new Date().toISOString()]);
    res.json(success(null, '添加成功'));
  } catch (e) {
    res.json(fail(e.message));
  }
});

// 编辑轮播图
router.put('/:id', authAdmin, upload.single("file"), (req, res) => {
  try {
    const { title, url, sort, status } = req.body;
    let imageUrl = req.body.image || '';
    if (req.file) imageUrl = '/uploads/banners/' + req.file.filename;
    
    const sets = [];
    const params = [];
    if (title !== undefined) { sets.push('title=?'); params.push(title); }
    if (url !== undefined) { sets.push('url=?'); params.push(url); }
    if (sort !== undefined) { sets.push('sort=?'); params.push(parseInt(sort)); }
    if (status !== undefined) { sets.push('status=?'); params.push(parseInt(status)); }
    if (imageUrl) { sets.push('image=?'); params.push(imageUrl); }
    
    if (sets.length === 0) return res.json(fail('没有要修改的字段'));
    params.push(req.params.id);
    run('UPDATE banners SET ' + sets.join(',') + ' WHERE id=?', params);
    res.json(success(null, '更新成功'));
  } catch (e) {
    res.json(fail(e.message));
  }
});

// 删除轮播图
router.delete('/:id', authAdmin, (req, res) => {
  try {
    const banner = get('SELECT * FROM banners WHERE id=?', [req.params.id]);
    if (banner && banner.image && banner.image.startsWith('/uploads/banners/')) {
      const filePath = path.join(__dirname, '..', '..', banner.image);
      if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
    }
    run('DELETE FROM banners WHERE id=?', [req.params.id]);
    res.json(success(null, '删除成功'));
  } catch (e) {
    res.json(fail(e.message));
  }
});

module.exports = router;
