using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
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
{
    /// <summary>
    /// 
    /// </summary>
    public class APIAttributeActionFilter : ActionFilterAttribute
    {

        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
            {
                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 TalSeconds = (DateTime.Now - START_TIME).TotalSeconds;
                    if (TalSeconds > 0.8)
                    {
                        T_FM_SYNC_LOG 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 = TalSeconds.ToString()
                        };


                        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();
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
    }
}
