/**
 * Created by pc on 2015/9/18.
 * @author wxl
 * @date 2015-09-18
 */
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('if_eq', function(v1, v2, options) {
    if (v1 == v2) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});
exports.handle = function(req, rh, maxAge, transEnc, queryString, callback) {
    co(function *(){
		try{
             var param = QS.parse(queryString);
			 var rId = param.rid;     //城市Id
			 var productId = param.productId;     //产品ID
			 var modelId =  param.modelId ;       //车型ID
			 var ratio =  param.ratio;            //首付
             var term  = param.term;              //期数
			 var rIdPatt = /^[1-9]\d{0,4}$/g;
			 var ip=req._remoteAddress;
			 var browser=param.browser;
			 var finalPayment = param.finalPayment ;
			 // 页面计数器/流程计数
			 var flow=param.flow;
			 var pageCountId=[0,8469,0,8479,8486][flow];
			 var applyCountId=[0,5256,0,5263,5270][flow];

             rIdPatt.compile(rIdPatt);
             var re1 = new RegExp(rIdPatt);
             if(!rId){
				 //返回404页面
				 toolUtil.get404Page(fs,hbs,req,rh,callback);
             }else if(!re1.test(rId)){
                 toolUtil.get404Page(fs,hbs,req,rh,callback);
             }
		     //金融产品详情
			 var url = "http://jr.pcauto.com.cn";
			 var urlX =url+"/interface/outer/mobile/productDetail.jsp?rId="+rId+"&productId="+productId+"&modelId="+modelId;
			 var x = r.coGet(urlX);
			 var RESULT = yield [x];
			 var jsonX = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));
			 jsonX.flow=flow;
			 jsonX.pageCountId=pageCountId;
			 jsonX.applyCountId=applyCountId;
			 var hasProduct = jsonX.hasProduct;
			 jsonX.ip = ip;
			 if(browser){
				if(browser == 'wx'){
				 jsonX.browser = browser;
				}
			}
			if(jsonX.exist == false){
				 toolUtil.get404Page(fs,hbs,req,rh,callback);
				 console.error('productId is not exist!');
				 return ;
			}
			if(jsonX.icon==''){
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
                  console.error('product/list.js: sgId or modelId not exist!');
                  return;
            }
			 //车型列表接口
			 if(jsonX.serialGroupId){
			    var urlY = url+"/interface/outer/mobile/listModel.jsp?sgId="+jsonX.serialGroupId;
			    var y = r.coGet(urlY);
			    var RESULT = yield [y];
			    var jsonY = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));
			    jsonX.list = jsonY.list;
			 }
			 jsonX.rid = rId;
			 //当存在产品详情
			 if(hasProduct == true) {
			  //首付处理
			  if(jsonX.downPaymentList && jsonX.downPaymentList.length > 0){
				 var shoufuFlag = 0;
				 if(ratio){
				  for(var j = 0; j < jsonX.downPaymentList.length ; j++){
					  if(ratio == jsonX.downPaymentList[j].downPayment){
						  shoufuFlag = 1;
						 // break;
					  }
			         if(shoufuFlag == 1){
                         jsonX.shoufu = ratio;
						 jsonX.downPayment = (ratio/100 *jsonX.price).toFixed(2);
				     }
				   }
				  }else{
                     shoufuFlag = 1;
					 var defaultFlag = 0;
					 for(var j = 0; j < jsonX.downPaymentList.length ; j++){
					  if(30 == jsonX.downPaymentList[j].downPayment){
						 jsonX.shoufu = 30;
						 jsonX.downPayment = (30/100 *jsonX.price).toFixed(2);
						 defaultFlag = 1;
						// break;
					  }
				     }
					 if(defaultFlag == 0){
                        jsonX.shoufu = jsonX.downPaymentList[0].downPayment;
						jsonX.downPayment = (jsonX.downPaymentList[0].downPayment/100 *jsonX.price).toFixed(2);
					 }
				  }
				  var firstdownPayment = jsonX.downPaymentList[0].downPayment;
				  var downPaymentArr=[];
				  	if(jsonX.downPaymentList.length >1 && jsonX.downPaymentList){
						for(var i = 1; i < jsonX.downPaymentList.length ; i++){
                          downPaymentArr.push(jsonX.downPaymentList[i]);
						}
					}
				    jsonX.downPaymentArr = downPaymentArr;
					jsonX.firstdownPayment = firstdownPayment;
				 }
				 if(shoufuFlag == 0){
					   toolUtil.get404Page(fs,hbs,req,rh,callback);
			     }
		      var loanValue =(jsonX.price - jsonX.downPayment).toFixed(2);
			  jsonX.loanValue = loanValue;
			 //期数处理
			 if(jsonX.periodsList && jsonX.periodsList.length >0){
				 var termFlag = 0;
				 if(term){
				   for(var j = 0 ; j < jsonX.periodsList.length ; j++){
					   if(jsonX.periodsList[j].periods == term){
						 termFlag = 1;
					  }
				   }
				   if(termFlag == 1){
                      jsonX.term = term;
					}
				 }else{
					 termFlag = 1;
					 var  defaultFlag = 0;
					 for(var z = 0 ; z < jsonX.periodsList.length ; z++){
                         if(24 ==jsonX.periodsList[z].periods){
							 jsonX.term = 24;
                             defaultFlag = 1;
							// break;
						 }
					 }
					 if(defaultFlag == 0){
                            jsonX.term = jsonX.periodsList[0].periods;
					 }
				 }
				 var firstPeriods = jsonX.periodsList[0].periods;
				 var PeriodsAry=[]
			     if(jsonX.periodsList && jsonX.periodsList.length > 1){
				  for(var i = 1; i < jsonX.periodsList.length ; i++){
					 PeriodsAry.push(jsonX.periodsList[i]);
				  }
				 }
				 jsonX.periodsList= PeriodsAry;
				 jsonX.firstPeriods =firstPeriods;
			    }
				if(termFlag ==0){
					 toolUtil.get404Page(fs,hbs,req,rh,callback);
				}
			 //当存在首付比例参数
			 if(ratio){
				if(jsonX.loanDetailList){
					for(var i = 0 ; i < jsonX.loanDetailList.length ; i ++){
						if(jsonX.loanDetailList[i].downPayment == ratio){
                          jsonX.loanDetailList[i].flag = 1; 
						}
					}
			 	 }
			  }			
			 //尾款情况
			if(jsonX.templateType == 3){
			 if(jsonX.finalPaymentList && jsonX.finalPaymentList.length >0){
				var finalPay =[];
				var firstFinalPay = jsonX.finalPaymentList[0].finalPayment;
				if(jsonX.finalPaymentList.length > 1 && jsonX.finalPaymentList.length){
				 for(var i = 1; i < jsonX.finalPaymentList.length ; i++){
                     finalPay.push(jsonX.finalPaymentList[i]);
				  }
				}
				jsonX.firstFinalPay =firstFinalPay;
				jsonX.finalPay = finalPay;
			   }
			  }else{
				if(jsonX.finalPaymentList && jsonX.finalPaymentList.length >0){
				var finalPay =[];
				var firstFinalPay = jsonX.finalPaymentList[0].finalPayment;
				if(jsonX.finalPaymentList.length > 1 && jsonX.finalPaymentListt.length){
				 for(var i = 1; i < jsonX.finalPaymentList.length ; i++){
                    finalPay.push(finalPayment[i]);
				 }
				}
				jsonX.firstFinalPay =firstFinalPay;
			   }
			 }
			 if(finalPayment){
				jsonX.finalPayDefault = finalPayment;
				jsonX.finalFlag = 1;
			 }else{
				jsonX.finalPayDefault = firstFinalPay;
			 }
			//1：等额本息 2:等额本金 3:尾款形
			 if(jsonX.repaymentType == 1){
              var template = hbs.compile(fs.readFileSync('./scripts/finance/product/productEqualDetail.html').toString());
			 }
			 if(jsonX.repaymentType == 2){
              var template = hbs.compile(fs.readFileSync('./scripts/finance/product/productCapitalDetail.html').toString());
			 }
			 if(jsonX.repaymentType == 3){
               var template = hbs.compile(fs.readFileSync('./scripts/finance/product/productFinalDetail.html').toString());
			 }
			//不存在产品详情
			}else{
				pageCountId=[0,8470,0,8480,8487][flow];
				jsonX.pageCountId=pageCountId;
			    var urlDetail ="http://price.pcauto.com.cn/dealer/interface/order/recommend_dealer.jsp?rid="+rId+"&sgid="+jsonX.serialGroupId+"&type=0";
			    //  = url +"/interface/outer/mobile/listDealer.jsp?rId="+rId+"&modelId="+modelId;
				// var urlDetail = "http://dev43.pcauto.com.cn:8001/interface/outer/mobile/listDealer.jsp?rId=3&modelId=38512"
				 var z = r.coGet(urlDetail);
			     var RESULT = yield [z];
				 var jsonZ = JSON.parse(iconv.decode(RESULT[0].body, 'GBK'));
				 var dealerList = jsonZ;
				 jsonX.shoufu = ratio;
				 jsonX.term =term;
				 if(ratio){
                   var downPayment= (jsonX.price * ratio/100).toFixed(2);
				   jsonX.downPayment = downPayment;
				 }
				   var loanValue =(jsonX.price - jsonX.downPayment).toFixed(2);
			       jsonX.loanValue = loanValue;
				   if(dealerList){
					 //大于一家经销商
					 if(dealerList.length >0){
						 for(var i = 0 ; i < 1; i++){
                          dealerList[i].check = 1
						 }
					 }
				  jsonX.dealerList = dealerList;
				  if(dealerList.length > 5){
				     jsonX.dealerShowLen = (dealerList.length - 5);
				   }
				 }
                 var template = hbs.compile(fs.readFileSync('./scripts/finance/product/dealerInquiry.html').toString());
			 }

			if(toolUtil.filterORG(jsonX.orgId)){//特殊处理
				jsonX.dealerList=[];
			}
			if(param.fmt === 'json') {
				rh.setHeader('Content-Type', 'application/json;charset=UTF-8');
				rh.setHeader('Cache-Control', 'max-age=' + (86400));
				rh.setBody(JSON.stringify(jsonX));
			}else {
				rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
				var path = require('../../../conf/config.js').config().path;
				jsonX.host = req.headers.host + path;
				var html = template(jsonX);
				rh.setHeader('Cache-Control', 'max-age=' + (86400));
				rh.setBody(html);
			}
             callback(null, rh);
	    }catch (e) {
            console.error(e);
			 //返回404页面
		    toolUtil.get404Page(fs,hbs,req,rh,callback);
            callback(e);
       }
    })();
};