/**
 * Created by wxl on 2015/9/21.
 * @des 推荐产品页
 */


var co       = require('co');
var fs       = require('fs');
var hbs      = require('handlebars');
var iconv    = require('iconv-lite');
var r        = require('../../../lib/r.js');
var QS       = require('querystring');
var toolUtil=require("../../../lib/toolUtil.js");

//判断是否为空，或者数组是否为空
hbs.registerHelper("isObject",function(obj,options){
    if(!toolUtil.isEmptyObject(obj)){
        if(obj.length!=0){
            return options.fn(this);
        }else{
            return options.inverse(this);
        }
    }else{
        return options.inverse(this);
    }
});
function getIp(req){
    var remoteAddr = req._remoteAddress;
    var forwarded = req.headers["X-Forwarded-For"];
    var realIp = req.headers["X-Real-IP"];

    var ip = null;
    if (realIp == null) {
        if (forwarded == null) {
            ip = remoteAddr;
        } else {
            ip = remoteAddr + "/" + forwarded;
        }
    } else {
        if (realIp.equals(forwarded)) {
            ip = realIp;
        } else {
            ip = realIp + "/" + forwarded.replaceAll(", " + realIp, "");
        }
    }
    return ip;
}

/**
 * 页面计数ID
 */
function getPageCountId(data,flow){
    var baseIds=[[0,8471,8475,8481,8488],
                [0,8472,8475,8482,8489],
                [0,8473,8476,8483,8490]];

    // 符合或者推荐
    if(data && data.product && data.product.orgName){
        // 符合
        if(data.isConform==1){
            return baseIds[0][flow];
        }else{
            return baseIds[1][flow];
        }
    }else{
        return baseIds[2][flow];
    }
}

/**
 * 提交ID
 */
function getApplyCountId(data,flow){
    var baseIds=[[0,5257,5260,5265,0],
                [0,5258,5260,5266,0],
                [0,5259,5261,5267,5271]];

    // 符合或者推荐
    if(data && data.product && data.product.orgName){
        // 符合
        if(data.isConform==1){
            return baseIds[0][flow];
        }else{
            return baseIds[1][flow];
        }
    }else{
        return baseIds[2][flow];
    }
}




var template = hbs.compile(fs.readFileSync('./scripts/finance/info/goodRecommend.html').toString());
exports.handle=function(req, rh, maxAge, transEnc, queryString, callback) {
    co (function *(){
        var param=QS.parse(queryString);//得到参数页

        try{
            var qualification=JSON.parse(param.qua);//选择资质
        }catch(e){
            toolUtil.get404Page(fs,hbs,req,rh,callback);
        }

        var modelId=param.modelId;
        var rId=param.rId;
        var isHelper=Number(param.isHelper);
        param.ip=getIp(req);
        
        var url="http://jr.pcauto.com.cn/interface/outer/mobile/findProByQualification.jsp?rid="+rId+"&modelId="+modelId;
        if(isHelper==0){
            url+="&productId="+param.productId;//产品id
            url+="&prepay="+param.downPayment;//首付比例
            url+="&term="+param.periods;//还款期数
            if(!toolUtil.checkNumber(param.productId)||!toolUtil.checkNumber(param.productId)||!toolUtil.checkNumber(param.productId))
            {
              toolUtil.get404Page(fs,hbs,req,rh,callback);
            }
        }
        if(qualification){
            url+="&age="+qualification.age;
            url+="&income="+ qualification.annualIncome;
            url+="&credit="+  qualification.creditSituation;
            url+="&education="+  qualification.education;
            url+="&house="+  qualification.housingSituation;
            url+="&marriage="+  qualification.maritalStatus;
            url+="&work="+  qualification.profession;
            if(!toolUtil.checkNumber(qualification.age)||isNaN(qualification.annualIncome)
                ||!toolUtil.checkNumber(qualification.education)||!toolUtil.checkNumber(qualification.housingSituation)
                ||!toolUtil.checkNumber(qualification.maritalStatus)
              ||!toolUtil.checkNumber(qualification.profession))
            {
                toolUtil.get404Page(fs,hbs,req,rh,callback);
            }
            var creditSituation=qualification.creditSituation;
            var arr= creditSituation.split(",");
            arr.forEach(function(e){
                if(!toolUtil.checkNumber(e)){
                    toolUtil.get404Page(fs,hbs,req,rh,callback);
                }
            })
        }
//http://price.pcauto.com.cn/dealer/interface/order/recommend_dealer.jsp
       // 请求参数：rid:城市ID，sgid:车系ID，type:0

        //   var x= r.coGet("http://jr.pcauto.com.cn/interface/outer/mobile/findProByQualification.jsp?rid=1&modelId=33354&age=4&education=7&marriage=12&house=15&work=23&credit=24,25&income=123123123");

        try {
            var x= r.coGet(url);

            var RESULT=yield [x];
            var jsonR = JSON.parse(iconv.decode(RESULT[0].body, "utf-8"));

            // 处理页面计数和流程计数
            var flow=param.flow;
            var pageCountId=getPageCountId(jsonR,flow);
            var applyCountId=getApplyCountId(jsonR,flow);

            jsonR.loan=jsonR.loan.toFixed(2);
            param.hasData=toolUtil.isEmptyObject(jsonR.product)?0:1;
            if(param.hasData){
                var urlDealers="http://jr.pcauto.com.cn/interface/outer/mobile/listDealer.jsp?rId="+rId+"&modelId="+modelId;
            }else{
                var urlDealers="http://price.pcauto.com.cn/dealer/interface/order/recommend_dealer.jsp?rid="+rId+"&type=0&sgid="+ jsonR.model.serialGroupId;
            }
            var y= r.coGet(urlDealers);
            var RESULTY=yield [y];
            var jsonDealers={};
            try{
                if(param.hasData){
                    jsonDealers= JSON.parse(iconv.decode(RESULTY[0].body,"utf-8"));
                }else{
                    var temp=JSON.parse(iconv.decode(RESULTY[0].body,"GBK"));
                    jsonDealers.dealerList=temp;
                }

            }catch(e){
                console.log("jsonDealers error");
            }
            if(toolUtil.filterORG(jsonR.product.orgId)){//特殊处理该经销商。
                jsonDealers.dealerList=[];
            }
            var jsonResult = {"data": jsonR, "dealers": jsonDealers};


            jsonResult.param = param;
            var path  = require('../../../conf/config.js').config().path;
            jsonResult.host=req.headers.host+path;
            jsonResult.cookieHost=req.headers.host;
            jsonResult.flow=flow;
            jsonResult.pageCountId=pageCountId;
            jsonResult.applyCountId=applyCountId;

            if(param.fmt=="json"){
                rh.setHeader('Content-Type', 'application/json; charset=UTF-8');
                rh.setBody(JSON.stringify(jsonResult));
            }else{
                var html = template(jsonResult);
                // 设置响应头信息
                rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
                if (maxAge)rh.setHeader('Cache-Control', 'max-age=' + (maxAge));
                // 设置响应内容
                rh.setBody(html);
            }

            // 回调通知
            callback(null, rh);
        }catch(e){
           toolUtil.get404Page(fs,hbs,req,rh,callback);
            console.log("info/goodRecommend.js:"+e);
        }
    })();

}

