<template>
    <view class="detail-image-content">
        <view class="detail-image-list">
            <view v-for="(item, index) in displayImages" :key="`detail-${index}`" class="detail-image-item"
                :class="{
                    'dragging': draggingIndex === index,
                    'can-drop': canDropIndex === index && draggingIndex !== index
                }" :style="draggingIndex === index ? draggingStyle : ''" @touchstart.stop="onTouchStart($event, index)"
                @touchmove.stop="onTouchMove($event, index)" @touchend.stop="onTouchEnd">
                <PicComp :src="item" @needPreviewPic="previewImageDetail" />
                <!-- <view class="image-type-tag">{{ getImageType(index) }}</view> -->
                <view class="detail-delete-btn" @click.stop="handleHideImage(item, index)" v-if="isDelete">
                    ×
                </view>
            </view>
            <view class="detail-upload-btn" @click="handleUploadImage">
                <u-icon name="plus" size="40rpx" color="#999" />
            </view>
        </view>
    </view>
</template>

<script>
import PicComp from './PicComp.vue'
import imageUpload from './imageUpload.js'
export default {
    name: 'ComponentName',
    components: {
        PicComp
    },
    data() {
        return {
            draggingIndex: -1,
            canDropIndex: -1,
            startX: 0,
            startY: 0,
            currentX: 0,
            currentY: 0,
            currentImgs: []
        }
    },
    watch: {
        images: {
            immediate: true,
            handler(newVal) {
                this.currentImgs = [...newVal]
            }
        }
    },
    computed: {
        displayImages() {
            return this.currentImgs
        },
        // 拖拽时的样式
        draggingStyle() {
            if (this.draggingIndex === -1) return ''
            return {
                transform: `translate(${this.currentX - this.startX}px, ${this.currentY - this.startY}px)`,
                zIndex: 1000
            }
        },
    },
    props: {
        images: {
            type: Array,
            default: () => []
        },
        isDelete: {
            type: Boolean,
            default: false
        },
        isPreview: {
            type: Boolean,
            default: false
        }
    },
    emits: ['imagesChanged', 'uploadComplete'],
    methods: {
        // 触摸开始
        onTouchStart(event, index) {
            if (this.draggingIndex !== -1) return
            this.draggingIndex = index
            const touch = event.touches[0]
            this.startX = touch.clientX
            this.startY = touch.clientY
            this.currentX = touch.clientX
            this.currentY = touch.clientY
        },

        // 触摸移动
        onTouchMove(event, index) {
            if (this.draggingIndex === -1 || this.draggingIndex !== index) return
            const touch = event.touches[0]
            this.currentX = touch.clientX
            this.currentY = touch.clientY
            this.findTargetIndex(touch.clientX, touch.clientY)
        },

        // 触摸结束
        async onTouchEnd() {
            if (this.draggingIndex === -1) return

            if (this.canDropIndex !== -1 && this.canDropIndex !== this.draggingIndex) {
                // 交换位置
                const images = [...this.currentImgs]
                const temp = images[this.draggingIndex]
                images[this.draggingIndex] = images[this.canDropIndex]
                images[this.canDropIndex] = temp
                this.currentImgs = images
            }

            this.resetDragState()

            //每次拖拽结束后把新的顺序传给父组件
            this.$emit('imagesChanged', [...this.currentImgs])
        },
        // 查找目标索引
        findTargetIndex(x, y) {
            const query = uni.createSelectorQuery().in(this)
            query.selectAll('.detail-image-item').boundingClientRect((rects) => {
                if (!rects || rects.length === 0) return
                let targetIndex = -1
                for (let i = 0; i < rects.length; i++) {
                    if (i === this.draggingIndex) continue
                    const rect = rects[i]
                    if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
                        targetIndex = i
                        break
                    }
                }
                this.canDropIndex = targetIndex
            }).exec()
        },

        // 重置拖拽状态
        resetDragState() {
            this.draggingIndex = -1
            this.canDropIndex = -1
            this.startX = 0
            this.startY = 0
            this.currentX = 0
            this.currentY = 0
        },
        // 预览图片
        previewImageDetail(src) {
            if(!this.isPreview){
                return false
            }
            const urlList = this.currentImgs.map(item => item)
            uni.previewImage({
                urls: urlList,
                current: src
            })
        },
        // 隐藏图片
        handleHideImage(item, index) {
            const itemIndex = this.currentImgs.findIndex(img => item === img)
            if (itemIndex !== -1) {
                this.currentImgs.splice(itemIndex, 1)
                // 将更新后的图片数组传给父组件
                this.$emit('imagesChanged', [...this.currentImgs])
                uni.$u.toast('图片已隐藏')
            }
        },
        // 上传图片
        async handleUploadImage() {
            try {
                const filePaths = await imageUpload.chooseImage(9)
                const uploadResults = await imageUpload.uploadFiles(filePaths)
                uploadResults.forEach(item => {
                    this.currentImgs.push(item.fileUrl)
                })
                this.$emit('uploadComplete', this.currentImgs)
            } catch (error) {
                console.error('上传失败:', error)
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.detail-image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    position: relative;

    .detail-image-item {
        position: relative;
        width: 200rpx;
        height: 200rpx;
        touch-action: none;
        transition: transform 0.2s ease, opacity 0.2s ease;
        z-index: 1;
        box-sizing: border-box;

        &.dragging {
            opacity: 0.6;
            transform: scale(1.05);
            z-index: 999;
            box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
        }

        &.can-drop {
            outline: 2rpx dashed #108cff;
            outline-offset: -2rpx;
            background-color: rgba(16, 140, 255, 0.1);
            border-radius: 8rpx;
        }

        // .image-type-tag {
        //     position: absolute;
        //     top: 10rpx;
        //     left: 10rpx;
        //     background-color: rgba(0, 0, 0, 0.6);
        //     color: white;
        //     padding: 5rpx 10rpx;
        //     border-radius: 12rpx;
        //     font-size: 22rpx;
        //     z-index: 1;
        // }

        .detail-delete-btn {
            position: absolute;
            top: -10rpx;
            right: -10rpx;
            width: 40rpx;
            height: 40rpx;
            background-color: #ff4d4f;
            color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            z-index: 10;
            cursor: pointer;
        }


    }

    .detail-upload-btn {
        width: 200rpx;
        height: 200rpx;
        border: 8rpx dashed #ddd;
        border-radius: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f9f9f9;
        cursor: pointer;
    }
}
</style>