/**
 * 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 template = hbs.compile(fs.readFileSync('./scripts/finance/common/chooseBrSe.html').toString());
var memCacheUtil=require("../../../lib/MemCacheUtil.js");
var toolUtil=require("../../../lib/toolUtil.js");
hbs.registerHelper("getBrands", function(brands,pLetter,options) { //brands 对应字母下的brands pLetter对应字母
  try {
      var rowTotal = brands.length / 4;
      var temp = [];
      for (var j = 0; j < rowTotal; j++) {
          var brandsNew = [];
          for (var i = 0; i < 4; i++) {
              if(brands[i+j*4])
              brandsNew.push(brands[i+j*4]);
          }
          temp.push({"brands":brandsNew,"rowNum":j,"pLetter":pLetter,"brandslth":brands.length});
      }
      /**
       * 返回结果 [{“brands”:[1obj,2obj,3obj,4obj],rowNum:"第几行"，pLetter：“letter”,brandslth:length长度（处理最后一知少于四个的情况)]
       */
     return options.fn(temp);
  }catch(e){}
    return options.reverse(this);
});


hbs.registerHelper("getpLetter", function(obj,pLetter) {
    try {
        obj.pLetter=pLetter;
        return options.fn(obj);
    }catch(e){}
    return options.reverse(this);
});
exports.handle=function(req, rh, maxAge, transEnc, queryString, callback) {
    co (function *(){
        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={};
        letters.forEach(function(e){
            lettersMap[e]=0;//初始化为全部不显示
        });

        var hotData={'index':'HOT','brands':[]};
        var param=QS.parse(queryString);//得到相应的参数
        var type=param.type?param.type:"default";//传值type=discount表贴自页跳转过来
        var src=param.src?param.src:0;//0表示跳转到金融产品列表页 1表示跳转到车型页
        var rid=param.rid;
        // 页面计数器
        var flow=param.flow;
        var pageCountId=[0,8467,0,8477][flow];

        //if(!toolUtil.checkNumber(rid)||!(src==0||src==1)||!(type=="default"||type=="discount")){
        //   toolUtil.get404Page(fs,hbs,req,rh,callback);
        //}
        try {
            var m = yield memCacheUtil.get("brands_" + type);//取缓存数据
            if (m) {
                var jsonX = m;
            } else {
                var resultX = yield r.coGet("http://jr.pcauto.com.cn/interface/outer/mobile/allBrand.jsp");//完整列表
                var jsonX = JSON.parse(iconv.decode(resultX.body, "utf-8"));
                if (type === "discount") {
                    // if(false){
                    var resultY = yield r.coGet("http://jr.pcauto.com.cn/interface/outer/mobile/hasDiscountProBrand.jsp");//有贴息列表
                    var jsonY = JSON.parse(iconv.decode(resultY.body, "utf-8"));
                    jsonX.list.forEach(function (ex) {
                        var index = ex.index;
                        var brands = ex.brands;
                        brands.forEach(function (eb) {
                            if (eb.isHot === 1 || eb.isHot === "1") {
                                hotData.brands.push(eb);//加入热门品牌当中
                            }
                        });

                              //  ex.show = 1;
                              //  lettersMap[ex.index] = 1;
                                brands.forEach(function (eb) {
                                    if(eb.show==1){
                                        eb.show=0;
                                    jsonY.list.forEach(function (ey) {
                                        if (ey.index ===index) {
                                              //  eb.show=0
                                                ey.brands.forEach(function (eby) {
                                                    if (eby.id === eb.id) {
                                                        eb.show = 1;
                                                        lettersMap[ex.index]=1;
                                                    }
                                                });
                                                ex.rowNum4 = ex.rowNum / 4 + 1;
                                            }

                                      });
                                    }

                        });

                        hotData.brands.forEach(function(e){
                            if(lettersMap[e.letter]==0){
                                e.show=0;
                            }
                        })
                    });
                } else {
                    jsonX.list.forEach(function (e) {
                      //  e.show = 1;
                        e.brands.forEach(function (eb) {
                            if (eb.isHot === 1 || eb.isHot === "1") {
                                hotData.brands.push(eb);//加入热门品牌当中
                            }
                            if(eb.show==1){lettersMap[e.index]=1}
                        });
                        e.rowNum4 = e.rowNum / 4 + 1;
                    });
                }
                hotData.rowNum = hotData.brands.length;
                hotData.rowNum4 = hotData.rowNum / 4 + 1;//一行四个
                jsonX.list.unshift(hotData);
                jsonX.lettersMap = lettersMap;
                //缓存车系如何弄？
                jsonX.src = src;//源头
                memCacheUtil.set("brands_" + type, jsonX, 60);
            }
            jsonX.param = param;
            var path  = require('../../../conf/config.js').config().path;
            jsonX.host=req.headers.host+path;
            jsonX.cookieHost=req.headers.host;
            jsonX.flow=flow;
            jsonX.pageCountId=pageCountId;
            
            if (param.fmt === "json") {
                rh.setHeader('Content-Type', 'application/json; charset=UTF-8');
                if(src!=0)rh.setHeader('Cache-Control', 'max-age=' + (86400));
                rh.setBody(JSON.stringify(jsonX));
            } else {
                var html = template(jsonX);
                // 设置响应头信息
                rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
                if(src!=0)rh.setHeader('Cache-Control', 'max-age=' + (86400));
                // 设置响应内容
                rh.setBody(html);
           }

            // 回调通知
            callback(null, rh);
        }catch(e){
            console.log("--chooseBrSe.js err--\n");
            console.log(e);
            toolUtil.get404Page(fs,hbs,req,rh,callback);
        }
    })();

}
