const express = require('express');
const router = express.Router();
const multer = require('multer');
const OSS = require('ali-oss');
const config = require('../config/oss');
const path = require('path');
const fs = require('fs');

// 确保上传目录存在
const uploadsDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}

const upload = multer({
    storage: multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // 限制5MB
    }
}).array('images');

router.post('/upload-images', (req, res) => {
    upload(req, res, async function(err) {
        if (err instanceof multer.MulterError) {
            console.error('Multer error:', err);
            return res.status(400).json({ error: '文件上传错误: ' + err.message });
        } else if (err) {
            console.error('Unknown error:', err);
            return res.status(500).json({ error: '未知错误: ' + err.message });
        }

        try {
            if (!req.files || req.files.length === 0) {
                return res.status(400).json({ error: '没有上传文件' });
            }

            // 验证OSS配置
            if (!config.accessKeyId || !config.accessKeySecret || !config.bucket || !config.endpoint) {
                console.error('OSS configuration missing:', config);
                return res.status(500).json({ error: 'OSS配置错误' });
            }

            const client = new OSS({
                accessKeyId: config.accessKeyId,
                accessKeySecret: config.accessKeySecret,
                bucket: config.bucket,
                endpoint: config.endpoint,
                secure: true
            });

            const uploadPromises = req.files.map(async file => {
                try {
                    const fileExt = file.originalname.split('.').pop().toLowerCase();
                    
                    // 验证文件类型
                    const allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
                    if (!allowedTypes.includes(fileExt)) {
                        throw new Error(`不支持的文件类型: ${fileExt}`);
                    }

                    const uniqueId = Math.random().toString(36).substring(2) + Date.now();
                    const fileName = `ueditor/${uniqueId}.${fileExt}`;
                    
                    console.log('Uploading file to OSS:', fileName);
                    const result = await client.put(fileName, file.buffer);
                    console.log('Upload result:', result);
                    
                    return {
                        url: `https://${config.bucket}.${config.endpoint}/${fileName}`,
                        name: fileName.split('/').pop()
                    };
                } catch (error) {
                    console.error('Individual file upload error:', error);
                    throw new Error(`文件 ${file.originalname} 上传失败: ${error.message}`);
                }
            });

            console.log('Processing all uploads...');
            const results = await Promise.all(uploadPromises);
            console.log('Upload results:', results);
            
            res.json(results);

        } catch (error) {
            console.error('Upload error:', error);
            res.status(500).json({ 
                error: error.message || '上传失败',
                details: error.stack
            });
        }
    });
});

module.exports = router; 