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

import styles from "./ModalCtrl.module.less";

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

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

interface ModalCtrlState {
  modals: ModalItem[];
}

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

  static showModal: (Component: ComponentType<any>, props?: any, showMask?: boolean) => 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 = {}, showMask = true) => {
    const key = `modal_${Date.now()}_${Math.random()}`;
    const priority = modalPriorityMap.get(Component) || 0;

    const modals = this.state.modals;
    modals.push({ key, Component, props, priority, showMask });
    modals.sort((a, b) => {
      return (a.priority || 0) - (b.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];
    return (
      <>
        <div
          className={styles.modalManagerBg}
          key={topModal.key}
          style={{ zIndex: 2000, backgroundColor: `rgba(0,0,0, ${topModal.showMask ? 0.7 : 0})` }}
        >
          <topModal.Component {...topModal.props}/>
        </div>
      </>
    );
  }
}
