const moment = require("moment");

class ecloudClient {
    constructor() {
        this.appKey = "9999"
        this.secret = "8888";

    }

    //获取请求参数
    async rformat(qobj) {
        var data = {
            timestamp: await this.getNewDate(),
            appKey: this.appKey,
            v: '1.2.14',
            nonce: await this.getRandomCode(6),
            signature: await this.signature(qobj, this.secret),
        }

        return data;
    }


    //获取当前时间
    async getNewDate() {
        let date = moment().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) {
        var keys = Object.keys(args);
        keys = keys.sort();
        var newArgs = {};
        keys.forEach(function (key) {
            newArgs[key] = args[key];
        });
        var string = '';
        for (var k in newArgs) {
            // string += '&' + k + '=' + newArgs[k];
            string += newArgs[k];
        }
        string = string.substr(1);

        var string = secret + string + secret;
        var crypto = require('crypto');
        return crypto.createHash('md5').update(string, 'utf8').digest('hex').toUpperCase();
    }


    async returnRu(rs) {
        var result = {};
        if (rs && rs.stdout) {
            var stdout = JSON.parse(rs.stdout) || {};
            var code = stdout.code;

            if (code == 0) {
                code = 1;
            } else if (code == 1) {
                code = 0;
            } else {
            }
            result.code = code;
            result.msg = stdout.msg;
            result.data = stdout.data;
        } else {
            result.code = 0;
            result.msg = '结算接口返回空';
        }

        return result;
    }

}

module.exports = ecloudClient;