/**
 * Created by lzh on 2015/9/23.
 * 金融首页
 */
var co    = require('co');
var fs    = require('fs');
var QS       = require('querystring');
var iconv    = require('iconv-lite');
var r     = require('../../lib/r.js');
var hbs   = require('handlebars');
var toolUtil = require('../../lib/toolUtil.js');
var template = hbs.compile(fs.readFileSync('./scripts/finance/index.html').toString());
var path  = require('../../conf/config.js').config().path;

function getRidInCookie(req){
	reg = /.*regionCity%22%3A(\d+)%2C%22.*/;
    var cookie = req.headers.cookie;
	var ridInCookie= cookie;
    if(!ridInCookie)
        return undefined;
    ridInCookie = ridInCookie.replace(reg, "$1");
    if(ridInCookie==cookie)
    	return undefined;
    return ridInCookie;
}

exports.handle = function(req, rh, maxAge, transEnc, queryString, callback) {
    co(function *(){
		try{

			 var param = QS.parse(queryString);
			 var rId = getRidInCookie(req);     //城市Id
			 var rIdPatt = /^[1-9]\d{0,4}$/g;
             rIdPatt.compile(rIdPatt);
             var re1 = new RegExp(rIdPatt);
			 var browser=param.browser;
             if(!rId){
                 //返回404页面
				 toolUtil.get404Page(fs,hbs,req,rh,callback);
				 console.error('index.js: rid not in cookie');
             }else if(!re1.test(rId)){
                 //返回404页面
				 toolUtil.get404Page(fs,hbs,req,rh,callback);
				 console.error('index.js: rid incorrect ' +rId);
             }
			 var url = "http://jr.pcauto.com.cn";
			 //热门车型推荐接口
			 var urlX = url+"/interface/outer/mobile/hotModel.jsp?rId="+rId;
			 //热门金融产品推荐
			 var urlY =url+"/interface/outer/mobile/hotProduct.jsp?rId="+rId;
             var x = r.coGet(urlX);
			 var y = r.coGet(urlY);
			 var RESULT = yield [x,y];
			 var jsonX = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));
			 var jsonY =JSON.parse(iconv.decode(RESULT[1].body, 'UTF-8'));
			 if(jsonX){
               var listArray = jsonX.list;
			 }
			 if(jsonY){
			   var bankArray = jsonY.list;
			 }
			if(listArray  && listArray.length >0){
			  for(var i = 0; i < listArray.length ; i++){
				//小型车
				var limLength = 5;
				if(listArray[i].tab == '小型车'){
					//显示前五的车型
				   var data =[];
				   var smallCarData = [];
				   if(listArray[i].data.length >limLength){
					  for(var j = 0 ; j < limLength ; j++){
                         data.push(listArray[i].data[j]);
					  }
                      smallCarData = data;
				   }else{
					   smallCarData = listArray[i].data;
				   }
				}
				//小型车
				if(listArray[i].tab == '紧凑型车'){
					//显示前五的车型
				   var data =[];
				   var compactCarData  = [];
				   if(listArray[i].data.length >limLength){
					  for(var j = 0 ; j < limLength ; j++){
                         data.push(listArray[i].data[j]);
					  }
                      compactCarData  = data;
				  }else{
					   compactCarData  = listArray[i].data;
				  }
				}
				//中大型车
				if(listArray[i].tab == '中大型车'){
                   //显示前五的车型
				   var data =[];
				   var largeCarData = [];
				   if(listArray[i].data.length >limLength){
					  for(var j = 0 ; j < limLength ; j++){
                         data.push(listArray[i].data[j]);
					  }
                      largeCarData = data;
				  }else{
					   largeCarData = listArray[i].data;
				  }
				}
				//中大型车
				if(listArray[i].tab == 'SUV'){
					 //显示前五的车型
				   var data =[];
				   var suvCarData  = [];
				   if(listArray[i].data.length >limLength){
					  for(var j = 0 ; j < limLength; j++){
                         data.push(listArray[i].data[j]);
					  }
                      suvCarData  = data;
				  }else{
					   suvCarData  = listArray[i].data;
				  }
				}
			  }
			}
			if(bankArray && bankArray.length > 0){
				for(var i = 0; i < bankArray.length ; i++){
					//推荐金融
					if(bankArray[i].tab == '推荐金融'){
                       var recommendFinance = bankArray[i].orgs;
					}
					//超低利率
					if(bankArray[i].tab == '超低利率'){
                       var lowRate = bankArray[i].orgs;
					}
					//零利息
					if(bankArray[i].tab == '零利息贷款'){
                       var zeroInterest = bankArray[i].orgs;
					}
					//零月供
					if(bankArray[i].tab == '零月供贷款'){
                       var zeroSupply = bankArray[i].orgs;
					}
				}
			}
			//	组装JSON数据
			var jsonCar ={};
			if(smallCarData){
			  jsonCar.smallCarData = smallCarData;
			}
			if(compactCarData){
			  jsonCar.compactCarData = compactCarData;
			}
			if(largeCarData){
			  jsonCar.largeCarData = largeCarData;
			}
			if(suvCarData){
			  jsonCar.suvCarData = suvCarData;
			}
			if(browser){
				if(browser == 'wx'){
				 jsonCar.browser = browser;
				}
			}
			var jsonFinance ={};
			if(recommendFinance && recommendFinance.length >0){
				 for(var i = 0; i < recommendFinance.length ; i++){
					  var modelsData =[];
					  var models = recommendFinance[i].models;
					  if(models  && models.length >0){
						  //当前金融结构下产品大于3取前3
						  if(models.length >3){
							  for(var j = 0 ; j < 3 ; j++){
                                modelsData.push(models[j]);
							  }
							  recommendFinance[i].models = modelsData;
						  }

					  }
				 }
				jsonFinance.recommendFinance =recommendFinance;
			}
			
			if(lowRate && lowRate.length >0){
				 for(var i = 0; i < lowRate.length ; i++){
					  var modelsData =[];
					  var models = lowRate[i].models;
					  if(models  && models.length >0){
						  //当前金融结构下产品大于3取前3
						  if(models.length >3){
							  for(var j = 0 ; j < 3 ; j++){
                                modelsData.push(models[j]);
							  }
							 lowRate[i].models = modelsData;
						  }

					  }
				 }
				jsonFinance.lowRate =lowRate;
			}
			if(zeroInterest && zeroInterest.length >0){
                for(var i = 0; i < zeroInterest.length ; i++){
					  var modelsData =[];
					  var models = zeroInterest[i].models;
					  if(models  && models.length >0){
						  //当前金融结构下产品大于3取前3
						  if(models.length >3){
							  for(var j = 0 ; j < 3 ; j++){
                                modelsData.push(models[j]);
							  }
							  zeroInterest[i].models = modelsData;
						  }

					  }
				 }              
				jsonFinance.zeroInterest =zeroInterest;
			}
			if(zeroSupply && zeroSupply.length >0){
                for(var i = 0; i < zeroSupply.length ; i++){
					  var modelsData =[];
					  var models = zeroSupply[i].models;
					  if(models  && models.length >0){
						  //当前金融结构下产品大于3取前3
						  if(models.length >3){
							  for(var j = 0 ; j < 3 ; j++){
                                modelsData.push(models[j]);
							  }
							zeroSupply[i].models = modelsData;
						  }

					  }
				 }        
				jsonFinance.zeroSupply =zeroSupply;
			}
			jsonCar.financeData = jsonFinance;
			jsonCar.rid=rId;
			jsonCar.host=req.headers.host+path;


            rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
            var html = template(jsonCar);
            rh.setHeader('Cache-Control', 'max-age=' + (maxAge));
            rh.setBody(html);
            callback(null, rh);
	    }catch (e) {
            console.error('index.js'+e);
			  //返回404页面
		    toolUtil.get404Page(fs,hbs,req,rh,callback);
            callback(e);
       }
    })();
};
