using RFrameGenerate.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RFrameGenerate.BLL;
using Wechat;
using weixinopen;
using RFrameGenerate.Model;

namespace System.Web.Mvc
{
    /// <summary>
    /// 微信自动授权登录,根据域名前缀自动登录
    /// </summary>
    public class WeiXinLoginAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 是否要授权
        /// </summary>
        public bool IsAuthorization = false;
        string appid = string.Empty;
        public bool OnActionExecuting1(ActionExecutingContext filterContext)
        {
            if (RFrameGenerate.Common.CurrentManage.IsDebug == true)
                return false;
            if (IsAuthorization == true)
            {
                #region 微信限制
                var Request = filterContext.HttpContext.Request;
                var weixinopen = Request.UserAgent.ToString();
                if (weixinopen.Contains("MicroMessenger") == false)
                {
                    string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7582db883b74dba0&redirect_uri=http%3A%2F%2Fhongbao.super.cn%2Findex%2Ftotal%3Fhelp%26ownerID%3DoPGaIjkZYBTaChHOK9Pgck1exbgE&response_type=code&scope=snsapi_userinfo&state=&connect_redirect=1#wechat_redirect";
                    filterContext.Result = new RedirectResult(url);
                    return true;
                }
                #endregion

                #region 公众号绑定
                if (string.IsNullOrEmpty(appid) == true)
                {
                    filterContext.Result = new ErrorResult("总部未绑定公众号,无法访问."); return true;
                }
                #endregion

                #region 授权登录
                /*2015/8/7 小周 如果url存在就从url获取*/
                //2015/8/30 第一次打开授权通过参数传递
                if (Request.QueryString.AllKeys.Contains(OpenIDManage.OpenTranIDKey) == true && string.IsNullOrEmpty(Request.QueryString[OpenIDManage.OpenTranIDKey]) != true)
                {
                    OpenIDManage.SetOpenID(Request.QueryString[OpenIDManage.OpenTranIDKey]);

                    if (filterContext.HttpContext.Request.IsAjaxRequest() != true && filterContext.HttpContext.Request.RequestType.ToLower() == "get")
                    {
                        //LogManage.Log("授权登录转发前url:" + filterContext.HttpContext.Request.Url.ToString());
                        string url = filterContext.HttpContext.Request.Path;
                        if (filterContext.HttpContext.Request.QueryString.Count > 0)
                        {
                            url += "?";
                            foreach (var v in filterContext.HttpContext.Request.QueryString.AllKeys)
                            {
                                if (v.ToLower() != OpenIDManage.OpenTranIDKey.ToLower())
                                    url += string.Format("{0}={1}&", v, filterContext.HttpContext.Request.QueryString[v]);
                            }
                            url = url.Substring(0, url.Length - 1);
                        }
                        //LogManage.Log("授权登录转的url:" + url);
                        filterContext.Result = new RedirectResult(url); return true;
                    }
                }

                var openid = OpenIDManage.GetOpenID();

                if (string.IsNullOrEmpty(openid) == true)
                {
                    string CookieUrl = Request.Url.ToString().ToLower();
                    string userid = CurrentManage.MerchantUserID;

                    string auturl = WeiXinOpenRequest.GetOAuthoUrl2(WeiXinOpenConfig.webdomain.Replace("appid", appid) + string.Format("BaseWeiXin/Call?url={0}&userid={1}&ia={2}", HttpUtility.UrlEncode(CookieUrl), userid, (isAutho == true ? 1 : 0)), "author", appid, Wechat.Enum.Scope.snsapi_userinfo);

                    filterContext.Result = new RedirectResult(auturl); return true;
                }
                #endregion
            }
            return false;
        }

        /// <summary>
        /// 是否要微信登录
        /// </summary>
        public bool IsAutoLogin = true;
        public bool isAutho;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (IsAuthorization == false && IsAutoLogin == false)
                return;

            #region 商家userid
            string url = filterContext.HttpContext.Request.Url.ToString();
            url = url.Substring(7);
            string merchantUserID = CurrentManage.TestUserID;
            if (url.Contains("localhost:") != true && url.Contains("192.168.1.116") != true && url.Contains("192.168.1.103") != true)
                merchantUserID = url.Substring(0, url.IndexOf("."));
            CurrentUser.SetMerchantUserID(merchantUserID);
            #endregion

            appid = HeadPay.GetAppid(merchantUserID, out isAutho);
            #region 公众号绑定
            if (string.IsNullOrEmpty(appid) == true)
            {
                filterContext.Result = new ErrorResult("总部未绑定公众号,无法访问."); return;
            }
            #endregion

            #region 授权
            if (OnActionExecuting1(filterContext) == true)
                return;
            #endregion

            if (IsAutoLogin == true)
            {
                //if (CurrentUser.GetCurrUserGuid() != Guid.Empty)
                //    return;
                //GetMemberRelation mymember = MemberManage.GetMemberRelation(OpenIDManage.GetOpenID(), merchantUserID);
                CurrnetMemberInfo mymember = null;// CurrentUser.GetMemberInfo();
                //if (mymember == null)
                {//登录
                    mymember = MemberManage.GetMemberRelation(OpenIDManage.GetOpenID(), merchantUserID);
                    CurrentUser.SetMemberInfo(mymember);

                    CurrentUser.SetMerchantGuid(mymember.MerchantGuid.Value);
                    CurrentUser.SetSMerchantGuid(mymember.MerchantGuid.Value);
                    CurrentUser.SetAppID(appid);
                    CurrentUser.SetIsDistribution(mymember.IsDistributor ?? false);
                    if (mymember.DistributionPropGuid != null)
                        CurrentUser.SetDistributionGuid(mymember.DistributionPropGuid.Value);
                    CurrentUser.SetCurrUser(mymember.MemberNickName, mymember.MemberGuid);
                    CurrentUser.SetIsSubscribe(mymember.IsAccredited);
                    CurrentUser.SetMerchantType(mymember.UserType ?? DictionaryConst.Versionb.unkown);
                    CurrentUser.SetLoginType(DictionaryConst.LoginType.WeiXin);
                }


                #region 推广关系*
                if (mymember.IsDistributor != true && filterContext.HttpContext.Request.QueryString.AllKeys.Contains(SessionKeys.ShareDistribution) == true)
                {//存在did
                    string distriGuid = filterContext.HttpContext.Request.QueryString[SessionKeys.ShareDistribution];
                    if (string.IsNullOrEmpty(distriGuid) != true)
                    {
                        Guid dg;
                        var isguid = Guid.TryParse(distriGuid, out dg);
                        if (isguid != true)
                        {
                            filterContext.Result = new ErrorResult("分销商不存在"); return;
                        }
                        if (dg != Guid.Empty)
                        {
                            MessageTemplateManage.ScanSendMessage(OpenIDManage.GetOpenID(), CurrentManage.MerchantGuid, dg, CurrentManage.AppId);
                            MemberManage.UpdateDID(OpenIDManage.GetOpenID(), dg);
                            mymember.DID = dg;
                        }
                    }
                }

                #endregion

                #region openid
                string openid = string.Empty;
                if (RFrameGenerate.Common.CurrentManage.IsDebug == true)
                {
                    openid = RFrameGenerate.Common.CurrentManage.TestMemberOpenID;
                }
                else
                {
                    openid = OpenIDManage.GetOpenID();
                }
                #endregion

                #region 打开店类型*

                if (mymember.ExpireDate != null && mymember.ExpireDate < DateTime.Now)
                {
                    filterContext.Result = new ErrorResult("店铺已过期");
                    return;
                }

                if (mymember.StoreState != true || mymember.StoreIsEnable != true)
                {
                    filterContext.Result = new ErrorResult("店铺已关闭");
                    return;
                }

                //if (mymember.IsAuthorize != true)zhou 2016/4/7 旗舰版授权
                //{
                //    filterContext.Result = new ErrorResult("商家公众号取消了授权,无法访问."); return;
                //}
                //if (mymember.verify_type_info == "-1")
                //{
                //    filterContext.Result = new ErrorResult("商家绑定的公众号未认证."); return;
                //}
                //if (mymember.service_type_info == "0")
                //{
                //    filterContext.Result = new ErrorResult("商家绑定的是订阅号,没有权限集,请绑点服务号."); return;
                //}

                if (CurrentManage.IsDistribution != true)
                {//普通会员打开上级
                    if (mymember.DID != null)
                        CookieManage.SetCookie(SessionKeys.ShareDistribution, mymember.DID.ToString(), 1);//上级
                    else
                        CookieManage.SetCookie(SessionKeys.ShareDistribution, string.Empty, 1);//总部
                }
                else
                {//分销商只打开自己的店      
                    CookieManage.SetCookie(SessionKeys.ShareDistribution, mymember.DistributionPropGuid.ToString(), 1);//自已的小店
                }
                #endregion

                #region 分销员小店是否关闭*

                if (CurrentManage.IsDistribution == true)
                {
                    if (mymember.DistributionIsEnable != true)
                    {
                        filterContext.Result = new ErrorResult("分销商店铺已关闭");
                        return;
                    }
                }
                else
                {
                    if (mymember.DID != null)
                    {
                        var dist = DistributionManage.GetDistributeionProp(mymember.DID.Value);
                        if (dist != null)
                        {
                            if (dist.IsEnable != true)
                            {
                                filterContext.Result = new ErrorResult("分销商店铺已关闭"); return;
                            }
                        }
                        else
                        {
                            //filterContext.Result = new ErrorResult("锁定的分销商不存在"); return;
                            CookieManage.SetCookie(SessionKeys.ShareDistribution, string.Empty, 1);//总部
                        }
                    }
                }

                #endregion

                #region 客服代码
                if (mymember.CustomerServicesGuid != null && string.IsNullOrEmpty(CurrentUser.GetCS()) == true)
                {
                    if (mymember.IsCustomerServices == true)
                    {
                        var cs = CustomerServiceManage.GetCustomerService(mymember.CustomerServicesGuid.Value);
                        if (cs != null && cs.success == true)
                            CurrentUser.SetCS(cs.code);
                    }
                    else
                    {
                        CurrentUser.SetCS("");
                    }
                }
                #endregion

                #region 如果是邀请别人成为分销商*
                if (CurrentManage.IsDistribution != true)
                {
                    string inviteropenid = string.Empty;

                    Guid? inviterdid = MemberManage.GetParentDID(OpenIDManage.GetOpenID());
                    if (filterContext.HttpContext.Request.QueryString.AllKeys.Contains("inviter") == true)
                    {
                        inviteropenid = filterContext.HttpContext.Request.QueryString["inviter"];

                    }
                    DistributionManage.AutoBecomeReseller(inviteropenid, inviterdid);
                }
                #endregion
            }
        }
    }
}