using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc.Filters;
using APT.Infrastructure.Core;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using APT.Migrations;
using NPOI.SS.Formula.Functions;
using APT.BaseData.Domain.Entities.FM;
using System.Configuration;
using APT.Utility;
using APT.BaseData.Domain.ApiModel.Platform;
using APT.Infrastructure.Api.Redis;
using Microsoft.Extensions.Logging;
using APT.BaseData.Domain.IServices.FM;

namespace APT.WebApi.Models
{
    /// <summary>
    /// ActionFilter
    /// </summary>
    public class CustomActionFilterAttribute : Attribute, IActionFilter
    {
        //private readonly ILogger<CustomActionFilterAttribute> _logger;

        ////IPFSysLogService SysLogService { get; set; }
        ////IFMSyncLogDetailService SyncLogDetailService { get; set; }
        ///// <summary>
        ///// 构造函数
        ///// </summary>
        ///// <param name="logger"></param>
        //public CustomActionFilterAttribute(ILogger<CustomActionFilterAttribute> logger)
        //{
        //    _logger = logger;
        //    //SysLogService = sysLogService; 
        //    //, IPFSysLogService sysLogService
        //    //SyncLogDetailService = syncLogDetailService;  , IFMSyncLogDetailService syncLogDetailService
        //}

        /// <summary>
        /// 在方法执行之前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            T_FM_SYNC_LOG log = new T_FM_SYNC_LOG()
            {
                ID = Guid.NewGuid(),
                START_TIME = DateTime.Now,
                END_TIME = DateTime.Now,
                API_NAME = context.HttpContext.Request.Path,
                DATA_COUNT = 0,
                IS_SUCCESS = true,
                IS_DELETED = false,
                //ORG_ID = context.ActionArguments[0] 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 = context.HttpContext.TraceIdentifier,
                ISINSERT = false,
                //FLOW_ID = ID,
                //FORM_ID = ID,
                //CREATER_ID = ID,
                //MODIFIER_ID = ID,
                //SYNC_PARAM = SYNC_PARAM,
                //LOGTYPE = ID,
            };
            if (context.ActionArguments != null || context.ActionArguments.Count > 0)
            {
                foreach (var item in context.ActionArguments)
                {
                    if (item.Key == "filter")
                    {
                        KeywordFilter kw = (KeywordFilter)item.Value;
                        if (kw.OrgId.HasValue)
                        {
                            log.ORG_ID = kw.OrgId;
                            log.SYNC_PARAM = kw.Parameter1;
                        }
                        else
                        {

                        }
                    }
                }
            }
            if (!context.HttpContext.Items.ContainsKey("syncLog"))
            {
                context.HttpContext.Items.Add("syncLog", log);
                context.HttpContext.Items.Add("syncID", log.ID);
            }
        }

        /// <summary>
        /// 在方法执行之后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            try
            {
                if (context.HttpContext.Items != null && context.HttpContext.Items.ContainsKey("syncLog"))
                {
                    var syncLog = (T_FM_SYNC_LOG)context.HttpContext.Items["syncLog"];
                    var conn = APT.Infrastructure.Api.ConfigurationManager.ConnectionStrings["default"];
                    if (syncLog.ORG_ID.HasValue)
                    {
                        List<EnumsResult> list = APT.Utility.DataHelper.GetEnum("FilePathHead");
                        string ORG_ID = syncLog.ORG_ID.Value.ToString().ToUpperInvariant();
                        int? orgVal = null;
                        foreach (var item in list)
                        {
                            if (item.NAME == ORG_ID)
                            {
                                orgVal = item.ID;
                                break;
                            }
                        }

                        switch (orgVal.Value)
                        {
                            case 1:
                                conn = conn.Replace("mh_ops", "mh_db");
                                break;
                            case 4:
                                conn = conn.Replace("mh_ops", "mh_dcjd");
                                break;
                            case 5:
                                conn = conn.Replace("mh_ops", "mh_gxbb");
                                break;
                            case 2:
                                conn = conn.Replace("mh_ops", "mh_lyxt");
                                break;
                            case 3:
                                conn = conn.Replace("mh_ops", "mh_lyyl");
                                break;
                            default:
                                break;
                        }
                    }

                    syncLog.TRACEIDENTIFIERED = context.HttpContext.TraceIdentifier;
                    syncLog.END_TIME = DateTime.Now;

                    if (context.HttpContext.Items.ContainsKey("Count"))
                    {
                        try
                        {
                            syncLog.DATA_COUNT = int.Parse(context.HttpContext.Items["Count"].ToString());
                        }
                        catch { }
                    }

                    using (var contextCnn = new MigrationContext(conn))
                    {
                        contextCnn.AddEntity(syncLog);
                        contextCnn.SaveChanges();
                    }
                }
            }
            catch
            {
            }
        }
    }
}
