const express = require('express');
const multer = require('multer');
const path = require('path');
const COS = require('cos-nodejs-sdk-v5');
const { authenticate } = require('../middleware/auth');

const router = express.Router();

// COS配置从环境变量读取，不再硬编码密钥
const cos = new COS({
  SecretId: process.env.TENCENT_SECRET_ID,
  SecretKey: process.env.TENCENT_SECRET_KEY
});

const cosConfig = {
  Bucket: process.env.COS_BUCKET || 'qingyuan-erp-files-1310040146',
  Region: process.env.COS_REGION || 'ap-hongkong'
};

const imageFormats = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];

const upload = multer({ 
  storage: multer.memoryStorage(),
  limits: { fileSize: 50 * 1024 * 1024 }
});

// 所有上传接口都需要认证
router.post('/single', authenticate, upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ success: false, error: '没有上传文件' });
    }
    
    const ext = req.file.originalname.split('.').pop().toLowerCase();
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substring(2, 8);
    const filename = 'uploads/' + timestamp + '_' + randomStr + '.' + ext;
    
    
    cos.putObject({
      Bucket: cosConfig.Bucket,
      Region: cosConfig.Region,
      Key: filename,
      Body: req.file.buffer,
      ContentType: req.file.mimetype,
      ACL: 'public-read'
    }, (err, data) => {
      if (err) {
        console.error('COS 上传失败:', err);
        return res.status(500).json({ success: false, error: '上传失败' });
      }
      
      
      const permanentUrl = 'https://' + cosConfig.Bucket + '.cos.' + cosConfig.Region + '.myqcloud.com/' + filename;
      
      
      res.json({
        success: true,
        data: {
          url: permanentUrl,
          key: filename,
          name: req.file.originalname,
          size: req.file.size,
          type: req.file.mimetype,
          isImage: imageFormats.includes(ext)
        },
        message: '文件上传成功'
      });
    });
  } catch (error) {
    console.error('上传异常:', error);
    res.status(500).json({ success: false, error: '上传失败' });
  }
});

router.post('/multiple', authenticate, upload.array('files', 10), (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ success: false, error: '没有上传文件' });
    }
    
    const uploadPromises = req.files.map(file => {
      return new Promise((resolve, reject) => {
        const ext = file.originalname.split('.').pop().toLowerCase();
        const filename = 'uploads/' + Date.now() + '_' + Math.random().toString(36).substring(2, 8) + '.' + ext;
        
        cos.putObject({
          Bucket: cosConfig.Bucket,
          Region: cosConfig.Region,
          Key: filename,
          Body: file.buffer,
          ContentType: file.mimetype,
          ACL: 'public-read'
        }, (err, data) => {
          if (err) reject(err);
          else {
            const permanentUrl = 'https://' + cosConfig.Bucket + '.cos.' + cosConfig.Region + '.myqcloud.com/' + filename;
            resolve({
              url: permanentUrl,
              key: filename,
              name: file.originalname,
              size: file.size,
              isImage: imageFormats.includes(ext)
            });
          }
        });
      });
    });
    
    Promise.all(uploadPromises)
      .then(results => res.json({ success: true, data: results }))
      .catch(error => {
        console.error('批量上传失败:', error);
        res.status(500).json({ success: false, error: '上传失败' });
      });
  } catch (error) {
    console.error('批量上传异常:', error);
    res.status(500).json({ success: false, error: '上传失败' });
  }
});

module.exports = router;
