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 FailPopup from '@/panels/FailPopup/index.jsx'
import VictoryPopup from '@/panels/VictoryPopup/index.jsx'

class GameStore {

  constructor() {
    makeAutoObservable(this);
  }

  gameInfo = {
    recordId: "",
    countdownSeconds: 180,
    targetConfig: {
      target1: 0, // 背包数量	
      target2: 0, // 飞机数量
    },
    isSubmit: false,
  }

  async start() {

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

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

    this.gameInfo.isSubmit = false;
    this.gameInfo.recordId = data.recordId;
    this.gameInfo.countdownSeconds = data.countdownSeconds;
    this.gameInfo.targetConfig = data.targetConfig

    return success;
  }


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

    const d = {
    };
    const param = AESEncrypt(JSON.stringify(d), "4fe20bdefdd4804f", "cDOiBC1n2QrkAY2P");

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

  async submit(score: number, suc: boolean, gameData?: any) {
    if (this.gameInfo.isSubmit) {
      return;
    }

    this.gameInfo.isSubmit = true;

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

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

    if (suc) {
      PageCtrl.changePage(HomePage);
      ModalCtrl.showModal(VictoryPopup, data);
    } else {
      ModalCtrl.showModal(FailPopup, { gameData: gameData, data: data });
    }
    return success;
  }
}

export default (new GameStore());
