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 { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";

class GameStore {

  constructor() {
    makeAutoObservable(this);
  }


  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;
  }

  gameInfo: {
    score: number,
    remainTimes: number,
  } = {
    score: 0,
    remainTimes: 0,
  }

  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) {
      PageCtrl.changePage(HomePage);
      return;
    }

    store.indexData.remainTimes = data.remainGameTimes;

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

  }

}

export default (new GameStore());
