<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { useStore } from "vuex";
import { useRouter } from "vue-router";
const store = useStore();
const route = useRouter();
let cartSum = computed(() => store.state.cartSum)
let cart = computed(() => store.state.cart)
let sizes = computed(() => store.state.sizes)
let colors = computed(() => store.state.colors)
let cartLoaderId = ref()
let session = ref(localStorage.getItem('defaultToken'))
let Coupon_amount= ref(computed(() => store.state.couponAmount))
let setting = computed(() => store.state.settings)
let cartParentProduct = ref([])
let form = reactive({
    'discount_code':'',
    'session':session.value
})
const ChangeSize = async(event, cartId)=>{
    cartLoaderId.value = cartId
    await axios.post('/api/product-size-change/'+event.target.value+'/'+cartId).then(response => {
        cartLoaderId.value = null
        cart.value.map((Cart)=>{
            if(Cart.id == response.data.cartId){
                if(Cart.id == response.data.cartId){
                    Cart.product_size = response.data.cart.product_size
                }
            }
        })
    })
}
const ChangeColor = async(event, cartId)=>{
    cartLoaderId.value = cartId
    await axios.post('/api/product-color-change/'+event.target.value+'/'+cartId+'/'+session.value).then(response => {
        cartLoaderId.value = null
        if(response.data.success == true){
            store.dispatch('cartSum', response.data.cartsum)
            cart.value.map((Cart)=>{
                if(Cart.id == response.data.cartId){
                    Cart.color_code = event.target.value
                    Cart.product_color = response.data.cart.product_color
                    Cart.product_image = response.data.product.image
                    Cart.product_price = response.data.product.product_price
                    Cart.total_price = response.data.product.product_price*Cart.quantity
                    Cart.product_name = response.data.product.product_name
                }
            })
        }else{
            toastr.error('Product color not allowed', 'Error', {timeOut: 3000},{progressBar:true})
        }
    })
    store.dispatch('CouponCheck', localStorage.getItem('coupon_type'))
}
const changeQuantity = async(event, cartId)=>{
    await axios.post('/api/product-quantity-change/'+event.target.value+'/'+cartId+'/'+session.value).then(response => {
        store.dispatch('cartSum', response.data.cartsum)
        cart.value.map((Cart, index)=>{
            if(Cart.id == response.data.cartId){
                Cart.quantity = response.data.cart.quantity
                Cart.total_price = response.data.cart.total_price
            }
        })
    })
    store.dispatch('CouponCheck', localStorage.getItem('coupon_type'))
}
const RemoveCart = async(id)=>{
    cart.value.map((c, index)=>{
        if(c.product_id == id){
            addtoCart.value = false
            cart.value.splice(index, 1);
            store.dispatch('cartRemove', c.id)
        }
    })
    store.dispatch('cartRemove', id)
}

let couponMessage = ref()
const normal = async()=>{    
    if(localStorage.getItem('authToken')){
        let AuthTokenId = localStorage.getItem('authToken').split('|')[0]
        session.value = AuthTokenId
    }
    if(sizes.value.length == 0){
        await axios.post('/api/setting-get').then(response => {
            axios.post('/api/size-color-get/'+session.value).then(response => {
                cartParentProduct.value = response.data.parentProduct
                // sizes.value = response.data.sizes
                // colors.value = response.data.colors
                store.dispatch('SizeColor', response.data)
                store.dispatch('CouponCheck', localStorage.getItem('coupon_type'))
                if(cartSum.value < 1){
                    route.push('/')
                }
            })
        })
    }else{
        axios.post('/api/size-color-get/'+session.value).then(response => {
            cartParentProduct.value = response.data.parentProduct
            // sizes.value = response.data.sizes
            // colors.value = response.data.colors
            store.dispatch('SizeColor', response.data)
            store.dispatch('CouponCheck', localStorage.getItem('coupon_type'))
            if(cartSum.value < 1){
                route.push('/')
            }
        })
    }
}
onMounted(async () => {
    window.scrollTo(0, 0);
    normal()
    store.dispatch('mobileMenuHideShow', false)  
    store.dispatch("SearchText", null)
    store.dispatch('rightSidebar', false)
    store.dispatch('LeftCategorySidebar',false) 
    store.dispatch('CartCompare','0px')
    store.dispatch('HeaderFooterOff',true)
})
const couponEnter = async(data)=>{
    axios.post('/api/couponCheck/'+session.value, form).then(response => {
        if(response.data.success == true){
            couponMessage.value = ''
            localStorage.setItem('discount',response.data.discount)
            localStorage.setItem('discount_code',form.discount_code)
            localStorage.setItem('coupon_type',response.data.coupon.amount_type)
            localStorage.setItem('coupon_amount',response.data.coupon.amount)
            store.dispatch('CouponCheck', localStorage.getItem('coupon_type'))
    
        }else{
            couponMessage.value = response.data.message
        }
    })
}
const CancelCoupon = async()=>{
    form.discount_code = ''
    localStorage.removeItem('discount')
    localStorage.removeItem('discount_code')
    localStorage.removeItem('coupon_type')
    localStorage.removeItem('coupon_amount')
    store.dispatch('cancelCoupon')
}
const increaseValue = async(cartId)=>{
    let cartQuantity = ref()
    cart.value.map((c)=>{
        if(c.id == cartId){
            cartQuantity.value = parseInt(c.quantity) + 1
            c.quantity = parseInt(c.quantity) + 1
            c.total_price = parseInt(c.product_price) * c.quantity
            let cartTotal = parseInt(cartSum.value) + parseInt(c.product_price)
            store.dispatch('cartSum', cartTotal)
        }
    })
    await axios.post('/api/product-quantity-change/'+cartQuantity.value+'/'+cartId+'/'+session.value).then(response => {
        // store.dispatch('cartSum', response.data.cartsum)
    })
    store.dispatch('CouponCheck', localStorage.getItem('coupon_type'))
}
const decreaseValue = async(cartId)=>{
    let cartQuantity = ref()
    cart.value.map((c)=>{
        if(c.id == cartId){
            if(c.quantity > 1){
                cartQuantity.value = parseInt(c.quantity) - 1
                c.quantity = parseInt(c.quantity) - 1
                c.total_price = parseInt(c.product_price) * c.quantity
                let cartTotal = parseInt(cartSum.value) - parseInt(c.product_price)
                store.dispatch('cartSum', cartTotal)
                axios.post('/api/product-quantity-change/'+cartQuantity.value+'/'+cartId+'/'+session.value).then(response => {
                    // store.dispatch('cartSum', response.data.cartsum)
                })
                store.dispatch('CouponCheck', localStorage.getItem('coupon_type'))
            }
        }
    })
    
}
</script>
<template>
<main class="main">
    <div class="page-header text-center">
        <div class="container-fluid">
            <h1 class="page-title">Shopping Cart<span>Shop</span></h1>
        </div><!-- End .container -->
    </div><!-- End .page-header -->
    <nav aria-label="breadcrumb" class="breadcrumb-nav">
        <div class="container-fluid">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><router-link to="/">Home</router-link></li>
                <li class="breadcrumb-item"><router-link to="/products">Shop</router-link></li>
                <li class="breadcrumb-item active" aria-current="page">Shopping Cart</li>
            </ol>
        </div><!-- End .container -->
    </nav><!-- End .breadcrumb-nav -->

    <div class="page-content">
        <div class="cart">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-9">
                        <table class="table table-cart table-mobile">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Price</th>
                                    <th >Size</th>
                                    <th>Color</th>
                                    <th>Quantity</th>
                                    <th>Total</th>
                                    <th></th>
                                </tr>
                            </thead>

                            <tbody>
                                <tr v-if="cart.length == 0">
                                    <td colspan="7" class="text-center">No Data Show</td>
                                </tr>
                                <tr v-for="(Cart, index) in cart" >
                                    <td colspan="7" class="cart-loader" v-if="cartLoaderId == Cart.id"></td>
                                    <td class="product-col" v-if="cartLoaderId !== Cart.id">
                                        <div class="product">
                                            <figure class="product-media">
                                                <router-link :to="'/product-details/'+Cart.product_code+'/'+Cart.product_name">
                                                    <img :src="setting.frontend_img_url+'/storage/image/product/'+Cart.product_image" :alt="Cart.product_name">
                                                </router-link>
                                            </figure>

                                            <h3 class="product-title">
                                                <router-link :to="'/product-details/'+Cart.product_code+'/'+Cart.product_name">
                                                    {{ Cart.product_name }}
                                                </router-link>
                                            </h3><!-- End .product-title -->
                                        </div><!-- End .product -->
                                    </td>
                                    <td class="price-col" v-if="cartLoaderId !== Cart.id">৳  {{ Cart.product_price }}</td>
                                    <td v-if="cartLoaderId !== Cart.id"><select @change="ChangeSize($event, Cart.id)">
                                            <option :value="size.name" :selected="Cart.product_size == size.name" v-for="size in sizes">{{size.name}}</option>
                                        </select>
                                    </td>
                                    <td v-if="cartLoaderId !== Cart.id">
                                        <select @change="ChangeColor($event, Cart.id)">
                                            <option v-if="!Cart.product_color">Select</option>
                                            <option :value="cartProd.product_attribute" :selected="Cart.color_code == cartProd.product_attribute" v-for="cartProd in cartParentProduct[index]"><span v-for="color in colors"><span v-if="color.color_code == cartProd.product_attribute">{{ color.name }}</span></span></option>
                                        </select>
                                    </td>
                                    <td class="quantity-col" v-if="cartLoaderId !== Cart.id">
                                        <div class="cart-product-quantity">
                                            <!-- <input @change="changeQuantity($event, Cart.id)" min="1" step="1" data-decimals="0" type="number" class="form-control" :value="Cart.quantity"> -->
                                            <div class="product-quantity-input">
                                                <div class="value-button decrease" id="decrease" @click="decreaseValue(Cart.id)" value="Decrease Value">-</div>
                                                <input type="number" id="number" disabled :value="Cart.quantity" />
                                                <div class="value-button increase" id="increase" @click="increaseValue(Cart.id)" value="Increase Value">+</div>
                                            </div>
                                        </div><!-- End .cart-product-quantity -->
                                    </td>
                                    <td class="total-col" v-if="cartLoaderId !== Cart.id">৳  {{ Cart.total_price }}</td>
                                    <td class="remove-col" v-if="cartLoaderId !== Cart.id"><button @click="RemoveCart(Cart.id)" class="btn-remove"><i class="icon-close"></i></button></td>
                                </tr>
                            </tbody>
                        </table><!-- End .table table-wishlist -->
                    </div><!-- End .col-lg-9 -->
                    <aside class="col-lg-3">
                        <div class="cart-bottom">
                            <div class="cart-discount">
                                <form @submit.prevent="couponEnter">
                                    <div class="input-group">
                                        <input type="text" v-model="form.discount_code" class="form-control" required placeholder="coupon code" v-if="Coupon_amount == 0">
                                        <input type="text"  class="form-control" required :value="'Discount Amount : '+Coupon_amount" v-if="Coupon_amount > 0" disabled>
                                        <div class="input-group-append">
                                            <button v-if="Coupon_amount == 0" class="btn btn-outline-primary-2" type="submit"><i class="icon-long-arrow-right"></i></button>
                                            <span v-if="Coupon_amount > 0" @click="CancelCoupon" class="cancel-coupon btn btn-outline-primary-2"><i class="icon-close"></i></span>
                                        </div><!-- .End .input-group-append -->
                                    </div><!-- End .input-group -->
                                </form>
                                <span class="text-danger" v-if="couponMessage">{{couponMessage}}</span>
                            </div><!-- End .cart-discount -->
                        </div><!-- End .cart-bottom -->
                        <div class="summary summary-cart">
                            <h3 class="summary-title">Cart Summary</h3><!-- End .summary-title -->

                            <table class="table table-summary">
                                <tbody>
                                    <tr class="summary-subtotal" v-if="Coupon_amount > 0">
                                        <td>Subtotal:</td>
                                        <td>৳ {{cartSum}}</td>
                                    </tr><!-- End .summary-subtotal -->
                                    <tr class="summary-subtotal" v-if="Coupon_amount > 0">
                                        <td>Discount:</td>
                                        <td>৳ {{ parseInt(Coupon_amount) }}</td>
                                    </tr><!-- End .summary-subtotal -->
                                    <tr class="summary-total">
                                        <td>Total:</td>
                                        <td>৳ {{parseInt(cartSum - Coupon_amount)}}</td>
                                    </tr><!-- End .summary-total -->
                                </tbody>
                            </table><!-- End .table table-summary -->
                            <router-link to="/checkout" class="btn btn-outline-primary-2 btn-order btn-block">PROCEED TO CHECKOUT</router-link>
                        </div><!-- End .summary -->
                    </aside><!-- End .col-lg-3 -->
                </div><!-- End .row -->
            </div><!-- End .container -->
        </div><!-- End .cart -->
    </div><!-- End .page-content -->
</main><!-- End .main -->
</template>
<style scoped>
.cart-product-quantity{
  width: 150px;
  margin: 0 auto;
  text-align: center;
  /* padding-top: 50px; */
  position: relative;
}
.product-quantity-input{
    position: relative;
}
.value-button {
  border: 1px solid #ddd;
  position: absolute;
  top:0;
  width: 40px;
  height: 100%;
  font-size: 25px;
  display:flex;
  justify-content: center;
  align-items: center;
  background: #eee;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.value-button:hover {
  cursor: pointer;
}

.value-button.decrease{
    right: 95px;
}
.value-button.increase{
    left: 95px;
}

input#number {
  text-align: center;
  border: none;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  margin: 0px;
  width: 40px;
  height: 40px;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
.cart-bottom{
}
.cancel-coupon{
    cursor:pointer;
}
td.cart-loader{
    width: 100%;
    height: 100px;
    background: #e6eaed;
    background: linear-gradient(90deg, #e6eaed 7%, #eff2f4 12%, #e6eaed 100%);
    background-size: 200% 100%;
    animation: 1.5s productSide linear infinite;
}
@keyframes productSide {
    to {
        background-position-x: -150%;
    }
}
.btn-outline-primary-2:hover,
.btn-outline-primary-2:focus,
.btn-outline-primary-2.focus,
.btn-outline-primary-2:not(:disabled):not(.disabled):active,
.btn-outline-primary-2:not(:disabled):not(.disabled).active,
.show>.btn-outline-primary-2.dropdown-toggle {
    color: #fff;
    background-color: v-bind(setting.color);
    border-color: v-bind(setting.color);
    box-shadow: none
}
.btn-outline-primary-2 {
    color: v-bind(setting.color);
    background-color: transparent;
    background-image: none;
    border-color: v-bind(setting.color);
    box-shadow: none
}
.breadcrumb-item a:hover,
.breadcrumb-item a:focus {
    color: v-bind(setting.color);
}
.table.table-summary .summary-total td {
    font-weight: 400;
    font-size: 1.6rem;
    color: v-bind(setting.color);
    border-bottom: none
}
.page-header h1 span {
    display: block;
    color: v-bind(setting.color);
    font-size: 3rem;
    margin-top: .8rem
}
.table .total-col {
    color: v-bind(setting.color);
    font-weight: 400;
    font-size: 1.6rem
}
@media screen and (max-width: 992px) {
    .product-col .product-media{
        height:auto!important;
    } 
}
</style>