<template>
    <view class="page-container">
        <!-- 支付信息录入卡片 -->
        <view class="info-card">
            <view class="info-card-title">支付信息</view>
            <!-- 开户人和银行名称同一行 -->
            <u-row class="info-row" justify="space-between">
                <u-col span="5.8">
                    <view class="info-label">开户人</view>
                    <u-input v-model="paymentInfo.accountHolder" placeholder="请输入开户人姓名" class="info-input" />
                </u-col>
                <u-col span="5.8">
                    <view class="info-label">银行名称</view>
                    <u-input v-model="paymentInfo.bankName" placeholder="请输入银行名称" class="info-input" />
                </u-col>
            </u-row>
            <!-- 银行账号单独一行 -->
            <u-row class="info-row">
                <u-col span="12">
                    <view class="info-label">银行账号</view>
                    <u-input v-model="paymentInfo.bankAccount" placeholder="请输入银行账号" class="info-input" />
                </u-col>
            </u-row>
            <!-- 身份证号单独一行 -->
            <u-row class="info-row">
                <u-col span="12">
                    <view class="info-label">身份证号</view>
                    <u-input v-model="paymentInfo.idNumber" placeholder="请输入身份证号" class="info-input" />
                </u-col>
            </u-row>
        </view>

        <view class="card_wrap">
            <view class="detail-image-section">
                <view class="detail-image-header">
                    <div class="detail-image-title">高清实物图（拖拽排序）</div>
                </view>
                <view class="detail-image-content">
                    <view class="detail-image-list">
                        <!-- 替换drag事件为touch事件 -->
                        <view class="detail-image-item" v-for="(item, index) in localDetailImages"
                            :key="'detail-' + index" :style="{ opacity: draggingIndex === index ? 0.5 : 1 }"
                            @touchstart="onTouchStart($event, index)" @touchmove="onTouchMove($event, index)"
                            @touchend="onTouchEnd">
                            <pic-comp :src="item"></pic-comp>
                            <view class="image-type-tag">{{ getImageType(index) }}</view>
                            <view class="detail-delete-btn" @click="deleteImage(index)">×</view>
                        </view>
                        <view class="detail-upload-btn" @click="uploadDetailImage">
                            <u-icon name="plus" size="40rpx" color="#999"></u-icon>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 支付总额卡片 -->
        <view class="card_wrap payment-card">
            <view class="payment-section">
                <view class="payment-total-container">
                    <text class="payment-label">支付总额</text>
                    <text class="payment-amount">￥0.00</text>
                </view>

                <view class="payment-buttons-row">
                    <view class="payment-button" @click="handleUnpaidClick">
                        <u-icon name="star" size="40rpx" color="#ff9500"></u-icon>
                        <text class="button-text">未收</text>
                    </view>
                    <view class="payment-button" @click="handleFollowUpClick">
                        <u-icon name="chat" size="40rpx" color="#108cff"></u-icon>
                        <text class="button-text">待跟进</text>
                    </view>
                </view>

                <view class="pay-now-button" @click="handlePayNowClick">
                    <text class="button-text">立即支付</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import picComp from './picComp.vue'

export default {
    components: {
        picComp
    },
    props: {
        detailImages: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            // 支付信息
            paymentInfo: {
                accountHolder: '', // 开户人
                bankName: '', // 银行名称
                bankAccount: '', // 银行账号
                idNumber: '' // 身份证号
            },
            // Local copy of detailImages prop to avoid direct mutation
            localDetailImages: [...this.detailImages],
            // 拖拽相关状态
            draggingIndex: -1, // 当前正在拖拽的元素索引
            startX: 0, // 触摸起始X坐标
            startY: 0 // 触摸起始Y坐标
        };
    },
    watch: {
        detailImages: {
            handler(newVal) {
                this.localDetailImages = [...newVal];
            },
            deep: true
        }
    },
    methods: {
        // 上传高清细节图
        uploadDetailImage() {
            uni.chooseImage({
                count: 9 - this.localDetailImages.length, // 最多选择9张
                sizeType: ['compressed'], // 压缩图片
                sourceType: ['album', 'camera'], // 从相册选择或拍照
                success: (res) => {
                    const tempFilePaths = res.tempFilePaths;
                    // 将图片路径添加到数组中
                    this.localDetailImages = [...this.localDetailImages, ...tempFilePaths];
                },
                fail: (err) => {
                    console.error('选择图片失败:', err);
                    uni.showToast({
                        title: '选择图片失败',
                        icon: 'none'
                    });
                }
            });
        },

        // 删除图片
        deleteImage(index) {
            uni.showModal({
                title: '提示',
                content: '确定要删除这张图片吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.localDetailImages.splice(index, 1);
                    }
                }
            });
        },

        // 获取图片类型
        getImageType(index) {
            const types = ['正面', '反面', '侧面', '扣子', '编号'];
            return types[index] || `细节${index - 4}`;
        },

        // 触摸开始（替代dragstart）
        onTouchStart(event, index) {
            this.draggingIndex = index;
            // 记录触摸起始坐标
            this.startX = event.touches[0].clientX;
            this.startY = event.touches[0].clientY;
            console.log('开始拖拽:', index);
        },

        // 触摸移动（替代dragover/drop）
        onTouchMove(event, currentIndex) {
            if (this.draggingIndex === -1) return; // 没有正在拖拽的元素则返回

            const moveX = event.touches[0].clientX;
            const moveY = event.touches[0].clientY;
            const diffX = moveX - this.startX;
            const diffY = moveY - this.startY;

            // 简单的拖拽距离判断（避免轻微滑动就触发交换）
            if (Math.abs(diffX) > 20 || Math.abs(diffY) > 20) {
                // 获取当前触摸位置对应的元素索引
                const targetIndex = this.getTargetIndexByPosition(moveX, moveY);
                if (targetIndex !== -1 && targetIndex !== this.draggingIndex) {
                    // 交换数组元素（核心排序逻辑）
                    [this.localDetailImages[this.draggingIndex], this.localDetailImages[targetIndex]] =
                        [this.localDetailImages[targetIndex], this.localDetailImages[this.draggingIndex]];
                    // 更新拖拽索引为目标索引（实现连续拖拽）
                    this.draggingIndex = targetIndex;
                    // 重置起始坐标
                    this.startX = moveX;
                    this.startY = moveY;
                }
            }
        },

        // 触摸结束（替代dragend）
        onTouchEnd() {
            console.log('拖拽结束');
            this.draggingIndex = -1; // 重置拖拽状态
        },

        // 根据触摸坐标获取目标元素索引（核心辅助方法）
        getTargetIndexByPosition(x, y) {
            // 获取所有图片元素的位置信息
            const query = uni.createSelectorQuery().in(this);
            return new Promise((resolve) => {
                query.selectAll('.detail-image-item').boundingClientRect(rects => {
                    for (let i = 0; i < rects.length; i++) {
                        const rect = rects[i];
                        // 判断坐标是否在元素范围内
                        if (
                            x >= rect.left &&
                            x <= rect.right &&
                            y >= rect.top &&
                            y <= rect.bottom
                        ) {
                            resolve(i);
                            return;
                        }
                    }
                    resolve(-1);
                }).exec();
            });
        },

        // 下一步按钮点击事件
        handleNextClick() {
            this.$emit('handleNextClick', {
                nowPage: 'formThree',
                form: {
                    detailImages: this.localDetailImages,
                    paymentInfo: this.paymentInfo
                }
            });
        },

        // 未收按钮点击事件
        handleUnpaidClick() {
            console.log('点击了未收按钮');
        },

        // 待跟进按钮点击事件
        handleFollowUpClick() {
            console.log('点击了待跟进按钮');
        },

        // 立即支付按钮点击事件
        handlePayNowClick() {
            console.log('点击了立即支付按钮');
        }
    }
}
</script>

<style lang="scss" scoped>
// 导入公共样式
@import './common.scss';

// 主样式
.page-container {
    box-sizing: border-box;
    padding: 0;
    background-color: map-get($colors, bg);
    font-family: map-get($font, family);
    -webkit-font-smoothing: map-get($font, smoothing);
    font-smoothing: map-get($font, smoothing);
}

.card_wrap {
    @include card;
    margin-bottom: 20rpx;

    &:hover {
        @include shadow(2);
    }
}

.detail-image-section {
    padding: map-get($sizes, padding-sm) map-get($sizes, padding);
}

.detail-image-content {
    margin-top: 20rpx;

    .detail-image-list {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
    }

    .detail-image-item {
        position: relative;
        width: 200rpx;
        height: 200rpx;
        box-sizing: border-box;
        touch-action: none; // 禁止浏览器默认触摸行为
        transition: opacity 0.2s; // 拖拽时的透明度过渡

        &:active {
            opacity: 0.7;
        }
    }

    .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;
        @include font-styles($size: small, $weight: bold);
        z-index: 10;
    }

    .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;
        box-sizing: border-box;
        cursor: pointer;

        &:hover {
            border-color: #108cff;
            background-color: rgba(16, 140, 255, 0.05);
        }
    }

    .no-images {
        @include font-styles($size: content, $weight: regular, $color: tertiary);
        text-align: center;
        padding: 80rpx 0;
        background-color: #f9f9f9;
        border-radius: 12rpx;
        margin-top: 20rpx;
    }
}

.detail-image-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: map-get($sizes, margin-sm);
    padding-bottom: map-get($sizes, margin-sm);
    border-bottom: 1rpx solid map-get($colors, border);
}

.detail-image-title {
    @include font-styles($size: content, $weight: bold, $color: primary);
}

/* 支付信息卡片样式 */
.info-card {
    @include card;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    padding: map-get($sizes, padding-sm) map-get($sizes, padding);
    box-sizing: border-box;

    &:hover {
        @include shadow(2);
    }

    .u-col {
        padding: 0;
        box-sizing: border-box;
    }

    .u-col:first-child {
        padding-right: 15rpx;
    }

    .u-col:last-child {
        padding-left: 15rpx;
    }
}

.info-card-title {
    @include font-styles($size: title, $weight: bold, $color: primary);
    margin-bottom: 25rpx;
    padding-bottom: 15rpx;
    border-bottom: 1rpx solid map-get($colors, border);
}

.info-row {
    margin-bottom: 20rpx;
    box-sizing: border-box;
    padding: 0;
}

.info-label {
    @include font-styles($size: tiny, $weight: regular, $color: tertiary);
    margin-bottom: 8rpx;
    display: block;
}

.info-input {
    border-radius: 8rpx;
    border: 1rpx solid #e5e7eb;
    padding: 12rpx 16rpx;
    width: 100%;
    box-sizing: border-box;
    @include font-styles($size: small, $weight: regular, $color: secondary);
}

/* 支付总额卡片样式 */
.payment-card {
    @include card;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
}

.payment-section {
    padding: map-get($sizes, padding-sm) map-get($sizes, padding);
}

.payment-total-container {
    background-color: #f5f7fa;
    border: 2rpx solid #e5e7eb;
    border-radius: 12rpx;
    padding: 24rpx 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24rpx;
}

.payment-label {
    font-size: 36rpx;
    color: map-get($colors, text-primary);
    font-weight: 700;
    min-width: 140rpx;
}

.payment-amount {
    font-size: 48rpx;
    font-weight: 600;
    color: #f53f3f;
    font-family: Consolas, 'Courier New', monospace, -apple-system, BlinkMacSystemFont;
}

/* 支付按钮行样式 */
.payment-buttons-row {
    display: flex;
    gap: 20rpx;
    margin-bottom: 24rpx;
}

.payment-button {
    flex: 1;
    border-radius: 12rpx;
    padding: 24rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border: 2rpx solid #e5e7eb;
    cursor: pointer;
    transition: all 0.3s ease;
    gap: 12rpx;
}

.payment-button:hover {
    background-color: #e6f7ed;
    border-color: #00b42a;
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 180, 42, 0.15);
}

/* 立即支付按钮样式 */
.pay-now-button {
    width: 100%;
    border-radius: 12rpx;
    padding: 32rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #108cff;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s ease;
    gap: 12rpx;
    box-shadow: 0 4rpx 12rpx rgba(16, 140, 255, 0.2);
}

.pay-now-button:hover {
    background-color: #007aff;
    transform: translateY(-2rpx);
    box-shadow: 0 6rpx 16rpx rgba(16, 140, 255, 0.25);
}

.button-text {
    font-size: 28rpx;
    font-weight: 500;
    color: inherit;
}
</style>