import { defineStore } from 'pinia';
import { store } from '@/store';
import { getTime } from '@/utils/dateUtil';

export interface INotificationStore {
  messages: any[];
}

export const notificationStore = defineStore({
  id: 'notificationStore',
  state: (): INotificationStore => ({
    messages: [],
  }),
  getters: {
    getMessages(): [any][] {
      return this.messages;
    },
  },
  actions: {
    setMessages(messages) {
      this.messages = messages;
    },
    isNotifyMsg(message) {
      return (
        (message.type !== undefined &&
          message.type === 3 &&
          message.msg !== undefined &&
          message.msg !== '') ||
        (message.type !== undefined &&
          message.type === 91 &&
          message.msg !== undefined &&
          message.msg !== '')
      );
    },
    addMessages(message) {
      message = JSON.parse(message);
      // console.log('message:' + JSON.stringify(message));
      if (this.isNotifyMsg(message)) {
        this.messages.unshift({
          desc: message.msg,
          pushAt: getTime(),
          type: message.code !== undefined && message.code !== 0 ? 'error' : 'success',
        });
      }

      // 数据最大保留条数，超出进行清理
      const limit = 10;
      if (this.messages.length > limit) {
        const sub = this.messages.length - limit;
        this.messages.splice(this.messages.length - sub);
      }
    },
  },
});

// Need to be used outside the setup
export function notificationStoreWidthOut() {
  return notificationStore(store);
}
