var co = require('co');
var fs = require('fs');
var hbs = require('handlebars');
var iconv = require('iconv-lite');
var qS = require('querystring');
var r = require('../../../lib/r.js');
var toolUtil = require('../../../lib/toolUtil.js');
var path  = require('../../../conf/config.js').config().path;

exports.handle = function(req,rh,maxAge,transEnc,queryString,callback) {
	co(function *() {
	try{
            // 接收参数
            var param = qS.parse(queryString);
            var rId=param.rId;
            var serialId=param.serialId;
            var modelId=param.modelId;
            var feature=param.feature==''?0:param.feature;
            var prepay=param.prepay==''?30:param.prepay;
            var term=param.term==''?24:param.term;
            var ip=req._remoteAddress;
            var type=param.type;

            // 页面计数器、流程计数器
            var flow=param.flow;
            var pageCountId=[0,8468,0,8478,8485][flow];
            var applyCountId=[0,5255,0,5262,5269][flow];
            var askCountId=[0,5275,0,5264,5271][flow];

            if(type=='discount')
                  feature=1;

            //前置条件检查
            //校验区域Id
            var rIdPatt = /^\d{1,4}$/g;
            rIdPatt.compile(rIdPatt);
            var reg = new RegExp(rIdPatt);

            if(!rId){
                  //返回404页面
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
                  console.error('product/list.js: rid is null');
                  return;

            }else if(!reg.test(rId)){
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
                  console.error('product/list.js: rid incorrect '+rId);
                  
            }

            // 检查车系ID 必须有
            if(!serialId){
                  toolUtil.get404Page(fs,hbs,req,rh,callback);

                  console.error('product/list.js: serialId is null');
            }else{
                  var serialIdPatt = /^[1-9]\d{0,5}$/g;
                  serialIdPatt.compile(serialIdPatt);
                  reg = new RegExp(serialIdPatt);

                  if(!reg.test(serialId)){
                        toolUtil.get404Page(fs,hbs,req,rh,callback);
                        console.error('product/list.js: serialId incorrect '+serialId);
                        return;     
                  }
            }

            // 检查车型ID
            if(modelId){
                  var modelIdPatt = /^[1-9]\d{0,5}$/g;
                  modelIdPatt.compile(modelIdPatt);
                  reg = new RegExp(modelIdPatt);

                  if(!reg.test(modelId)){
                        toolUtil.get404Page(fs,hbs,req,rh,callback);
                        console.error('product/list.js: modelId incorrect '+modelId);
                        return; 
                  }  
            }
            var prepayArray=[20,30,40,50,60];
            var termArray=[12,18,24,36];

            // 检查还款期限，首付比例取值返回
            if(prepayArray.indexOf(parseInt(prepay)) == -1){
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
                  console.error('product/list.js: prepay incorrect '+prepay);
                  return; 
            }

            if(termArray.indexOf(parseInt(term)) == -1){
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
                  console.error('product/list.js: term incorrect '+term);
                  return; 
            }
           
            

            /**
             * 字典确认所选车型/车系、当前城市下是否有产品（待添加）
             */

            var domain='http://jr.pcauto.com.cn';
            //加载产品列表 和 车型数据
            var x=r.coGet(domain+'/interface/outer/mobile/listProduct.jsp?pageNo=1&pageSize=100&rId='+rId+'&modelId='+modelId+'&serialGroupId='+serialId+'&feature='+feature+'&prepay='+prepay+'&term='+term);
            var y=r.coGet(domain+'/interface/outer/mobile/listModel.jsp?sgId='+serialId);

            var RESULT = yield [x,y];
            var data = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));

            // 如果品牌，图标都没数据，跳转到404页
            if(data.brandName=='' || data.icon==''){
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
                  console.error('product/list.js: sgId or modelId not exist!');
                  return;
            }

            // 没有返回推荐车型信息，跳至异常页面
            if(!data.modelId || data.modelId==0){
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
                  console.error('product/list.js: no model match');
                  return;
            }

            var models =JSON.parse(iconv.decode(RESULT[1].body, 'UTF-8'));

            // 没有产品列表，加载经销商数据
            if(!data.list||data.list.length==0){
                  var z=r.coGet("http://price.pcauto.com.cn/dealer/interface/order/recommend_dealer.jsp?rid="+rId+"&sgid="+serialId+"&type=0");
                  var dealerData = yield[z];

                  var dealers;
                  try{
                        dealers = JSON.parse(iconv.decode(dealerData[0].body, 'GBK'));
                  }catch(e){
                        console.error('product/list.js: dealers data load error : modelId='+data.modelId)
                  }
                  data.dealers=dealers==undefined?null:dealers;
            }

            // 添加页面数据
            data.models = models.list;
            data.rId=rId;
            data.sgId=serialId;
            data.ip = ip;
            data.type=type;
            data.path4city=req.orginalUrl.replace(/\/r\d+/,'');
             //去掉f参数
            data.path4city=data.path4city.substring(0,data.path4city.length-3);
            data.path4city=data.path4city.replace('wx/','');

            // 去掉url中的选项,替换discount=choose
             data.path4item=req.orginalUrl.replace('wx/','');
             data.path4item=req.orginalUrl.replace(/f(\d+)-/,'');
             //去掉f参数
            data.path4item=data.path4item.substring(0,data.path4item.length-3);

            var itemIndex=req.orginalUrl.indexOf('-s');
            data.path4item=data.path4item.substring(0,itemIndex>0?itemIndex:data.path4item.length-1);
            
            data.prefix='http://'+req.headers.host+path;

            data.path4models=data.path4item;
            // data.path4models.replace(//,)

            

      //      data.feature=feature;
            data.prepay=prepay;
            data.term=term;
            data.browser=param.browser;
            data.host=req.headers.host+path;
            data.flow=flow;
            data.pageCountId=pageCountId;
            data.applyCountId=applyCountId;
            data.askCountId=askCountId;

            if(param.fmt === 'json') {
                  rh.setHeader('Content-Type','application/json;charset=UTF-8');
                  rh.setHeader('Cache-Control', 'max-age=' + (86400));
                  rh.setBody(JSON.stringify(data));

            }else {
                  rh.setHeader('Content-Type','text/html;charset=UTF-8');
                  var template;

                  // 无数据跳转到无产品列表页
                  if(data.list&&data.list.length!=0){
                        template=hbs.compile(fs.readFileSync('./scripts/finance/product/list.html').toString());
                  }else{
                        template=hbs.compile(fs.readFileSync('./scripts/finance/product/listEmpty.html').toString());
                  }

                  var html = template(data);
                  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);
	}
	})();
}