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

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

DD.prototype.GetAccessToken = function () {
    console.log(Config.ddAppKey);
    console.log(Config.ddAppSecret);
    var url = `https://api.dingtalk.com/v1.0/oauth2/accessToken`;
    var self = this;
    let option = {
        url: url,
        method: 'POST',
        headers: {
            "content-type": "application/json"
        },
        json: {
            "appKey": Config.ddAppKey,
            "appSecret": Config.ddAppSecret
        }
    }
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            console.log(error, body)
            var data = body;
            if (error) {
                reject(error)
            } else {
                console.log(data.message);
                if (data.message) {
                    console.log('无效的clientId或者clientSecret')
                    reject(data)
                } else {
                    self.accessToken = {
                        access_token: data.accessToken,
                        expires_in: data.expireIn
                    }
                    console.log('当前access_token', JSON.stringify(self.accessToken))
                    // 定时重新获取access_token
                    clearTimeout(this.getAccessTokenTimer)
                    this.getAccessTokenTimer = setTimeout(() => {
                        self.GetAccessToken()
                    }, (7200 * 1000) - 60000);
                    resolve(data)
                }
            }
        })
    })
}

DD.prototype.GetUserId = function (code) {
    var self = this;
    var url = `https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=${self.accessToken.access_token}`;
    let option = {
        url: url,
        method: 'POST',
        headers: {
            "content-type": "application/json"
        },
        json: {
            "code": code,
        }
    }
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            console.log(error, body);
            var data = body;
            if (error) {
                reject(error)
            } else {
                switch (data.errcode) {
                    case 45009:
                        console.log('token调用上限')
                        reject(data)
                        break;
                    case 0:
                        self.userId = data.result.userid;
                        console.log('当前用户id', self.userId)
                        resolve(data.result)
                        break;
                }
            }
        })
    })
}

DD.prototype.GetUserInfo = function () {
    var self = this;
    var url = `https://oapi.dingtalk.com/topapi/v2/user/get?access_token=${self.accessToken.access_token}`;
    let option = {
        url: url,
        method: 'POST',
        headers: {
            "content-type": "application/json"
        },
        json: {
            "userid": self.userId,
        }
    }
    return new Promise((resolve, reject) => {
        request(option, function (error, response, body) {
            console.log(error, body)
            var data = body;
            if (error) {
                reject(error)
            } else {
                switch (data.errcode) {
                    case 45009:
                        console.log('token调用上限')
                        reject(data)
                        break;
                    case 0:
                        self.userInfo = data.result;
                        console.log('当前用户信息', JSON.stringify(self.userInfo))
                        resolve(data.result)
                        break;
                }
            }
        })
    })
}


DD.prototype.getJsApiTicket = function () {
    const self = this;
    let option = {
        url: `https://api.dingtalk.com/v1.0/oauth2/jsapiTickets`,
        method: 'POST',
        headers: {
            "content-type": "application/json",
            "x-acs-dingtalk-access-token": self.accessToken.access_token
        }
    }
    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 = DD

