import { defineStore } from 'pinia';

export const useGameStore = defineStore('game', {
  state: () => ({
    // 关卡完成状态
    levels: {
      first: {
        started: false,
        completed: false,
        lastStage: 'garbageCleanup', // 当前完成到的阶段
      },
      second: {
        started: false,
        completed: false,
        parts: {
          part1: false,
          part2: false,
          part3: false,
          part4: false
        }
      },
      third: {
        started: false,
        completed: false
      },
      fourth: {
        started: false,
        completed: false
      }
    }
  }),
  actions: {
    // 设置关卡开始状态
    setLevelStarted(level) {
      if (this.levels[level]) {
        this.levels[level].started = true;
      }
    },
    // 设置第一关状态
    setFirstLevelStatus(status, stage) {
      this.levels.first.completed = status;
      if (stage) {
        this.levels.first.lastStage = stage;
      }
    },
    // 设置第二关各部分状态
    setSecondLevelPartStatus(part, status) {
      if (this.levels.second.parts.hasOwnProperty(part)) {
        this.levels.second.parts[part] = status;
        
        // 检查是否所有部分都完成了
        const allPartsCompleted = Object.values(this.levels.second.parts).every(p => p === true);
        if (allPartsCompleted) {
          this.levels.second.completed = true;
        }
      }
    },
    // 设置第三关状态
    setThirdLevelStatus(status) {
      this.levels.third.completed = status;
    },
    // 设置第四关状态
    setFourthLevelStatus(status) {
      this.levels.fourth.completed = status;
    },
    // 重置所有进度
    resetAllProgress() {
      this.levels = {
        first: {
          started: false,
          completed: false,
          lastStage: 'garbageCleanup',
        },
        second: {
          started: false,
          completed: false,
          parts: {
            part1: false,
            part2: false,
            part3: false,
            part4: false
          }
        },
        third: {
          started: false,
          completed: false
        },
        fourth: {
          started: false,
          completed: false
        }
      };
    }
  },
  persist: {
    key: 'game_progress',
    storage: {
      getItem: (key) => uni.getStorageSync(key),
      setItem: (key, value) => uni.setStorageSync(key, value),
    },
  },
});