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

function QyWeChat(config) {
    this.config = config;
    this.accessToken = {};
    this.getAccessTokenTimer = null;
    this.userId = null;
    this.userInfo = {};
}

QyWeChat.prototype.GetAccessToken = function () {
    var url = `https://oauth.bhu.edu.cn/gettoken?clientid=${Config.corpid}&client_secret=${Config.corpsecret}`;
    var self = this;
    let option = {
        url: url,
        method: 'GET',
        headers: {
            "content-type": "application/json"
        }
    }
    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 {
                switch (data.errcode) {
                    case 45009:
                        console.log('token调用上限')
                        reject(data)
                        break;
                    case 0:
                        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)
                        break;
                }
            }
        })
    })
}

QyWeChat.prototype.GetUserId = function (code) {
    var self = this;
    var url = `https://oauth.bhu.edu.cn/user/getuserdetail?access_token=${self.accessToken.access_token}&code=${code}`;
    let option = {
        url: url,
        // qs: {
        //     grant_type: 'client_credential',
        //     appid: this.config.App_Id,
        //     secret: this.config.App_Secret
        // },
        method: 'GET',
        headers: {
            "content-type": "application/json"
        }
    }
    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 {
                switch (data.errcode) {
                    case 45009:
                        console.log('token调用上限')
                        reject(data)
                        break;
                    case 0:
                        self.userId = data.userid;
                        console.log('当前用户id', self.userId)
                        resolve(data)
                        break;
                }
            }
        })
    })
}

QyWeChat.prototype.GetUserInfo = function () {
    var self = this;
    var url = `https://oauth.bhu.edu.cn/user/getuserinfo?access_token=${self.accessToken.access_token}&userid=${self.userId}`;
    let option = {
        url: url,
        method: 'GET',
        headers: {
            "content-type": "application/json"
        }
    }
    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 {
                switch (data.errcode) {
                    case 45009:
                        console.log('token调用上限')
                        reject(data)
                        break;
                    case 0:
                        self.userInfo = data;
                        console.log('当前用户信息', JSON.stringify(self.userInfo))
                        resolve(data)
                        break;
                }
            }
        })
    })
}


QyWeChat.prototype.getFwQywxUser = function (token) {
    const tmp = new Date().getTime();
    let option = {
        url: `http://oaapp.fuwai.com:12800/auth/token/validate`,
        method: 'POST',
        headers: {
            "content-type": "application/json"
        },
        json: {
            "appCode": Config.fw_sso_app_code,
            "token": token,
            "timestamp": tmp,
            "signature": md5(`${Config.fw_sso_app_code}:${Config.fw_sso_secret}:${tmp}`).toLocaleUpperCase()
        }
    }
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            console.log(error, body);
            var data = body;
            if (error) {
                reject(error);
            } else {
                resolve(data);
            }
        })
    })
}

QyWeChat.prototype.getJsApiTicket = function () {
    const self = this;
    let option = {
        url: `https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=${self.accessToken.access_token}&type=agent_config`,
        method: 'GET',
        headers: {
            "content-type": "application/json"
        }
    }
    return new Promise((resolve, reject) => {
        if (self.jsApiTicket &&
            self.jsApiTicket.timestamp + 7200 > parseInt(new Date().getTime() / 1000)) {
            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 = QyWeChat

