const moment = require("moment");

class ecloudsignClient {

    constructor() {
        this.appKey = "yyzm68fu5g3epaa3pc";
        this.secret = "5ccba1e4baea71eaa2d1132a2205fef2";
    }

    //获取请求参数
    async rformat(qobj) {
        qobj.timestamp = await this.getNewDate();
        qobj.appKey = this.appKey;
        qobj.v = '1.0';
        qobj.nonce = await this.getRandomCode(6);
        let signature = await this.signature(qobj, this.secret);
        qobj.signature = signature;
        return qobj;
    }

    //获取当前时间
    async getNewDate() {
        let date = moment().add(13, "hours").format("YYYY-MM-DD HH:mm:ss");
        return date;
    }

    //随机生成数字
    async getRandomCode(iun) {
        var randStr = "";
        for (var i = 0; i < iun; i++) {//此处的12为生成12位数字，可随即更改
            var randItem = Math.floor(Math.random() * 10);
            randStr += randItem;
        }
        return randStr;
    }

    async signature(args, secret) {
        let newArgs = tosort(args);
        var string = '';
        for (var k in newArgs) {
            if(typeof newArgs[k] == "object"){
                let kvalue = tosort(newArgs[k]);
                    newArgs[k] = JSON.stringify(kvalue[0]);
                // newArgs[k] = JSON.stringify(kvalue);
            }
            // string += '&' + k + '=' + newArgs[k];
            string += newArgs[k];
        }
        console.log(string)
        var str = secret + string + secret;
        console.log(str)
        var crypto = require('crypto');
        return crypto.createHash('md5').update(str,'utf8').digest('hex').toUpperCase();
    }
}

function tosort(args){
    if(args.length == 2){
        return args;
    }
    var keys = Object.keys(args);
    keys = keys.sort();
    var newArgs = {};
    keys.forEach(function (key) {
        newArgs[key] = args[key];
    });
    return newArgs;
}

module.exports = ecloudsignClient;
