/*** 微服务发包及通用解包！***/
/*  
    根据serviceType中转网关返回并解析。
*/

var wfwServices = {}
wfwServices.services = {}

wfwServices.setWfw = function(serviceType){
        
        if(serviceType == 'uc_pwd_service') //UC密码修改
        {
            this.services.servicetype = 'uc';
            this.services.serviceurl = '/rest/SGGZJUcasCustPwdManageService/fSendRequestSync';
        }
        else if(serviceType == 'jzqs_adapter_service') //集中清算
        {
            this.services.servicetype = 'jzqs';
            this.services.serviceurl = '/rest/SJZQSAdapterAsyncService/fSendAsyncRequest';
        }
        else if(serviceType == 'sfcg_adapter_service')//三方
        {
            this.services.servicetype = 'sfcg';
            this.services.serviceurl = '/rest/SFCGAdapterService/fSendRequestSync';
        }
        else if(serviceType == 'ucm_order_service')
        {
            this.services.servicetype = 'ucmobile';
            this.services.serviceurl = '/rest/SGGZJOrderService/fSendRequestSync';
        }
        else if(serviceType == 'ucm_prod_service')
        {
            this.services.servicetype = 'ucmobile';
            this.services.serviceurl = '/rest/SGGZJProdService/fSendRequestSync';
        }
        else if(serviceType == 'zhlc_szhlc_service'){//综合理财
            this.services.servicetype = 'zhlc';
            this.services.serviceurl = '/rest/SZHLCQueryService/fSendRequestSync';
        }
        else if(serviceType == 'uc_asset_service'){//资产分析服务
            this.services.servicetype = 'uc';
            this.services.serviceurl = '/rest/SGGZJJHAssetIndependService';
        }
        else if(serviceType == 't0'){//策略中台服务
            this.services.servicetype = 'clzt';
            this.services.serviceurl = '/rest/T0TradeGatewayService';
        }
        else if(serviceType == 'fql'){//策略中台服务
            this.services.servicetype = 'fql';
            this.services.serviceurl = 'fqlapi/intranet_service';
        }
        else if(serviceType == 'uc_asset'){//资产分析服务
            this.services.servicetype = 'uc';
            this.services.serviceurl = '/rest/SGGZJAssetService';
        }
        else if(serviceType == 'uc_behavior_service'){//君弘学堂服务
            this.services.servicetype = 'uc';
            this.services.serviceurl = '/rest/SGGZJBehaviorService';
        }
        return this.services;
}

wfwServices.parse = function(ret)
{
    ucParse = ['uc','ucmobile','zhlc','clzt','fql']
    if(ret.RNUM>0)
    {
        if(ucParse.indexOf(this.services.servicetype) != -1)
        {
          return this.parseUC(ret.list[0].rts_data);
        }
        else if(this.services.servicetype == 'jzqs')
        {
          return this.parseJzqs(ret.list[0].rts_data);
        }
    }
    return "N/A";
}

//uc通用解包 RNUM=1$rts_no=0&rts_data=
wfwServices.parseUC = function(rts_data)
{
  try {
        let rep = JSON.parse(rts_data)
        let repData = rep.data;
        if(repData.result == '0') 
        {
          return repData.msg;
        }
        return repData;
    } catch (d) {
        return 'N/A';
  }

}

//清算通用解包
wfwServices.parseJzqs = function(rts_data)
{
  try {
        let rep = JSON.parse(rts_data)
        let repData = rep.data;
        if(repData.result == '0') 
        {
          return repData.msg;
        }
        return JSON.parse(repData.resultListStr);
    } catch (d) {
        return 'N/A';
  }
}

function fyCallbackWrap() {
    var totalCallTimes = 0;
    var utils = {};

    /**
     * 将 url 的附带参数转化成 JSON 对象
     * @param  {String} str 类似于`"name=abc&age=12"`
     * @return {JSON}     JSON键值对
     */
    utils.queryToJson = function (str) {
        return str.split('&').reduce(function (prev, curr) {
            var val = curr.substring(curr.indexOf("=") + 1, curr.length);
            curr = curr.split('=');
            val = val.replace(/\(-\)/g, ";").replace('(%)', '$');
            val = val.replace(/\(~\)/g, "=").replace('(^)', "&");
            prev[curr[0]] = val;
            return prev;
        }, {});
    };
    // utils.queryToJson = function (str) {
    //   return str.split('&').reduce(function (prev, curr) {
    //     curr = curr.split('=');
    //     curr[1] = curr[1].replace('(~)', "=").replace('(^)', "&");
    //     curr[1] = curr[1].replace(/\(-\)/g, ";");
    //     prev[curr[0]] = curr[1];
    //     return prev;
    //   }, {});
    // };

    /**
     * 将 JSON 对象转换成 url 查询字符串
     * @param  {JSON} obj JSON键值对
     * @return {String}     查询串
     */
    utils.jsonToQuery = function (obj) {
        var ret = [];
        var key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                ret.push(key + '=' + obj[key]);
            }
        }
        //console.log(ret.join('&'))
        return ret.join('&');
    };

    utils.RetToJson = function (str) {
        if(str=='' || str==null){
            $(".lx-come").append('接口返回空');
        }
        var obj = {};
        var arr = str.split('$');
        var acurr = "";
        // console.log('str:',str)
        acurr = arr[0].split('=');
        obj[acurr[0]] = acurr[1];

        var str2 = arr[1].split(';');
        var retArr = [];
        for (var i in str2) {
            if (str2[i] == '') continue;
            var objItem = {};
            objItem = utils.queryToJson(str2[i]);
            retArr.push(objItem);
        }
        obj["list"] = retArr;
        return obj;
    };

    //function GetUserInfo($scope) {
    //var request = {
    //    fytype: 'innercmd',
    //    method: 'getuserinfo',
    //    mname: '用户信息获取'
    //};
    //
    //fyCallbackWrap.FY_KCXPQuery('用户信息获取',request).then(function(raw)
    //{
    //   var userInfo = JSON.parse(JSON.stringify(raw)).list[1]; //用户信息结构，Ret为当前用户
    //   $scope.userInfo = userInfo;
    //   $scope.$apply();
    //});
//};
//    FY_KCXPQuery('用户信息获取',request)
    //    .then(function(raw) {
    //    var userInfo = JSON.parse(JSON.stringify(raw)).list[1]; //用户信息结构，Ret为当前用户
    //    $scope.userInfo = userInfo;
    //    $scope.$apply();
    //});

    return function FY_KCXPQuery(funcname, req, log) {
        var sReq = "";
        var emun = {
            'innercmd': '内部请求',
            'kcxpcmd': '外部请求',
            'jzjy': '集中交易',
            'zhlc': '综合理财',
            'uc': '用户中心',
            'ucmobile': '用户中心移动',
            'opt': '期权相关',
            'rzjzjy': '集中交易信用',
            't2': '综合理财t2',
            't2jzjy': '综合理财T2透传',
            'h5uc': 'h5uc请求',
            'wfwcmd': '微服务透传',
			'ltscmd': '低延时',
			'openinfo': '内存缓存'
        }

        return new Promise(function (resolve, reject) {
            var callTimes = totalCallTimes++;
            var callBegin = +new Date();

            sReq += utils.jsonToQuery(req);

            // console.log(sReq)

            function onReject(err) {
                var content = '%cauto-error-log: %c[' + [funcname, err].join('] %c[') + ']';
                console.info(content, 'color: #C30062', 'color: #4A4A4A', 'color: #4A4A4A', 'color: red');
                // console.info('\t\tdetail:', data);
                reject(err);
            }

            function fyCallback(err, raw) {
                var callEnd = +new Date();
                var vret = "";
               //  console.log('raw:', raw)
                if (raw == null || raw == '') {
                    vret = '';
                }
                else {
                    vret = utils.RetToJson(raw);
                }
                
                var retde = function (eq) {
                    if (emun[req.fytype] == '内部请求' || emun[req.fytype] == '内存缓存') {
                        return emun[req.fytype] + ':' + req.method;
                    }
                    else if (req.fytype == 'wfwcmd') {
                        return emun[req.fytype] + ':' + req.servicetype;
                    }
                    else {
                        return emun[req.rtsname] + ':' + req.funcid;
                    }
                }
                // if(log){
                  let reqstr = decodeURI(JSON.stringify(req, null, '  '))
                    console.log([
                        '%c请求地址：'+FConfig._FYURL,
                        '%c\nFYQRY(' + callTimes + ') 请求详情, [' + retde(req) + '][' + funcname + ']',
                        '%c请求结构：',
                        '%c' + JSON.stringify(req, null, '  '),
                        '%c应答结果：',
                        '%c' + JSON.stringify(vret, null, '  '),
                        '%c耗时：%c' + (callEnd - callBegin) + 'ms',
                        ''
                    ].join('\n'), 'color: green', 'color: blue', 'color: gray', 'color: blue', 'color: gray', 'color: blue', 'color: gray');
                // }
                try {
                    raw = vret;
                } catch (ex) {
                    err = raw;
                }

                if (err) {
                    onReject(err);
                }
                else {
                    if(req.fytype == 'wfwcmd')
                    {
                        raw = wfwServices.parse(raw)
                    }
                    resolve(raw);                   
                }
            }

            var options = {
                fytype: req.fytype,
                path: FYServer,
                data: sReq,
                callback: fyCallback
            };
            CallFYEX(options);
        });
    }

}
