<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { getGoods } from "@/services/goods";
import { useRoute, useRouter } from "vue-router";

import { useCartStore } from "@/store/Cart.js";
import { storeToRefs } from "pinia";

import { showToast } from "vant";
import "vant/es/toast/style";

const route = useRoute();
const router = useRouter();


const cartStore = useCartStore()
const { cartItems: items } = storeToRefs(cartStore)


const active = ref(0);

// const goods = ref({
//     goods_attr: {
//         spe: [],
//     },
// });

const goodsNumber = ref(0);

//取得goods_id
const props = defineProps({
    goods: {
        type: Object,
        default: {},
    },
});

const emit = defineEmits(["close"]);

const goods = computed(() => {
    return props.goods;
});

// watch(() => props.id, async (nVal) => {
//     if (nVal > 0) {
//         let res = await getGoods(nVal);
//         if (res.code === 200) {
//             goods.value = res.data;
//             goodsNumber.value = 0;
//         }
//     }
// }, { immediate: true })

onMounted(() => {
    console.log('gd', props.goods);
});

const discount = computed(() => {
    return Math.ceil((goods.value.shop_price / goods.value.market_price) * 10);
});

// Card
const card = ref({
    goods: props.goods,
    number: 1,
    sku: {}
})

const cartItems = computed(() => {
    return items.value.reduce((acc, cur) => {
        acc[cur.goods_pid] = cur;
        return acc;
    }, {});
});

const handleAddCart = () => {
    const sku = Object.keys(card.value.sku).reduce((result, key) => {
        result[key] = {
            name: card.value.goods.goods_attr.spe[key].values.find(obj => obj.id == card.value.sku[key]).label,
            value: card.value.sku[key]
        };
        return result;
    }, {});

    card.value.goods.goods_pid = card.value.goods.goods_id + '-' + Object.values(sku).map(v => v.value).join('-')
    card.value.goods.add_info = sku

    changeItemNum(card.value.goods, card.value.number)

    showToast({
        message: "已加入購物車",
        duration: 1000,
    });
    
    card.value = {
        goods: {},
        number: 1,
        sku: {}
    }

    emit("close", { id: card.value.goods.goods_id, num: card.value.number })
};

const changeItemNum = (goods, num) => {
    //用goods_id取得item

    goods.goods_pid = goods.goods_pid || goods.goods_id
    let item = cartItems.value[goods.goods_pid];
    if (!item) {
        return addToCart(goods, num);
    }

    if (item.goods_number + num <= 0) {
        cartStore.delCart(item.goods_pid);
    } else {
        cartStore.updateCart(item, item.goods_number + num);
    }
};

const addToCart = async (goods, num, type = 0) => {

    //上傳商品至購物車

    let gs = {
        goods_pid: goods.goods_pid || goods.goods_id,
        add_info: goods.add_info || '',
        buymax: goods.buymax,
        cat_id: goods.cat_id,
        goods_id: goods.goods_id,
        goods_name: goods.goods_name,
        goods_number: num,
        goods_price: goods.shop_price,
        goods_sn: goods.goods_sn,
        goods_thumb: goods.goods_thumb
    };

    let res = cartStore.addCart(gs);

    if (!res) {
        return showToast("添加失敗！");
    }

    if (type === 0) {
        showToast("添加成功！");
    }

    return;
};

</script>

<template>
    <!-- Main Start -->
    <main class="main-wrap product-page mb-xxl" v-if="active === 0">
        <!-- Banner Section Start -->
        <div class="banner-box product-banner">
            <van-swipe>
                <van-swipe-item v-for="images in goods.goods_gallery" :index="images.img_id">
                    <img class="banner_img" :src="images.img_url" />
                </van-swipe-item>
                <template #indicator="{ active, total }">
                    <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
                </template>
            </van-swipe>
        </div>
        <!-- Banner Section End -->

        <!-- Product Section Section Start -->
        <section class="product-section">
            <div class="name">
                <div>
                    {{ goods.goods_name }}
                </div>
            </div>

            <div class="rating">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                    class="feather feather-star">
                    <polygon
                        points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2">
                    </polygon>
                </svg>
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                    class="feather feather-star">
                    <polygon
                        points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2">
                    </polygon>
                </svg>
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                    class="feather feather-star">
                    <polygon
                        points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2">
                    </polygon>
                </svg>
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                    class="feather feather-star">
                    <polygon
                        points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2">
                    </polygon>
                </svg>
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                    class="feather feather-star">
                    <polygon
                        points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2">
                    </polygon>
                </svg>
                <span class="font-xs content-color">(150次點擊)</span>
            </div>
            <div class="price">
                <span>${{ goods.shop_price }}</span>
                <del>${{ goods.market_price }}</del>
                <span>{{ discount }}折</span>
            </div>

            <!-- Product Detail Start -->
            <div class="product-detail section-p-t">
                <div class="product-detail-box">
                    <h2 class="title-color">產品介紹</h2>
                    <p class="content-color font-base" v-html="goods.goods_desc">
                    </p>
                </div>
            </div>
            <!-- Product Detail End -->
        </section>
        <!-- Product Section Section End -->
        <div class="attr-section" v-if="goods.goods_attr.spe" v-for="(spec, index) in goods.goods_attr.spe" :key="index">
            {{ spec.name }}
            {{ spec.attr_id }}
            <!-- <van-radio-group v-model="card['sku'][spec.attr_id]" direction="horizontal" >
                <van-radio name="v.id" v-for="(v,i) in spec.values" :key="v.id">
                    {{ v.label }}
                </van-radio>
            </van-radio-group> -->
            <van-radio-group v-model="card['sku'][spec.attr_id]" direction="horizontal">
                <van-radio :name="v.id" v-for="(v, i) in spec.values" :key="v.id">
                    {{ v.label }}
                </van-radio>
            </van-radio-group>
        </div>
    </main>

    <!-- Main End -->

    <!-- Main Start -->
    <main class="main-wrap detail-page mb-xxl" v-if="active == 1">
        <section class="detail-section" v-html="goods.goods_desc"></section>
    </main>
    <!-- Main End -->
    <footer class="footer-nav">
        <ul class="footer-left">
            <li class="footer-item">
                <div>
                    <van-stepper theme="round" v-model="card.number" :min="0" :default-value="1" button-size="24" />
                </div>
            </li>
        </ul>
        <ul class="footer-right">
            <li class="add-cart" @click="handleAddCart">加入購物車</li>
        </ul>
    </footer>
</template>

<style lang="less" scoped>
.goods-header {
    // padding: calc(10px + (15 - 10) * ((100vw - 320px) / (1920 - 320))) 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .logo-wrap {
        padding: 0 15px;
        font-size: 24px;
        line-height: 44px;
        // display: flex;
        // align-items: center;
    }

    .tab-wrap {
        width: 100%;
    }

    .avatar-wrap {
        padding: 0 15px;
        font-size: 24px;
        line-height: 44px;
    }
}

.van-swipe-item {
    color: #fff;
    font-size: 20px;
    line-height: 200px;
    text-align: center;
    background-color: #39a9ed;
}

.custom-indicator {
    position: absolute;
    right: 5px;
    bottom: 5px;
    padding: 2px 5px;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.1);
}

.banner_img {
    width: 100%;
}

.product-section {
    .name {
        font-weight: 700;
        color: #222;
        line-height: 20px;
        // margin-top: -3px;
        display: flex;
        background-color: #f2f2f2;
        padding: 15px;
        margin-left: -15px;
        margin-right: -15px;
    }
}

.footer-nav {
    max-width: 600px;
    width: 100%;
    height: 50px;
    position: fixed;
    z-index: 100;
    bottom: 0px;
    background: #f8f8f8;
    border-top: 1px solid #eeeeee;
    display: flex;

    .footer-left {
        width: 70%;
        display: flex;

        li {
            line-height: 50px;
            text-align: center;
            width: 100%;
            border-right: 1px solid #eeeeee;

        }
    }

    .footer-right {
        width: 30%;
        font: 15px;
        display: flex;

        .add-cart {
            width: 100%;
            line-height: 50px;
            color: #fff;
            background-color: #ff7f24;
            text-align: center;
        }

        .buy-now {
            width: 100%;
            line-height: 50px;
            color: #fff;
            background-color: #067062;
            text-align: center;
        }
    }
}
</style>
