const API = require("../../lib/API")
const { v4: uuidv4 } = require('uuid')
const Redis = require('../../plugin/DataBase/Redis')
const db = require("../../plugin/DataBase/db.js")
const { BaseStdResponse } = require("../../BaseStdResponse")
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const { url } = require("../../config.json")

// 配置 Multer 存储选项
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        const { student_num } = req.body
        if (!student_num) {
            return cb(new Error('缺少参数'))
        }
        const destPath = path.join('uploads', 'faces', student_num)
        fs.mkdirSync(destPath, { recursive: true }) // 确保目录存在
        cb(null, destPath)
    },
    filename: (req, file, cb) => {
        const randomName = uuidv4()
        cb(null, `${randomName}.webm`)
    }
})

// 限制文件类型为 webm
const fileFilter = (req, file, cb) => {
    const extname = path.extname(file.originalname).toLowerCase() === ".webm"
    const mimetype = file.mimetype === "video/webm"
    if (extname && mimetype) {
        return cb(null, true)
    } else {
        cb(new Error('只允许上传 webm 格式的视频'))
    }
}

// 初始化 Multer
const upload = multer({
    storage: storage,
    fileFilter: fileFilter,
    limits: { fileSize: 200 * 1024 * 1024 } // 最大 200MB
}).single('upload')

class UploadFaceVideo extends API {
    constructor() {
        super()

        this.noEncrypt()
        this.setMethod("POST")
        this.setPath("/UploadFaceVideo")
    }

    async onRequest(req, res) {
        upload(req, res, async (err) => {
            if (err) {
                this.logger.error(`视频上传失败！${err.stack || ''}`)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: err.message ?? '视频上传失败！'
                })
            }

            const { student_num, key } = req.body

            if ([student_num, key].some(value => value === '' || value === null || value === undefined)) {
                return res.json({
                    ...BaseStdResponse.MISSING_PARAMETER
                })
            }

            if (!req.file) {
                return res.json({
                    ...BaseStdResponse.MISSING_PARAMETER,
                    msg: '请上传 webm 视频文件'
                })
            }

            try {
                const code = await Redis.get(`faceReco:${student_num}`)
                if (!code || code !== key)
                    return res.json({
                        ...BaseStdResponse.ERR,
                        msg: '令牌已过期！请刷新页面重试'
                    })

                await Redis.del(`faceReco:${student_num}`)
            } catch (err) {
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '令牌验证失败！请刷新页面重试'
                })
            }

            const videoPath = `/uploads/faces/${student_num}/${req.file.filename}`
            const videoUrl = `${url}/uploads/faces/${student_num}/${req.file.filename}`
            const time = new Date().getTime()

            let sql = 'UPDATE lepao_face SET video_path = ?, create_time = ?, state = ?, url = ? WHERE student_num = ?'
            let rows = await db.query(sql, [videoPath, time, 1, videoUrl, student_num])
            if (!rows || rows.affectedRows !== 1)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '上传失败，请稍后再试'
                })

            res.json({
                ...BaseStdResponse.OK
            })
        })
    }
}

module.exports.UploadFaceVideo = UploadFaceVideo
