<template>
	<view class="container">
		<uni-nav-bar :border="false" :statusBar="true" :title="$t('index.cart')" backgroundColor="#B60001" color="white"
			fixed="true">
			<template #left>
				<view @tap="scanEvent">
					<block v-if="isEdit">
						<view class="btn blue" style="font-size: 30rpx;" @click.stop="changeStatus(false)">
							{{$t('index.finish')}}
						</view>
					</block>
					<block v-else>
						<view class="btn" style="font-size: 30rpx;" @click.stop="changeStatus(true)">
							{{$t('index.edit')}}
						</view>
					</block>
				</view>
			</template>
		</uni-nav-bar>
		<view v-for="(item, index) in carList" :key="item.id">
			<view class="list-box">
				<view class="checkbox" style="width: 60rpx" :class="{'active': isEdit ? item.isDelete : item.active}"
					@click="onChosed(index)">
					<view class="unChosed"></view>
					<icon class="chosed" type="success" color="#B60001" size="16" />
				</view>
				<view class="content-box" @click="onChosed(index)">
					<image class="image" mode="aspectFill" :src="item.pictureUrl"></image>
					<view class="type">
						{{item.platformProductPriceVo.deliveryWay === 'deliver' ? $t('index.delivery') : $t('index.pickup-self')}}
					</view>
					<view class="content">
						<view class="name">{{item.productName}}({{item.platformProductPriceVo.availableCount || ''}})
						</view>
						<view class="parameter">{{$t('index.card-num')}}：{{item.brandNumber}} |
							{{$t('index.factory')}}：{{item.manufacturer}}
						</view>
						<view class="parameter">{{$t('index.spec')}}：{{item.platformProductPriceVo.varieties}}
						</view>
						<view class="box">
							<view class="price">
								{{item.price}}<text class="unit">{{$t('index.unit.price')}}/{{item.unit}}</text>
							</view>
							<!-- <view class="stepper-box">
								<view class="reduce" :class="{'disabled': item.count <= 0}" @click="onReduce(index)"></view>
								<input class="uni-input" @input="event=>onInput(event, index)" v-model="item.count" type="digit" />
								<view class="plus" :class="{'disabled': item.count >= item.availableCount}" @click="onPlus(index)"></view>
							</view> -->
							<block v-if="!isEdit">
								<step-price :key="item.id" style="height: 26px" :min="1"
									:max="item.platformProductPriceVo.availableCount" :value="Number(item.count)"
									@reduce="number=> onNumberChange(number, index)"
									@plus="number=> onNumberChange(number, index)"
									@input="number=> onNumberChange(number, index)" />
							</block>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="fixed-box" v-if="isLogin && carList.length">
			<view class="handle" @click="onSelectAll">
				<view class="checkbox" style="width: 50rpx" :class="{'active': allSelect}">
					<view class="unChosed"></view>
					<icon class="chosed" type="success" color="#B60001" size="16" />
				</view>
				<text class="text">{{$t('index.select-all')}}</text>

				<text class="all-price" v-if="!isEdit">{{$t('index.sum')}}：<text class="peice">{{totalPrice}}</text>
					{{$t('index.yuan')}}</text>
			</view>

			<view class="btn-box">
				<block v-if="isEdit">
					<view class="btn red" @click.stop="deleteCarMessage">{{$t('index.delete')}}</view>
				</block>
				<block v-else>
					<view class="btn red" @click.stop="onSettlement">{{$t('index.settlement')}}</view>
				</block>
			</view>
		</view>
		<auth-btn :show="!isLogin" url="/pages/cart/index"></auth-btn>
		<no-data :show="isNoData"></no-data>
	</view>
</template>

<script>
	import {
		getCartList,
		addCartPost,
		deleteCartGet
	} from '@/config/api.js'
	import noData from '../../components/no-data/no-data.vue';
	import authBtn from '../../components/auth-btn/auth-btn.vue';
	import stepPrice from '../../components/step-price/step-price.vue';
	export default {
		name: 'car',
		components: {
			noData,
			authBtn,
			stepPrice
		},
		data() {
			return {
				isLogin: false,
				isEdit: false,
				allSelect: false,
				totalPrice: 0,
				carList: []
			}
		},
		computed: {
			isNoData() {
				return this.isLogin && this.carList.length === 0
			}
		},
		watch: {
			'carList': {
				deep: true,
				immediate: true,
				handler: function(newV) {
					let priceAyy = newV.map(item => {
						let count = Number(item.count)
						let salePrice = 0
						for (let i = 0; i < item.productTieredPricing.length; i++) {
							let priceItem = item.productTieredPricing[i]
							if (count > Number(priceItem.minBatchNum) && (count <= Number(priceItem
									.maxBatchNum) || priceItem.maxBatchNum == undefined)) {
								salePrice = priceItem.salePrice
								item.price = salePrice
							}
							if (item.productTieredPricing.length - 1 == i && salePrice == 0) {
								salePrice = priceItem.salePrice
								item.price = salePrice
							}
						}
						if (item.active) {
							return parseFloat((count * salePrice).toFixed(2))
						} else {
							return 0
						}
					})
					let price = priceAyy.reduce((item, next) => {
						return item + next;
					}, 0)

					this.totalPrice = price.toFixed(2)

					if (this.isEdit) {
						let allSelect = !newV.some(item => !item.isDelete)
						this.allSelect = allSelect
					} else {
						let allSelect = !newV.some(item => !item.active)
						this.allSelect = allSelect
					}
				}
			}
		},
		methods: {
			// 切换“编辑”“删除”状态
			changeStatus(flag) {
				this.isEdit = flag
				if (flag) {
					let allSelect = !this.carList.some(item => !item.isDelete)
					this.allSelect = allSelect
				} else {
					let allSelect = !this.carList.some(item => !item.active)
					this.allSelect = allSelect
				}
			},
			// 选中某一个
			onChosed(index) {
				if (this.isEdit) {
					this.carList[index].isDelete = !this.carList[index].isDelete
				} else {
					this.carList[index].active = !this.carList[index].active
				}
			},
			// 选中全部
			onSelectAll() {
				if (this.isEdit) {
					this.carList.forEach(item => item.isDelete = !this.allSelect)
				} else {
					this.carList.forEach(item => item.active = !this.allSelect)
				}
			},
			// 减少数量
			// onReduce(index) {
			// 	let item = {...this.carList[index]}
			// 	if(item.count <= 0) return
			// 	this.carList[index].count = item.number > 1 ? (item.number - 1) : 0
			// },
			// 增加数量
			// onPlus(index) {
			// 	let item = {...this.carList[index]}
			// 	if(item.number >= item.stock) return
			// 	this.carList[index].number = item.number + 1
			// },
			// 输入数量
			// onInput(e, index) {
			// 	const {
			// 		value = ''
			// 	} = e.detail || {}
			// 	// 为空返回
			// 	if (value === '') return
			// 	let formatted = String(value).replace(/[^0-9.]/g, '')
			// 	const pair = formatted.split('.');
			// 	if (formatted.indexOf('.') !== -1) {
			// 		formatted = `${pair[0]}.${pair[1].slice(0, 3)}`
			// 	}
			// 	formatted = Math.max(Math.min(this.carList[index].stock, formatted), 0)
			// 	this.$nextTick(()=> {
			// 		this.carList[index].number = Number(formatted)
			// 	})
			// },
			deleteCartMethod(id) {
				return new Promise((resolve, reject) => {
					deleteCartGet(id).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},
			deleteCarMessage() {
				let deleteList = this.carList.filter(item => item.isDelete).map(item => item.id)
				if (deleteList.length) {
					let _this = this;
					uni.showModal({
						title: this.$t('index.notice-tip'),
						content: this.$t('index.msg-cart-delete'),
						success: function(res) {
							if (res.confirm) {
								_this.deleteCar(deleteList)
							}
						}
					});
				} else {
					uni.showToast({
						title: this.$t('index.msg-product-select'),
						icon: 'none'
					});
				}
			},
			// 删除
			deleteCar(deleteList) {
				let promiseEvent = []
				deleteList.forEach(id => {
					promiseEvent.push(this.deleteCartMethod(id))
				})
				Promise.all(promiseEvent).then(res => {
					setTimeout(() => {
						uni.showToast({
							title: this.$t('index.msg-delete-succ'),
							icon: 'none'
						})
						this.isEdit = false
						this.getCartList()
					}, 30)
				})
			},
			onSettlement() {
				let ids = this.carList.filter(item => item.active).map(item => item.id).join(',')
				if (ids) {
					uni.navigateTo({
						url: `/pages/placeOrder/index?ids=${ids}`
					});
				} else {
					uni.showToast({
						title: this.$t('index.msg-product-select'),
						icon: 'none'
					});
				}
			},
			getCartList() {
				getCartList().then(({
					content
				}) => {
					let carList = []
					content.forEach(item => {
						let carts = item.carts
						carts.forEach(car => {
							car['active'] = false
							car['isDelete'] = false
							if (car.usable) {
								carList.push(car)
							}
						})
						// carList = [...carList, ...carts]
					})
					this.carList = carList
				})
			},
			onNumberChange(count, index) {
				let {
					businessId,
					sellerName,
					sellerCode,
					source,
					specsId
				} = this.carList[index]
				addCartPost({
					cartList: [{
						businessId,
						sellerCode,
						sellerName,
						source,
						count,
						specsId
					}]
				}, {
					custom: {
						load: false
					}
				}).then(res => {
					this.carList[index].count = count
				})
			}
		},
		onShow() {
			const value = uni.getStorageSync('token');
			this.isLogin = !!value
			if (!!value) {
				this.getCartList()
			} else {
				this.carList = []
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding-bottom: 140rpx;
		// min-height: calc(100vh - 140rpx);
		// background-color: #fff;
	}

	.checkbox {
		flex: none;
		position: relative;

		&.active {
			.unChosed {
				opacity: 0;
			}

			.chosed {
				opacity: 1;
			}
		}

		.unChosed {
			box-sizing: border-box;
			width: 30rpx;
			height: 30rpx;
			border: 1rpx solid #D5E2F3;
			border-radius: 50%;
			position: absolute;
			top: 50%;
			left: 0;
			transform: translateY(-50%);
			opacity: 1;
			transition: opacity .3;
		}

		.chosed {
			position: absolute;
			top: 50%;
			left: 0;
			transform: translateY(-50%);
			opacity: 0;
			transition: opacity .3;
		}
	}

	.list-box {
		padding: 22rpx 30rpx;
		background-color: #fff;
		margin-top: 20rpx;
		display: flex;

		.content-box {
			flex: auto;
			display: flex;
			position: relative;

			.image {
				flex: none;
				width: 120rpx;
				height: 120rpx;
				border-radius: 10rpx;
			}

			.type {
				position: absolute;
				top: 90rpx;
				left: 0;
				width: 120rpx;
				height: 30rpx;
				background-color: rgba(25, 26, 35, .5);
				font-size: 12px;
				color: #fff;
				text-align: center;
				line-height: 30rpx;
				border-radius: 0 0 5px 5px;
			}

			.content {
				flex: auto;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				margin-left: 20rpx;
				// line-height: 1;


				.name {
					font-size: 30rpx;
					color: #333;
					font-weight: 500;
				}

				.parameter {
					font-size: 12px;
					color: #99A0AF;
				}

				.box {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 4px;

					.price {
						font-size: 40rpx;
						color: #B60001;

						.unit {
							color: #B60001;
							font-size: 12px;
						}
					}
				}
			}
		}

		.stepper-box {
			display: flex;
			align-self: flex-end;

			.reduce {
				width: 54rpx;
				height: 40rpx;
				border: 1rpx solid #D5E2F3;
				border-right: 1rpx solid #D5E2F3;
				border-top-left-radius: 20rpx;
				border-bottom-left-radius: 20rpx;
				position: relative;

				&.disabled {
					background-color: #f5f5f5;
				}

				&::after {
					content: " ";
					position: absolute;
					top: 50%;
					left: 20rpx;
					width: 14rpx;
					height: 0;
					border-top: 1px solid #D5E2F3;
				}
			}

			.uni-input {
				box-sizing: border-box;
				width: 72rpx;
				height: 42rpx;
				text-align: center;
				font-size: 12px;
				color: #B60001;
				border-top: 1rpx solid #D5E2F3;
				border-bottom: 1rpx solid #D5E2F3;
			}

			.plus {
				width: 54rpx;
				height: 40rpx;
				border: 1rpx solid #D5E2F3;
				border-left: 1rpx solid #D5E2F3;
				border-top-right-radius: 20rpx;
				border-bottom-right-radius: 20rpx;
				position: relative;

				&.disabled {
					background-color: #f5f5f5;
				}

				&::before {
					content: " ";
					position: absolute;
					top: 50%;
					left: 20rpx;
					width: 14rpx;
					height: 0;
					border-top: 1px solid #D5E2F3;
				}

				&::after {
					content: " ";
					position: absolute;
					top: 14rpx;
					left: 48%;
					width: 0;
					height: 14rpx;
					border-right: 1px solid #D5E2F3;
				}
			}
		}
	}

	.fixed-box {
		position: fixed;
		left: 0;
		bottom: 0;
		right: 0;
		height: 120rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		background-color: #fff;
		z-index: 99;

		.handle {
			display: flex;
			align-items: center;

			.text {
				font-size: 28rpx;
				color: #99A0AF;
			}
		}

		.all-price {
			color: #B60001;
			font-size: 28rpx;
			margin-left: 40rpx;

			.flag {
				font-size: 12px;
			}

			.peice {
				color: #B60001;
				font-size: 28rpx;
			}
		}

		.btn-box {
			display: flex;
			align-items: center;

			.btn {
				width: 160rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background-color: #FFFFFF;
				border: 1rpx solid #D5E2F3;
				border-radius: 4rpx;
				font-size: 28rpx;
				color: #99A0AF;

				&+.btn {
					margin-left: 20rpx;
				}

				&.red {
					background-color: #DE0000;
					border: 1rpx solid #DE0000;
					color: #fff;
				}

				&.blue {
					background-color: #B60001;
					border: 1rpx solid #B60001;
					color: #fff;
				}
			}
		}
	}
</style>