/*
*Created by xmy_zjl on 2015/10/9
*/

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;

var template = hbs.compile(fs.readFileSync('./scripts/finance/common/brand.html').toString());

exports.handle = function(req,rh,maxAge,transEnc,queryString,callback) {
	co(function *() {
		try{
			var param = qS.parse(queryString);
                  var browser = param.browser === 'wx'?param.browser:'0';//判断是否微信
                  var domain = 'http://jr.pcauto.com.cn';//定义后端接口域名
			//设置字母
			var  letters=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
			var lettersMap={};
			var hotData = {'index':'HOT','brands':[]};
                  var jR = {};//定义存储结果的对象

			letters.forEach(function(e) {
				lettersMap[e]=0;//初始化为全部置灰，不可点击
			});

			//获取top300品牌数据
			var x = yield r.coGet(domain +'/interface/outer/mobile/top300Brands.jsp');

			//转换成utf-8编码，防止乱码
			var jx = JSON.parse(iconv.decode(x.body, 'UTF-8'));

                  jx.list.forEach(function(item) {
            	     if(item) {
                              var count = 0;//定义初始有金融产品品牌数为0
            		    item.brands.forEach(function(item2) {
            			   if(item2) {//品牌下有数据
                                          count += item2.hasProduct;
                                          if(item2.isHot === 1) {//热门品牌
                                                hotData.brands.push(item2); //品牌为热门品牌，加入热门队列
                                          }
            			   }
            		    });
                              if(count !== 0) {
                                    lettersMap[item.index] = 1;//字母下有品牌,且有产品，高亮显示，可以点击
                              }
            	     }
                  });
            
                  jR = jx;//加入品牌数据
                  jR.host = req.headers.host +path;
                  jR.lettersMap = lettersMap;//加入字母规则
                  jR.param = param;//传入参数回传
                  jR.browser = browser;//加入微信识别
                  jR.list.unshift(hotData);//在list队列最前端插入热门品牌数据
                  jR.flow=param.flow;

                  if(param.fmt === 'json') {//返回json
            	     rh.setHeader('Content-Type','application/json;charset=UTF-8');
            	     rh.setBody(jR);
                  }else {//返回html
            	     rh.setHeader('Content-Type','text/html;charset=UTF-8');
            	     var html = template(jR);//设置响应数据
            	     rh.setHeader('Cache-Control','max-age='+(maxAge));
            	     rh.setBody(html);
                  }
                  callback(null,rh);//回调显示
		}catch(e) {
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
			console.error('common/brand.js:'+ e);
			callback(e);
		}
	})();
}