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

class PushUtils {
    constructor() {
        this.logCtl = system.getObject("web.common.oplogCtl");
        this.cacheManager = system.getObject("db.common.cacheManager");
        this.merchantpushlogSve = system.getObject("service.merchant.merchantpushlogSve");
        this.execClient = system.getObject("util.execClient");
        this.merchantpushSve = system.getObject("service.merchant.merchantpushSve");
    }
    getUUID() {
        var uuid = uuidv4();
        var u = uuid.replace(/\-/g, "");
        return u;
    }

    async getCachePushItemUrl(merchant_id) {
        return await this.cacheManager["MerchantPushUrlCache"].cache(merchant_id, null, 3600);
    }
    /**
     * 推送到第三方数据
     * @param {*} reqUrl 请求推送的url
     * @param {*} params 推送的参数
     */
    async push(merchantId, field, params) {
        try {
            var pushConfig = await this.getCachePushItemUrl(merchantId) || {};
            var reqUrl = pushConfig[field];
            if(!reqUrl) {
                this.logCtl.error({
                    optitle: "推送到第三方数据异常error",
                    op: "merchantId = " + merchantId + "; reqUrl is empty, field = " + field,
                    content: "reqUrl is empty",
                    clientIp: "pushUtils中没有ip"
                });
                return;
            }
            // 签名
            params.sign = await this.createSign(params, merchantId);
            params.requestid = this.getUUID();
            var rtn = await this.execClient.execPost(params, reqUrl);
            var returnValue = 0;
            if (rtn.stdout) {
                var result = JSON.parse(rtn.stdout);
                if (result.code == "success") {
                    returnValue = 1;
                }
            }
            //记录推送结果
            this.merchantpushlogSve.create({
                merchant_id: merchantId,//商户id            
                api: reqUrl,//接口地址        
                params: JSON.stringify(params),//推送数据信息  
                rs: rtn.stdout,//推送返回结果  
                success: returnValue//是否推送成功  
            });
        } catch (e) {
            console.log(e.stack);
            this.logCtl.error({
                optitle: "推送到第三方数据异常error",
                op: reqUrl + ";params=" + JSON.stringify(params) + ";reqid=" + params.requestid,
                content: e.stack,
                clientIp: "pushUtils中没有ip"
            });
        }
    }
    /**
     * 多次推送到第三方数据
     * @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 appInfo = await this.cacheManager["ApiAppIdCheckCache"].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;
