using jiouosdp.Controllers;
using RFrameGenerate.BLL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Wechat;
using weixinopen;

namespace jiouosdp.Areas.WeiXinApi.Controllers
{
    [LF(IsLoginFilter = false, IsMaintenance = false)]
    [PF(IsPermissionFilter = false)]
    public class AuthoEventController : BaseController
    {
        //
        // GET: http://localhost:63587/WeiXinApi/AuthoEvent/Index
        //signature=79162219e02c1f877543727c6970c6e1a6447e5e
        //timestamp=1425367809
        //nonce=888573083
        //encrypt_type=aes
        //msg_signature=f181d1545c332b227fe3c343fedd8ec3cd0155f4
        public ActionResult Index(string signature, string timestamp, string nonce, string encrypt_type, string msg_signature)
        {
            try
            {
                StreamReader stream = new StreamReader(Request.InputStream);
                string sPostData = stream.ReadToEnd();

                //Wechat.LogManage.Log("授权事件接收URL 数据URL:" + Request.Url + ",数据:" + sPostData);

                //只能托管给一个第三方平台
                if (sPostData.Contains(weixinopen.WeiXinOpenConfig.component_appid) != true)
                    return Content("success");

                //string sPostData = "<xml><AppId><![CDATA[wxd6c2d16dd1a52703]]></AppId><Encrypt><![CDATA[MTD1SGJhdlNcypijw7nuQWwE4O2+nNVpEnz/1pb9YcKLb0H+NPNuicD0UZ3wk5uKtjm90ktRDuHzfWmdu79ELnmZDZWd9Ve75sBZRub9zQ4jtvOow56X0/by5nHWEjWzQQxtrh1GQBRkuhirFILGU6Sw3fzozSrJtPynutPxt5PIYfoO4Yy6SQ8Rp4MZSj10rQKehprd2aXt83R2FlSaLOVq0k+FKmJ03GEqCkWE39GQSQiMGKjTQeqW6swpcVCsSO81Da0N9H+81DqugV+diK9QaSwYXxcEKysnSZboMm0PtYBGAMVUIfuccG9GHI7sLNDxPiF7XEm9xXIlVQiCaX7NF0sLCWka/jp9GAYHj9RPSCu+by/94U1gGQ8JqMcTOigy3pgOl2jq97umcTA4dEDmFqd975ehGQwVFZ9rtZruHqTXpXMxktPIGOmkHRjQSLASN+nRCqwGp8aP1C7wFw==]]></Encrypt></xml>";

                WXBizMsgCrypt crypt = new WXBizMsgCrypt(WeiXinOpenConfig.component_token, WeiXinOpenConfig.component_Key, WeiXinOpenConfig.component_appid);
                string msg = string.Empty;
                var result = crypt.DecryptMsg(msg_signature, timestamp, nonce, sPostData, ref msg);
                if (result == 0)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(msg);
                    var root = doc.FirstChild;
                    string InfoType = root["InfoType"].InnerText;
                    switch (InfoType)
                    {
                        case "component_verify_ticket":

                            WeiXinOpenConfig.component_verify_ticket = root["ComponentVerifyTicket"].InnerText;
                            break;
                        case "unauthorized":

                            //api转发
                            try
                            {
                                var appidtran = ApiTranAppIdList.GetByAppid(root["AuthorizerAppid"].InnerText);
                                if (appidtran != null && appidtran.iscallauthoevent == true)
                                {
                                    var callxml = PostXmls.PostXml(appidtran.redirect_uri + string.Format("WeiXin/AuthoEvent/Index?signature={0}&timestamp={1}&nonce={2}&encrypt_type={3}&msg_signature={4}",signature,timestamp,nonce,encrypt_type,msg_signature), sPostData);
                                    return Content(callxml);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManage.Log("转发api出错(unauthorized" + root["AuthorizerAppid"].InnerText + "):" + ex.Message);
                                return Content("");
                            }

                            WeChatManage.CancelAuthorization(root["AuthorizerAppid"].InnerText);
                            break;
                        case "none":
                        default:
                            Wechat.LogManage.Log("授权事件接收URL,类型" + InfoType + ",URL:" + Request.Url + ",解密后的数据:" + msg); break;
                    }
                }
                else
                {
                    Wechat.LogManage.Log("授权事件接收URL出错了,code:" + result);
                }
                //推送component_verify_ticket协议
                //<xml>
                //<AppId> </AppId>第三方平台appid
                //<CreateTime>1413192605 </CreateTime>时间戳
                //<InfoType> </InfoType>component_verify_ticket
                //<ComponentVerifyTicket> </ComponentVerifyTicket>Ticket内容
                //</xml>

                //推送取消授权通知
                //<xml>
                //<AppId></AppId>第三方平台appid
                //<CreateTime>1413192760</CreateTime>时间戳
                //<InfoType> </InfoType>unauthorized
                //<AuthorizerAppid></AuthorizerAppid>取消授权的公众号
                //</xml>
                //--none，代表该消息推送给服务

            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("授权事件接收URL,出错了," + ex.Message);
            }
            return Content("success");
        }
    }
}
