var request = require("request");
var { Config } = require("../lib/Config");
var md5 = require("js-md5");

function YunSchool(config) {
    this.config = config;
    this.accessToken = {};
    this.getAccessTokenTimer = null;
    this.userId = null;
    this.userInfo = {};
    this.code = "";
}

YunSchool.prototype.GetAccessToken = function (code) {
    if (!code) {
        return Promise.reject(new Error("code is required"));
    }
    console.log("COnfig>>", Config);
    this.code = code;
    var url = `https://wep.cau.edu.cn/api/third/get-token?appid=${Config.yunSchoolAppid}&appsecret=${Config.yunSchoolSecret}`;
    var self = this;
    let option = {
        url: url,
        method: "GET",
        headers: {
            "content-type": "application/x-www-form-urlencoded",
        }
    };
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            console.log("body>>",body);

            const data = typeof body === 'string'? JSON.parse(body):body;
            console.log("data>>",data);

            if (data.d.access_token) {
                self.accessToken = {
                    access_token: data.d.access_token,
                    expires_in: data.d.expires_in,
                };
                console.log("yunSchool当前access_token",self.accessToken);
                resolve(data);
            }
            else{
                resolve({"msg":"获取token失败"});
            }
        });
    });
};

YunSchool.prototype.GetUserInfo = function (code) {
    if (!code) {
        return Promise.reject(new Error("code is required"));
    }
    var self = this;
    var url = `https://wep.cau.edu.cn/uc/api/oauth/user-by-code?access_token=${self.accessToken.access_token}&code=${code}`;
    let option = {
        url: url,
        method: "POST",
        headers: {
            "content-type": "application/x-www-form-urlencoded",
        },
    };
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            var data = JSON.parse(body);
            console.log("yunSchool当前用户信息",data);
            if (error) {
                reject(error);
            } else {
                switch (data.e) {
                    case 0:
                        self.userInfo = data.d;
                        resolve(data.d);
                    default:
                        reject(data)
                }
            }
        });
    });
};

module.exports = YunSchool;