var request = require('request');
var { Config } = require('../lib/Config');
function Weshao(config) {
    this.config = config;
    this.accessToken = {};
    this.getAccessTokenTimer = null;
    this.userId = null;
    this.userInfo = {};
}

Weshao.prototype.GetToken = function (code, redirectUri) {
    var url = 'https://api.weishao.com.cn/oauth/token';
    var self = this;
    let option = {
        url: url,
        method: 'POST',
        headers: {
            "content-type": "application/json"
        },
        json: {
            "grant_type": "authorization_code",
            "client_id": Config.appId,
            "client_secret": Config.appSecret,
            "code": code,
            "redirect_uri": redirectUri
        }
    }
    console.log(url);
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            console.log(error, body)
            var data = typeof body == 'object' ? body : JSON.parse(body)
            if (error) {
                reject(error)
            } else {
                self.accessToken = {
                    access_token: data.access_token,
                    expires_in: data.expires_in
                }
                console.log('当前access_token', JSON.stringify(self.accessToken))
                // 定时重新获取access_token
                clearTimeout(this.getAccessTokenTimer)
                this.getAccessTokenTimer = setTimeout(() => {
                    self.GetAccessToken()
                }, (data.expires_in - 60) * 1000 || 60000)
                resolve(data)
            }
        })
    })
}

Weshao.prototype.GetUserInfo = function () {
    var self = this;
    var url = `https://api.weishao.com.cn/profile?access_token=${self.accessToken.access_token}`;
    let option = {
        url: url,
        method: 'GET',
        headers: {
            "content-type": "application/json"
        }
    }

    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            var data = JSON.parse(body)
            console.log(data);
            if (data.errcode) {
                reject(data);
            } else {
                self.userInfo = data;
                console.log('当前用户信息', JSON.stringify(self.userInfo));
                resolve(data);
            }
        })
    })
}

module.exports = Weshao

