/**
 * Created by lzh on 2015/9/15.
 * 微信接入接口
 */
var QS       = require('querystring');
var wxUtil=require('../../../lib/wxUtil.js');
var tsUtil=require('../../../lib/tsUtil.js');
var r        = require('../../../lib/r.js');
var X2J = require('../../../lib/tsUtil.js');
var iconv = require('iconv-lite');
var xml2js=require("xml2js");
var co=require("co");
exports.handle = function(req, rh, maxAge, transEnc, queryString, callback) {
    co(function *(){
		try{
          if(req.method==="GET"){
          var  param= QS.parse(queryString);
          
          if(wxUtil.checkSignature(param)){
              rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
              rh.setBody(param.echostr);//把该参数返回给微信端
              // 回调通知
              callback(null, rh);
          }else{
          	console.log("can't not connect to weixin");
          	  rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
              rh.setBody('');
              callback(null, rh);
          }
		//接收消息及事件都属于post接口
        }else{

          //获取xml数据
          var strXML=iconv.decode(req.body,"utf-8");//得到xml数据
          var x=wxUtil.xml2Json(strXML);
          var xmlJson=yield x;
          if(xmlJson.MsgType==="event" && xmlJson.Event==='subscribe' && xmlJson.EventKey===''){//用户关注(非扫描二维码)
              //发送文本消息
              var options={"ToUserName":xmlJson.FromUserName,"FromUserName":xmlJson.ToUserName,
                  MsgType:"text",Content:"哈喽，感谢您关注我们“太平洋汽车贷款平台”，我们平台立足于中国领先的汽车垂直网站太平洋汽车网，为您提供专业的汽车贷款服务，让您足不出户即能申请最实惠、最适合您的汽车贷款！\n\n点击菜单“我要贷款”，即可申请贷款购车！如果有任何关于贷款购车方面的疑问，欢迎留言咨询，我们将会有专人在线为您解答哦！"
              };
              var resBody=wxUtil.ToXml(options);
              rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
              rh.setBody(resBody);
              callback(null, rh);
          }


		  var orderId = ''
		  var openId = '';
		  //接受事件推送
		  if(xmlJson.MsgType == 'event'){
			//扫描带参数二维码用户未关注
		    if(xmlJson.Event == 'subscribe'){
				  openId = xmlJson.FromUserName   //获取openId
                  orderId=xmlJson.EventKey.replace("qrscene_","");//得到orderId
			}
			//扫描带参数二维码用户已关注
		   if(xmlJson.Event == 'SCAN'){
              openid= xmlJson.FromUserName   //获取openId
			  orderId=xmlJson.EventKey;//得到对应的oderId内容
		   }
		  }

		  //获取个人信息
			 if(openId){
				// var param = {"openid":openId, "access_token":token};
		        // var userInf = yield wxUtil.getUserInfo(openid);
				 var url ="http://jr.pcauto.com.cn/interface/outer/weixin/account.jsp?orderId="+orderId+"&openId="+openId;
		           var y = r.coGet(url);
		           var RESULT = yield [y];
		           var jsonY = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));
				   if(jsonY.code == 0){
					   // console.log(openid+'success');
				   }else{
					   // console.log(openid+'false');
				   }
			 }
		  //模拟订单数据
		 // 车贷订单查询接口(微信)
		  if(orderId != ''){
           var url ="http://jr.pcauto.com.cn/interface/outer/weixin/order.jsp?orderId="+orderId;
		   var x = r.coGet(url);
		   var RESULT = yield [x];
		   var jsonX = JSON.parse(iconv.decode(RESULT[0].body, 'UTF-8'));
		   if(jsonX && jsonX.code == 0){
				 jsonX.ToUserName =xmlJson.FromUserName ;
			     jsonX.FromUserName=xmlJson.ToUserName;
                 jsonX.MsgType = 'text';
				 var xmlData = X2J.tsXml(jsonX);
				 rh.setHeader('Content-Type', 'text/xml; charset=UTF-8');
                 rh.setBody(xmlData);
		   }else{
				var msgResult = {"code":-1,"msg":"订单信息不存在!"};
				rh.setHeader('Content-Type', 'text/json; charset=UTF-8');
                rh.setBody(JSON.stringify(msgResult));
			}
		  }
	  }
	      callback(null, rh);
	    }catch (e) {
            console.error('jrweixin/infosave.js'+e);
            callback(e);
       }
    })();
};