using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Security;
using LDX.BaseData.Domain.IServices;
using LDX.Core;
using LDX.Core.Caching;
using LDX.MES.Domain.IServices.FM;

namespace LDX.WebApi
{
    /// <summary>
    /// 指定用于验证请求的 System.Security.Principal.IPrincipal 的Api授权筛选器。
    /// </summary>
    public class ApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute, IOverrideFilter
    {
        /// <summary>
        /// 是否需要登录
        /// </summary>
        public bool NeedLogin { get; set; }

        /// <summary>
        /// 为操作授权时调用。
        /// </summary>
        /// <param name="actionContext">上下文。</param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
            //var authorization = actionContext.Request.Headers.Authorization;
            //if ((authorization != null) && (authorization.Parameter != null))
            //{
            //    //解密用户ticket,并校验用户名密码是否匹配
            //    var encryptTicket = authorization.Parameter;
            //    if (ValidateTicket(encryptTicket))
            //    {

            //        base.IsAuthorized(actionContext);
            //    }
            //    else
            //    {
            //        HandleUnauthorizedRequest(actionContext);
            //    }
            //}
            ////如果取不到身份验证信息，并且不允许匿名访问，则返回未验证401
            //else
            //{
            //    var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
            //    bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
            //    if (isAnonymous) base.OnAuthorization(actionContext);
            //    else HandleUnauthorizedRequest(actionContext);
            //}
        }
        //校验用户名密码（正式环境中应该是数据库校验）
        private bool ValidateTicket(string encryptTicket)
        {
            var token= FormsAuthentication.Decrypt(encryptTicket);
            if(token.Expired)
                throw new Exception("令牌已过期");
            //解密Ticket
            var strTicket = token.UserData;
            //从Ticket里面获取用户名和密码
            //var index = strTicket.IndexOf("&");
            //var strUser = new Guid(strTicket.Substring(0, index));
            //string strPwd = strTicket.Substring(index + 1);
            var strArray  = strTicket.Split('&');
            if (strArray.Length != 3)
                throw new Exception("令牌参数数量不正确!");
            var strUser = new Guid(strArray[0]);
            string strPwd = strArray[1];
            string type = strArray[2];
            ServiceLocator locator = ServiceLocator.Instance;
            var userService = locator.GetService<IFMUserService>();
            //var platformService = locator.GetService<IPlatformUserService>();
            if (type == "0")
            {
                var user = userService.Get(i => i.ID == strUser && i.PASSWORD == strPwd);
                return user == null ? false : true;
            }
            else {
				//var platformServiceInfo = platformService.Get(i => i.ID == strUser && i.PASSWORD == strPwd);
				//return platformServiceInfo == null ? false : true;
				return false;
            }
        }

        private static bool SkipAuthorization(HttpActionContext actionContext)
        {
            return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>()
                || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>();
        }

        #region IOverrideFilter 成员

        public Type FiltersToOverride
        {
            get { return typeof(IAuthorizationFilter); }
        }

        #endregion
    }
}