using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices.BS;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using APT.Migrations;
using APT.Utility;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace APT.WebApi.Models//APT.BS.WebApi.Models
{
    /// <summary>
    /// 
    /// </summary>
    public class APIAttributeActionFilter : ActionFilterAttribute// IActionFilter 
    {
        IFMUserService UserService { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userService"></param>
        public APIAttributeActionFilter(IFMUserService userService)
        {
            UserService = userService;
        }

        /// <summary>
        /// API请求开始时记录时间信息
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            context.HttpContext.Items.Add("1", System.DateTime.Now);
            context.HttpContext.Items.Add("2", context.HttpContext.TraceIdentifier);
        }

        /// <summary>
        /// 结束时写入结束时间
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            try
            {
                #region     操作记录

                //var API_NAME = context.HttpContext.Request.Path;
                //bool isRecord = false;
                ////switch (API_NAME)
                ////{
                ////    case "":
                ////        isRecord = true;
                ////        break;
                ////    default:
                ////        break;
                ////}
                ////isRecord = true;
                //if (isRecord)
                //{
                //    //避免不需要的反射

                //    //bool? IsSuccessful = null;
                //    //try
                //    //{
                //    //    IsSuccessful = ((APT.Infrastructure.Core.JsonActionResult`1[System.Boolean])((Microsoft.AspNetCore.Mvc.ObjectResult)context.Result).Value).IsSuccessful;
                //    //}
                //    //catch { }
                //    var ResultValue = ((Microsoft.AspNetCore.Mvc.ObjectResult)context.Result).Value;
                //    Type TResultValue = ResultValue.GetType();
                //    bool? IsSuccessful = null;
                //    PropertyInfo[] propsVal = TResultValue.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                //    foreach (var prop in propsVal)
                //    {
                //        if (prop.Name == "IsSuccessful")
                //        {
                //            var fdsafd = prop.GetValue(ResultValue);
                //            IsSuccessful = (bool)fdsafd;
                //            break;
                //        }
                //    }
                //    if (IsSuccessful.HasValue && IsSuccessful.Value)
                //    {
                //        //执行成功记录操作结果

                //    }
                //}

                #endregion
                #region     T_FM_SYNC_LOG 获取

                T_FM_SYNC_LOG log = null;
                if (context.HttpContext.Items != null && context.HttpContext.Items.ContainsKey("1"))
                {
                    DateTime START_TIME = DateTime.Now;
                    string TRACEIDENTIFIER = string.Empty;
                    if (context.HttpContext.Items != null && context.HttpContext.Items.Count > 0)
                    {
                        foreach (var item in context.HttpContext.Items)
                        {
                            if (item.Key != null && item.Key.ToString() == "1")
                            {
                                START_TIME = Convert.ToDateTime(item.Value);
                            }
                            else if (item.Key != null && item.Key.ToString() == "2")
                            {
                                TRACEIDENTIFIER = item.Value.ToString();
                            }
                        }
                    }
                    double SYNC_PARAM = (DateTime.Now - START_TIME).TotalSeconds;
                    if (SYNC_PARAM > 0.8)
                    {
                        log = new T_FM_SYNC_LOG()
                        {
                            ID = Guid.NewGuid(),
                            START_TIME = START_TIME,
                            END_TIME = DateTime.Now,
                            API_NAME = context.HttpContext.Request.Path,
                            DATA_COUNT = 0,
                            IS_SUCCESS = true,
                            IS_DELETED = false,
                            ORG_ID = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId,
                            ENTITY_ORG_TPYE = 0,
                            FLOW_STATUS = 0,
                            FLOW_SEND_STATUS = 0,
                            //CREATE_TIME = DateTime.Now,
                            //MODIFY_TIME = DateTime.Now,
                            TRACEIDENTIFIER = TRACEIDENTIFIER,
                            TRACEIDENTIFIERED = context.HttpContext.TraceIdentifier,
                            ISINSERT = false,
                            LOGTYPE = DataHelper.GetRequestType(context.HttpContext.Request.Headers) == 2 ? SyncLogType.APITimeResponsenAPP : SyncLogType.APITimeResponsen,
                            //FLOW_ID = ID,
                            //FORM_ID = ID,
                            CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID,
                            //MODIFIER_ID = ID,
                            //SYNC_PARAM = SYNC_PARAM,
                            //LOGTYPE = ID,
                            SYNC_PARAM = SYNC_PARAM.ToString()
                        };

                        //var commonService = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<IFMUserService>();
                        //commonService.AddEntity<T_FM_SYNC_LOG>(log);

                    }
                }

                #endregion
                #region    数据库操作

                if (log != null)//增加别的判断 (log != null||(isRecord&& !=null  ))
                {
                    Infrastructure.Core.IUnitOfWork UnitOfWork = UserService.UnitWork();
                    Type TUnitOfWork = UnitOfWork.GetType();
                    PropertyInfo[] props = TUnitOfWork.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                    List<string> listInfo = new List<string>();
                    TenantInfo tenantInfo = null;
                    foreach (var prop in props)
                    {
                        if (prop.Name == "TenantInfo")
                        {
                            var fdsafd = prop.GetValue(UnitOfWork);
                            tenantInfo = (TenantInfo)fdsafd;
                            break;
                        }
                    }
                    if (!string.IsNullOrEmpty(tenantInfo.Conn))
                    {
                        using (var contextCnn = new MigrationContext(tenantInfo.Conn))
                        {
                            contextCnn.AddEntity(log);
                            contextCnn.SaveChanges();
                        }
                    }
                }

                #endregion
            }
            catch
            {
            }
        }
    }
}
