import { makeAutoObservable, toJS, } from 'mobx';
import API from "@/api";
import { AESDecrypt, AESEncrypt } from "@/utils/Crypto.ts";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import Settlechance from "@/components/settlechance/settlechance";
import Settlenochance from "@/components/settlenochance/settlenochance";

class GameStore {

  constructor() {
    makeAutoObservable(this);
  }

  gameInfo = {
    recordId: "",
    levelIndex: -1,
    levelIdxArr: [],
    countdownSeconds: 180,
    remainTipTimes: 0,
    cd: 180,
    isSubmit: false,
  }

  async start() {

    const { success, data: d } = await API.start();
    if (!success) return false;

    const data = JSON.parse(AESDecrypt(d, "7A2F4B8D1E6C3905", "cDOiBC1n2QrkAY2P")) as any;

    this.gameInfo.levelIdxArr.sort(() => Math.random() - 0.5);
    this.gameInfo.levelIndex = -1;
    this.gameInfo.isSubmit = false;
    this.gameInfo.recordId = data.recordId;
    this.gameInfo.countdownSeconds = data.countdownSeconds;
    this.gameInfo.remainTipTimes = data.remainTipTimes

    return success;
  }

  async suggest() {
    const { success, data } = await API.suggest();
    return success;
  }

  async middleSubmit(score: number) {
    if (this.gameInfo.isSubmit) {
      return;
    }

    const d = {
      recordId: this.gameInfo.recordId,
      score,
      timestamp: Date.now(),
    };
    console.log(1, d);
    const param = AESEncrypt(JSON.stringify(d), "7A2F4B8D1E6C3905", "cDOiBC1n2QrkAY2P");

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

  async submit(score: number) {
    if (this.gameInfo.isSubmit) {
      return;
    }

    this.gameInfo.isSubmit = true;

    const d = {
      recordId: this.gameInfo.recordId,
      score,
      timestamp: Date.now(),
    };
    console.log(2, d);
    const param = AESEncrypt(JSON.stringify(d), "7A2F4B8D1E6C3905", "cDOiBC1n2QrkAY2P");

    const { success, data } = await API.submit({ param });
    if (!success) {
      PageCtrl.changePage(HomePage);
      return success;
    }

    if (data.drawChance) {
      ModalCtrl.showModal(Settlechance, { data });
    }else {
      ModalCtrl.showModal(Settlenochance, { data });
    }

    return success;
  }
}

export default (new GameStore());
