import { defineStore } from 'pinia';
import { createStorage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '../mutation-types';
const storage = createStorage({ prefixKey: '', storage: sessionStorage });
import router from '../../router/index';
export interface IUserState {
  token: string;
  selectGoods: any[];
  selectVip: any[];
  schoolId: string;
}

export const useStudentRegisterStore = defineStore('student-register-store', {
  state: (): IUserState => ({
    token: storage.get(ACCESS_TOKEN, ''),
    selectGoods: [] as any,
    selectVip: [] as any,
    schoolId: storage.get('register_school_id', '')
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getGoods(): any[] {
      return this.selectGoods;
    },
    getVip(): any {
      return this.selectVip;
    },
    getSchoolId(): string {
      return this.schoolId;
    }
  },
  actions: {
    /**
     * 设置token
     * @param token
     */
    setToken(token: string) {
      this.token = token;
      storage.set(ACCESS_TOKEN, token);
    },
    /**
     * 删除token
     */
    deleteToken() {
      this.token = '';
      storage.remove(ACCESS_TOKEN);
    },
    /**
     * 设置选择的商品
     * @param goods 商品
     */
    setGoods(goods: any) {
      this.selectGoods.push(goods);
    },
    /**
     * 删除商品
     * @param goodsId 商品编号
     */
    deleteGoods(goodsId: string | number): void {
      const index = this.selectGoods.findIndex(
        (goods: any) => goods.productSkuId === goodsId
      );
      this.selectGoods.splice(index, 1);
    },
    /**
     * 设置选中的AI学练工具
     * @param vip 小酷商品
     */
    setVip(vip: any) {
      this.selectVip = vip;
    },
    /**
     * 删除选中AI学练工具
     * @param goodsId 商品编号
     */
    deleteVip(goodsId: string | number): void {
      const index = this.selectVip.findIndex(
        (goods: any) => goods.goodsId === goodsId
      );
      this.selectVip.splice(index, 1);
    },
    /**
     * 判断vip是否选中
     * @param goodsId 商品编号
     * @returns boolean
     */
    selectedVip(goodsId: string | number): Boolean {
      const index = this.selectVip.findIndex(
        (goods: any) => goods.goodsId === goodsId
      );
      return index >= 0 ? true : false;
    },
    /**
     * 初始化学校编号
     * @param token
     */
    setShoolId(schoolId: string) {
      this.schoolId = schoolId;
      storage.set('register_school_id', schoolId);
    },
    /**
     * 退出登录
     */
    studentLoutOut(): void {
      this.deleteToken();
      router.replace({
        path: '/student-register',
        query: {
          sId: this.schoolId
        }
      });
    }
  }
});

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