import {makeAutoObservable,} from 'mobx';
import API from "@/api";
import store from "@/store/store.ts";
import {Toast} from "@grace/ui";
import {AESEncrypt} from "@/utils/Crypto.ts";
import {PAGE_MAP} from "@/utils/constants.ts";
import {ECard, getPosterId} from "@/common.ts";

class GameStore {

  startInfo: {
    userRecordId?: number | string
  } = {}

  async start() {

    if (store.indexData.remainTimes <= 0) {
      Toast.show("今日游戏次数已用尽，明天再来吧～");
      return false;
    }

    const {success, data} = await API.start();

    store.updateIndex();
    if (!success) {
      return false;
    }

    this.startInfo = data;

    return success;
  }

  async submit(win: boolean, soc: number) {

    const startId = this.startInfo.userRecordId;
    const score = win ? soc : 0;

    const params: {
      startId: string | number,
      score: number,
      param?: string,
    } = {
      startId,
      score,
    }

    params.param = AESEncrypt(JSON.stringify({
      timestamp: Date.now(),
      ...params,
    }), "CPI851051A6AEA6F", "cDOiBC1n2QrkAY2P");

    const {success, data} = await API.submit(params);

    if (!success) {
      store.changePage(PAGE_MAP.HOME_PAGE);
      return;
    }

    store.indexData.remainTimes = data.remainGameTimes;

    if (win && data) {
    } else {
    }

  }

  async poster(card: ECard) {

    const posterId = getPosterId(card);

    const {success} = await API.poster({posterId});

    return success;

  }

}

const gameStore: GameStore = makeAutoObservable(new GameStore());

export default gameStore;
