import { IssueItem } from '../types';
import { NotificationHandle } from 'element-plus';
import { defineStore } from 'pinia';
import { ref } from 'vue';

import mitt from 'mitt';

export const getPlace = (arr: [string, string]): string => {
  return arr.filter(Boolean).join('-');
};
export const emitter = mitt();

/** 消息轮播的store */
const useViolationNoticeStore = defineStore('violation-notice', () => {
  const list = ref<IssueItem[]>([]);
  let notiHandler: NotificationHandle | null = null;

  /** 追加新消息 */
  const add = (newList: IssueItem[]) => {
    // 只有消息为空时，才需要去主动触发消息提示
    if (list.value.length > 0) {
      list.value = [...newList, ...list.value];
    } else {
      list.value = [...newList];
      emitter.emit('showNotice');
    }
  };

  const clear = () => {
    // 清空的时候要把当前已有的也清空掉，同时关闭消息
    list.value = [];
    notiHandler?.close();
  };

  /** 获取最后一条消息（最旧的） */
  const getLastNotice = () => {
    if (list.value.length === 0) return null;
    // 获取最后一条,同时原数据也要减去这一条
    return list.value.pop()!;
  };

  return { list, add, clear, getLastNotice };
});

export default useViolationNoticeStore;
