import { ConfigManager } from "../../common/RunningParameters/ConfigManager";
// import FocusManager from "../FocusManagers/FocusManager";
import PlatformLogger from "../../common/RunningParameters/PlatformSettings";
// 定义 IPage 接口
interface IPage {
    InstanceId: string;
    SetOwnerContainer(container: PageContainer): void;
    SetInstanceId(id: string): void;
    ViewStateData: { [key: string]: any };
}

// 定义 PageClosedEventArgs 接口
interface PageClosedEventArgs {
    InstanceId: string;
    ViewStateData: { [key: string]: any };
}

// 定义 FocusManager 接口
enum ConfigType {
    System,
    Client,
    User
}

// 定义 PageContainer 类
class PageContainer {
    private _pageStack: IPage[] = [];
    public AllPagesClosed: ((sender: PageContainer, args: PageClosedEventArgs) => void) | null = null;
    private _currentPage: IPage | null = null;
    public get CurrentPage(): IPage | null {
        return this._currentPage;
    }
    private set CurrentPage(value: IPage | null) {
        this._currentPage = value;
        this.RaisePropertyChanged("CurrentPage");
    }

    private _ClosedCallbackList: { [key: string]: (page: IPage) => void } = {};

    public IsShowInfo: boolean = false;
    public DisplayInfoList: any[] = [];
    public BusyStateTip: string = "数据处理中...";
    public IsBusy: boolean = false;
    public IsOverlay: boolean = false;

    private _busyAdorner: HTMLElement | null = null;
    private _sprocket: HTMLElement | null = null;

    constructor() {
        // 模拟 WPF 的静态构造函数逻辑
        // 在 TypeScript 中无法直接实现静态构造函数，这里可以在实例构造函数中初始化一些静态相关的逻辑
    }

    public OnContentChanged(oldContent: any, newContent: any): void {
        const page = newContent as IPage;
        if (page === null && newContent !== null) {
            throw new Error("Content必须继承IPage对象");
        }

        if (page !== null && page.InstanceId !== "") {
            this.CurrentPage = page;

            if (!this._pageStack.includes(page)) {
                page.SetOwnerContainer(this);
                this._pageStack.push(page);
            }
        }
    }

    public PushPage(page: IPage, closedCallback: ((page: IPage) => void) | null = null): string {
        if (page === null) {
            return "";
        } else {
            if (page.InstanceId === "") {
                page.SetInstanceId(this.generateGuid());
            }
            if (closedCallback !== null) {
                this._ClosedCallbackList[page.InstanceId] = closedCallback;
            }
            // 模拟移除父元素的逻辑
            // 在 Web 环境中，可能需要根据具体情况实现
            this.OnContentChanged(null, page);
            return page.InstanceId;
        }
    }

    public ClosePage(): { [key: string]: any } | null {
        if (this._currentPage !== null) {
            const closePage = this._currentPage;
            this._pageStack.pop();

            if (this._pageStack.length > 0) {
                this.OnContentChanged(null, this._pageStack[this._pageStack.length - 1]);
            } else {
                if (this.AllPagesClosed !== null) {
                    this.AllPagesClosed(this, {
                        InstanceId: closePage.InstanceId,
                        ViewStateData: closePage.ViewStateData
                    });
                }
            }
            if (this._ClosedCallbackList[closePage.InstanceId]) {
                this._ClosedCallbackList[closePage.InstanceId](closePage);
            }
            closePage.SetInstanceId("");
            return closePage.ViewStateData;
        }

        return null;
    }

    public CloseAndOpenPage(page: IPage): string {
        if (page === null) {
            return "";
        } else {
            if (this._currentPage !== null) {
                this._currentPage.SetInstanceId("");
                this._pageStack.pop();
            }

            return this.PushPage(page);
        }
    }

    public OnApplyTemplate(): void {
        this._busyAdorner = document.getElementById("BusyAdorner");
        this._sprocket = document.getElementById("sprocketControl");
    }

    public SetBusyAdorner(isBusy: boolean, tip: string | null): void {
        if (this._busyAdorner !== null) {
            this._busyAdorner.textContent = tip ?? "正在处理...";
            this._busyAdorner.style.display = isBusy ? "block" : "none";
            if (this._sprocket !== null) {
                // 模拟 IsIndeterminate 属性
                // 在 Web 环境中，可能需要根据具体情况实现
            }
        }
    }

    public set IsBusyValue(value: boolean) {
        this.IsBusy = value;
        this.OnIsBusyChanged();
    }

    private OnIsBusyChanged(): void {
        //TODO焦点控制需要用到微软的框架
        const focusManager = null;//FocusManager.GetManagerInstance(this);
        if (focusManager !== null) {
            focusManager.CanAcceptUserInput = !this.IsBusy;
        } else {
            const handler = (e: KeyboardEvent) => {
                e.preventDefault();
            };
            if (this.IsBusy) {
                document.addEventListener("keydown", handler);
            } else {
                document.removeEventListener("keydown", handler);
            }

            const mouseHandler = (e: MouseEvent) => {
                e.preventDefault();
            };
            if (this.IsBusy) {
                document.addEventListener("mousedown", mouseHandler);
                document.addEventListener("mouseup", mouseHandler);
            } else {
                document.removeEventListener("mousedown", mouseHandler);
                document.removeEventListener("mouseup", mouseHandler);
            }
        }
        this.SetBusyAdorner(this.IsBusy, this.BusyStateTip);
    }

    public async ModalInvoke(action: () => Promise<void>, busyStateTip: string): Promise<void> {
        this.BusyStateTip = busyStateTip;
        this.IsBusyValue = true;

        if (ConfigManager.GetInstance().GetConfigValue("ModalInvoke", ConfigType.Client) !== "Legacy") {
            try {
                const win = new ModalWindow(action);
                win.DelayCancel = 120;
                await win.showDialog();
                this.IsBusyValue = false;
                if (win.IsCancel) {
                    throw new Error("用户强制中断了操作！");
                }
                return;
            } catch (ex) {
                PlatformLogger.SystemErrorInfo("ModalInvoke:初始化ModalWindow发生异常！", ex as Error);
            }
        }

        try {
            await action();
        } finally {
            this.IsBusyValue = false;
        }
    }

    private RaisePropertyChanged(propertyName: string): void {
        // 模拟属性变更通知
        // 在 Vue 中，可以使用事件或响应式系统实现
    }

    private generateGuid(): string {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            const r = Math.random() * 16 | 0,
                v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
}

// 定义 ModalWindow 类
class ModalWindow {
    private action: () => Promise<void>;
    private thread: NodeJS.Timeout | null = null;
    private watch: number = Date.now();
    public DelayCancel: number = 30;
    public IsCancel: boolean = false;

    constructor(action: () => Promise<void>) {
        this.action = action;
    }

    public async showDialog(): Promise<void> {
        const dialog = document.createElement("div");
        dialog.style.position = "fixed";
        dialog.style.bottom = "0";
        dialog.style.left = "0";
        dialog.style.backgroundColor = "rgba(0, 0, 0, 0.5)";
        dialog.style.color = "white";
        dialog.style.padding = "10px";
        dialog.textContent = "系统处理中...";
        document.body.appendChild(dialog);

        try {
            this.thread = setTimeout(() => {
                this.action().then(() => {
                    dialog.remove();
                }).catch((ex) => {
                    PlatformLogger.SystemErrorInfo("ModalInvoke2Dialog:调用发生异常！", ex);
                    dialog.remove();
                });
            }, 0);

            document.addEventListener("keydown", this.handleKeyDown.bind(this));
        } finally {
            document.removeEventListener("keydown", this.handleKeyDown.bind(this));
        }
    }

    private handleKeyDown(e: KeyboardEvent): void {
        if ((Date.now() - this.watch) / 1000 < this.DelayCancel) return;
        if (e.key === "x" && e.ctrlKey) {
            if (this.thread !== null) {
                clearTimeout(this.thread);
                this.IsCancel = true;
            }
        }
    }
}

export { PageContainer };
