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

// 配置Multer的存储选项
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/avatar/');
    },
    filename: (req, file, cb) => {
        const uuid = req.params.uuid;
        const fileExtension = path.extname(file.originalname);
        cb(null, `${uuid}${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('avatar');

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

        this.setMethod("POST");
        this.setPath("/User/UploadAvatar/:uuid/:session");
    }

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

            let { uuid, session } = req.params;

            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.json({
                    ...BaseStdResponse.ACCESS_DENIED,
                    endpoint: 48153145
                });
            }

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

            const avatarPath = `/avatar/${req.file.filename}`; // 获取文件路径

            let sql = 'UPDATE users SET avatar = ? WHERE uuid = ?';
            let result = await db.query(sql, [avatarPath, uuid]);

            if (result && result.affectedRows > 0) {
                sql = 'SELECT username, wxid, avatar, email FROM users WHERE uuid = ?';
                let rows = await db.query(sql, [uuid]);

                if (!rows || rows.length === 0) {
                    return res.json({
                        ...BaseStdResponse.DATABASE_ERR
                    });
                }

                res.json({
                    ...BaseStdResponse.OK,
                    data: {
                        uuid,
                        username: rows[0].username,
                        wxid: rows[0].wxid,
                        email: rows[0].email,
                        avatar: rows[0].avatar,
                        session
                    }
                });
            } else {
                res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '头像更新失败！' });
            }
        });
    }
}

module.exports.UploadAvatar = UploadAvatar;
