using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;

using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Repository.BackendRepository.Interface;
using Backend.Models;
using Backend.Services.Implement;

namespace Backend.Controllers
{
    public class MybaseController<T> : Controller where T : MybaseController<T>
    {
        private ILogger<T> _logger;
        protected ILogger<T> Logger => _logger ?? (_logger = HttpContext?.RequestServices.GetService<ILogger<T>>());

        private IBackendRepository backendRepository => HttpContext?.RequestServices.GetService<IBackendRepository>();
        private IUserInfoRepository userInfoRepository => HttpContext?.RequestServices.GetService<IUserInfoRepository>();

        public string baseURL => HttpContext?.Request.Scheme + "://" + HttpContext?.Request.Host + "/";

        public BackgroundService backgroundService;
        protected MyUserInfo myUserInfo = null;
        public string controllerName;
        public string actionName;
        public string main_system_type = "device_system_category_layer2";
        public string sub_system_type = "device_system_category_layer3";
        public string system_setting_type = "system_setting";

        public MybaseController() { }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            EDFunction edFunction = new EDFunction();
            var myAccount = edFunction.AESDecrypt(HttpContext.Session.GetString("MyAccount"));
            controllerName = ControllerContext.RouteData.Values["controller"].ToString();   //controller名稱
            actionName = ControllerContext.RouteData.Values["action"].ToString();   //action名稱
            bool isAjaxCall = filterContext.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            if (string.IsNullOrEmpty(myAccount))
            {

                if (isAjaxCall)
                {
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 499;
                    return;
                }
                else
                {
                    filterContext.Result = new RedirectToRouteResult(
                                        new RouteValueDictionary
                                        {
                                            {"controller", "Login"},
                                            {"action", "Index"}
                                        });
                    return;
                }
            }

            backgroundService = new BackgroundService(backendRepository);

            //取得當前登入使用者資訊
            myUserInfo = userInfoRepository.GetMyUserInfoByAccount<MyUserInfo>(myAccount);
            var showview = backendRepository.GetAllAsync<string>($@"select ap.ShowView from userinfo us
            left join role_auth ra on ra.role_guid = us.role_guid
            left join auth_page ap on ap.AuthCode = ra.AuthCode
            where us.userinfo_guid = '{myUserInfo.Userinfo_guid}'");
            myUserInfo.ShowView = showview.Result;

            ViewBag.myUserInfo = myUserInfo;
            ViewBag.role = showview.Result;
            #region 記錄人員操作記錄
            var content = JsonConvert.SerializeObject(filterContext.ActionArguments);
            var parameter = content.CompareTo("{}") == 0 ? null : content;
            List<string> removeParam = new List<string>() { "ChangePassword" }; //移除不紀錄參數的actionName
            if (removeParam.Any(x => actionName.Contains(x)))
            {
                parameter = "{}";
            }

            Dictionary<string, object> operatorLog = new Dictionary<string, object>();

            operatorLog = new Dictionary<string, object>()
            {
                { "@controller_name", controllerName},
                { "@action_name", actionName},
                { "@parameter", parameter},
                { "@created_by", myUserInfo.Userinfo_guid}
            };

            if (actionName != "CompareData" && controllerName != "NiagaraDataSynchronize") //skip the log
                backendRepository.InsertOperatorLog(operatorLog, "operation_back_log");

            //operatorLogRepository.Add(operatorLog, properties);
            #endregion
        }

    }
}