const API = require("../../lib/API");
const { v4: uuidv4 } = require('uuid');
const { BaseStdResponse } = require("../../BaseStdResponse");
const db = require("../../plugin/DataBase/db");
const AccessControl = require("../../lib/AccessControl");
const multer = require('multer');
const path = require('path');

const { url } = require("../../config.json")

// 配置Multer的存储选项
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/');
    },
    filename: (req, file, cb) => {
        const fileName = uuidv4();
        const fileExtension = path.extname(file.originalname);
        cb(null, `${fileName}${fileExtension}`);
    }
});

// 限制文件类型
const fileFilter = (req, file, cb) => {
    // 只接受以下扩展名的图片文件
    const allowedTypes = /jpeg|jpg|png|gif/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);

    if (extname && mimetype) {
        return cb(null, true);
    } else {
        cb(new Error('只允许上传图片文件 (jpeg, jpg, png, gif)'));
    }
};

// 初始化Multer中间件
const upload = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: { fileSize: 3 * 1024 * 1024 } // 限制文件大小为3MB
}).single('upload');

class UploadAvatar extends API {
    constructor() {
        super();

        this.noEncrypt()
        this.setMethod("POST");
        this.setPath("/UploadAvatar");
    }

    async onRequest(req, res) {
        // 使用Multer中间件处理文件上传
        upload(req, res, async (err) => {
            if (err) {
                this.logger.error(`图片上传失败！${err.stack || ''}`)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '图片上传失败！'
                });
            }

            let { uuid, session } = req.body

            if ([uuid, session].some(value => value === '' || value === null || value === undefined)) {
                return res.json({
                    ...BaseStdResponse.MISSING_PARAMETER,
                    endpoint: 1513126
                });
            }

            if (!await AccessControl.checkSession(uuid, session)) {
                return res.status(401).json({
                    ...BaseStdResponse.ACCESS_DENIED,
                    endpoint: 481545
                });
            }

            if (!req.file) {
                return res.json({
                    ...BaseStdResponse.MISSING_PARAMETER,
                    msg: '请上传图片文件'
                });
            }

            const picturePath = url + '/uploads/' + req.file.filename; // 获取文件路径

            let sql = 'UPDATE users SET avatar = ? WHERE uuid = ?'
            let r = await db.query(sql, [picturePath, uuid])
            if (r && r.affectedRows > 0)
                return res.json({
                    ...BaseStdResponse.OK,
                    data: {
                        picturePath
                    }
                });

            res.json({
                ...BaseStdResponse.ERR,
                msg: '上传头像失败！'
            })
        });
    }
}

module.exports.UploadAvatar = UploadAvatar;
