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 phone=getPhoneInCookie(req);

            //前置条件检查 ^[1][3-8]+\\d{9}
            //校验手机号
            var telPatt = /^[1][3-8]+\d{9}/g;
            telPatt.compile(telPatt);
            var reg = new RegExp(telPatt);
            if(!phone || phone==req.headers.cookie || !reg.test(phone)){
                  // 重定向到验证手机页面
                    var jsonResult={"param":param};
                    jsonResult.host=req.headers.host+path;
                    jsonResult.cookieHost=req.headers.host;
                    var template = hbs.compile(fs.readFileSync('./scripts/finance/info/sendCode.html').toString());
                    var html = template(jsonResult);
                    // 设置响应头信息
                    rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
                    if(maxAge)rh.setHeader('Cache-Control', 'max-age=' + (maxAge));
                    // 设置响应内容
                    rh.setBody(html);
                    // 回调通知
                    callback(null, rh);
                  return;
            }

            var domain='http://jr.pcauto.com.cn';
            //加载订单
            var x=r.coGet(domain+'/interface/outer/mobile/myOrder.jsp?tel='+phone);

            var RESULT = yield [x];
            var data = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));
            data.browser=param.browser;
            data.host=req.headers.host+path;


            if(param.fmt === 'json') {
                  rh.setHeader('Content-Type','application/json;charset=UTF-8');
                  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/order/order.html').toString());
                  }else{
                        template=hbs.compile(fs.readFileSync('./scripts/finance/order/noOrder.html').toString());
                  }
                  // 微信访问标识
                  data.fromWechat=req.headers['user-agent'].indexOf('MicroMessenger') >0 ? true:undefined;
                  var html = template(data);

                  rh.setHeader('Cache-Control','max-age='+(maxAge));
                  rh.setBody(html);
            }
            callback(null, rh);

      }catch(e) {
            toolUtil.get404Page(fs,hbs,req,rh,callback);
            console.error('order/order.js:'+e);
            callback(e);
      }
      })();
}

function getPhoneInCookie(req){
      reg = /.*phone%22:%22(\d+).*/;
      var phoneInCookie = req.headers.cookie;
      phoneInCookie=phoneInCookie;

      if(!phoneInCookie){
        phoneInCookie =undefined;
      }else{
        phoneInCookie = phoneInCookie.replace(reg, "$1");
      }

      return phoneInCookie;
};