import { defineStore } from "pinia";
import { store } from "@/stores";
import https from "@/https";
import { gameListStore } from "./game-list";
import { fomartName } from "@/utils";

export const noticeStore = defineStore("notice", {
  persist: true,
  state: () => {
    return {
      notice: <Array<any>>[],
      // 首页下载TOP
      showTopDownload: true,
      broadcast: <Array<any>>[],
    };
  },
  actions: {
    closeShowTopDownload() {
      this.showTopDownload = false;
    },
    setBroadcast(res: any) {
      if (res.gameId) {
        return;
      }
      let obj: any = { ...res };
      obj.txt = res.txt
        .replace("{#uid}", fomartName(`${res.uid}`))
        .replace("{#game}", res.gameAlias)
        .replace("{#coins}", res.coins / 10000);
      if (this.broadcast.length >= 2) {
        let data = [this.broadcast[this.broadcast.length - 1]];
        data.push(obj);
        this.broadcast = [...data];
      } else {
        this.broadcast.push(obj);
      }
    },
    setNotice(message: any) {
      if (!message.gameId) {
        return;
      }
      let data = [...this.notice];
      if (
        !data.find(
          (el: any) =>
            el.serverTime == message.serverTime && el.uid == message.uid
        )
      ) {
        let newItem = gameListStore().originalList.find(
          (item: any) => item.gameId === message.gameId
        );
        data.push({ ...newItem, ...message });
        if (data.length > 18) {
          this.notice = data.slice(data.length - 18, data.length);
        } else {
          this.notice = [...data];
        }
        this.setNoticeTxt();
      }
    },
    setNoticeTxt() {
      this.notice.forEach((item: any) => {
        if (item.txt) {
          item.txt = item.txt
            .replace("{#uid}", fomartName(`${item.uid}`))
            .replace("{#game}", item.gameAlias)
            .replace("{#coins}", item.coins / 10000);
        }
      });
    },
    async getNotice() {
      if (this.notice.length > 0) return;
      const res = await https.getNotice();
      if (res.code !== 0) return;
      this.notice = [...res.data];
    },
    setAllNotice(data: Array<any>) {
      if (data.length > 18) {
        this.notice = data.slice(data.length - 18, data.length);
      } else {
        this.notice = [...data];
      }
      this.setNoticeTxt();
    },
  },
});

// Need to be used outside the setup
export const useNoticeStoreWithOut = () => {
  return noticeStore(store);
};
