using Microsoft.Extensions.DependencyInjection;
using Rougamo;
using Rougamo.Context;
using SlnMesnac.WPF.Page.Loading;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：T14-GEN3-7895
* 命名空间：SlnMesnac.WPF.Attribute
* 唯一标识：fff40cb6-18aa-47e0-917c-1fa653e6f978
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2024-12-30 10:19:41
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.WPF.Attribute
{
    /// <summary>
    /// 权限过滤
    /// </summary>
    public class RequirePermissionAttribute : MoAttribute
    {
        private LoadingWindow loadingWindow;
        private string _permissionName;

        public RequirePermissionAttribute(string permissionName)
        {
            _permissionName = permissionName;

            
        }
        public override void OnEntry(MethodContext context)
        {
            Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
            newWindowThread.SetApartmentState(ApartmentState.STA); // 设置为 STA 模式
            newWindowThread.IsBackground = true; // 设置为后台线程
            newWindowThread.Start();

            bool hasPermission = CheckPermission(_permissionName);

            if (!hasPermission)
            {
                // 如果用户没有权限，抛出异常或采取其他措施
                throw new UnauthorizedAccessException("User does not have the required permission.");
            }

            base.OnEntry(context);
        }


        public override void OnExit(MethodContext context)
        {
            Thread.Sleep(200);
            if(loadingWindow != null)
            {
                loadingWindow.Dispatcher.Invoke(new Action(() =>
                {
                    loadingWindow.Close(); // 关闭窗口
                }));
            }

            
            base.OnExit(context);
        }

        /// <summary>
        /// 判断权限
        /// </summary>
        /// <param name="permissionName"></param>
        /// <returns></returns>
        private bool CheckPermission(string permissionName)
        {
            return true; 
        }

        private void ThreadStartingPoint()
        {
            Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                loadingWindow = App.ServiceProvider.GetService<LoadingWindow>();
                loadingWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                loadingWindow.Topmost = true;
                loadingWindow.Show();
            }));

            Dispatcher.Run();
        }
    }
}
