<template>
	<page-meta :page-style="themeColor"></page-meta>
	<view>
		<block v-if="diyData">
			<block v-for="(item, index) in diyData.value" :key="index">
				<view v-if="item.componentName == 'GoodsCategory'">
					<diy-category @tologin="toLogin" ref="category" :value="item"></diy-category>
				</view>
			</block>
		</block>

		<ns-login ref="login"></ns-login>
		<loading-cover ref="loadingCover"></loading-cover>
		<uni-popup ref="skuPopup" type="bottom" class="sku-layer" v-if="goods_Item_Detail">
			<view class="sku-info">
				<view class="header">
					<view class="img-wrap" @click="previewMedia()">
						<!-- @error="imageError()" -->
						<image :src="$util.img(goods_Item_Detail.sku_image, { size: 'mid' })" mode="aspectFit" />
					</view>

					<view class="main">
						<view class="goods_name">{{ goods_Item_Detail.goods_name }}</view>
						<view class="price-wrap">
							<text class="unit price-style small">￥</text>

							<block>
								<text class="price price-style large">
									{{
										parseFloat(showPrice(goods_Item_Detail))
											.toFixed(2)
											.split('.')[0]
									}}
								</text>

								<text class="unit price-style small">
									.{{
										parseFloat(showPrice(goods_Item_Detail))
											.toFixed(2)
											.split('.')[1]
									}}
								</text>
							</block>
						</view>
						<view class="stock">
							<block v-if="goods_Item_Detail.stock_show">
								库存{{ goods_Item_Detail.stock }}
							</block>
						</view>
					</view>

					<view class="sku-close iconfont icon-close" @click="closeSkuPopup()"></view>
				</view>

				<view class="body-item">
					<scroll-view scroll-y class="wrap">
						<view class="number-wrap">
							<view class="number-line">
								<text class="title font-size-base">购买数量</text>
								<text class="limit-txt color-base-text" v-if="limitNumber > 0">
									(每人限购{{ limitNumber }}件)
									<!-- {{ goods_Item_Detail.unit }} 换 件-->
								</text>
								<text v-if="goods_Item_Detail.maxBuy > 0 && goods_Item_Detail.minBuy > 1
									" class="limit-txt color-base-text">
									({{ goods_Item_Detail.minBuy }}件起售，限购{{
										goods_Item_Detail.maxBuy
									}}件)
								</text>
								<text v-else-if="goods_Item_Detail.maxBuy > 0" class="limit-txt color-base-text">
									(限购{{ goods_Item_Detail.maxBuy }}件)
								</text>
								<text v-else-if="goods_Item_Detail.minBuy > 1" class="limit-txt color-base-text">
									({{ goods_Item_Detail.minBuy }}件起售)
								</text>
								<view class="number">
									<button type="default" class="decrease color-line-border"
										:class="{ disabled: decreaseDisabled }" @click="changeNum('-')">
										-
									</button>
									<input id="tet" type="number"
										class="uni-input color-line-border font-size-goods-tag" @blur="blur"
										v-model="number" placeholder="0" @input="keyInput(false)" />
									<!-- <input id="tet" type="number" v-model="number"> -->
									<button type="default" class="increase color-line-border"
										:class="{ disabled: increaseDisabled }" @click="changeNum('+')">
										+
									</button>
									<!-- v-if="max_buy == 1" -->
									<!-- <button v-else type="default" class="increase color-line-border" @click="changeNum('+')">+</button> -->
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<u-number-keyboard mode="number" @change="change" :dotDisabled="true"
					@backspace="backspace"></u-number-keyboard>
				<view class="footer">
					<button type="primary" v-if="goods_Item_Detail.stock" @click="confirm()">
						加入购物车
					</button>

					<button type="primary" v-else disabled="true">库存不足</button>
				</view>
			</view>
		</uni-popup>

		<!-- 底部tabBar -->
		<view id="tab-bar"><diy-bottom-nav></diy-bottom-nav></view>
	</view>
</template>

<script>
	export default {
		components: {},
		data() {
			return {
				diyData: null,
				viewTrue: true,

				number: 1,
				limitNumber: 0, // 限购
				minNumber: 0,
				goods_Item_Detail: {},
				loading: false
			};
		},
		onLoad() {
			uni.hideTabBar();
			this.getDiyInfo();
			uni.$on('getGoodsItem', data => {
				this.goods_Item_Detail = data;
				this.number = this.goods_Item_Detail.number;
				this.$refs.skuPopup.open();
			});
			// 监听同步购物车
			uni.$on('syncCartList', () => {
				try {
					this.$refs.category[0].$refs.categoryItem.forEach(v => {
						v.syncCartList()
					})
				} catch (e) {
					//TODO handle the exception
					// this.init();
					console.log(e);
				}
			})
		},
		onHide() {
			// this.viewTrue = false;
			console.log(getCurrentPages(), ' getApp()')
		},
		mounted() {
			// this.getDiyInfo();
			// this.viewTrue = true;
			// uni.$on('getGoodsItem', data => {
			// 	this.goods_Item_Detail = data;
			// 	this.number = this.goods_Item_Detail.number;
			// 	this.$refs.skuPopup.open();
			// });
		},
		onShow(e) {
			try {
				this.$nextTick(() => {
					this.$refs.category[0].$refs.categoryItem.forEach(v => {
						v.syncCartList()
					})
				})
			} catch (err) {
				//TODO handle the exception
				// this.getDiyInfo();
				console.log(err);
			}

			// if (uni.$currentMethod !== 'navigateBack') {
			// this.getDiyInfo();
			// }
			// // this.viewTrue = true;
			// uni.$on('getGoodsItem', data => {
			// 	this.goods_Item_Detail = data;
			// 	this.number = this.goods_Item_Detail.number;
			// 	this.$refs.skuPopup.open();
			// });
		},
		onPullDownRefresh() {
			// that.viewTrue = false;
			// setTimeout(function() {
			// that.viewTrue = true;
			this.getDiyInfo();
			// uni.stopPullDownRefresh();
			// }, 1000);
		},
		computed: {
			decreaseDisabled: function() {
				let min = this.goods_Item_Detail.minBuy > 0 ? this.goods_Item_Detail.minBuy : 1;
				return this.goods_Item_Detail.number <= min;
			},
			increaseDisabled: function() {
				let max =
					this.goods_Item_Detail.maxBuy > 0 &&
					this.goods_Item_Detail.maxBuy < this.goods_Item_Detail.stock ?
					this.goods_Item_Detail.maxBuy :
					this.goods_Item_Detail.stock;
				return this.goods_Item_Detail.number >= max;
			},
			skuHeight() {
				let height = 48;
				if (this.goods_Item_Detail) {
					if (
						this.goods_Item_Detail.goods_spec_format &&
						this.goods_Item_Detail.goods_spec_format.length
					) {
						height = 51 + this.goods_Item_Detail.goods_spec_format.length * 9.5;
					}
				}
				height += 'vh';
				return height;
			}
		},
		methods: {
			change(e) {
				if (!this.number) {
					this.number = e;
				} else {
					this.number = this.number + String(e);
				}
			},
			backspace() {
				let str = String(this.number);
				str = str.slice(0, -1);
				this.number = str;
			},
			getDiyInfo() {
				this.$api.sendRequest({
					url: '/api/diyview/info',
					data: {
						name: 'DIY_VIEW_GOODS_CATEGORY'
					},
					success: res => {
						if (res.code == 0 && res.data) {
							this.diyData = res.data;
							if (this.diyData.value) {
								this.diyData = JSON.parse(this.diyData.value);
								if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
							}
							uni.stopPullDownRefresh();
						}
					}
				});
			},
			toLogin() {
				this.$refs.login.open('/pages/goods/category');
			},
			showPrice(data) {
				let price = data.price;
				if (data.discount_price && parseFloat(data.discount_price) < parseFloat(price))
					price = data.discount_price;
				if (data.member_price && parseFloat(data.member_price) < parseFloat(price))
					price = data.member_price;
				return price;
			},
			changeNum(tag) {

				if (this.goods_Item_Detail.max_buy) {
					// is_limit 是否限购  limit_type限购类型 1单次 2长期
					if (this.goods_Item_Detail.is_limit && this.goods_Item_Detail.limit_type == 1) {
						if (this.goods_Item_Detail.number >= this.goods_Item_Detail.max_buy && tag == "+") {
							this.$util.showToast({
								title: `每人限购${this.goods_Item_Detail.max_buy}件`
							});
							return
						}


					} else if (this.goods_Item_Detail.is_limit && this.goods_Item_Detail.limit_type == 2) {
						if (this.goods_Item_Detail.purchased_num >= this.goods_Item_Detail.max_buy) {
							this.$util.showToast({
								// title: `每人长期限购${this.goods_Item_Detail.max_buy}件，您已购买${this.goods_Item_Detail.purchased_num}件`
								title: `每人长期限购${this.goods_Item_Detail.max_buy}件`
							});
							return
						}
					}
				}


				if (this.goods_Item_Detail.stock == 0) return;
				var min = 1;
				var stock = this.goods_Item_Detail.stock;

				if (this.maxBuy == 1) {
					stock = 1;
				}

				if (this.goods_Item_Detail.is_limit == 1 && this.maxBuy > 0 && this.maxBuy < stock)
					stock = this.maxBuy;

				if (
					this.goods_Item_Detail.is_limit == 1 &&
					this.goods_Item_Detail.limit_type == 2 &&
					this.maxBuy > 0 &&
					this.goods_Item_Detail.purchased_num > 0
				) {
					let maxBuy = this.maxBuy - this.goods_Item_Detail.purchased_num;
					stock =
						maxBuy < this.goods_Item_Detail.stock ? maxBuy : this.goods_Item_Detail.stock;
				}

				if (this.minBuy > 1) {
					min = this.minBuy;
				}

				if (tag == '+') {
					// 加
					if (this.number < stock) {
						this.number++;
					} else {
						if (this.number >= this.goods_Item_Detail.stock) {
							this.$util.showToast({
								title: '库存不足'
							});
							return;
						}

						if (this.goods_Item_Detail.is_limit == 1 && this.maxBuy > 0) {
							if (this.goods_Item_Detail.limit_type == 1) {
								this.$util.showToast({
									title: '该商品每次最多购买' + this.maxBuy + this.goods_Item_Detail.unit
								});
								return;
							}

							if (this.goods_Item_Detail.limit_type == 2) {
								let message =
									'该商品每人限购' + this.maxBuy + this.goods_Item_Detail.unit;
								message +=
									this.goods_Item_Detail.purchased_num > 0 ?
									'，您已购买了' +
									this.goods_Item_Detail.purchased_num +
									this.goods_Item_Detail.unit :
									'';
								this.$util.showToast({
									title: message
								});
								return;
							}
						}

						if (
							this.type == 'seckill' &&
							this.goods_Item_Detail.seckill_id &&
							this.goods_Item_Detail.num > 0
						) {
							this.$util.showToast({
								title: '该商品每人限购' +
									this.goods_Item_Detail.num +
									this.goods_Item_Detail.unit
							});
							return;
						}

						if (
							this.type == 'presale' &&
							this.goods_Item_Detail.presale_id &&
							this.goods_Item_Detail.presale_num > 0
						) {
							this.$util.showToast({
								title: '该商品每人限购' +
									this.goods_Item_Detail.presale_num +
									this.goods_Item_Detail.unit
							});
							return;
						}
					}
				} else if (tag == '-') {
					// 减
					if (this.number > min) {
						this.number -= 1;
					} else {
						if (this.minBuy > 1) {
							this.$util.showToast({
								title: '该商品' + this.minBuy + '件起售'
							});
						}
						return;
					}
				}
				if (this.number > this.limitNumber && this.limitNumber) {
					this.number = this.limitNumber;
				}
			},
			closeSkuPopup() {
				this.$refs.skuPopup.close();
			},
			//输入数量
			keyInput(flag, callback) {
				setTimeout(() => {
					var stock = this.goods_Item_Detail.stock;

					// 库存为0
					if (this.goods_Item_Detail.stock == 0) {
						this.number = 0;
						return;
					}

					// 防止空
					if (flag && this.number.length == 0) this.number = 1;

					// 防止输入0和负数、非法输入
					if (flag && (this.number <= 0 || isNaN(this.number))) this.number = 1;

					if (this.number > stock) {
						this.number = stock;
					}
					// 商品起售数
					if (this.minBuy > 1 && this.number < this.minBuy) {
						this.number = this.minBuy;
					}

					if (flag) this.number = parseInt(this.number);
					if (callback) callback();
				}, 0);
			},
			blur() {
				if (!this.number) {
					this.number = 0;
				}
				if (this.number > this.limitNumber && this.limitNumber) {
					this.number = this.limitNumber;
				}
				if (this.number < this.minNumber && this.minNumber) {
					this.number = this.minNumber;
				}

				if (
					this.goods_Item_Detail.is_limit == 1 &&
					this.maxBuy > 0 &&
					this.number > this.maxBuy
				) {
					this.number = this.maxBuy;
				}

				if (
					this.goods_Item_Detail.is_limit == 1 &&
					this.maxBuy > 0 &&
					this.goods_Item_Detail.purchased_num > 0
				) {
					let maxBuy = this.maxBuy - this.goods_Item_Detail.purchased_num;
					if (this.number > maxBuy) this.number = maxBuy;
				}
				if (this.number < this.minBuy && this.minBuy > 0) {
					this.number = this.minBuy;
				}

				if (this.number <= 0) {
					this.number = 1;
				}
			},
			//提交
			confirm() {
				console.log(this.number, ` this.number`);
				// 删除待付款物流方式缓存
				uni.removeStorageSync('delivery');
				if (this.preview) {
					this.$util.showToast({
						title: '预览商品无法购买'
					});
					return;
				}

				if (!uni.getStorageSync('token')) {
					this.$refs.login.open();
					return;
				}

				//纠正数量
				this.keyInput(true, () => {
					if (this.goods_Item_Detail.stock == 0) {
						this.$util.showToast({
							title: '商品已售罄'
						});
						return;
					}

					if (this.number.length == 0 || this.number <= 0) {
						this.$util.showToast({
							title: '购买数量不能小于等于0'
						});
						return;
					}

					if (this.goods_Item_Detail.buy_num > this.goods_Item_Detail.stock) {
						this.$util.showToast({
							title: '库存小于最低购买数量'
						});
						return;
					}

					if (this.number > this.goods_Item_Detail.stock) {
						this.$util.showToast({
							title: '库存不足'
						});
						return;
					}

					if (
						this.goods_Item_Detail.is_limit == 1 &&
						this.goods_Item_Detail.limit_type == 1 &&
						this.maxBuy > 0 &&
						this.number > this.maxBuy
					) {
						this.$util.showToast({
							title: '该商品每次最多购买' + this.maxBuy + this.goods_Item_Detail.unit
						});
						return;
					}

					if (
						this.goods_Item_Detail.is_limit == 1 &&
						this.goods_Item_Detail.limit_type == 2 &&
						this.maxBuy > 0 &&
						this.number + this.goods_Item_Detail.purchased_num > this.maxBuy
					) {
						let message = '该商品每人限购' + this.maxBuy + this.goods_Item_Detail.unit;
						message +=
							this.goods_Item_Detail.purchased_num > 0 ?
							'，您已购买了' +
							this.goods_Item_Detail.purchased_num +
							this.goods_Item_Detail.unit :
							'';
						this.$util.showToast({
							title: message
						});
						return;
					}

					if (
						this.type == 'join_cart' &&
						this.goods_Item_Detail.is_limit == 1 &&
						this.maxBuy > 0 &&
						this.cartNumber + this.number > this.maxBuy
					) {
						this.$util.showToast({
							title: '该商品每人限购' + this.maxBuy + this.goods_Item_Detail.unit
						});
						return;
					}


					if (this.goods_Item_Detail.max_buy) {
						// is_limit 是否限购  limit_type限购类型 1单次 2长期
						if (this.goods_Item_Detail.is_limit && this.goods_Item_Detail.limit_type == 1) {
							if (this.number > this.goods_Item_Detail.max_buy) {
								this.$util.showToast({
									title: `每人限购${this.goods_Item_Detail.max_buy}件`
								});
								return
							}


						} else if (this.goods_Item_Detail.is_limit && this.goods_Item_Detail.limit_type == 2) {
							if (this.goods_Item_Detail.purchased_num >= this.goods_Item_Detail.max_buy) {
								this.$util.showToast({
									// title: `每人长期限购${this.goods_Item_Detail.max_buy}件，您已购买${this.goods_Item_Detail.purchased_num}件`
									title: `每人长期限购${this.goods_Item_Detail.max_buy}件`
								});
								return
							}
						}
					}



					if (this.btnSwitch) return;
					this.btnSwitch = true;
					this.$api.sendRequest({
						url: '/api/cart/add',
						data: {
							sku_id: this.goods_Item_Detail.sku_id,
							num: this.number,
							is_all: 1
						},
						success: res => {
							var data = res.data;
							if (data > 0) {
								this.$util.showToast({
									title: '加入购物车成功'
								});
								this.cartNumber += this.number;
								if (this.callback) this.callback();
								this.$store.dispatch('getCartNumber');
							}

							this.$refs.skuPopup.close();
							setTimeout(function() {
								console.log('start pulldown');
							}, 1000);
							// uni.startPullDownRefresh();
							console.log(this.$refs.category);
							this.btnSwitch = false;
						},
						fail: res => {
							this.$refs.skuPopup.close();
							this.btnSwitch = false;
						}
					});
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	::v-deep {
		.u-icon__icon {
			font-size: 50rpx !important;
		}

		.bottom {
			flex-direction: column;
			justify-content: center !important;
			align-items: flex-start !important;
		}

		.bottom div:nth-child(2) {
			width: 100%;
			justify-content: flex-end;
		}
	}

	/deep/ .uni-popup__wrapper.uni-center {
		background: rgba(0, 0, 0, 0.6);
	}

	/deep/ .uni-popup__wrapper-box {
		border-radius: 0 !important;
	}

	/deep/ .uni-popup__wrapper.uni-custom.center .uni-popup__wrapper-box {
		overflow-y: visible;
	}

	/deep/ .loading-layer {
		background: #fff !important;
	}

	// 分类四一级展开
	/deep/ .category-template-4 .template-four .uni-popup__wrapper-box {
		border-radius: 0px 0px 14px 14px !important;
		overflow: hidden;
	}

	/deep/ .category-template-4 .template-four .uni-popup {
		top: 100rpx;
	}

	/* #ifndef H5 */
	/deep/ .category-template-4 .template-four.wx .uni-popup {
		top: 165rpx;
	}

	/* #endif */
	/deep/ .category-template-4 .content-wrap .categoty-goods-wrap .goods-list {
		margin-top: 30rpx;
	}

	/deep/ .category-template-4 .content-wrap .goods-list .goods-item .footer-wrap .right-wrap .num-action {
		width: 44rpx;
		height: 44rpx;
	}

	.sku-layer {

		.sku-info {
			max-height: 75vh;
			// height: 65vh;
			position: relative;

			.header {
				padding: 30rpx 30rpx 20rpx 210rpx;
				position: relative;
				border-bottom: 2rpx solid $color-line;
				min-height: 170rpx;

				.img-wrap {
					width: 160rpx;
					height: 160rpx;
					position: absolute;
					left: 20rpx;
					border-radius: $border-radius;
					overflow: hidden;
					padding: 2rpx;
					background-color: #fff;
					line-height: 208rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

			.main {
				font-size: 24rpx;
				line-height: 40rpx;
				padding-right: 40rpx;

				.price-wrap {
					font-weight: bold;

					.unit {
						margin-right: 4rpx;
					}
				}

				.stock {
					font-size: $font-size-tag;
					color: $color-tip;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					height: 70rpx;
					overflow: hidden;
				}

				.price {
					word-wrap: break-word;
				}

				.goods_name {
					font-size: 30rpx;
					font-weight: 600;
				}

				.sku-name {
					display: -webkit-box;
					-webkit-line-clamp: 1;
					-webkit-box-orient: vertical;
					overflow: hidden;
					height: 42rpx;

					.spec-value {
						&::after {
							content: '/';
						}

						&:last-child {
							&::after {
								content: '';
							}
						}
					}
				}
			}

			.sku-close {
				position: absolute;
				top: 20rpx;
				right: 40rpx;
				width: 40rpx;
				height: 80rpx;
				font-size: 40rpx;
			}
		}

		.body-item {
			padding: 0 30rpx;
			height: 120rpx;
			box-sizing: border-box;
			overflow: scroll;

			.wrap {
				height: 120rpx;
			}

			.sku-list-wrap {
				padding-bottom: 0rpx;

				.title {
					padding: 20rpx 0;
					display: block;
				}
			}

			.items {
				position: relative;
				display: inline-block;
				border: 2rpx solid $color-line;
				padding: 4rpx 30rpx;
				border-radius: 8rpx;
				margin: 0 20rpx 20rpx 0;
				background-color: #fff;
				font-size: $font-size-tag;

				.disabled {
					border: 2rpx dashed;
				}

				image {
					height: 44rpx;
					width: 44rpx;
					border-radius: $border-radius;
					margin-right: 10rpx;
					display: inline-block;
					vertical-align: middle;
				}
			}

			.number-wrap {
				.number-line {
					padding: 20rpx 0;
					line-height: 72rpx;
				}

				.title {
					font-weight: 400;
				}

				.number {
					display: flex;
					height: 72rpx;
					border-radius: 6rpx;
					float: right;

					button {
						display: inline-block;
						line-height: 64rpx;
						height: 68rpx;
						width: 60rpx;
						font-size: 48rpx;
						box-sizing: content-box;
						border: 2rpx solid $color-line;
						padding: 0;
						margin: 0;
						border-radius: 0;
						background-color: #fff !important;

						&.disabled {
							background: #f7f7f7 !important;
						}
					}

					input {
						display: inline-block;
						line-height: 64rpx;
						height: 68rpx;
						width: 72rpx;
						text-align: center;
						font-weight: 700;
						border: 2rpx solid;
						margin: 0;
						padding: 0;
						vertical-align: top;
						background-color: $color-bg !important;
					}
				}
			}
		}

		.keyBoard {
			padding: 0 30rpx;
		}

		/deep/ .u-keyboard {
			background-color: #fff;

			.u-keyboard__button-wrapper {
				.u-keyboard__button-wrapper__button {
					background-color: #eee;
				}
			}
		}

		.footer {
			height: 100rpx;
			width: 100%;
			margin-top: 40rpx;
			color: #fff;
			z-index: 1;
			display: flex;
			justify-content: center;
			align-items: flex-start;

			button {
				width: 100%;
				height: 80rpx;
				background-color: var(--goods-btn-color);
				font-weight: bold;
			}
		}
	}
</style>