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

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

        this.runpy = config.runpy

        this.setPath('/Face/BeginFaceReco')
        this.setMethod('POST')
    }

    /**
     * 获取图片并转换为Base64
     * @param {string} url - 图片链接
     * @returns {Promise<string>} - Base64字符串
     */
    async getImageBase64(url) {
        try {
            const response = await axios.get(url, {
                proxy: false,
                responseType: "arraybuffer"
            })
            const base64 = Buffer.from(response.data, "binary").toString("base64")

            // 获取图片MIME类型
            const contentType = response.headers["content-type"]
            return `data:${contentType};base64,${base64}`
        } catch (error) {
            throw new Error(`获取图片失败: ${error.message}`)
        }
    }

    async onRequest(req, res) {
        let { face_code } = req.body

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

        try {
            let sql = `
                SELECT
                    f.student_num,
                    l.name,
                    l.user_avatar,
                    l.academy_name,
                    l.state
                FROM 
                    lepao_face f
                JOIN
                    lepao_account l
                ON
                    f.student_num = l.student_num
                WHERE
                    f.face_code  = ?
            `
            let rows = await db.query(sql, [face_code])
            if (!rows)
                return res.json({
                    ...BaseStdResponse.DATABASE_ERR,
                    msg: '获取用户人脸信息失败，请重试'
                })
            if (rows.length !== 1)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '采集码输入错误'
                })
            if(rows[0].state !== 1)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '账号状态为未登录，请用乐跑登录器更新账号状态后再进行人脸识别'
                })

            const face_img = await this.getImageBase64('https://lepao-cloud.xxoo365.top/view.php/a517e6d3b4cf9834c99ff819b473d58d.jpg')
            // 此时应该从乐跑获取人脸照片

            const key = uuidv4()

            await Redis.set(`faceReco:${rows[0].student_num}`, key, {
                EX: 1800
            })

            let resData = {
                ...rows[0],
                key,
                face_img
            }

            res.json({
                ...BaseStdResponse.OK,
                data: resData
            })
        } catch (error) {
            this.logger.error(`获取用户人脸信息失败。${error.stack}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '获取用户人脸信息失败，请重试'
            })
        }
    }
}

module.exports.BeginFaceReco = BeginFaceReco
