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

WeChat.prototype.GetAccessToken = function (code) {
    var url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${Config.appId}&secret=${Config.appSecret}&code=${code}&grant_type=authorization_code`;
    var self = this;
    let option = {
        url: url,
        method: 'GET',
        headers: {
            "content-type": "application/json"
        }
    }
    console.log(url);
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            console.log(error, body)
            var data = JSON.parse(body)
            if (error) {
                reject(error)
            } else {
                self.accessToken = {
                    access_token: data.access_token,
                    expires_in: data.expires_in
                }
                self.openid = data.openid;
                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)
            }
        })
    })
}

WeChat.prototype.GetUserInfo = function () {
    var self = this;
    var url = `https://api.weixin.qq.com/sns/userinfo?access_token=${self.accessToken.access_token}&openid=${self.openid}&lang=zh_CN`;
    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);
            }
        })
    })
}


WeChat.prototype.jsCode2Session = function (code) {
    var self = this;
    var url = `https://api.weixin.qq.com/sns/jscode2session?appid=${Config.appId}&secret=${Config.appSecret}&js_code=${code}&grant_type=authorization_code`;
    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);
            }
        })
    })
}

WeChat.prototype.getJsApiTicket = function () {
    const self = this;
    let option = {
        url: `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${self.accessToken.access_token}&type=jsapi`,
        method: 'GET',
        headers: {
            "content-type": "application/json"
        }
    }
    return new Promise((resolve, reject) => {
        if (self.jsApiTicket &&
            self.jsApiTicket.timestamp + 7200 * 1000 < new Date().getTime()) {
            resolve(self.jsApiTicket);
            return;
        }

        request(option, function (error, response, body) {
            console.log(error, body);
            if (error) {
                reject(error);
            } else {
                const timestamp = parseInt(new Date().getTime() / 1000);
                const data = {...JSON.parse(body), timestamp}
                self.jsApiTicket = data;
                resolve(data);
            }
        })
    })
}

module.exports = WeChat

