using jiouosdp.Controllers;
using RFrameGenerate.BLL;
using RFrameGenerate.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Param;
using Wechat;
using Wechat.Enum;
using Wechat.Model;
using weixinopen;
using weixinopen.Model;

namespace jiouosdp.Areas.WeiXinApi.Controllers
{
    [LF(IsLoginFilter = false, IsMaintenance = false)]
    [PF(IsPermissionFilter = false)]
    public class WeiXinOpenController : BaseController
    {
        //
        // GET: /wx1efed944cad6ca0f/

        public ActionResult callback(string appid, string type = "weixin")
        {
            //appid： wx570bc396a51b8ff8
            //Username： gh_3c884a361561
            try
            {
                #region ip检查
                string ip = "ip=none";
                try
                {
                    ip = GetIP();
                }
                catch (Exception ex)
                {
                    LogManage.Log("callback:ip检查" + ex.Message);
                }
                #endregion

                Wechat.LogManage.Log("CallBack消息与事件接收URL->ip:" + ip + ",url:" + Request.Url, true);
                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();
                            stream.Dispose();
                            if (type.ToLower() != "weixinhai")
                            {
                                WXBizMsgCrypt crypt = new WXBizMsgCrypt(WeiXinOpenConfig.component_token, WeiXinOpenConfig.component_Key, WeiXinOpenConfig.component_appid);
                                string data = string.Empty;
                                //Wechat.LogManage.Log("公众号消息与事件接收URL->加密Data:" + xml);

                                //api转发
                                try
                                {
                                    var appidtran = ApiTranAppIdList.GetByAppid(appid);
                                    if (appidtran != null)
                                    {
                                        string echostr = string.Empty;
                                        if (getpara.ContainsKey("echostr"))
                                            echostr = getpara["echostr"];
                                        var callxml = PostXmls.PostXml(appidtran.redirect_uri + string.Format("weixin/WeiXinOpen/callback?echostr={0}&msg_signature={1}&timestamp={2}&nonce={3}&signature={4}&appid={5}", echostr, getpara["msg_signature"], getpara["timestamp"], getpara["nonce"], getpara["signature"], appid), xml);
                                        Response.Write(callxml);
                                        Response.End();
                                        return Content("");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Wechat.LogManage.Log("公众号消息与事件接收URL->加密Data:" + xml);
                                    LogManage.Log("转发api出错(callback,appid:" + appid + "):" + ex.Message);
                                    string sEncryptMsg = string.Empty;
                                    crypt.EncryptMsg("", getpara["timestamp"], getpara["nonce"], ref sEncryptMsg);
                                    return Content(sEncryptMsg);
                                }

                                var result = crypt.DecryptMsg(getpara["msg_signature"], getpara["timestamp"], getpara["nonce"], xml, ref data);

                                //Wechat.LogManage.Log("公众号消息与事件接收URL->解密Data:" + data);
                                if (result != 0)
                                {
                                    LogManage.Log("回调时解密失败 URL:" + Request.Url + " Data:" + xml);
                                    break;
                                }
                                if (appid == "wx570bc396a51b8ff8")
                                    LogicalProcessingTest(data, getpara["timestamp"], getpara["nonce"], appid);
                                else
                                    LogicalProcessing(data, getpara["timestamp"], getpara["nonce"], appid);
                            }
                            else
                            {
                                LogicalProcessingWeiXinHai(xml, getpara["timestamp"], getpara["nonce"], appid);
                            }
                            break;
                        default:
                            Response.Write("success");
                            break;
                    }
                }
                else
                {
                    Wechat.LogManage.Log("公众号消息与事件接收URL->验证失败");
                }
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log(string.Format("公众号消息与事件接收URL发生了异常,消息:{0},栈:{1}", ex.Message, ex.StackTrace));
            }
            Response.End();
            return Content("");
        }


        #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 LogicalProcessingTest(string xml, string sTimeStamp, string sNonce, string appid)
        {
            WXBizMsgCrypt crypt = new WXBizMsgCrypt(WeiXinOpenConfig.component_token, WeiXinOpenConfig.component_Key, WeiXinOpenConfig.component_appid);
            string sEncryptMsg = string.Empty;

            LogManage.Log("全网发布检测接到的数据xml:" + 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 || receive.Content.Contains(""))//采用了强制进入方式,文档好像有bug
                            {
                                LogManage.Log("------------------强制进入----------------------:" + receive.Content);
                                Response.Write("");

                                string[] str = receive.Content.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                                LogManage.Log("测试auth_code" + weixinopen.WeiXinOpenConfig.auth_code);
                                weixinopen.WeiXinOpenConfig.auth_code = str[1];

                                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((obj) =>
                                {
                                    System.Threading.Thread.Sleep(500);
                                    SendServiceTextMsg sendmsg = new SendServiceTextMsg()
                                    {
                                        //access_token = "xxxx", 
                                        touser = wei.FromUserName,
                                        MsgType = MsgType.text,
                                        content = weixinopen.WeiXinOpenConfig.auth_code + "_from_api",
                                    };
                                    try
                                    {
                                        WeiXinOpenRequest.get_authorizer_access_token(weixinopen.WeiXinOpenConfig.auth_code);
                                        StateMsg msg = WeiXinOpenRequest.SendServiceMsg(sendmsg.ToJson(), appid);
                                    }
                                    catch (Exception ex)
                                    {
                                        LogManage.Log("------------------发送客户消息" + ex.Message + "--------------------" + weixinopen.WeiXinOpenConfig.auth_code);
                                    }
                                }));
                                return;
                            }

                            crypt.EncryptMsg(text.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
                            Response.Write(sEncryptMsg);
                        }
                        #endregion
                    }
                    break;
                case MsgType.Event:
                    #region 专用测试公众号
                    {
                        SendPassiveTextMsg text = new SendPassiveTextMsg()
                        {
                            FromUserName = wei.ToUserName,
                            ToUserName = wei.FromUserName,
                            MsgType = MsgType.text,
                            CreateTime = DateTime.Now,
                            Content = wei.GetEventType().ToString().ToUpper() + "from_callback",
                        };
                        crypt.EncryptMsg(text.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
                        Response.Write(sEncryptMsg);
                    }
                    #endregion
                    break;
                default:
                    LogManage.Log("后台回调default");
                    break;
            }
        }
        public void LogicalProcessing(string xml, string sTimeStamp, string sNonce, string appid)
        {
            WXBizMsgCrypt crypt = new WXBizMsgCrypt(WeiXinOpenConfig.component_token, WeiXinOpenConfig.component_Key, WeiXinOpenConfig.component_appid);
            string sEncryptMsg = string.Empty;
            WeiXinReceive wei = new WeiXinReceive(xml);
            LogManage.Log("接到的数据xml:" + xml);

            //SendPassiveTextMsg text = new SendPassiveTextMsg()
            //{
            //    FromUserName = wei.ToUserName,
            //    ToUserName = wei.FromUserName,
            //    MsgType = MsgType.text,
            //    CreateTime = DateTime.Now,
            //    Content = "您好,我们正在努力开发中...",
            //};
            //crypt.EncryptMsg(text.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
            //Response.Write(sEncryptMsg);

            /*----------------------------------------------------*/

            switch (wei.GetMsgType())
            {
                case MsgType.text:
                    {
                        ReceiveTextMsg receive = wei.EntityTo<ReceiveTextMsg>();
                        if (receive.Content == "客服")
                        {
                            string re = string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>", wei.FromUserName, wei.ToUserName, DateTimeHelper.ConvertDateTimeInt(DateTime.Now));
                            crypt.EncryptMsg(re, sTimeStamp, sNonce, ref sEncryptMsg);
                            Response.Write(sEncryptMsg);
                        }
                        else
                        {
                            string resultxml = AutoReplyManage.GetContentByKeywordToXml(receive.Content, wei.FromUserName, wei.ToUserName);
                            crypt.EncryptMsg(resultxml, sTimeStamp, sNonce, ref sEncryptMsg);
                            Response.Write(sEncryptMsg);
                        }
                    }
                    break;
                case MsgType.location:
                    ReceiveLocationMsg rlm = wei.EntityTo<ReceiveLocationMsg>();
                    //Wechat.LogManage.Log("上报地理位置事件FromUserName:" + rlm.FromUserName + " Location_X:" + rlm.Location_X + " Location_Y:" + rlm.Location_Y);
                    crypt.EncryptMsg("", sTimeStamp, sNonce, ref sEncryptMsg);
                    Response.Write(sEncryptMsg);
                    break;
                case MsgType.Event:
                    #region Event
                    switch (wei.GetEventType())
                    {
                        case EventType.subscribe://关注
                            {
                                string resultxml = AutoReplyManage.GetContentByKeywordToXml(DictionaryConst.WeiXinAutoReply.ReplyKeyword.Subscribe, wei.FromUserName, wei.ToUserName);

                                crypt.EncryptMsg(resultxml, sTimeStamp, sNonce, ref sEncryptMsg);
                                Response.Write(sEncryptMsg);
                                MemberManage.UpdateMember(wei.FromUserName, wei.ToUserName);
                                MemberManage.UpdateMemberIsAccredited(wei.FromUserName, true);
                                if (xml.Contains("<Ticket>") == true)
                                {
                                    //扫描带参数二维码
                                    //<xml><ToUserName><![CDATA[toUser]]></ToUserName>
                                    //<FromUserName><![CDATA[FromUser]]></FromUserName>
                                    //<CreateTime>123456789</CreateTime>
                                    //<MsgType><![CDATA[event]]></MsgType>
                                    //<Event><![CDATA[subscribe]]></Event>
                                    //<EventKey><![CDATA[qrscene_123123]]></EventKey>事件KEY值，qrscene_为前缀，后面为二维码的参数值
                                    //<Ticket><![CDATA[TICKET]]></Ticket>二维码的ticket，可用来换取二维码图片
                                    //</xml>

                                    ReceiveQRCodeEventMsg qrcode = wei.EntityTo<ReceiveQRCodeEventMsg>();
                                    try
                                    {
                                        var wechat = WeChatManage.GetWeChatByUserName(wei.ToUserName);
                                        var mer = MerchantManage.GetMerchantByAppID(wechat.WeChatGuid);
                                        CurrentUser.SetAppID(wechat.appid);
                                        CurrentUser.SetMerchantGuid(mer.MerchantGuid);

                                        Guid didGuid=Guid.Parse(qrcode.EventKey.Replace("qrscene_", string.Empty));
                                        MessageTemplateManage.ScanSendMessage(wei.FromUserName, mer.MerchantGuid, didGuid, wechat.appid);
                                        MemberManage.UpdateDID(wei.FromUserName, didGuid);
                                    }
                                    catch (Exception ex)
                                    {
                                        LogManage.Log("扫码带参数公众号二维码:" + ex.Message);
                                    }
                                    //SendPassiveTextMsg text = new SendPassiveTextMsg()
                                    //{
                                    //    CreateTime = DateTime.Now,
                                    //    FromUserName = wei.ToUserName,
                                    //    Content = "扫码id:" + qrcode.EventKey + ",Ticket:" + qrcode.Ticket,
                                    //    MsgType = MsgType.text,
                                    //    ToUserName = wei.FromUserName,
                                    //};
                                    //crypt.EncryptMsg(text.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
                                    //Response.Write(sEncryptMsg);
                                }
                            }
                            break;
                        case EventType.unsubscribe://取消关注
                            {
                                crypt.EncryptMsg("", sTimeStamp, sNonce, ref sEncryptMsg);
                                Response.Write(sEncryptMsg);
                                MemberManage.Unsubscribe(wei.FromUserName);
                                MemberManage.UpdateMemberIsAccredited(wei.FromUserName, false);
                            }
                            break;
                        case EventType.Location:
                            ReceiveLocationEventMsg rlem = wei.EntityTo<ReceiveLocationEventMsg>();
                            crypt.EncryptMsg("", sTimeStamp, sNonce, ref sEncryptMsg);
                            Response.Write(sEncryptMsg);
                            //Wechat.LogManage.Log("上报地理位置事件FromUserName:" + rlem.FromUserName + " Latitude:" + rlem.Latitude + " Longitude:" + rlem.Longitude);
                            break;
                        case EventType.CLICK:
                            {
                                ReceiveMenuEventMsg receiveEvent = wei.EntityTo<ReceiveMenuEventMsg>();
                                if (receiveEvent.EventKey == "客服")
                                {
                                    string re = string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>", wei.FromUserName, wei.ToUserName, DateTimeHelper.ConvertDateTimeInt(DateTime.Now));
                                    crypt.EncryptMsg(re, sTimeStamp, sNonce, ref sEncryptMsg);
                                    Response.Write(sEncryptMsg);
                                }
                                else if (receiveEvent.EventKey == "我的二维码")
                                {
                                    try
                                    {
                                        var member = MemberManage.GetMemberInfo(wei.FromUserName);
                                        if (member != null)
                                        {
                                            CurrentUser.SetAppID(member.appid);
                                            CurrentUser.SetMerchantGuid(member.MerchantGuid);
                                            CurrentUser.SetSMerchantGuid(member.MerchantGuid);
                                            CurrentUser.SetCurrUser(member.MemberOpenID, member.MemberGuid);

                                            string mediaidinfo = member.UploadImageMediaInfo ?? string.Empty;// 123456789456,2015/11/06 14:38:40
                                            string[] info = mediaidinfo.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                                            if (info == null) info = new string[] { };

                                            string mediaid = info.Length > 0 ? info[0] : string.Empty;
                                            if (string.IsNullOrEmpty(mediaidinfo) == true || (info != null && info.Length == 2 && Convert.ToDateTime(info[1]).AddDays(3) < DateTime.Now))
                                            {
                                                #region 上传
                                                string codeimage = member.DistributionQRCode;
                                                if (string.IsNullOrEmpty(codeimage) == true)
                                                    codeimage = DistributionManage.GetShowQRcode(member.MemberOpenID, member.DistributionPropGuid);
                                                string imagepath = AppDomain.CurrentDomain.BaseDirectory + codeimage.Substring(codeimage.IndexOf("/upload")).Replace("/", "\\");
                                                imagepath = imagepath.Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0];
                                                var image = weixinopen.WeiXinOpenRequest.UploadingTempMultimedia(UploadType.image, imagepath, appid);
                                                if (image.state == true)
                                                {
                                                    mediaid = image.media_id;
                                                    DistributionManage.UpdateMediaID(mediaid, member.DistributionPropGuid);
                                                }
                                                else
                                                    mediaid = null;
                                                #endregion
                                            }

                                            if (string.IsNullOrEmpty(mediaid) != true)
                                            {
                                                SendPassiveImageMsg img = new SendPassiveImageMsg()
                                                {
                                                    CreateTime = DateTime.Now,
                                                    FromUserName = wei.ToUserName,
                                                    MediaId = mediaid,
                                                    MsgType = MsgType.image,
                                                    ToUserName = wei.FromUserName,
                                                };
                                                crypt.EncryptMsg(img.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
                                                Response.Write(sEncryptMsg);
                                            }
                                            else
                                            {
                                                SendPassiveTextMsg text1 = new SendPassiveTextMsg()
                                                {
                                                    Content = "请先进入我的小店,打开[分销中心],再打开[二维码]就可以在这里查看了",
                                                    CreateTime = DateTime.Now,
                                                    FromUserName = wei.ToUserName,
                                                    ToUserName = wei.FromUserName,
                                                    MsgType = MsgType.text,
                                                };
                                                crypt.EncryptMsg(text1.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
                                                Response.Write(sEncryptMsg);
                                            }
                                        }
                                        else
                                        {
                                            SendPassiveTextMsg text1 = new SendPassiveTextMsg()
                                            {
                                                Content = "您还不是分销商",
                                                CreateTime = DateTime.Now,
                                                FromUserName = wei.ToUserName,
                                                ToUserName = wei.FromUserName,
                                                MsgType = MsgType.text,
                                            };
                                            crypt.EncryptMsg(text1.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
                                            Response.Write(sEncryptMsg);
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        SendPassiveTextMsg text1 = new SendPassiveTextMsg()
                                        {
                                            Content = "获取失败,请稍候再试.",
                                            CreateTime = DateTime.Now,
                                            FromUserName = wei.ToUserName,
                                            ToUserName = wei.FromUserName,
                                            MsgType = MsgType.text,
                                        };
                                        Wechat.LogManage.Log("我的二维码出错:" + ex.Message);
                                        crypt.EncryptMsg(text1.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
                                        Response.Write(sEncryptMsg);
                                    }
                                }
                                else
                                {
                                    string resultxml = AutoReplyManage.GetContentByKeywordToXml(receiveEvent.EventKey, wei.FromUserName, wei.ToUserName);
                                    crypt.EncryptMsg(resultxml, sTimeStamp, sNonce, ref sEncryptMsg);
                                    Response.Write(sEncryptMsg);
                                }
                            }
                            break;
                        case EventType.SCAN:
                            {
                                //<xml>
                                //<ToUserName><![CDATA[toUser]]></ToUserName>
                                //<FromUserName><![CDATA[FromUser]]></FromUserName>
                                //<CreateTime>123456789</CreateTime>
                                //<MsgType><![CDATA[event]]></MsgType>
                                //<Event><![CDATA[SCAN]]></Event>
                                //<EventKey><![CDATA[SCENE_VALUE]]></EventKey>事件KEY值，是一个32位无符号整数，即创建二维码时的二维码scene_id
                                //<Ticket><![CDATA[TICKET]]></Ticket>二维码的ticket，可用来换取二维码图片
                                //</xml>
                                ReceiveQRCodeEventMsg qrcode = wei.EntityTo<ReceiveQRCodeEventMsg>();
                                try
                                {
                                    var wechat = WeChatManage.GetWeChatByUserName(wei.ToUserName);
                                    var mer = MerchantManage.GetMerchantByAppID(wechat.WeChatGuid);
                                    CurrentUser.SetAppID(wechat.appid);
                                    CurrentUser.SetMerchantGuid(mer.MerchantGuid);
                                    MessageTemplateManage.ScanSendMessage(wei.FromUserName, mer.MerchantGuid, Guid.Parse(qrcode.EventKey), wechat.appid);
                                    MemberManage.UpdateDID(wei.FromUserName, Guid.Parse(qrcode.EventKey));



                                }
                                catch (Exception ex)
                                {
                                    LogManage.Log("扫码带参数公众号二维码SCAN:" + ex.Message);
                                }
                                //SendPassiveTextMsg text = new SendPassiveTextMsg()
                                //{
                                //    CreateTime = DateTime.Now,
                                //    FromUserName = wei.ToUserName,
                                //    Content = "扫码id:" + qrcode.EventKey + ",Ticket:" + qrcode.Ticket,
                                //    MsgType = MsgType.text,
                                //    ToUserName = wei.FromUserName,
                                //};
                                //crypt.EncryptMsg(text.ToXml(), sTimeStamp, sNonce, ref sEncryptMsg);
                                //Response.Write(sEncryptMsg);

                            }
                            break;
                        /*接入会话：
                          <xml>
                              <ToUserName><![CDATA[touser]]></ToUserName>
                              <FromUserName><![CDATA[fromuser]]></FromUserName>
                              <CreateTime>1399197672</CreateTime>
                              <MsgType><![CDATA[event]]></MsgType>
                              <Event><![CDATA[kf_create_session]]></Event>
                              <KfAccount><![CDATA[test1@test]]></KfAccount>
                          </xml>
                         关闭会话：

                          <xml>
                              <ToUserName><![CDATA[touser]]></ToUserName>
                              <FromUserName><![CDATA[fromuser]]></FromUserName>
                              <CreateTime>1399197672</CreateTime>
                              <MsgType><![CDATA[event]]></MsgType>
                              <Event><![CDATA[kf_close_session]]></Event>
                              <KfAccount><![CDATA[test1@test]]></KfAccount>
                          </xml>
                         转接会话：

                          <xml>
                              <ToUserName><![CDATA[touser]]></ToUserName>
                              <FromUserName><![CDATA[fromuser]]></FromUserName>
                              <CreateTime>1399197672</CreateTime>
                              <MsgType><![CDATA[event]]></MsgType>
                              <Event><![CDATA[kf_switch_session]]></Event>
                              <FromKfAccount><![CDATA[test1@test]]></FromKfAccount>
                              <ToKfAccount><![CDATA[test2@test]]></ToKfAccount>
                          </xml>*/
                        default:
                            {
                                string resultxml = AutoReplyManage.GetContentByKeywordToXml(DictionaryConst.WeiXinAutoReply.ReplyKeyword.Default, wei.FromUserName, wei.ToUserName);
                                crypt.EncryptMsg(resultxml, sTimeStamp, sNonce, ref sEncryptMsg);
                                Response.Write(sEncryptMsg);
                                break;
                            }
                    }
                    #endregion
                    break;
                default:
                    {
                        string resultxml = AutoReplyManage.GetContentByKeywordToXml(DictionaryConst.WeiXinAutoReply.ReplyKeyword.Default, wei.FromUserName, wei.ToUserName);
                        crypt.EncryptMsg(resultxml, sTimeStamp, sNonce, ref sEncryptMsg);
                        Response.Write(sEncryptMsg);
                        break;
                    }
            }

            /*----------------------------------------------------*/

        }
        public void LogicalProcessingWeiXinHai(string xml, string sTimeStamp, string sNonce, string appid)
        {
            WeiXinReceive wei = new WeiXinReceive(xml);

            switch (wei.GetMsgType())
            {
                case MsgType.text:
                    {
                        ReceiveTextMsg receive = wei.EntityTo<ReceiveTextMsg>();
                        string resultxml = AutoReplyManage.GetContentByKeywordToXml(receive.Content, wei.FromUserName, wei.ToUserName);
                        Response.Write(resultxml);
                    }
                    break;
                case MsgType.location:
                    Response.Write("");
                    break;
                case MsgType.Event:
                    #region Event
                    switch (wei.GetEventType())
                    {
                        case EventType.subscribe://关注
                            {
                                var wechat = WeChatManage.GetWeChatByUserName(wei.ToUserName);
                                string resultxml = AutoReplyManage.GetContentByKeywordToXml(DictionaryConst.WeiXinAutoReply.ReplyKeyword.Subscribe, wei.FromUserName, wei.ToUserName);
                                Response.Write(resultxml);
                                MemberManage.UpdateMember(wei.FromUserName, wei.ToUserName);
                            }
                            break;
                        case EventType.unsubscribe://取消关注
                            {
                                Response.Write("");
                                MemberManage.Unsubscribe(wei.FromUserName);
                            }
                            break;
                        case EventType.Location:
                            ReceiveLocationEventMsg rlem = wei.EntityTo<ReceiveLocationEventMsg>();
                            Response.Write("");
                            //Wechat.LogManage.Log("上报地理位置事件FromUserName:" + rlem.FromUserName + " Latitude:" + rlem.Latitude + " Longitude:" + rlem.Longitude);
                            break;
                        case EventType.CLICK:
                            {
                                ReceiveMenuEventMsg receiveEvent = wei.EntityTo<ReceiveMenuEventMsg>();
                                string resultxml = AutoReplyManage.GetContentByKeywordToXml(receiveEvent.EventKey, wei.FromUserName, wei.ToUserName);
                                Response.Write(resultxml);
                            }
                            break;
                        default:
                            {
                                string resultxml = AutoReplyManage.GetContentByKeywordToXml(DictionaryConst.WeiXinAutoReply.ReplyKeyword.Default, wei.FromUserName, wei.ToUserName);
                                Response.Write(resultxml);
                                break;
                            }
                    }
                    #endregion
                    break;
                default:
                    {
                        string resultxml = AutoReplyManage.GetContentByKeywordToXml(DictionaryConst.WeiXinAutoReply.ReplyKeyword.Default, wei.FromUserName, wei.ToUserName);
                        Response.Write(resultxml);
                        break;
                    }
            }

            /*----------------------------------------------------*/

        }

        #endregion

        #region 微信授权

        public ActionResult LoginOautho()
        {
            return View();
        }

        public JsonResult geturl()
        {
            string url;
            try
            {
                url = weixinopen.WeiXinOpenRequest.GetOAuthoUrl2(WeiXinOpenConfig.webdomain + "weixin/WeiXinOpen/Call", "1", CurrentManage.AppId, Scope.snsapi_userinfo);
                //Wechat.LogManage.Log("登录授权的发起页域名:" + url);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "No", Msg = ex.Message });
            }
            return Json(new { Result = "OK", Url = url });
        }

        public JsonResult get_refresh_authorizer_access_token()
        {
            return Json(new { Result = "No", Msg = "禁止点击" });
            string msg = string.Empty;
            try
            {
                var token = weixinopen.WeiXinOpenRequest.get_refresh_authorizer_access_token(CurrentManage.AppId);
                msg = "expires_in:" + token.expires_in + ",authorizer_appid" + token.authorizer_appid;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return Json(new { Result = "No", Msg = msg });
        }

        public ActionResult Call(string code, string state, string appid)
        {
            #region 参数日志
            //Wechat.LogManage.Log("登录时授权url:" + Request.Url);
            #endregion
            var getpara = GetOrPostParam.GetRequestGet(Request);
            string openid = string.Empty;

            var token = weixinopen.WeiXinOpenRequest.get_access_token(code, CurrentManage.AppId);
            var wei = weixinopen.WeiXinOpenRequest.GetUserInfo(token.openid, CurrentManage.AppId);
            return Content("[关注了]获取粉信息unionid:" + wei.unionid + ",appid:" + appid);
        }
        #endregion

        #region 公众号授权给第三方平台
        public JsonResult geturl2()
        {
            string url = WeiXinOpenRequest.GetWeiXinOAuthoUrl(WeiXinOpenConfig.webdomain + "weixin/WeiXinOpen/Call2");

            return Json(new { Result = "OK", Url = url });
        }

        /// <summary>
        /// 获取授权码
        /// </summary>
        /// <param name="auth_code">授权码</param>
        /// <param name="expires_in">过期时间</param>
        /// <param name="tran">0不转发,1转发,2全部转发指定域名</param>
        /// <param name="domainid">转发标识</param>
        /// <returns></returns>
        public ActionResult Call2(string auth_code, string expires_in, string merchant_id, string tran = "0", string domainid = "")
        {
            WeiXinOpenConfig.auth_code = auth_code;
            //Wechat.LogManage.Log("公众号一键登录授权给第三方平台方auth_code:" + auth_code + ",expires_in:" + expires_in, true);
            if (string.IsNullOrEmpty(auth_code) != true && string.IsNullOrEmpty(expires_in) != true)
            {
                try
                {
                    if (tran == "0")//不转发
                    {
                        weixinopen.Model.Uxuezhang uxuezhang = new weixinopen.Model.Uxuezhang();
                        AuthorizerToken authorizer = WeiXinOpenRequest.get_authorizer_access_token(auth_code);
                        CurrentUser.SetAppID(authorizer.authorizer_appid);
                        uxuezhang = weixinopen.WeiXinOpenRequest.Get_Authorizer_Info(authorizer.authorizer_appid);

                        string fileName = Server.MapPath("/upload/wechatqr");

                        var result = WeChatManage.UpdateWeChat(uxuezhang, merchant_id, fileName);
                        //return Content("公众号一键登录授权给第三方平台方[成功]" + uxuezhang.nick_name + "," + uxuezhang.head_img + "," + uxuezhang.qrcode_url + "," + uxuezhang.appid + "," + uxuezhang.alias + "," + result.Msg);
                        RFrameGenerate.Common.Utils.WriteCookie(RFrameGenerate.Common.SessionKeys.COOKIE_URL_REFERRER, "/WeiXinBase/Authorization/Index");
                        return Redirect("/theme/main/control");
                    }
                    else if (tran == "1") //api转发
                    {
                        var appidtran = ApiTranAppIdList.GetByUserID(merchant_id);
                        if (appidtran != null)
                        {
                            return Redirect(appidtran.redirect_uri + string.Format("weixin/WeiXinOpen/Call2?auth_code={0}&expires_in={1}&merchant_id={2}&tran=0", auth_code, expires_in, merchant_id));
                        }
                        return Content("授权出错了,请联系管理员并提供当前授权公众的appid,[1]");
                    }
                    else//全部转发
                    {
                        var appidtran = ApiTranAppIdList.GetByAppid(domainid);
                        if (appidtran != null)
                        {
                            #region 转发url保存
                            if (appidtran.isautoadd == true)
                            {
                                weixinopen.Model.Uxuezhang uxuezhang = new weixinopen.Model.Uxuezhang();
                                AuthorizerToken authorizer = WeiXinOpenRequest.get_authorizer_access_token(auth_code);
                                CurrentUser.SetAppID(authorizer.authorizer_appid);
                                uxuezhang = weixinopen.WeiXinOpenRequest.Get_Authorizer_Info(authorizer.authorizer_appid);
                                ApiTranAppIdList.AddConfig(uxuezhang.appid, merchant_id, merchant_id, appidtran.redirect_uri);
                            }
                            #endregion

                            return Redirect(appidtran.redirect_uri + string.Format("weixin/WeiXinOpen/Call2?auth_code={0}&expires_in={1}&merchant_id={2}&tran=0", auth_code, expires_in, merchant_id));
                        }
                        return Content("授权出错了,请联系管理员[2]");
                    }
                }
                catch (Exception ex)
                {
                    return Content("[失败] Message:" + ex.Message + ex.StackTrace);
                }
            }
            else
            {
                return Content("公众号一键登录授权给第三方平台方[失败]");
            }
        }

        public JsonResult DZ()
        {
            return Json(new { Result = "OK" });
        }

        #endregion
    }
}
