/**
 * Created by lzh on 2015/9/14.
 * 获取临时二维码
 */
var QS       = require('querystring');
var iconv    = require('iconv-lite');
var hbs   = require('handlebars');
var co=require("co");
var fs       = require('fs');
var wxUtil=require('../../../lib/wxUtil.js');
var hp = require('../../../lib/httpsagent.js');
var toolUtil = require('../../../lib/toolUtil.js');

exports.handle = function(req, rh, maxAge, transEnc, queryString, callback) {
    co(function *(){
        try{
            var param = QS.parse(queryString);
			var orderId = param.orderId;
            //场景值ID（32位非0整型 4294967296-1 - 4294967295）
            var orderIdPatt = /^[1-9]\d{0,12}$/g;
            orderIdPatt.compile(orderIdPatt);
            var re1 = new RegExp(orderIdPatt);
            if(!orderId){
                toolUtil.get404Page(fs,hbs,req,rh,callback);
				return;
            }else if(!re1.test(orderId)){
                 toolUtil.get404Page(fs,hbs,req,rh,callback);
				 return;
            }
            else{
                if(orderId >4294967295 || orderId <-4294967296){
                  toolUtil.get404Page(fs,hbs,req,rh,callback);
				  return;
                }
            }
            //创建临时二维码参数
            var options ={
                "expire_seconds": 604800,
                "action_name": "QR_SCENE",
                "action_info": {
                    "scene": {
                        "scene_id": +orderId
                    }
                }
            }
            var  ticket = yield wxUtil.getQrCode(options);
            var Result = {}
            Result.code = 200;
            Result.desc = "success";
            Result.url = ticket;
            rh.setHeader('Content-Type', 'application/json; charset=UTF-8');
            rh.setBody(JSON.stringify(Result));
            callback(null, rh);
        } catch (e) {
            console.error('qrcode.js'+e);
			toolUtil.get404Page(fs,hbs,req,rh,callback);
            callback(e);
        }
    })();
};
