<script setup>
import { ref, computed, onMounted } from 'vue';
import GarbageCleanupZone from './components/garbageCleanup.vue';
import OilFilmSeparationZone from './components/oilFilmSeparationZone.vue';
import SelectReagents from './components/selectReagents.vue';
import CompleteComponent from './components/complete.vue';
import navBar from '@/components/navBar.vue';
import success from '@/components/success.vue';
import { useGameStore } from '@/stores/game';

const gameStore = useGameStore();

const ASSETS = Object.freeze({
  bg1: '/static/first/oneBackground.png',
  bg2: '/static/first/oilBackground.png',
  bg3: '/static/first/reagentsBackground.png',
  completeBg: '/static/first/completeBg.png',
  title: '/static/first/oneTitle.png',
  progress1: '/static/first/progressOne.png',
  progress2: '/static/first/progressTwo.png',
  progress3: '/static/first/progressThree.png',
  purificationValue: '/static/first/purificationValue.png',
  completionPopup: 'https://userone-oss-cdn.angelgroup.com.cn/static/2026-01-23/d204d71cf2a54b18a6404e6132618cd6%E5%AE%8C%E6%88%90%E5%BC%B9%E7%AA%97.webp',
  nextStep: '/static/first/nextStep.png',
});

// 当前游戏阶段
const currentStage = ref(gameStore.levels.first.lastStage || 'garbageCleanup');

// 各阶段完成状态
const isGarbageCleaned = ref(false);
const isOilSeparationComplete = ref(false);
const isAcidBaseNeutralizationComplete = ref(false);

onMounted(() => {
  // 如果第一关已经完成，直接显示完成状态
  if (gameStore.levels.first.completed) {
    showCompleteComponent.value = true;
    currentStage.value = 'acidBaseNeutralization';
    isGarbageCleaned.value = true;
    isOilSeparationComplete.value = true;
    isAcidBaseNeutralizationComplete.value = true;
  }
});

// 其他状态
const showPurificationValue = ref(false);
const showCompletionModal = ref(false);
const showCompleteComponent = ref(false);
const showSuccess = ref(false);
const purificationValueStyle = ref({
  top: '66%',
  left: '35%',
});
const purificationTimer = ref(null);

// 引用子组件
const oilFilmZoneRef = ref(null);
const acidBaseZoneRef = ref(null);

// 根据当前阶段计算使用的资源
const currentBg = computed(() => {
  switch (currentStage.value) {
    case 'garbageCleanup':
      return ASSETS.bg1;
    case 'oilFilmSeparation':
      return ASSETS.bg2;
    case 'acidBaseNeutralization':
      return ASSETS.bg3;
    default:
      return ASSETS.bg1;
  }
});

const currentTitle = computed(() => {
  return ASSETS.title;
});

// 进度条图片
const currentProgress = computed(() => {
  if (showCompleteComponent.value) {
    // 显示complete组件时，进度条用第三阶段
    return ASSETS.progress3;
  }

  switch (currentStage.value) {
    case 'garbageCleanup':
      return ASSETS.progress1;
    case 'oilFilmSeparation':
      return ASSETS.progress2;
    case 'acidBaseNeutralization':
      return ASSETS.progress3;
    default:
      return ASSETS.progress1;
  }
});

// 下一步按钮是否可用
const isNextStepEnabled = computed(() => {
  if (showCompletionModal.value) {
    // 显示弹窗时，下一步按钮不可用
    return false;
  }

  switch (currentStage.value) {
    case 'garbageCleanup':
      return isGarbageCleaned.value;
    case 'oilFilmSeparation':
      return isOilSeparationComplete.value;
    case 'acidBaseNeutralization':
      return isAcidBaseNeutralizationComplete.value;
    default:
      return false;
  }
});

// 垃圾清理完成回调
const onGarbageAllCleared = () => {
  isGarbageCleaned.value = true;
};

// 显示净化值效果
const showPurificationValueEffect = () => {
  // 如果已有定时器，先清除
  if (purificationTimer.value) {
    clearTimeout(purificationTimer.value);
    purificationTimer.value = null;
  }

  showPurificationValue.value = true;

  // 设置新的定时器，1秒后隐藏
  purificationTimer.value = setTimeout(() => {
    showPurificationValue.value = false;
    purificationTimer.value = null;
  }, 1000);
};

// 隐藏净化值效果
const hidePurificationValue = () => {
  // 隐藏时也清除定时器
  if (purificationTimer.value) {
    clearTimeout(purificationTimer.value);
    purificationTimer.value = null;
  }
  showPurificationValue.value = false;
};

// 向左移动时净化值位置
const onMoveLeft = () => {
  purificationValueStyle.value = {
    top: '66%',
    left: '35%',
  };
};
// 向右移动时净化值位置
const onMoveRight = () => {
  purificationValueStyle.value = {
    top: '66%',
    left: '75%',
  };
};

// 油膜分离完成回调
const onOilSeparationComplete = () => {
  isOilSeparationComplete.value = true;
};

// 酸碱中和完成回调
const onAcidBaseNeutralizationComplete = () => {
  isAcidBaseNeutralizationComplete.value = true;
};

// 关闭完成弹窗
const closeCompletionModal = () => {
  showCompletionModal.value = false;
  // 显示complete组件
  showCompleteComponent.value = true;
};

// 下一步按钮点击
const handleNextStep = () => {
  // 如果已显示complete组件，点击下一步显示success弹窗
  if (showCompleteComponent.value) {
    showSuccess.value = true;
    return;
  }

  // 根据当前阶段执行不同的逻辑
  switch (currentStage.value) {
    case 'garbageCleanup':
      if (!isGarbageCleaned.value) {
        uni.showToast({
          title: '请先清理所有垃圾',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      transitionToOilSeparation();
      break;

    case 'oilFilmSeparation':
      if (!isOilSeparationComplete.value) {
        uni.showToast({
          title: '请先完成油膜分离',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      transitionToAcidBaseNeutralization();
      break;

    case 'acidBaseNeutralization':
      if (!isAcidBaseNeutralizationComplete.value) {
        uni.showToast({
          title: '请先完成酸碱中和',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      // 酸碱中和完成后，点击下一步显示完成弹窗
      showCompletionModal.value = true;
      break;
  }
};

// 过渡到油膜分离阶段
const transitionToOilSeparation = () => {
  setTimeout(() => {
    currentStage.value = 'oilFilmSeparation';
    gameStore.setFirstLevelStatus(false, 'oilFilmSeparation');
    uni.hideLoading();
  }, 1000);
};

// 过渡到酸碱中和阶段
const transitionToAcidBaseNeutralization = () => {
  setTimeout(() => {
    currentStage.value = 'acidBaseNeutralization';
    gameStore.setFirstLevelStatus(false, 'acidBaseNeutralization');
    uni.hideLoading();
  }, 1000);
};

// 成功弹窗确认按钮点击
const handleSuccessConfirm = () => {
  showSuccess.value = false;
  gameStore.setFirstLevelStatus(true, 'acidBaseNeutralization');
  uni.reLaunch({
    url: '/pages/start/index'
  });
};
</script>

<template>
  <view class="container">
    <navBar />
    <!-- 根据当前显示模式显示不同背景 -->
    <image
      class="bg"
      v-if="!showCompleteComponent"
      :src="currentBg"
      :style="{ height: currentStage === 'acidBaseNeutralization' ? '78%' : '100%' }"
      mode="aspectFill"
    />
    <image
      class="bg"
      v-else
      :src="ASSETS.completeBg"
      mode="aspectFill"
    />

    <!-- 顶部标题容器 -->
    <view class="top">
      <image
      class="topTitle"
      :src="currentTitle"
      :style="{ top: showCompleteComponent ? '14%' : (currentStage === 'acidBaseNeutralization' ? '6%' : '8%') }"
      mode="aspectFill"
    ></image>
    </view>

    <!-- 根据当前阶段显示不同内容 -->
    <template v-if="currentStage === 'garbageCleanup' && !showCompleteComponent">
      <!-- 垃圾清理组件 -->
      <garbage-cleanup-zone
        @all-cleared="onGarbageAllCleared"
        @show-purification="showPurificationValueEffect"
        @hide-purification="hidePurificationValue"
        @move-left="onMoveLeft"
        @move-right="onMoveRight"
      />
    </template>

    <template v-else-if="currentStage === 'oilFilmSeparation' && !showCompleteComponent">
      <!-- 油膜分离组件 -->
      <oil-film-separation-zone
        ref="oilFilmZoneRef"
        @stage-complete="onOilSeparationComplete"
      />
    </template>

    <template v-else-if="currentStage === 'acidBaseNeutralization' && !showCompleteComponent">
      <!-- 酸碱中和组件 -->
      <select-reagents
        ref="acidBaseZoneRef"
        @stage-complete="onAcidBaseNeutralizationComplete"
      />
    </template>

    <!-- 完成后的组件（显示在completeBg上） -->
    <template v-if="showCompleteComponent">
      <complete-component />
    </template>

    <!-- 净化值显示区域 -->
    <view class="purificationValue" :class="{ show: showPurificationValue }" :style="purificationValueStyle">
      <image class="purificationValueImg" :src="ASSETS.purificationValue" mode="aspectFill"></image>
    </view>

    <!-- 完成弹窗 - 全屏覆盖 -->
    <view class="completion-modal" v-if="showCompletionModal" @click="closeCompletionModal">
      <image
        class="modal-image"
        :src="ASSETS.completionPopup"
        mode="scaleToFill"
      />
    </view>

    <success
      :show="showSuccess"
      :badge-index="1"
      @close="showSuccess = false"
      @confirm="handleSuccessConfirm"
    />

    <!-- 底部内容（始终显示） -->
    <view class="bottomContent">
      <view class="progress">
        <image :src="currentProgress" class="progressPic" mode="scaleToFill"/>
      </view>
      <view class="nextStep" @click="handleNextStep">
        <image
          :src="ASSETS.nextStep"
          class="nextStepPic"
          :class="{ disabled: !isNextStepEnabled }"
        />
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.container {
  min-height: 100vh;
  width: 100%;
  position: relative;
  overflow: hidden;

  .bg {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: -1;
    transition: opacity 0.8s ease;
  }

  .top {
    width: 100%;
    height: 380rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;

    .topTitle {
      position: absolute;
      width: 192rpx;
      height: 108rpx;
    }
  }

  .purificationValue {
    position: absolute;
    top: 66%;
    left: 35%;
    transform: translate(-50%, -50%) scale(0);
    opacity: 0;
    transition: opacity 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275), transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    z-index: 20;
    pointer-events: none;

    &.show {
      opacity: 1;
      transform: translate(-50%, -50%) scale(1);
    }

    .purificationValueImg {
      width: 368rpx;
      height: 382rpx;
    }
  }

  // 完成弹窗样式
  .completion-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;

    .modal-image {
      width: 100%;
      height: 100%;
    }
  }

  .bottomContent {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 158rpx;
    border-radius: 40rpx 40rpx 0 0;
    background: linear-gradient(180deg, #73D8FF 0%, #3498F4 100%);
    border-top: 4rpx solid #CCECFD;
    display: flex;
    align-items: center;
    justify-content: space-between;
    z-index: 15;

    .progress {
      padding: 0 32rpx;

      .progressPic {
        width: 428rpx;
        height: 56rpx;
        transition: all 0.5s ease;
      }
    }

    .nextStep {
      padding: 0 22rpx;

      .nextStepPic {
        width: 222rpx;
        height: 128rpx;
        transition: all 0.3s ease;

        &.disabled {
          opacity: 0.5;
          filter: grayscale(0.5);
        }

        &:not(.disabled):active {
          transform: scale(0.95);
        }
      }
    }
  }
}
</style>