const API = require("../../../lib/API")
const axios = require('axios')
const config = require('../../../config.json')
const { BaseStdResponse } = require("../../../BaseStdResponse");
const https = require("https")

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

        this.setPath('/UniLogin/GetLoginUrl')
        this.setMethod('GET')
    }

    async onRequest(req, res) {
        let { type, device } = req.query

        const uniConfig = config.unilogin

        let url = `${uniConfig.url}/connect.php?act=login&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${type || 'qq'}&redirect_uri=${encodeURIComponent(uniConfig.return_url)}`
        if (device && device === 'uniapp')
            url = `${uniConfig.url}/connect.php?act=login&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${type || 'qq'}&redirect_uri=${encodeURIComponent(uniConfig.uni_return_url)}`

        try {
            const r = await axios.get(url, {
                proxy: false,
                httpsAgent: new https.Agent({
                    rejectUnauthorized: false
                })
            })

            if (!r || r.data?.code !== 0 || !r.data?.url) {
                this.logger.error(`获取聚合登录链接失败！${r.data?.msg || 'api接口错误'}`)
                return res.json({
                    ...BaseStdResponse.ERR,
                    msg: '请尝试其他登录方式或稍后再试'
                })
            }

            res.json({
                ...BaseStdResponse.OK,
                data: r.data.url
            })
        } catch (error) {
            this.logger.error(`获取聚合登录链接失败！${error.message || 'api接口错误'}`)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '请尝试其他登录方式或稍后再试！'
            })
        }
    }
}

module.exports.GetLoginUrl = GetLoginUrl;