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

namespace jiouosdp.Controllers
{
    /// <summary>
    /// 微信内所有页面必须继承
    /// </summary>
    [PF(IsPermissionFilter = false)]
    [LF(IsLoginFilter = false)]
    [IsWeiXinOpenAttribute(IsWeiXinOpen = true)]//在微信中打开
    [WeiXinLoginAttribute(IsAutoLogin = true, IsAuthorization = true)]//自动登录
    public class BaseWeiXinController : Controller
    {
        static BaseWeiXinController()
        {
            CurrentManage.SimulationLogin();
        }

        private string openid;
        /// <summary>
        /// 当前粉的OpenID
        /// </summary>
        protected string OpenID
        {
            get
            {
                if (RFrameGenerate.Common.CurrentManage.IsDebug == true)
                {
                    OpenIDManage.SetOpenID(CurrentManage.TestMemberOpenID);
                    return CurrentManage.TestMemberOpenID;
                }

                if (string.IsNullOrEmpty(openid) == true)
                    openid = OpenIDManage.GetOpenID();
                return openid;
            }
        }
        /// <summary>
        /// 授权回调
        /// </summary>
        [IsWeiXinOpenAttribute(IsWeiXinOpen = false)]
        [WeiXinLoginAttribute(IsAutoLogin = false, IsAuthorization = false)]//自动登录
        public ActionResult Call(string code, string state, string appid, string url, string userid, string ia)
        {
            /*2015/8/7 小周 跳转url 不读cookie改成读参数*/
            url = HttpUtility.HtmlDecode(url);
            //LogManage.Log("微信回调:" + Request.Url.ToString() + ",授权之前url:" + url, true);

            try
            {
                ViewBag.loadurl = url;
                #region 参数检查
                if (string.IsNullOrEmpty(appid) == true)
                {
                    LogManage.Log("授权回调appid没有返回来,当前url:" + Request.Url.ToString());

                    ViewBag.Msg = "微信服务器授权超时,";
                    System.Threading.Thread.Sleep(300);
                    return View();
                }
                if (state != "author")
                {
                    LogManage.Log("授权回调state错误,当前url:" + Request.Url.ToString());

                    ViewBag.Msg = "微信服务器授权超时,";
                    System.Threading.Thread.Sleep(300);
                    return View();
                }
                if (string.IsNullOrEmpty(code) == true)
                {
                    LogManage.Log("授权回调code为空,当前url:" + Request.Url.ToString());

                    ViewBag.Msg = "微信服务器授权超时,";
                    System.Threading.Thread.Sleep(300);
                    return View();
                }
                #endregion

                ComponentAccessToken webToken = WeiXinOpenRequest.get_access_token(code, appid);

                string oldopenid = webToken.openid;
                BindMemberInfo member = MemberBindMerchantManage.GetMemberInfo(oldopenid);
                T_BAS_Merchants merch = MerchantManage.GetMerchantByUserID(userid);
                if (merch == null) return new ErrorResult("找不到商家店铺" + userid);

                T_BAS_MemberBindMerchant mbm = null;
                string id = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
                if (member == null)//不是分销商
                {
                    string newopenid = oldopenid;
                    string newuserid = userid;

                    var istop = HeadPay.IsTopMerchant(merch.MerchantGuid);
                    if (ia == "0" || istop == true)//不能直接授权,
                    {
                        var mbmPara = ParameterMagage.GetMemberBindMerchant(merch.MerchantGuid);

                        if (istop != true)
                            newopenid = string.Format("{0}-6-1-{1}", newopenid, newuserid);

                        mbm = MemberBindMerchantManage.Get(oldopenid);
                        if (mbm == null)//没有绑定,创建新的openid
                        {
                            mbm = new T_BAS_MemberBindMerchant()
                            {
                                UserID = newuserid,
                                NewOpenID = newopenid,
                                OpenID = oldopenid,
                                MemberBindMerchantGuid = Guid.NewGuid(),
                                CreateDate = DateTime.Now,
                                SMerchantGuid = Guid.Empty,
                            };
                            MemberBindMerchantManage.Add(mbm);
                        }
                        else
                        {
                            if (mbmPara == DictionaryConst.MemberMerchant.First)
                            {
                                newopenid = mbm.NewOpenID;
                                newuserid = mbm.UserID;
                            }
                            else
                            {
                                if (mbm.UserID != newuserid)
                                {
                                    member = MemberBindMerchantManage.GetMemberInfo(mbm.NewOpenID);//加盟是否是分销商
                                    if (member == null)
                                    {
                                        LogManage.Log("锁定最后一个关系,不是分销销");
                                        mbm.UserID = newuserid;
                                        mbm.NewOpenID = newopenid;
                                        MemberBindMerchantManage.Update(mbm);
                                    }
                                    else
                                    {
                                        LogManage.Log("锁定最后一个关系,是分销销" + member.userid);
                                        newuserid = member.userid;
                                        newopenid = member.openid;
                                    }
                                }
                            }
                        }
                    }

                    MemberManage.WebSNSUpdateMember(newopenid, webToken.access_token, appid, newuserid);

                    url = url.Replace(string.Format("://{0}.shop.", userid), string.Format("://{0}.shop.", newuserid));
                    //参数openid
                    CurrentUser.SetMerchantUserID(newuserid);
                    webToken.openid = newopenid;
                }
                else//原来进入过商店,跳到原来店铺
                {
                    LogManage.Log(string.Format("id:{0},12", id));
                    MemberManage.WebSNSUpdateMember(webToken.openid, webToken.access_token, appid, member.userid);//更新原来分销会员
                    url = url.Replace(string.Format("://{0}.shop.", userid), string.Format("://{0}.shop.", member.userid));//跳到原来来店
                    CurrentUser.SetMerchantUserID(member.userid);
                    LogManage.Log("原来进入过商店,跳到原来店铺:" + url);
                }

                #region 第一次打开授权通过参数传递
                if (url.ToLower().Contains(OpenIDManage.OpenTranIDKey.ToLower()) != true)//zhouxq 2015/11/25 参数重新
                {
                    if (url.Contains("?") == true)
                        url += string.Format("&{0}={1}", OpenIDManage.OpenTranIDKey.ToLower(), webToken.openid);
                    else
                        url += string.Format("?{0}={1}", OpenIDManage.OpenTranIDKey.ToLower(), webToken.openid);
                }
                #endregion
                LogManage.Log("授权成功,开始转发:" + url);
                return Redirect(url);
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("授权回调处理失败当前url:" + Request.Url.ToString() + ",转发地址:" + url + ",Message:" + ex.Message + ",StackTrace:" + ex.StackTrace);
                ViewBag.Msg = "微信服务器授权超时,";

                if (ex.Message.Contains("\"errcode\":61006") == true)
                {
                    return new ErrorResult("component_verify_ticket已过期");
                }
                else
                {
                    System.Threading.Thread.Sleep(300);
                    return View();
                }
            }
        }
        /// <summary>
        /// 获取当前用户
        /// (根据openid获取)
        /// </summary>
        /// <returns></returns>
        protected T_BAS_Member GetCurrentMember()
        {
            var currentmember = Session[SessionKeys.COOKIE_WX_Current];
            if (currentmember == null)
            {
                Session[SessionKeys.COOKIE_WX_Current] = currentmember = MemberManage.GetMemberByOpenID(OpenID);
            }
            return (T_BAS_Member)(currentmember);
        }

        /// <summary>
        /// 获取客户ip
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        protected string GetIP()
        {
            string ip = string.Empty;
            if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
                ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
            if (string.IsNullOrEmpty(ip))
                ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
            return ip;
        }

        protected ContentResult ErrorContent(string msg)
        {
            return Content(string.Format("<div style='color:red;font-;font-size: 3em;text-align: center;margin-top: 10%;'>{0}</div>", msg));
        }

    }
}