<template>
    <CommonLayout>
        <template #default>
            <!-- <div style="padding-top: 60px;"></div> -->
            <div class="goods-details" >
                <!-- 顶部导航栏 -->
                <div class="header">
                    <div class="back-button" @click="goBack">
                        <i class="icon-back"></i>
                    </div>
                    <h1 class="product-title"></h1>
                </div>

                <!-- 商品轮播图 -->
                <swiper
                  class="product-carousel"
                  :modules="[Pagination]"
                  :pagination="{ clickable: true }"
                  :loop="productImages.length > 1"
                  :initial-slide="currentImageIndex"
                  @slideChange="onSwiperChange"
                >
                  <swiper-slide v-for="(image, index) in productImages" :key="index">
                    <img :src="image" alt="Product Image" class="product-image" />
                  </swiper-slide>
                </swiper>
                
                <!-- 商品信息区域 -->
                <div class="product-info">
                    <h2 class="product-name">{{ goodsDetail?.title }}</h2>
                    <div class="redemption-tag" v-if="goodsDetail?.top">
                        <span class="trophy-icon">🏆</span>
                        <span class="tag-text">{{ goodsDetail?.topName }}</span>
                    </div>
                </div>

                <!-- 价格选择区 -->
                <div class="pricing-options">
                    <div class="pricing-option" v-if="goodsDetail?.onlyPoints" :class="{ active: selectedPriceOption === 'pointsOnly' }"
                        @click="selectPriceOption('pointsOnly')">
                        <div class="option-price">
                            <span class="points">{{ formatNumber(goodsDetail?.onlyPoints) }}</span>
                            <span class="points-label">{{ t('points') }}</span>
                        </div>
                        <div class="option-radio">
                            <div class="radio-circle" :class="{ selected: selectedPriceOption === 'pointsOnly' }"></div>
                        </div>
                    </div>

                    <div class="pricing-option" v-if="goodsDetail?.point2" :class="{ active: selectedPriceOption === 'pointsAndMoney' }"
                        @click="selectPriceOption('pointsAndMoney')">
                        <div class="option-price">
                            <span class="points">{{ formatNumber(goodsDetail?.point2) }}</span>
                            <span class="points-label">{{ t('points') }}</span>
                            <span class="plus-sign">+</span>
                            <span class="points">{{ goodsDetail?.price }}</span>
                        </div>
                        <div class="option-radio">
                            <div class="radio-circle" :class="{ selected: selectedPriceOption === 'pointsAndMoney' }">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 数量选择器 -->
                <div class="quantity-selector">
                    <div class="quantity-label">{{ t("goods_details.quantity") }}</div>
                    <div class="quantity-controls">
                        <button class="quantity-btn decrease" @click="decreaseQuantity">−</button>
                        <div class="quantity-display">{{ quantity }}</div>
                        <button class="quantity-btn increase" @click="increaseQuantity">+</button>
                    </div>
                </div>

                <div class="detail" v-html="goodsDetail.detail"></div>

                <!-- 底部结算栏 -->
                <div class="checkout-bar">
                    <div class="total-price">
                        <div class="total-label">{{ t("goods_details.total")}}</div>
                        <div class="total-amount">
                            <span class="points">{{ formatNumber(totalPoints) }}</span>
                            <span class="points-label">{{ t("Points") }}</span>
                            <span class="plus-sign" v-if="selectedPriceOption === 'pointsAndMoney'">+</span>
                            <span class="money" v-if="selectedPriceOption === 'pointsAndMoney'">{{ formatPriceWithUnit(totalMoney) }}</span>
                        </div>
                    </div>
                    <button class="exchange-button" @click="handleExchange">{{ t("Exchange") }}</button>
                </div>
            </div>
        </template>
    </CommonLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import CommonLayout from "@/views/CommonLayout.vue";
import { useLoadingStore } from "@/stores/loadingStore";
import { formatPriceWithUnit, inputChange, formatNumber } from "@/utils/common";
import { goodsConfig } from "@/config";
// Swiper相关
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Pagination } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/pagination';
const onSwiperChange = (swiper: any) => {
    currentImageIndex.value = swiper.activeIndex;
};


import { useI18n } from "vue-i18n";

const { t } = useI18n(); // 解构出t方法
const goodsDetail = ref<any>(
    {
        id: 1,
        title: '',
        description: '',
        onlyPoints: 0,
        point2: 0,
        price: 0,
        imageUrl: ''
    }
);

const totalPoint = ref(3022);

onMounted(() => {
     useLoadingStore().setLoading(false);
    // 获取商品详情数据
    const goodsDetailData = localStorage.getItem('goodsDetail');

    if (goodsDetailData) {
        goodsDetail.value = JSON.parse(goodsDetailData);
        productImages.value = goodsDetail.value.imageUrl?.split(",") || [];
        console.log(goodsDetail.value.imageUrl?.split(","));
        
        // 设置默认选中的价格选项
        // 如果只有 onlyPoints，选中 pointsOnly
        // 如果只有 point2，选中 pointsAndMoney
        // 如果两个都有，默认选中 pointsOnly（第一个）
        if (goodsDetail.value.onlyPoints && !goodsDetail.value.point2) {
            selectedPriceOption.value = 'pointsOnly';
        } else if (!goodsDetail.value.onlyPoints && goodsDetail.value.point2) {
            selectedPriceOption.value = 'pointsAndMoney';
        } else if (goodsDetail.value.onlyPoints && goodsDetail.value.point2) {
            // 两个都有，默认选中第一个（pointsOnly）
            selectedPriceOption.value = 'pointsOnly';
        }
    } else {
        console.error('No product details found in local storage.');
    }

    const point = localStorage.getItem("totalPoint");
    if (point) {
        totalPoint.value = Number(point);
    }
});

// 类型定义
type PriceOption = 'pointsOnly' | 'pointsAndMoney';

// 路由
const router = useRouter();

const goBack = () => {
    // 设置标记，表明这是一个返回操作
    router.currentRoute.value.meta.isBack = true;
    router.back();
}

// 图片资源 - 注意：路径需要根据实际项目结构调整
const productImages = ref<string[]>([]);

const currentImageIndex = ref<number>(0);
const selectedPriceOption = ref<PriceOption>('pointsAndMoney');
const quantity = ref<number>(1);

// 计算属性
const totalPoints = computed<number>(() => {
    if (selectedPriceOption.value === 'pointsOnly') {
        return goodsDetail.value.onlyPoints * quantity.value;
    } else {
        return goodsDetail.value.point2 * quantity.value;
    }
});

const totalMoney = computed<number>(() => {
    if (selectedPriceOption.value === 'pointsAndMoney') {
        return (goodsDetail.value.price2 * quantity.value);
    }
    return 0;
});

// 方法
const selectPriceOption = (option: PriceOption): void => {
    selectedPriceOption.value = option;
};

const increaseQuantity = (): void => {
    quantity.value++;
    // 检查积分是否足够
    const currentPoint = totalPoints.value; // 当前积分
    const add = 1; // 假设每次增加数量为1
    if (currentPoint > totalPoint.value && add > 0) {
        quantity.value--;
        alert(t("goods_details.not_enough_points"));
        return;
    }
};

const decreaseQuantity = (): void => {
    if (quantity.value > 0) {
        quantity.value--;
    }
};

const handleExchange = (): void => {
    if (quantity.value <= 0) {
        // 如果你有toast组件
        // toast.warning('Please select at least one item');
        alert(t("goods_details.please_redeem"));
        return;
    }

        // 检查积分是否足够
    if (totalPoints.value > totalPoint.value) {
        alert(t("goods_details.not_enough_points"));
        return;
    }
    
    // 保存使用的积分
    localStorage.setItem("pointsUsed", totalPoints.value.toString());
    
    // 计算总金额：商品价格 + 运费（根据 feeType）
    let totalAmount = totalMoney.value; // 商品价格
    let feeAmount = 0; // 运费
    
    // 保存商品价格（不含运费）
    if (totalMoney.value > 0) {
        localStorage.setItem("goodsPrice", totalMoney.value.toString());
        inputChange("SelectGoods", "price", totalMoney.value.toString());
    }
    
    // 处理运费
    // feeType === 0: 无运费
    // feeType === 1: 固定运费（在 CardView 中处理）
    // feeType === 2: 在地址页选择运费（在 AddressView 中处理）
    // feeType === 3: 在商品页选择运费（详情页不适用）
    
    if (goodsConfig.value.feeType === 1 && goodsConfig.value.fee) {
        // 固定运费：保存运费信息供后续页面使用
        feeAmount = goodsConfig.value.fee;
        localStorage.setItem("shippingFee", formatPriceWithUnit(goodsConfig.value.fee));
    }
    // feeType === 0 或 2 的情况：feeAmount 保持为 0，在其他页面处理
    
    // 保存总金额（商品价格 + 运费）
    totalAmount = totalMoney.value + feeAmount;
    localStorage.setItem("moneyAmount", totalAmount.toString());
    
    inputChange("SelectGoods", "title", goodsDetail.value.title);
    useLoadingStore().setLoading(true);
    setTimeout(() => {
        router.push("/address");
    }, 200);
};

const nextImage = (): void => {
    currentImageIndex.value = (currentImageIndex.value + 1) % productImages.value.length;
};

const prevImage = (): void => {
    currentImageIndex.value = (currentImageIndex.value - 1 + productImages.value.length) % productImages.value.length;
};

// 触摸滑动相关变量
const touchStartX = ref<number>(0);
const touchEndX = ref<number>(0);
const touchThreshold = 50; // 触发滑动的阈值

// 设置当前图片
const setCurrentImage = (index: number): void => {
    currentImageIndex.value = index;
};

// 处理触摸开始
const handleTouchStart = (e: TouchEvent): void => {
    touchStartX.value = e.touches[0].clientX;
};

// 处理触摸移动
const handleTouchMove = (e: TouchEvent): void => {
    touchEndX.value = e.touches[0].clientX;
};

// 处理触摸结束
const handleTouchEnd = (): void => {
    const swipeDistance = touchEndX.value - touchStartX.value;

    // 向左滑动（下一张）
    if (swipeDistance < -touchThreshold) {
        nextImage();
    }

    // 向右滑动（上一张）
    if (swipeDistance > touchThreshold) {
        prevImage();
    }

    // 重置触摸值
    touchStartX.value = 0;
    touchEndX.value = 0;
};
</script>

<style scoped>
.goods-details {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    background-color: #f8f8f8;
    min-height: 100vh;
    position: relative;
    padding-bottom: 80px;
}

.header {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: rgba(0, 0, 0, 0);
    color: white;
    position: absolute;
    top: 30px;
    left: 0;
    right: 0;
    z-index: 2;
}

.back-button {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    left: 15px;
    font-size: 24px;
    padding: 5px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: rgba(116, 103, 103, 0.5);
}

.icon-back {
    display: inline-block;
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
}

.icon-back:before {
    content: "\2190"; /* Unicode for left arrow */
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    font-size: 24px;
    color: white; /* Explicitly set color */
    display: block;
    line-height: 24px;
}

.product-title {
    flex: 1;
    text-align: center;
    font-size: 20px;
    font-weight: 500;
}

.product-carousel {
    position: relative;
    background-color: transparent;
    height: 350px;
    width: 100%;
    overflow: hidden;
    z-index: 1;
}

.carousel-wrapper {
    display: flex;
    height: 100%;
    width: 100%;
    transition: transform 0.3s ease;
}

.carousel-item {
    flex: 0 0 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.carousel-controls {
    position: absolute;
    bottom: 15px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
}

.carousel-dots {
    display: flex;
    gap: 6px;
}

.carousel-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.5);
    cursor: pointer;
}

.carousel-dot.active {
    background-color: white;
}

.carousel-indicator {
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    padding: 5px 10px;
    border-radius: 15px;
    font-size: 14px;
}

.product-image {
    width: 100%;
    max-height: 100%;
    object-fit: contain;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    margin-top: 10px;
}

.carousel-indicator {
    position: absolute;
    bottom: 15px;
    right: 15px;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    padding: 5px 10px;
    border-radius: 15px;
    font-size: 14px;
}

.product-info {
    padding: 15px;
    background-color: white;
}

.product-name {
    font-size: 18px;
    margin-bottom: 10px;
    font-weight: 500;
    text-align: left;
}

.redemption-tag {
    display: flex;
    align-items: center;
    color: #ff9500;
    font-size: 14px;
}

.trophy-icon {
    margin-right: 5px;
}

.pricing-options {
    margin-top: 10px;
    background-color: white;
}

.pricing-option {
    display: flex;
    align-items: center;
    padding: 20px 15px;
    border-bottom: 1px solid #f0f0f0;
    position: relative;
}

.detail {
    padding: 15px;
    background-color: white;
    margin-top: 10px;
    font-size: 14px;
    line-height: 1.6;
}

.option-label {
    color: #888;
    margin-bottom: 5px;
}

.option-price {
    flex: 1;
}

.points {
    color: var(--global-primary-color);
    font-size: 24px;
    font-weight: bold;
}

.points-label {
    color: var(--global-primary-color);
    margin-left: 5px;
}

.plus-sign {
    margin: 0 5px;
    color: #ffa530;
}

.money {
    color: var(--global-primary-color);
    font-weight: bold;
}

.option-radio {
    width: 24px;
    height: 24px;
}

.radio-circle {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    border: 2px solid #ccc;
    box-sizing: border-box;
}

.radio-circle.selected {
    border-color: var(--global-primary-color);
    background-color: var(--global-primary-color);
    box-shadow: 0 0 0 2px #fff inset;
}

.quantity-selector {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 15px;
    background-color: white;
    margin-top: 10px;
}

.quantity-label {
    font-size: 16px;
}

.quantity-controls {
    display: flex;
    align-items: center;
}

.quantity-btn {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    border: none;
    font-size: 20px;
    cursor: pointer;
}

.quantity-display {
    width: 60px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: white;
    font-size: 18px;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
}

.checkout-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: white;
    display: flex;
    align-items: center;
    z-index: 10000;
    padding: 15px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.total-price {
    flex: 1;
}

.total-label {
    font-size: 16px;
    margin-bottom: 5px;
}

.exchange-button {
    background-color: var(--global-primary-color);
    color: white;
    border: none;
    border-radius: 25px;
    padding: 15px 30px;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
}
</style>