import { Canceler } from 'axios';
import { defineStore } from 'pinia';
import {
  getMessage,
  getUserInfo,
  NoticeInfo,
  NoticeInfoParams,
  UserInfo,
} from '@/api/common';
import { BaseLoginUrl } from '@/constants/constants';

export interface MainStateType {
  cancelReqToken: Canceler[];
  userInfo: Omit<UserInfo, 'accessToken'>;
  isshoweventlist: Boolean;
  videohandle: any;
  videoisshow: Boolean;
  videotitle: string;
}

export interface MainActionsType {
  pushReqToken(cancelToken: Canceler): void;
  clearReqToken(): void;
  removeToken(): void;
  getUserInfo(ticket: string): Promise<true | undefined>;
  getMessage(params: NoticeInfoParams): Promise<NoticeInfo[] | undefined>;
  setEventListshow(isshow:boolean):void;
}

export default defineStore<'main', MainStateType, {}, MainActionsType>('main', {
  state: () => ({
    cancelReqToken: [],
    userInfo: {},
    isshoweventlist: false,
    videohandle: {},
    videoisshow: false,
    videotitle:"-",
  }),
  actions: {
    async getMessage(params) {
      try {
        const { rows } = await getMessage(params);
        return rows;
      } catch (err) {
        console.log(err);
      }
    },
    setEventListshow(isshow) { 
       this.isshoweventlist = isshow; 
    },
    async getUserInfo(ticket) {
      try {
        const {
          data: { accessToken, ...userInfo },
        } = await getUserInfo(ticket);
        if (accessToken) {
          window.localStorage.setItem('Authorization', accessToken);
        }
        this.userInfo = userInfo;
        return true;
      } catch (err) {
        window.location.href = BaseLoginUrl;
        console.log(err);
      }
    },
    pushReqToken(cancelToken) {
      this.cancelReqToken.push(cancelToken);
    },
    removeToken() { 
       window.localStorage.removeItem('Authorization');
    },
    clearReqToken() {
        this.cancelReqToken.forEach((cancel) => {
         cancel('axios cancel by router change');
       });
      this.cancelReqToken = [];
    },
  },
});
