/**
 * 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');
var path  = require('../../../conf/config.js').config().path;
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 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);
             }else if(!re1.test(rId)){
                 toolUtil.get404Page(fs,hbs,req,rh,callback);
             }
			 var sort =param.sort;                   //排序
			 var level =param.level;                 //级别
			 var bid = param.bid;                    //品牌ID
			 var prePayRange = param.prePayRange;    //首付范围
			 var paymentRange = param.paymentRange;  //月供范围
			 var pageSize = param.pageSize;          //每页大小
			 var pageNo = param.pageNo;              //当前页码
             var url = "http://jr.pcauto.com.cn";
             var flow=param.flow;
			 //按预算选车型接口
			 var urlX = url+"/interface/outer/mobile/listModelByBudget.jsp?rId="+rId;
			 if(level){
				urlX = urlX  + '&level='+level;
				//默认紧凑车型
			 }else{
				 level=73
				 urlX = urlX  + '&level=73';
			 }
             //
			 if(bid){
                urlX  = urlX  + '&bId='+bid;
				//jsonX.bId = bId;
			 }
			 if(prePayRange){
               urlX = urlX  + '&prePayRange='+prePayRange;
			 }else{
			   prePayRange = 5;
			   urlX = urlX  + '&prePayRange=5';
			 }
			 if(paymentRange){
               urlX  = urlX  + '&paymentRange='+paymentRange;
			 }else{
               paymentRange=3;
			   urlX  = urlX  + '&paymentRange=3';

			 }
			 if(sort){
               urlX  = urlX  + '&sort='+sort;
			 }
			 if(pageSize){
               urlX  = urlX  + '&pageSize='+pageSize;
			 }else{
               urlX  = urlX  + '&pageSize=10';
			 }
			 if(pageNo){
                urlX  = urlX  + '&pageNo='+pageNo;
			 }
             var x = r.coGet(urlX);
			 var RESULT = yield [x];
			 var jsonX = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));
			 jsonX.rId = rId;
			 jsonX.prePayRange = prePayRange;
			 jsonX.paymentRange = paymentRange;
			 jsonX.level = level;
			 if(browser){
				if(browser == 'wx'){
				 jsonX.browser = browser;
				}
			}
			 if(bid){
			     jsonX.bid = bid;
			 }else{
				 jsonX.bid = '';
			 }
			// jsonX.bid =bid;
			 if(sort){
			  jsonX.sort = sort;
			 }else{
                jsonX.sort =1;
			 }
             //选择品牌
			 if(bid){
				 var urlBid = url +"/interface/outer/mobile/top300Brands.jsp";
				 var y = r.coGet(urlBid);
			     var RESULT = yield [y];
			     var jsonY = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));
				 var list = jsonY.list;
				 if(list && list.length >0){
				  for(var i = 0 ; i < list.length ; i ++){
				    var brands = list[i].brands; 
					if(brands && brands.length >0){
					for(var j = 0 ; j <brands.length; j++){
						if(brands[j].id == bid){
							var name = brands[j].name;
							break;
						}
					   }
					 }
					}
				   }
				   jsonX.brandName = name;
				   jsonX.bid =bid;
			      }
			 
			 //控制跳转到不同的页面
			 // 1：默认  2：月供
			 if(sort){
			  if(sort== '1'){
			     var template = hbs.compile(fs.readFileSync('./scripts/finance/common/budgetSerial1.html').toString());
			   }
               if(sort == '2'){
                 var template = hbs.compile(fs.readFileSync('./scripts/finance/common/budgetSerial2.html').toString());
			   }
			 }else{
                  var template = hbs.compile(fs.readFileSync('./scripts/finance/common/budgetSerial1.html').toString());
			 }
            rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
            jsonX.host=req.headers.host+path;
            jsonX.flow=flow;
            var html = template(jsonX);
            rh.setHeader('Cache-Control', 'max-age=' + (86400));
            rh.setBody(html);
            callback(null, rh);
	    }catch (e) {
            console.error('budgetSerial.js'+e);
			 //返回404页面
		    toolUtil.get404Page(fs,hbs,req,rh,callback);
            callback(e);
       }
    })();
};