<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue';
import { useDrag } from './hooks/useDrag';
import navBar from '@/components/navBar.vue';
import { useGameStore } from '@/stores/game';

const gameStore = useGameStore();

const ASSETS = Object.freeze({
  title: '/static/second/part2/title.webp',
  center: '/static/second/part2/center.webp',
  zzjd1: '/static/second/zzjd1.webp',
  zzjd2: '/static/second/zzjd2.webp',
  zzjd3: '/static/second/zzjd3.webp',
  zzjd4: '/static/second/zzjd4.webp',
  zzjd5: '/static/second/zzjd5.webp',
  zzjd6: '/static/second/zzjd6.webp',
  zzjd: '/static/second/zzjd.webp',
  panzi: '/static/second/panzi.webp',
  resetIcon: '/static/second/reset.webp',
  blockIcon: '/static/second/block.webp',
  arrow: '/static/second/jt.webp',
  lv: '/static/second/part2/lv.webp',
  ys: '/static/second/part2/ys.webp',
  yw: '/static/second/part2/yw.webp',
  lv1: '/static/second/part2/lv1.webp',      
  ys1: '/static/second/part2/ys1.webp',
  yw1: '/static/second/part2/yw1.webp',
  lv2: '/static/second/part2/lv2.webp',
  ys2: '/static/second/part2/ys2.webp',
  yw2: '/static/second/part2/yw2.webp',
  lv3: '/static/second/part2/lv3.webp',
  ys3: '/static/second/part2/ys3.webp',
  yw3: '/static/second/part2/yw3.webp',
  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',
});

const trayItems = ref([
  { id: 1, type: 'lv', icon: ASSETS.lv1, label: '点击拖动', status: 'default' },
  { id: 2, type: 'lv', icon: ASSETS.lv1, label: '点击拖动', status: 'default' },
  { id: 3, type: 'ys', icon: ASSETS.ys1, label: '点击拖动', status: 'default' },
  { id: 4, type: 'yw', icon: ASSETS.yw1, label: '点击拖动', status: 'default' },
  { id: 5, type: 'ys', icon: ASSETS.ys1, label: '点击拖动', status: 'default' },
  { id: 6, type: 'yw', icon: ASSETS.yw1, label: '点击拖动', status: 'default' },
]);

const placedCount = computed(() => {
  return trayItems.value.filter(item => item.status === 'placed').length;
});

const isComplete = computed(() => {
  return placedCount.value === 6;
});

const PROGRESS_MAP = [
  ASSETS.zzjd1, // 0
  ASSETS.zzjd2, // 1
  ASSETS.zzjd3, // 2
  ASSETS.zzjd4, // 3
  ASSETS.zzjd5, // 4
  ASSETS.zzjd6, // 5
  ASSETS.zzjd,  // 6
];

const currentProgressImg = computed(() => {
  return PROGRESS_MAP[placedCount.value] || ASSETS.zzjd1;
});

const currentProgressImgStyle = computed(() => {
  const currentImg = PROGRESS_MAP[placedCount.value] || ASSETS.zzjd1;
  
  if (currentImg === ASSETS.zzjd6) {
    return { width: '94rpx', height: '580rpx' };
  }
  
  if (currentImg === ASSETS.zzjd) {
    return { width: '70rpx', height: '554rpx' };
  }
  
  // 默认尺寸
  return { width: '94rpx', height: '548rpx' };
});

const showCompletion = ref(false);

const handleReset = () => {
  trayItems.value.forEach(item => {
    item.status = 'default';
  });
};

const handleComplete = () => {
  if (isComplete.value) {
    showCompletion.value = true;
  }
};

const closeCompletion = () => {
  showCompletion.value = false;
  gameStore.setSecondLevelPartStatus('part2', true);
  uni.navigateBack();
};

const centerRect = ref(null);
const instance = getCurrentInstance();

onMounted(() => {
  const query = uni.createSelectorQuery().in(instance);
  query.select('.center-wrapper').boundingClientRect(data => {
    if (data) {
      centerRect.value = data;
    }
  }).exec();
});

const {
  isDragging,
  draggedItem,
  dragPosition,
  handleTouchStart,
  handleTouchMove,
  handleTouchEnd,
  handleMouseDown,
  handleMouseMove,
  handleMouseUp,
  handleMouseLeave
} = useDrag({
  onDrop: (item, position) => {
    if (centerRect.value && item) {
      const { left, right, top, bottom } = centerRect.value;
      const { x, y } = position;
      
      if (x >= left && x <= right && y >= top && y <= bottom) {
        item.status = 'placed';
      }
    }
  }
});

const getTrayItemIcon = (item) => {
  if (item.status === 'placed') {
    if (item.type === 'ys') return ASSETS.ys2;
    if (item.type === 'yw') return ASSETS.yw2;
    return ASSETS.lv2;
  }
  if (draggedItem.value && draggedItem.value.id === item.id) {
    if (item.type === 'ys') return ASSETS.ys2;
    if (item.type === 'yw') return ASSETS.yw2;
    return ASSETS.lv2;
  }
  return item.icon;
};

const getGhostIcon = () => {
  if (!draggedItem.value) return '';
  if (draggedItem.value.type === 'ys') return ASSETS.ys3;
  if (draggedItem.value.type === 'yw') return ASSETS.yw3;
  return ASSETS.lv3;
};
</script>

<template>
  <view class="part2-container">
    <navBar />
    <!-- 拖拽时的镜像 -->
    <view 
      v-if="isDragging"
      class="drag-ghost"
      :style="{ left: dragPosition.x + 'px', top: dragPosition.y + 'px' }"
    >
      <image :src="getGhostIcon()" mode="widthFix" class="ghost-icon" />
    </view>

    <!-- 顶部标题 -->
    <view class="header-section">
      <image class="title-img" :src="ASSETS.title" mode="widthFix" />
    </view>
    
    <view class="status-bar">
      <view class="status-item">
        <text class="label">余氯：</text>
        <image class="icon" :src="ASSETS.lv" mode="widthFix" />
      </view>
      <view class="status-item">
        <text class="label">异色：</text>
        <image class="icon" :src="ASSETS.ys" mode="widthFix" />
      </view>
      <view class="status-item">
        <text class="label">异味：</text>
        <image class="icon" :src="ASSETS.yw" mode="widthFix" />
      </view>
    </view>

    <!-- 主体区域 -->
    <view class="main-area">
      <!-- 中间吸附区域 -->
      <view class="center-wrapper">
        <image class="center-img" :src="ASSETS.center" mode="scaleToFill" />
      </view>
    </view>

    <!-- 右侧进度条 -->
    <view class="progress-wrapper">
      <text class="progress-title">组装进度</text>
      <image class="progress-img" :src="currentProgressImg" :style="currentProgressImgStyle" mode="scaleToFill" />
    </view>

    <!-- 下方托盘区域 -->
    <view class="tray-area">
      <image class="tray-img" :src="ASSETS.panzi" mode="scaleToFill" />
      <view class="tray-items-grid">
        <view 
          v-for="item in trayItems" 
          :key="item.id" 
          class="tray-item"
          @touchstart="handleTouchStart($event, item)"
          @touchmove.stop.prevent="handleTouchMove"
          @touchend="handleTouchEnd(item)"
          @mousedown="handleMouseDown($event, item)"
          @mousemove="handleMouseMove"
          @mouseup="handleMouseUp"
          @mouseleave="handleMouseUp"
        >
          <image class="item-icon" :src="getTrayItemIcon(item)" mode="aspectFit" />
          <text class="item-label">{{ item.label }}</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="btn-group">
      <view class="action-btn reset-btn" @click="handleReset">
        <image class="btn-icon" :src="ASSETS.resetIcon" mode="widthFix" />
        <text>重置</text>
      </view>
       <view 
        :class="['action-btn', 'complete-btn', { 'complete-btn-active': placedCount === 6 }]" 
        @click="handleComplete"
      >
        <template v-if="placedCount < 6">
          <image class="btn-icon block-icon" :src="ASSETS.blockIcon" mode="widthFix" />
          <view class="btn-text-col">
            <text class="main-text">完成</text>
            <text class="sub-text">完成{{ placedCount }}/6吸附</text>
          </view>
        </template>
        <template v-else>
          <text class="complete-text">完成</text>
        </template>
      </view>
    </view>

    <image class="arrow-icon" :src="ASSETS.arrow" mode="scaleToFill" />

    <view class="completion-overlay" v-if="showCompletion" @click="closeCompletion">
      <image
        class="completion-img"
        :src="ASSETS.completionPopup"
        mode="scaleToFill"
        @click.stop="closeCompletion"
      />
    </view>
  </view>
</template>

<style scoped lang="scss">
.part2-container {
  width: 100vw;
  height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #77CFF8;
  box-sizing: border-box;
}

.header-section {
  margin-top: 200rpx;
  z-index: 10;
  flex-shrink: 0;
  
  .title-img {
    width: 400rpx;
    height: auto;
  }
}

.status-bar {
  position: absolute;
  top: 280rpx;
  left: 42%;
  transform: translateX(-50%);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10rpx;
  width: 494rpx;
  height: 114rpx;
  background: #ffffff8a;
  border-radius: 20rpx;
  padding: 0 20rpx;
  z-index: 10;
  box-sizing: border-box;
  
  .status-item {
    display: flex;
    align-items: center;
    
    .label {
      font-size: 28rpx;
      color: #000000;
      font-weight: bold;
      white-space: nowrap;
    }
    
    .icon {
      width: 80rpx;
      height: 80rpx;
      margin-left: -12rpx;
    }
  }
}

.main-area {
  width: 100%;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  margin-top: 180rpx;
  flex-shrink: 0;
}

.center-wrapper {
  position: relative;
  margin-left: -130rpx;
  
  .center-img {
    width: 512rpx;
    height: 512rpx;
  }
}

.progress-wrapper {
  position: absolute;
  top: 298rpx;
  right: 26rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 20;
  
  .progress-title {
    font-size: 32rpx;
    color: #000;
    margin-bottom: 24rpx;
    font-weight: 600;
  }
  
  .progress-img {
    width: 94rpx;
    height: 548rpx;
  }
}

.tray-area {
  width: 88%;
  display: flex;
  justify-content: center;
  margin-top: 16rpx;
  margin-bottom: 20rpx;
  position: relative;
  z-index: 10;
  flex-shrink: 0;
  
  .tray-img {
    width: 100%;
    height: 466rpx;
  }

  .tray-items-grid {
    position: absolute;
    top: 50rpx;
    left: 50%;
    transform: translateX(-50%);
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 30rpx 60rpx;
    width: 540rpx;
    
    .tray-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .item-icon {
        width: 136rpx;
        height: 120rpx;
        margin-bottom: 6rpx;
      }
      
      .item-label {
        font-size: 26rpx;
        color: #333;
        font-weight: bold;
      }
    }
  }
}

.btn-group {
  display: flex;
  justify-content: center;
  gap: 80rpx;
  margin-top: 20rpx;
  margin-bottom: 60rpx;
  z-index: 20;
  flex-shrink: 0;

  .action-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 42rpx;
    height: 84rpx;
    box-sizing: border-box;
  }

  .reset-btn {
    width: 230rpx;
    background: #BAC4CA;
    box-shadow: 0 6rpx 2rpx 0 #529bbda6, 0 4rpx 4rpx 0 #ffffff8c inset;
    border: 2rpx solid #000000;
    color: #5E5C5C;
    font-size: 34rpx;
    font-weight: bold;

    .btn-icon {
      width: 44rpx;
      height: 44rpx;
      margin-right: 10rpx;
    }
  }

  .complete-btn {
    width: 250rpx;
    background: #5EB6F0;
    border: 2rpx solid #000000;
    box-shadow: 0 6rpx 2rpx 0 #529bbda6, 0 4rpx 2rpx 0 #76DDEE inset;
    color: #134571;
    
    .block-icon {
      width: 44rpx;
      height: auto;
      margin-right: 16rpx;
    }

    .btn-text-col {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      
      .main-text {
        font-size: 32rpx;
        font-weight: bold;
        line-height: 1;
        margin-bottom: 4rpx;
        margin-left: 20rpx;
      }
      
      .sub-text {
        font-size: 20rpx;
        line-height: 1;
      }
    }

    .complete-text {
      font-size: 34rpx;
      font-weight: bold;
    }

    &.complete-btn-active {
      border-radius: 40rpx;
      background: #FAD43E;
      box-shadow: 0 4rpx 2rpx 0 #ffffff80 inset, 0 6rpx 2rpx 0 #3d330ba6;
    }
  }
}

.arrow-icon {
  position: absolute;
  top: 50%;
  left: 68%;
  width: 116rpx;
  height: 144rpx;
  z-index: 100;
}

.drag-ghost {
  position: fixed;
  z-index: 9999;
  transform: translate(-50%, -50%);
  pointer-events: none;
  
  .ghost-icon {
    width: 260rpx;
    height: auto;
  }
}

.completion-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;

  .completion-img {
    width: 100%;
    height: 100%;
  }
}
</style>
