/**
 * Created by wxl on 2015/9/10.
 * 微信接入接口
 */
var QS       = require('querystring');
var wxUtil=require('../../../lib/wxUtil.js');
var iconv    = require('iconv-lite');
var xml2js=require("xml2js");
var r=require("../../../lib/r.js");
var co=require("co");
exports.handle = function(req, rh, maxAge, transEnc, queryString, callback) {
    co(function *(){
      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.signature);//把该参数返回给微信端
              // 回调通知
              callback(null, rh);
          }else{
              console.log("can't not connect to weixin");
          }
      }else{//接收消息及事件都属于post接口
          var strXML=iconv.decode(req.body,"utf-8");//得到xml数据
          var x=wxUtil.xml2Json(strXML);
          var xmlJson=yield x;
          if(xmlJson.MsgType==="text"){//接收到的是文本消息
              //发送文本消息
              var options={"ToUserName":xmlJson.FromUserName,"FromUserName":xmlJson.ToUserName,
                  MsgType:"text",Content:"so ,what ,how"
              };
              var resBody=wxUtil.ToXml(options);
              rh.setHeader('Content-Type', 'text/html; charset=UTF-8');
              rh.setBody(resBody);
              callback(null, rh);
          }else if(xmlJson.MsgType==="event"){
              if(xmlJson.Event==="subscribe"){//未订阅时，扫描二维码的方式进来
                 var phone=xmlJson.EventKey.replace("qrscene_","");//得到phone，并得到对应的openId
                  r.writeToCache(xmlJson.ToUserName,phone,7200);//把open_id=>phone一对一关系
              }else if(xmlJson.Event==="SCAN"){
                  var phone=xmlJson.EventKey();//得到对应的phone内容
                  r.writeToCache(xmlJson.ToUserName,phone,7200);//把open_id=>phone一对一关系
              }
          }
      }
    })();
};
