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

const ASSETS = Object.freeze({
    box: '/static/second/part4/index/box.webp',
    white: '/static/second/part4/index/white.webp',
    grey: '/static/second/part4/index/grey.webp',
    black: '/static/second/part4/index/black.webp',
    blue: '/static/second/part4/index/blue.webp',
    sequence: '/static/second/part4/index/sequence.webp',
    arrange: '/static/second/part4/index/arrange.webp',
    white1: '/static/second/part4/index/white1.webp',
    blue1: '/static/second/part4/index/blue1.webp',
    black1: '/static/second/part4/index/black1.webp',
    white2: '/static/second/part4/index/white2.webp',
    blue2: '/static/second/part4/index/blue2.webp',
    black2: '/static/second/part4/index/black2.webp',
    grey2: '/static/second/part4/index/grey2.webp',
    empty: '/static/second/part4/index/empty.webp',
    progress1: '/static/second/part4/index/progress1.webp',
    progress2: '/static/second/part4/index/progress2.webp',
    progress3: '/static/second/part4/index/progress3.webp',
    progress4: '/static/second/part4/index/progress4.webp',
    right: '/static/second/part4/index/right.webp',
    resetIcon: '/static/second/reset.webp',
    blockIcon: '/static/second/block.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 BATTERY_TYPES = ['white', 'grey', 'blue', 'black'];
const ARRANGE_KEYS = ['arrange1', 'arrange2', 'arrange3', 'arrange4'];

// 电池类型与arrange区域的双向映射
const BATTERY_ARRANGE_MAP = Object.freeze({ white: 'arrange1', grey: 'arrange2', blue: 'arrange3', black: 'arrange4' });
const ARRANGE_BATTERY_MAP = Object.freeze(Object.fromEntries(Object.entries(BATTERY_ARRANGE_MAP).map(([k, v]) => [v, k])));

// 热区配置
const HOTAREA_CONFIG = Object.freeze([
    { class: 'btn-white1', batteryIndex: 0 },
    { class: 'btn-white2', batteryIndex: 0 },
    { class: 'btn-white3', batteryIndex: 0 },
    { class: 'btn-grey', batteryIndex: 1 },
    { class: 'btn-black', batteryIndex: 2 },
    { class: 'btn-blue1', batteryIndex: 3 },
    { class: 'btn-blue2', batteryIndex: 3 },
    { class: 'btn-blue3', batteryIndex: 3, requireBlackPlaced: true },
]);

// 进度列表配置
const PROGRESS_LIST = Object.freeze([
    { key: 'arrange1', label: 'PP棉（1/4）' },
    { key: 'arrange2', label: '活性炭（2/4）' },
    { key: 'arrange3', label: 'RO膜（3/4）' },
    { key: 'arrange4', label: '后置炭棒（4/4）' },
]);

// 电池在各个arrange位置的样式配置
const BATTERY_STYLE_MAP = Object.freeze({
    white: {
        arrange1: { left: '-16rpx', top: '-96rpx', width: '330rpx', height: '330rpx' },
        arrange2: { left: '-20rpx', top: '-100rpx', width: '342rpx', height: '342rpx' },
        arrange3: { left: '-20rpx', top: '-100rpx', width: '342rpx', height: '342rpx' },
        arrange4: { left: '-20rpx', top: '-100rpx', width: '342rpx', height: '342rpx' },
    },
    grey: {
        arrange1: { left: '8rpx', top: '20rpx', width: '270rpx', height: '100rpx' },
        arrange2: { left: '20rpx', top: '20rpx', width: '260rpx', height: '98rpx' },
        arrange3: { left: '8rpx', top: '20rpx', width: '270rpx', height: '100rpx' },
        arrange4: { left: '8rpx', top: '16rpx', width: '270rpx', height: '100rpx' },
    },
    blue: {
        arrange1: { left: '0', top: '-44rpx', width: '298rpx', height: '224rpx' },
        arrange2: { left: '0', top: '-44rpx', width: '298rpx', height: '224rpx' },
        arrange3: { left: '0', top: '-44rpx', width: '298rpx', height: '224rpx' },
        arrange4: { left: '0', top: '-44rpx', width: '298rpx', height: '224rpx' },
    },
    black: {
        arrange1: { left: '-12rpx', top: '-92rpx', width: '324rpx', height: '324rpx' },
        arrange2: { left: '-12rpx', top: '-92rpx', width: '324rpx', height: '324rpx' },
        arrange3: { left: '-12rpx', top: '-92rpx', width: '324rpx', height: '324rpx' },
        arrange4: { left: '-12rpx', top: '-92rpx', width: '324rpx', height: '324rpx' },
    },
});

const PROGRESS_IMAGES = [ASSETS.empty, ASSETS.progress1, ASSETS.progress2, ASSETS.progress3, ASSETS.progress4];
const createState = (keys, defaultVal) => Object.fromEntries(keys.map(k => [k, defaultVal]));

const batteryItems = ref([
    { id: 1, type: 'white', icon: ASSETS.white, dragIcon: ASSETS.white1, status: 'default' },
    { id: 2, type: 'grey', icon: ASSETS.grey, dragIcon: ASSETS.grey, status: 'default' },
    { id: 3, type: 'black', icon: ASSETS.black, dragIcon: ASSETS.black1, status: 'default' },
    { id: 4, type: 'blue', icon: ASSETS.blue, dragIcon: ASSETS.blue1, status: 'default' },
]);

const arrangeStatus = ref(createState(ARRANGE_KEYS, false));
const arrangeError = ref(createState(ARRANGE_KEYS, false));
const arrangePlaced = ref(createState(ARRANGE_KEYS, null));
const batteryCorrectlyPlaced = ref(createState(BATTERY_TYPES, false));
const arrangeRects = ref({});
const showCompletion = ref(false);

const completedCount = computed(() => Object.values(batteryCorrectlyPlaced.value).filter(Boolean).length);
const tasteBarImage = computed(() => PROGRESS_IMAGES[completedCount.value]);
const isComplete = computed(() => completedCount.value === 4);

const handleReset = () => {
    batteryItems.value.forEach(item => item.status = 'default');
    ARRANGE_KEYS.forEach(key => {
        arrangeStatus.value[key] = false;
        arrangeError.value[key] = false;
        arrangePlaced.value[key] = null;
    });
    BATTERY_TYPES.forEach(type => batteryCorrectlyPlaced.value[type] = false);
};

const handleComplete = () => isComplete.value && (showCompletion.value = true);
const closeCompletion = () => showCompletion.value = false;

// 获取电池图标
const getBatteryIcon = (item) => draggedItem.value?.id === item.id ? item.dragIcon : item.icon;
const getGhostIcon = () => draggedItem.value?.dragIcon || '';
const getDraggedType = () => draggedItem.value?.type || '';

// 获取放置图片样式
const getPlacedImgStyle = (arrangeKey) => {
    const batteryType = arrangePlaced.value[arrangeKey];
    const style = BATTERY_STYLE_MAP[batteryType]?.[arrangeKey];
    return style ? { position: 'absolute', ...style } : {};
};

// 判断进度项是否高亮
const isProgressItemActive = (arrangeKey) => {
    const batteryType = ARRANGE_BATTERY_MAP[arrangeKey];
    if (isDragging.value && draggedItem.value?.type === batteryType) return true;
    const battery = batteryItems.value.find(item => item.type === batteryType);
    return battery?.status === 'placed' && !batteryCorrectlyPlaced.value[batteryType];
};

// 判断电池状态
const isDraggingItem = (item) => isDragging.value && draggedItem.value?.id === item.id;
const shouldShowBattery = (item) => !isDraggingItem(item) && item.status !== 'placed';
const isHotareaEnabled = (hotarea) => !hotarea.requireBlackPlaced || batteryItems.value[2].status === 'placed';

// 检测坐标是否在矩形区域内
const isInRect = ({ x, y }, rect) => rect && x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;

// 检测并处理放置结果
const checkAndPlace = (item, position) => {
    const correctArrange = BATTERY_ARRANGE_MAP[item.type];
    for (const arrangeName of ARRANGE_KEYS) {
        if (isInRect(position, arrangeRects.value[arrangeName]) && !arrangeStatus.value[arrangeName]) {
            arrangeStatus.value[arrangeName] = true;
            arrangePlaced.value[arrangeName] = item.type;
            item.status = 'placed';
            arrangeName === correctArrange 
                ? (batteryCorrectlyPlaced.value[item.type] = true) 
                : (arrangeError.value[arrangeName] = true);
            break;
        }
    }
};

const {
    isDragging, draggedItem, dragPosition,
    handleTouchStart, handleTouchMove, handleTouchEnd,
    handleMouseDown, handleMouseMove, handleMouseUp,
} = useDrag({ onDrop: (item, position) => item && checkAndPlace(item, position) });

const instance = getCurrentInstance();
onMounted(() => {
    const query = uni.createSelectorQuery().in(instance);
    ARRANGE_KEYS.forEach(name => {
        query.select(`.${name}`).boundingClientRect(data => data && (arrangeRects.value[name] = data));
    });
    query.exec();
});
</script>

<template>
    <view class="part4-container">
        <navBar />
        <!-- 拖拽镜像 -->
        <view v-if="isDragging" class="drag-ghost" :style="{ left: `${dragPosition.x}px`, top: `${dragPosition.y}px` }">
            <image :src="getGhostIcon()" mode="scaleToFill" :class="['ghost-icon', `ghost-${getDraggedType()}`]" />
        </view>

        <!-- 标题 -->
        <view class="title">滤芯排序游戏</view>
        
        <!-- 排序区域 -->
        <image :src="ASSETS.arrange" mode="scaleToFill" class="arrange" />
        <view 
            v-for="key in ARRANGE_KEYS" :key="key"
            :class="[key, { 'arrange-active': arrangeStatus[key] && !arrangeError[key], 'arrange-error': arrangeError[key] }]"
        >
            <image v-show="arrangeStatus[key]" :src="ASSETS[`${arrangePlaced[key]}2`]" mode="scaleToFill" :style="getPlacedImgStyle(key)" />
        </view>
        
        <!-- 提示图 -->
        <image :src="ASSETS.sequence" mode="scaleToFill" class="sequence" />
        
        <!-- 排序进度 -->
        <view class="progress">
            <view class="progress-title">排序进度</view>
            <view class="progress-list">
                <view v-for="item in PROGRESS_LIST" :key="item.key" :class="['progress-item', { 'progress-item-active': isProgressItemActive(item.key) }]">
                    <image v-if="batteryCorrectlyPlaced[ARRANGE_BATTERY_MAP[item.key]]" :src="ASSETS.right" mode="scaleToFill" class="progress-icon-done" />
                    <view v-else class="progress-icon"><view class="progress-icon-inner" /></view>
                    <text class="progress-text">{{ item.label }}</text>
                </view>
            </view>
            <view class="progress-divider" />
            <view class="taste-section">
                <text class="taste-label">口感指数</text>
                <text class="taste-value">{{ completedCount * 25 }}%</text>
            </view>
            <image :src="tasteBarImage" mode="scaleToFill" class="taste-bar" />
        </view>

        <!-- 电池盒 -->
        <image :src="ASSETS.box" mode="scaleToFill" class="box" />
        
        <!-- 电池区域 -->
        <view class="battery">
            <image 
                v-for="item in batteryItems" :key="item.id"
                v-show="shouldShowBattery(item)" 
                :src="getBatteryIcon(item)" 
                mode="scaleToFill" :class="item.type" 
            />
            <view 
                v-for="hotarea in HOTAREA_CONFIG" :key="hotarea.class"
                v-show="isHotareaEnabled(hotarea)"
                :class="['btn', hotarea.class]"
                @touchstart="handleTouchStart($event, batteryItems[hotarea.batteryIndex])"
                @touchmove.stop.prevent="handleTouchMove"
                @touchend="handleTouchEnd"
                @mousedown="handleMouseDown($event, batteryItems[hotarea.batteryIndex])"
                @mousemove="handleMouseMove"
                @mouseup="handleMouseUp"
            />
        </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': isComplete }]" @click="handleComplete">
                <image v-if="!isComplete" class="btn-icon block-icon" :src="ASSETS.blockIcon" mode="widthFix" />
                <text class="complete-text">完成</text>
            </view>
        </view>

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

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

.title {
    margin-top: 188rpx;
    margin-bottom: 30rpx;
    color: #2D4B5D;
    font-size: 48rpx;
    font-weight: 600;
    text-shadow: 1rpx 1rpx 0 #FFF, -1rpx -1rpx 0 #FFF, 1rpx -1rpx 0 #FFF, -1rpx 1rpx 0 #FFF;
    z-index: 1;
}

.arrange {
    position: absolute;
    left: 40rpx;
    top: 280rpx;
    width: 382rpx;
    height: 768rpx;
}

.arrange-active {
    background-color: #00CC99;
}

.arrange-error {
    background-color: #FF6938;
}

.arrange1,
.arrange2,
.arrange3,
.arrange4 {
    position: absolute;
    left: 100rpx;
    width: 290rpx;
    height: 131rpx;
    border: 12rpx;
}

.arrange1 { top: 320rpx; }
.arrange2 { top: 499rpx; }
.arrange3 { top: 677rpx; }
.arrange4 { top: 855rpx; }

.sequence {
    position: absolute;
    right: 14rpx;
    top: 308rpx;
    width: 304rpx;
    height: 218rpx;
}

.progress {
    position: absolute;
    right: 26rpx;
    top: 540rpx;
    width: 280rpx;
    background: #FFFFFF;
    border-radius: 24rpx;
    padding: 20rpx;
    box-sizing: border-box;
    border: 4rpx solid #000;
    box-shadow: 0 6rpx 0 0 #00000040, 0 -12rpx 0 0 #77D1F6 inset;
}

.progress-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #000000;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 16rpx;
    background: #AFE5FB;
    border-radius: 12rpx 12rpx 0 0;
    height: 62rpx;
}

.progress-list {
    display: flex;
    flex-direction: column;
    gap: 12rpx;
}

.progress-divider {
    margin-top: 20rpx;
    margin-bottom: 10rpx;
    border-top: 5rpx dashed #C2D7E0;
}

.progress-item {
    display: flex;
    align-items: center;
    gap: 12rpx;
}

.progress-item-active {
    background: #FFAA00;
    border-radius: 40rpx;
    padding: 0 16rpx 0 8rpx;
    margin-left: -8rpx;
}

.progress-icon {
    width: 24rpx;
    height: 24rpx;
    border-radius: 50%;
    border: 2rpx solid #8B9294;
    background: #F5F5F8;
    flex-shrink: 0;
    display: flex;
    justify-content: center;
    align-items: center;
}

.progress-icon-inner {
    width: 16rpx;
    height: 16rpx;
    border-radius: 16rpx;
    background: #D9D9D9;
}

.progress-icon-done {
    width: 24rpx;
    height: 24rpx;
    flex-shrink: 0;
}

.progress-text {
    font-size: 28rpx;
    color: #000000;
    white-space: nowrap;
}

.taste-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16rpx;
    margin-bottom: 8rpx;
}

.taste-label {
    font-size: 24rpx;
    color: #000000;
    font-weight: 600;
}

.taste-value {
    font-size: 24rpx;
    color: #000000;
    font-weight: 600;
    text-shadow: 1rpx 1rpx 0 #FFF, -1rpx -1rpx 0 #FFF, 1rpx -1rpx 0 #FFF, -1rpx 1rpx 0 #FFF;
    z-index: 1;
}

.taste-bar {
    width: 100%;
    height: 40rpx;
}

.box {
    position: absolute;
    bottom: 74rpx;
    width: 354rpx;
    height: 598rpx;
    transform: rotate(90deg);
}

.white,
.grey,
.black,
.blue {
    position: absolute;
}

.white {
    bottom: 274rpx;
    left: 142rpx;
    width: 330rpx;
    height: 330rpx;
    z-index: 4;
}

.grey {
    bottom: 216rpx;
    left: 128rpx;
    width: 258rpx;
    height: 248rpx;
    z-index: 5;
}

.black {
    bottom: 226rpx;
    left: 326rpx;
    width: 310rpx;
    height: 314rpx;
    z-index: 6;
}

.blue {
    bottom: 194rpx;
    right: 100rpx;
    width: 276rpx;
    height: 308rpx;
    z-index: 5;
}

.btn {
    position: absolute;
    z-index: 20;
}

.btn-white1 {
    bottom: 397rpx;
    left: 245rpx;
    width: 104rpx;
    height: 84rpx;
}

.btn-white2 {
    bottom: 439rpx;
    left: 188rpx;
    width: 60rpx;
    height: 45rpx;
}

.btn-white3 {
    bottom: 447rpx;
    left: 342rpx;
    width: 86rpx;
    height: 36rpx;
}

.btn-grey {
    bottom: 274rpx;
    left: 124rpx;
    width: 268rpx;
    height: 98rpx;
    transform: rotate(40deg);
}

.btn-black {
    bottom: 346rpx;
    left: 352rpx;
    width: 246rpx;
    height: 68rpx;
    transform: rotate(18deg);
}

.btn-blue1 {
    bottom: 244rpx;
    right: 250rpx;
    width: 87rpx;
    height: 96rpx;
    transform: rotate(-38deg);
}

.btn-blue2 {
    bottom: 387rpx;
    right: 138rpx;
    width: 46rpx;
    height: 80rpx;
    transform: rotate(-38deg);
}

.btn-blue3 {
    bottom: 312rpx;
    right: 167rpx;
    width: 108rpx;
    height: 98rpx;
    transform: rotate(22deg);
}

.drag-ghost {
    position: fixed;
    z-index: 9999;
    transform: translate(-50%, -50%);
    pointer-events: none;

    .ghost-icon {
        display: block;
    }

    .ghost-white {
        width: 448rpx;
        height: 456rpx;
    }

    .ghost-grey {
        width: 258rpx;
        height: 248rpx;
    }

    .ghost-black {
        width: 456rpx;
        height: 442rpx;
    }

    .ghost-blue {
        width: 418rpx;
        height: 456rpx;
    }
}

.btn-group {
    position: absolute;
    bottom: 60rpx;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: center;
    gap: 80rpx;
    z-index: 20;

    .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: 230rpx;
        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;
        }

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

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

.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>
