import { App } from 'vue';

export default {
  install(app: App) {
    // 创建或获取一个统一的alert容器
    const getOrCreateAlertsContainer = () => {
      let alertsContainer = document.querySelector('.alerts-container');
      if (!alertsContainer) {
        alertsContainer = document.createElement('div');
        alertsContainer.setAttribute('class', 'alerts-container');
        document.body.appendChild(alertsContainer);
      }
      return alertsContainer;
    };

    const alertMethod = (
      message: string,
      type: 'success' | 'warning' | 'error' | 'info',
      duration = 3000
    ) => {
      const alertsContainer = getOrCreateAlertsContainer();
      const alertContainer = document.createElement('div');
      alertContainer.setAttribute('class', `alert alert-${type}`);
      const alertContent = document.createElement('div');
      alertContent.innerText = message;
      const close = document.createElement('div');
      close.innerText = '×';
      const to1 = window.setTimeout(() => {
        alertContainer.attributeStyleMap.set(
          'animation',
          'fadeOut 0.6s ease-out'
        );
        alertContainer.attributeStyleMap.set('animation-play-state', 'running');
      }, duration - 450);
      const to2 = window.setTimeout(() => {
        alertsContainer.removeChild(alertContainer);
      }, duration);
      close.onclick = () => {
        alertContainer.attributeStyleMap.set(
          'animation',
          'fadeOut 0.6s ease-out'
        );
        alertContainer.attributeStyleMap.set('animation-play-state', 'running');
        window.setTimeout(() => {
          alertsContainer.removeChild(alertContainer);
          window.clearTimeout(to1);
          window.clearTimeout(to2);
        }, 450);
      };
      alertContainer.appendChild(alertContent);
      alertContainer.appendChild(close);
      alertsContainer.appendChild(alertContainer);
    };

    // 使用 app.provide 提供 alert 方法
    app.provide('alert', alertMethod);
  },
};
