import React, { ComponentType, Component } from "react";

import styles from "./ModalCtrl.module.less";
// import PrizePanel from "@/panels/PrizePanel/PrizePanel.tsx";
// import FailPanel from "@/panels/FailPanel/FailPanel.tsx";

// 弹窗优先级配置Map，key为弹窗组件名（建议用组件.displayName或组件名字符串），value为优先级数值
// 数值越大优先级越高，未配置的默认0
const modalPriorityMap = new Map<ComponentType<any>, number>([
  // [PrizePanel, 20],
  // [FailPanel, 15],
]);

interface ModalItem {
  key: string;
  Component: ComponentType<any>;
  props?: any;
  priority?: number; // 新增优先级字段
}

interface ModalCtrlState {
  modals: ModalItem[];
}

export class ModalCtrl extends Component<{}, ModalCtrlState> {
  state = {
    modals: [],
  };

  static showModal: (Component: ComponentType<any>, props?: any) => void = null;
  static closeModal: (Component?: ComponentType<any>) => void = null;
  static closeAllModal: () => void = null;

  componentDidMount() {
    ModalCtrl.showModal = this.showModal;
    ModalCtrl.closeModal = this.closeModal;
    ModalCtrl.closeAllModal = this.closeAllModal;
  }

  componentWillUnmount() {
    ModalCtrl.showModal = null;
    ModalCtrl.closeModal = null;
    ModalCtrl.closeAllModal = null;
  }

  showModal = (Component: ComponentType<any>, props: any = {}) => {
    const key = `modal_${Date.now()}_${Math.random()}`;
    const priority = modalPriorityMap.get(Component) || 0;

    const modals = this.state.modals;
    modals.push({ key, Component, props, priority })
    modals.sort((a, b) => {
      return (b.priority || 0) - (a.priority || 0);
    });

    this.setState({ modals });
  };

  closeModal = (Component?: ComponentType<any>) => {
    let modals = this.state.modals;
    if (!Component) {
      modals.pop();
    } else {
      modals = modals.filter((modal) => {
        return modal.Component != Component;
      });
    }

    this.setState({ modals });
  };

  closeAllModal = () => {
    const modals = this.state.modals;
    modals.length = 0;
    this.setState({ modals });
  }

  render() {
    const { modals } = this.state;
    if (!modals.length) return null;
    const topModal = modals[modals.length - 1];
    console.log(modals)
    return (
      <>
        <div className={styles.modalManagerBg} key={topModal.key} style={{ zIndex: 2000 }}>
          <topModal.Component {...topModal.props}/>
        </div>
      </>
    );
  }
}
