/**
 * Created by wxl on 2015/9/21.
 * @des :通过brandId来取车系数据，这个车系数据可先缓存
 */
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 memCacheUtil=require("../../../lib/MemCacheUtil.js");
var toolUtil=require("../../../lib/toolUtil.js");
exports.handle=function(req, rh, maxAge, transEnc, queryString, callback) {
    co (function *()
    {
        var param = QS.parse(queryString);
        var brandId = param.bid;//品牌id
        var type = param.type=="1"?"discount":"default";//是否促息信息。
        if(!toolUtil.checkNumber(brandId)){
            toolUtil.replyError(rh,callback,500);
        }

        var m = yield memCacheUtil.get("serialsByBrandId_" + brandId + "_" + type);//取缓存数据
        var ResultX = yield r.coGet("http://jr.pcauto.com.cn/interface/outer/mobile/allManuSerialGroup.jsp?bId="+brandId);
        var jsonX = JSON.parse(iconv.decode(ResultX.body, "utf-8"));
        if (m) {
             var jsonX =m;
        } else {
             if (type === "discount") {
                var ResultY = yield r.coGet("http://jr.pcauto.com.cn/interface/outer/mobile/hasDiscountManuSerialGroup.jsp?bId="+brandId);
                 var jsonY = JSON.parse(iconv.decode(ResultY.body, "utf-8"));
                jsonX.list.forEach(function (ex) {
                    ex.serials.forEach(function (esy) {
                         esy.show=0;
                    });
                    jsonY.list.forEach(function (ey) {
                        if (ey.manufacturer === ex.manufacturer) {
                            ex.serials.forEach(function (esy) {
                                esy.show=0;
                                ey.serials.forEach(function (eys) {
                                    if (eys.id === esy.id) {
                                        esy.show = 1;
                                    }
                                })
                            })

                        }
                    })
                })

            }

            if (jsonX == null) {
                memCacheUtil.set("serialsByBrandId_" + brandId + "_" + type,jsonX, 60);
            }
        }

        // 设置响应头信息
        rh.setHeader('Content-Type', 'application/json; charset=UTF-8');
        if (maxAge) {
            rh.setHeader('Cache-Control', 'max-age=' + (maxAge));
        }
        rh.setBody(JSON.stringify(jsonX));
        callback(null, rh);
    })();
}