var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");

const CtlBase = require("../../ctl.base");
const axios = require("axios");
const jwt = require("jsonwebtoken");

class AuthCtl extends CtlBase {
    constructor() {
        super("auth", CtlBase.getServiceName(AuthCtl));
        this.redisClient = system.getObject("util.redisClient");
    }
    async saveAuths(pobj, query, req) {
        var auths = pobj.auths;
        var xrtn = await this.service.saveAuths(auths, pobj.app_id, pobj.company_id);
        return system.getResult(xrtn);
    }
    async findAuthsByRoles(pobj, query, req) {
        var roleids = pobj.roleids;
        var xrtn = await this.service.findAuthsByRole(roleids, pobj.app_id, pobj.company_id);
        return system.getResult(xrtn);
    }

    /**
     * 易代账获取初始化token
     * @param {*} code 
     */
    async getOpenToken(body) {
        const url = `${settings.ydzUrl()}/auth/getToken`
        const ydzKey = settings.ydzKey();
        return await this.publicTokenFun(url, "authorization_code", ydzKey.appKey, body.code, "code");
    }

    /**
     * 刷新opentoken(access_token)
     */
    async refreshToken() {
        const url = `${settings.ydzUrl()}/auth/refreshToken`
        const ydzKey = settings.ydzKey();
        const getRedisResult = JSON.parse(await this.redisClient.get('ydzToken')).refresh_token;
        return await this.publicTokenFun(url, "refresh_token", ydzKey.appKey, getRedisResult, "refreshToken")
    }

    async publicTokenFun(url, grantType, appKey, data, specialKey) {
        let params = {
            grantType,
            appKey
        }
        params[specialKey] = data;
        const res = await this.getRequest(url, params);
        let deTokenExp = Number((jwt.decode(res.data.result.access_token).exp));
        let timestamp = Math.round(new Date() / 1000);
        if (res.data.code == 200) {
            let ydzToken = {
                access_token: res.data.result.access_token,
                refresh_token: res.data.result.refresh_token
            }
            const addRedisResult = await this.redisClient.setWithEx('ydzToken', JSON.stringify(ydzToken), Number(deTokenExp - timestamp));
            // const getRedisResult = await this.redisClient.get('ydzToken');
            return system.getResult(addRedisResult);
        } else {
            return system.getResultFail(201, res.data.message);
        }
    }

    /**
     * 公用get请求
     * @param {*} url 
     * @param {*} data 
     */
    async getRequest(url, data = {}) {
        try {
            console.log(` ${url} : 请求信息 ------- `);
            console.log(JSON.stringify(data));
            const res = await axios.get(url, {
                params: data,
                headers: {
                    "Content-Type": "application/json",
                }
            });
            return res;
        } catch (err) {
            console.log(` ${url} : 返回错误信息 ------- `);
            console.log(err)
            throw (err)
        }
    }
}
module.exports = AuthCtl;