using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CallCenter.Utility;
using CallCenterAPI.WechatSDK;
using System.IO;
using CallCenterAPI.WechatSDK.Code;

namespace CallCenterApi.Interface.Controllers.weixin
{
    public class WxReceiveController : Controller
    {
        /// <summary>
        /// 本系统提供给微信服务端调用的接口
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            Log log = LogFactory.GetLogger("WxReceive");
            #region 基本数据配置
            string signature = Request["signature"]; //响应微信发送的Token验证需要的签名
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];
            string echostr = Request["echostr"];
            string msg_signature = Request["msg_signature"];  //解密微信推送的消息需要的签名
            //微信公众号-基本设置-服务器配置-令牌(Token)【必需】
            var token = Configs.GetValue("WechatToken"); ;
            //微信公众号-基本设置-服务器配置-消息加解密密钥(EncodingAESKey)【必需】
            var encodingAESKey = Configs.GetValue("WechatEncodingAESKey"); ;
            #endregion

            #region 响应微信发送的Token验证, GET
            if (!RequestString.IsPost())
            {
                if (!WxHelper.CheckSignature(signature, timestamp, nonce, token))
                    return Content("error");
                else
                    return Content(echostr);
            }
            #endregion

            #region 获取微信推送消息，POST
            StreamReader srResult = new StreamReader(RequestString.GetInputStream());
            string dataEncrypt = srResult.ReadToEnd();
            string dataDecrypt = "";
            int ret = 0;
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, Configs.GetValue("WechatAppid"));
            ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, dataEncrypt, ref dataDecrypt);
            if (ret != 0)
            {
                log.Error($"微信消息推送解密失败，错误代码：{ret}");
                return Content("error");
            }
            XmlHelper xml = new XmlHelper();
            xml.LoadFromXmlString(dataDecrypt);
            string openid = xml.GetValue("FromUserName");
            string type = xml.GetValue("MsgType");
            if (type != "event")
            {
                WxHelper.CreateSession(openid);
            }
            return Content("success");
            #endregion

        }
    }
}