{% extends 'shop/base.html' %}

{% load static shoptags %}

{% block extrastyle %}{{ block.super }}
<style>
	.table td {
		vertical-align: middle;
	}
</style>
{% endblock %}

{% block breadcrumb %}
<div class="container my-4">
	<nav class="breadcrumb is-marginless is-small" aria-label="breadcrumbs">
		<ul>
			<li><a href="{% url 'shop:home' %}">首页</a></li>
			<li class="is-active"><a href="#" aria-current="page">{{ title }}</a></li>
		</ul>
	</nav>
</div>
{% endblock %}

{% block section %}
<div class="container">
	{{ carts_values|json_script:"carts-data" }}
	<div id="carts">
		<div class="box is-radiusless" v-if="cartsData.length > 0">
			<template>
				<b-table checkable hoverable :is-row-checkable="(row) => Number(row.sku.stock) > Number(row.num)"
					:checked-rows.sync="checkedRows" :data="cartsData">
					<b-table-column field="id" label="ID" v-slot="props">
						{$ props.row.id $}
					</b-table-column>
					<b-table-column field="pic" label="商品图" v-slot="props">
						<figure class="image is-128x128">
							<b-image :src="`${props.row.sku.img}`" :alt="props.row.sku.title" ratio="1by1"></b-image>
						</figure>
					</b-table-column>
					<b-table-column field="title" label="标题" v-slot="props">
						{$ props.row.sku.title $}
						<div class="is-flex">
							<p class="mt-2 mr-3" v-for="(spec, value, i) in props.row.sku.specs" :key="i">
								<span class=" has-text-grey-light">
									{$ value $}
								</span>：<strong>{$ spec $}</strong>
							</p>
						</div>
					</b-table-column>
					<b-table-column field="stock" label="库存" width="120" v-slot="props">
						{$ props.row.sku.stock $}
					</b-table-column>
					<b-table-column field="price" label="单价" width="120" v-slot="props">
						<span class="is-size-5 has-text-grey">¥</span>{$ props.row.sku.price $}
					</b-table-column>
					<b-table-column field="count" label="数量" v-slot="props">
						<b-field>
							<b-numberinput @input="updateCartNum(props.row)" controls-position="compact" size="is-small"
								type="is-light" :min="1" :max="props.row.sku.stock" :editable='true'
								v-model="props.row.num">
							</b-numberinput>
						</b-field>
					</b-table-column>
					<b-table-column field="total_price" label="小计" width="120" v-slot="props">
						<span class="is-size-5 has-text-grey">¥</span>
						{$ parseFloat(props.row.sku.price * props.row.num).toFixed(2) $}
					</b-table-column>
					<b-table-column field="caozuo" label="操作" width="80" v-slot="props">
						<button class="delete" @click="delCart(props.row)">删除</button>
					</b-table-column>

					<template #footer>
						<div
							class="has-background-light is-flex is-align-items-center is-justify-content-space-between">
							<div class="has-text-danger-dark ml-3">
								已选<span class="is-size-4 pl-2 pr-2">{$ checkedRows.length $}</span>件商品
							</div>
							<div class=" is-flex is-align-items-center has-text-danger-dark ">
								<span class="is-size-5">合计：</span> <span class="is-size-3 pr-5">¥ {$ total $}</span>
								<button class="button is-primary is-radiusless is-large pl-6 pr-6"
									:disabled="checkedRows.length > 0 ? false : true" @click="cartBuy">
									去结算
								</button>
							</div>
						</div>
					</template>
				</b-table>
			</template>
		</div>
		<div class="has-text-centered has-text-danger is-size-5" v-else>
			<img src="{% static 'img/noCart1.png' %}" />
			<p> 亲，购物车还是空的哟~ </p>
			<a class=" button is-primary is-outlined mt-4" href="{% url 'shop:home' %}">继 续 逛</a>
		</div>
	</div>
</div>
{% endblock %}


{% block extravue %}
<script>
	var cartsData = JSON.parse(document.getElementById('carts-data').textContent);
	var carts = new Vue({
		el: '#carts',
		delimiters: ['{$', '$}'],
		data: {
			cartsData,
			checkedRows: [],  // 选择的动态
			total: 0
		},
		created() {
			cartsData.forEach(item => {
				if (item.num < item.sku.stock) {
					this.checkedRows.push(item)
				}
			})
		},
		watch: {
			// 监听选中商品
			checkedRows: {
				handler: function (rows, oldrows) {
					let total = 0;
					rows.forEach(row => {
						total += row.sku.price * row.num
					})
					this.total = total.toFixed(2)
				},
				immediate: true,
				deep: true
			},

		},
		methods: {
			// 修改数量
			updateCartNum(row) {
				fetch("{% url 'shop:shopapi:update-cart-num' %}", {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						'X-Requested-With': 'XMLHttpRequest',
						'X-CSRFToken': bayke.getCookie('csrftoken'),
					},
					body: JSON.stringify({ cartid: row.id, num: row.num }),
				}).then(response => bayke.handleJSONResponse(response)).then(data => {
					// 处理响应数据
					let cartnumsum = this.checkedRows.reduce((prev, curr) => prev + curr.num, 0);
					header._data.cartcount = cartnumsum
					bayke.toastMessage('is-success', '修改成功.')
				}).catch(error => {
					// 处理错误
					let message = Object.values(error).join()
					bayke.toastMessage('is-danger', message)
				});
			},

			// 删除购物车
			delCart(row) {
				this.$buefy.dialog.confirm({
					message: '是否确认删除该购物车商品！',
					cancelText: '取消',
					onConfirm: () => {
						this.delCartsFunc({ cartid: row.id, num: row.num })
						// 前端删除数组
						this.cartsData.forEach(item => {
                            if (item.id == row.id){
                                this.cartsData.splice(this.cartsData.indexOf(item), 1)
                                this.checkedRows.splice(this.checkedRows.indexOf(item), 1)
                                header._data.cartcount = parseInt(header._data.cartcount) - parseInt(row.num)
                            }
                        })
					}
				})
			},

			// 购物车结算
			cartBuy() {
				let data = {
					baykeshopordersku_set: []
				}
				this.checkedRows.forEach(el => {
					data.baykeshopordersku_set.push({
						sku: el.sku.id,
						count: el.num
					})
				})
				fetch("{% url 'shop:shopapi:create-order' %}", {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						'X-Requested-With': 'XMLHttpRequest',
						'X-CSRFToken': bayke.getCookie('csrftoken'),
					},
					body: JSON.stringify(data),
				}).then(response => bayke.handleJSONResponse(response)).then(data => {
					// 处理响应数据
					this.checkedRows.forEach(el => {
						this.delCartsFunc({cartid: el.id, num: el.num})
					})
					bayke.toastMessage('is-success', '正在跳转至支付页面...')
					location.href = data.cashurl
				}).catch(error => {
					// 处理错误
					let message = Object.values(error).join()
					bayke.toastMessage('is-danger', message)
				});
			},

			// 删除购物车
			async delCartsFunc(_data) {
				await fetch("{% url 'shop:shopapi:del-cart' %}", {
					method: 'DELETE',
					headers: {
						'Content-Type': 'application/json',
						'X-Requested-With': 'XMLHttpRequest',
						'X-CSRFToken': bayke.getCookie('csrftoken'),
					},
					body: JSON.stringify(_data),
				}).then(response => bayke.handleJSONResponse(response)).then(data => {
					// 处理响应数据
					bayke.toastMessage('is-success', '删除成功.')
				}).catch(error => {
					// 处理错误
					let message = Object.values(error).join()
					bayke.toastMessage('is-danger', message)
				});
			}
		}
	})

</script>
{% endblock %}