import { makeAutoObservable, } from 'mobx';
import API from "@/api";
import store from "@/store/store.ts";
import { Toast } from "@grace/ui";
import { AESDecrypt, 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";
import FailPanel from "@/panels/FailPanel/FailPanel.tsx";
import SucPanel from "@/panels/SucPanel/SucPanel.tsx";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";

class GameStore {

  constructor() {
    makeAutoObservable(this);
  }


  startInfo: {
    recordId?: number | string
    countdownSeconds?: number
  } = {}

  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 = JSON.parse(AESDecrypt(data, "3C8C48E792E9241B", "cDOiBC1n2QrkAY2P"));

    return success;
  }

  gameInfo: {
    score: number,
    remainTimes: number,
    level: number,
    maxScore: number,
    cd: number,
  } = {
      score: 0,
      remainTimes: 0,
      level: 0,
      maxScore: 0,
      cd: GameConfig.gameCd,
    }

  reset() {
    this.gameInfo = {
      score: 0,
      remainTimes: 0,
      level: 0,
      maxScore: 0,
      cd: this.startInfo.countdownSeconds || GameConfig.gameCd,
    }
  }

  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() {
    const { recordId } = this.startInfo;
    const { score } = this.gameInfo;
    const param = AESEncrypt(JSON.stringify({
      recordId,
      score,
      timestamp: Date.now()
    }), "3C8C48E792E9241B", "cDOiBC1n2QrkAY2P");

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

    if (!success) {
      PageCtrl.changePage(HomePage);
      return;
    }

    if (data.reachTargetScore) {
      ModalCtrl.showModal(SucPanel, data);
    } else {
      ModalCtrl.showModal(FailPanel, data);
    }

  }

}

export default (new GameStore());
