const system = require("../../system");
const uuidv4 = require('uuid/v4');
const md5 = require("MD5");

class PushUtils {
    constructor() {
        this.logCtl = system.getObject("service.common.oplogSve");
        this.execClient = system.getObject("util.execClient");
    }
    getUUID() {
        var uuid = uuidv4();
        var u = uuid.replace(/\-/g, "");
        return u;
    }

    async getCachePushItemUrl(merchant_id) {
        var cacheManager = system.getObject("db.common.cacheManager");
        return await cacheManager["MerchantPushUrlCache"].cache(merchant_id, null, 3600);
    }

    /**
     * 多次推送到第三方数据
     * @param {*} reqUrl 请求推送的url
     * @param {*} params 推送的参数
     */
    async pushMany(reqUrl, params) {
        try {
            params.requestid = this.getUUID();
            var rtn = this.execClient.execPost(params, reqUrl);
            //TODO:可以做多次推送，规则待定

            // var result = JSON.parse(rtn.stdout);
            // if (result && result.code == 200) {
            //     var resultdata = result.data;
            //     return { code: 1, msg: "success" };
            // } else {
            //     return { code: -1, msg: "err" };
            // }
        } catch (e) {
            this.logCtl.error({
                optitle: "多次推送到第三方数据异常error",
                op: url + ";params=" + JSON.stringify(params) + ";reqid=" + params.requestid,
                content: e.stack,
                clientIp: pobj.clientIp
            });
        }
    }

    async createSign(params, appId) {
        var cacheManager = system.getObject("db.common.cacheManager");
        var appInfo = await cacheManager["ApiAppKeyCheckCache"].cache(appId, null, 3000);

        var signArr = [];
        var keys = Object.keys(params).sort();

        for (let k = 0; k < keys.length; k++) {
            const tKey = keys[k];
            if (tKey != "sign" && params[tKey]) {
                signArr.push(tKey + "=" + params[tKey]);
            }
        }
        var resultSignStr = signArr.join("&") + "&key=" + appInfo.appSecret;
        return md5(resultSignStr).toUpperCase();
    }
}

module.exports = PushUtils;
