using JiouSDP.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Param;
using Wechat;
using Wechat.Enum;
using Wechat.Model;
//测试公众号  全自动化测试
namespace JiouSDP.Areas.WeiXinApi.Controllers
{
    [LF(IsLoginFilter = false)]
    [PF(IsPermissionFilter = false)]
    public class wx570bc396a51b8ff8Controller : BaseController
    {
        //
        // GET: /wx1efed944cad6ca0f/

        public ActionResult callback()
        {
            //appid： wx570bc396a51b8ff8
            //Username： gh_3c884a361561
            try
            {
                Wechat.LogManage.Log("公众号消息与事件接收URL->url:" + Request.Url);
                var getpara = GetOrPostParam.GetRequestGet(Request);

                if (Verify(getpara) == true)//验证成功
                {
                    //注意排重的问题,详细见开发文档
                    //.....

                    switch (Request.HttpMethod.ToUpper())
                    {
                        case "GET"://验证URL有效性
                            if (getpara.ContainsKey("echostr") == true)
                            {
                                string echostr = getpara["echostr"];//随机字符串
                                Response.Write(echostr);
                            }
                            break;
                        case "POST":
                            StreamReader stream = new StreamReader(Request.InputStream);
                            string xml = stream.ReadToEnd();
                            Wechat.LogManage.Log("公众号消息与事件接收URL->data:" + xml);
                            LogicalProcessing(xml);
                            break;
                        default:
                            Wechat.LogManage.Log("公众号消息与事件接收URL->HttpMethod::" + Request.HttpMethod.ToUpper());
                            Response.Write("success");
                            break;
                    }
                }
                else
                {
                    Wechat.LogManage.Log("公众号消息与事件接收URL->验证失败");
                }
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log(string.Format("公众号消息与事件接收URL发生了异常,消息:{0}", ex.Message));
            }
            Response.End();
            return View();
        }

        #region api

        /// <summary>
        /// 验证消息真实性
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool Verify(SortedDictionary<string, string> param)
        {
            try
            {
                if (param.ContainsKey("signature") && param.ContainsKey("timestamp") && param.ContainsKey("nonce"))
                {
                    string signature = param["signature"];//微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
                    string timestamp = param["timestamp"];//时间戳
                    string nonce = param["nonce"];//随机数

                    bool isWeiXinService = WeiXinSignature.CheckSignature(signature, weixinopen.WeiXinOpenConfig.component_token, timestamp, nonce);
                    if (isWeiXinService == true)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    //    Wechat.LogManage.Log("非微信服务器发送的请求");
                    return false;
                }
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log(string.Format("[Verify]信息:{0}", ex.Message));
                return false;
            }
        }
        /// <summary>
        /// 逻辑处理
        /// </summary>
        /// <param name="xml"></param>
        public void LogicalProcessing(string xml)
        {
            WeiXinReceive wei = new WeiXinReceive(xml);
            switch (wei.GetMsgType())
            {
                case MsgType.text:
                    {
                        #region 专用测试公众号
                        {
                            ReceiveTextMsg receive = wei.EntityTo<ReceiveTextMsg>();
                            SendPassiveTextMsg text = new SendPassiveTextMsg()
                            {
                                FromUserName = wei.ToUserName,
                                ToUserName = wei.FromUserName,
                                MsgType = MsgType.text,
                                CreateTime = DateTime.Now,
                                Content = "第三方开发平台",
                            };
                            if (receive.Content == "TESTCOMPONENT_MSG_TYPE_TEXT")
                            {
                                text.Content = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
                            }
                            else if (receive.Content == "QUERY_AUTH_CODE:" + weixinopen.WeiXinOpenConfig.auth_code)
                            {
                                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((obj) =>
                                {
                                    System.Threading.Thread.Sleep(2000);
                                    SendServiceTextMsg sendmsg = new SendServiceTextMsg()
                                    {
                                        access_token = "xxxx",
                                        touser = wei.FromUserName,
                                        MsgType = MsgType.text,
                                        content = weixinopen.WeiXinOpenConfig.auth_code + "_from_api",
                                    };
                                    StateMsg msg = WeiXinRequest.SendServiceMsg(sendmsg.ToJson());
                                }));
                                Response.Write("");
                                return;
                            }
                            Response.Write(text.ToXml());
                        }
                        #endregion
                    }
                    break;
                case MsgType.location:
                    Response.Write("success");
                    break;
                case MsgType.Event:
                    #region 专用测试公众号
                    {
                        SendPassiveTextMsg text = new SendPassiveTextMsg()
                        {
                            FromUserName = wei.ToUserName,
                            ToUserName = wei.FromUserName,
                            MsgType = MsgType.text,
                            CreateTime = DateTime.Now,
                            Content = wei.GetEventType() + "from_callback",
                        };
                        Response.Write(text.ToXml());
                    }
                    #endregion                    
                    break;
                default:
                    SendPassiveTextMsg sendDefault = new SendPassiveTextMsg()
                    {
                        FromUserName = wei.ToUserName,
                        ToUserName = wei.FromUserName,
                        MsgType = MsgType.text,
                        CreateTime = DateTime.Now,
                        Content = "第三方开发平台",
                    };
                    Response.Write(sendDefault.ToXml());
                    break;
            }
        }

        #endregion

    }
}
