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";
import { GameConfig } from "@/pages/GamePage/config/Config.ts";

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,
    level: number,
    maxScore: number,
  } = {
    score: 0,
    remainTimes: 0,
    level: 0,
    maxScore: 0,
  }

  addScore(s: number) {
    const score = this.gameInfo.score + s;
    this.gameInfo.score = score;
    this.gameInfo.maxScore = Math.max(score, this.gameInfo.maxScore);

    const { levelCfg } = GameConfig;

    for (let i = levelCfg.length - 1; i >= 0; i--) {
      if (score >= levelCfg[i].score) {
        this.gameInfo.level = i;
        break;
      }
    }
  }

  async submit(score: number) {

    const startId = this.startInfo.userRecordId;

    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 (data) {
    } else {
    }

  }

}

export default (new GameStore());
