<template>
  <div class="nana-error-report-container">
    <Transition name="nana-scale-transform">
      <div v-if="messageItems.length > 0" class="nana-error-report" @click="showError">
        <img :src="ErrorIcon" />
        <span>{{ errorCount }}</span>
        <img :src="WarningIcon" /> 
        <span>{{ warningCount }}</span>
      </div>
    </Transition>
  </div>
  <a-modal v-model:open="showModal" title="错误报告" width="60%" height="80%">
    <a-alert
      v-for="(item, index) in messageItems"
      :key="index"
      :message="item.message"
      :type="item.type"
      :description="item.detail"
    />
    <template #footer>
      <a-button @click="messageItems = [];showModal = false">清空</a-button>
      <a-button @click="showModal = false">关闭</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue';
import WarningIcon from '../AlertIcons/warning.svg';
import ErrorIcon from '../AlertIcons/error.svg';

export interface ErrorReportItem {
  time?: number,
  message: string,
  detail?: string,
  type: 'error' | 'warning' | 'info',
}
export interface ErrorReportRef {
  logError(info: ErrorReportItem): void;
}

const messageItems = ref<ErrorReportItem[]>([]);
const errorCount = ref(0);
const warningCount = ref(0);
const showModal = ref(false);

function logError(info: ErrorReportItem) {
  messageItems.value.push(info);
  if (info.type === 'error') 
    errorCount.value++;
  if (info.type === 'warning') 
    warningCount.value++;
}
function showError() {
  showModal.value = true;
}

provide<ErrorReportRef>("ErrorReporter", {
  logError,
});

onMounted(() => {
  (window as any).$error = logError;
})
</script>

<style lang="scss">
.nana-error-report-container {
  position: fixed;
  top: 2rem;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  pointer-events: none;
  z-index: 100;

  img {
    width: 1rem;
    height: 1rem;
  }
  span {
    color: #333;
  }
}
.nana-error-report {
  display: flex;
  flex-direction: row;
  align-items: center; 
  width: auto;
  gap: 0.5rem;
  background-color: #fff;
  padding: 0.6rem;
  border-radius: 0.5rem;
  pointer-events: all;
}
</style>