<template>
	<view class="">
		<z-nav-bar title="健康超市"></z-nav-bar>
		<!-- 一级分类 -->
		<view class="oneBox">
			<view class="oneLevel">
				<u-tabs :scrollable="false" :current="current" lineWidth="42" :inactiveStyle="{fontSize:'32rpx'}"
					:list="oneLevel" @click="getTowLevel" lineColor="#54a966"
					:activeStyle="{color: '#303133',fontWeight: 'bold', transform: 'scale(1.01)'}"></u-tabs>
			</view>
		</view>
		<!-- <view class="search_box" @click="onPageJump('../peanut/searchFor')">
			<text class="icon_search"></text>
			<text class="prompt">搜索...</text>
		</view> -->
		
		<!-- 二级分类、商品 -->
		<view class="twoBox" style="">
			<!-- <u-sticky> -->
			<u-tabs v-if="utabs" :list="towLevel" :current = "0" :inactiveStyle="{fontSize:'28rpx'}" lineWidth="40" @click="getCategoryList"
				:activeStyle="{transform: 'scale(1.01)'}"></u-tabs>
			<!-- </u-sticky> -->
		</view>
		<view class="classfyBody">
			<!-- 二级分类、商品 -->
			<view class="towLevel" v-if="towLevel.length > 0">
				<view class="towLevelContent" v-if="commodityList && commodityList.length > 0">
					<view class="commodityItem" v-for="(item,index) in commodityList" :key="index"
						@click.stop="toDetail(item.productId)">
						<view class="box">
							<image :src="item.productImages" mode=""></image>
							<view class="commodityContent">
								<view class="commodityTitle">
									{{item.productName}}
									<span v-if="item.productStock==0" style="color: #aaa;font-size:26rpx;">（暂无库存）</span>
								</view>
								<view class="commodityPrice">
									<text class="price" v-if="item.price">￥
										<b style="font-size: 40rpx;">{{item.price}}</b>
										<span class="priceTag" v-if="item.activityPrice">原价：￥{{item.activityPrice}}</span>
									</text>
									<text class="SoldNumber" v-if="item.sumSales">已售<span>{{item.sumSales}}</span>件</text>
									<!-- <text class="icon" @click.stop="addShopCar(item)" v-if="item.productStock">								
									<u-icon name="shopping-cart" :size="26" color="#eba00b"></u-icon>
								</text> -->
									<view class="publierInfo" v-if="item.author && item.publisher">
										<span class="c999 f24">{{item.author}}著</span><span class="c999 f24">/ {{item.publisher}}</span>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-else style="text-align: center;font-size: 30rpx;color: #888;margin: 20rpx 0 0 0;flex: 1;">
					暂无商品
				</view>
			</view>
			<view v-else style="text-align: center;font-size:30rpx;color: #888;margin: 50rpx 0 0 0;">
				暂无分类
			</view>
		</view>
		<view>
			<u-back-top :scroll-top="scrollTop" bottom="60" :customStyle='bgiStyle' :iconStyle="iconStyle"></u-back-top>
		</view>
		<music-play :playData="playData"></music-play>
	</view>
</template>

<script>
	import musicPlay from '@/components/music.vue'
	import $http from '@/config/requestConfig.js';
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				playData:{},
				highlight: '', // 高亮下标
				current: 0,
				twocurrent:0,
				oneLevel: [],
				towLevel: [],
				commodityList: [] ,// 商品列表		
				utabs:false,
				bgiStyle: {
					background: '#2ab58833'
				},
				iconStyle: {					
					fontSize: '40rpx',
					fontWeight: 'bold',
					color: '#54a966',
				},
				scrollTop: 0,
			}
		},
		// contentButtonClick(e) {
		// 	console.log(e)
		// },		
		// onLoad(e) {
		// 	//获取一级分类
		// 	this.$http
		// 		.post('book/shopcategory/getOneLevel')
		// 		.then(res => {
		// 			this.oneLevel = res.list
		// 			this.current = e.type
		// 			this.getTowLevel(this.oneLevel[e.type])
		// 		})
		// },
		//页面显示
		onShow() {
			this.getOneLevel()
		},
		computed: {
			...mapState(['userInfo']),
		},		
		mounted () {
		    setTimeout(() => { // 解决vant-tab组件官方问题：底部条位置错误
		      this.utabs = true
		    }, 200)
		},
		components: {
			musicPlay
		},
		methods: {
			onPageScroll(e) {
				this.scrollTop = e.scrollTop;
			},
			// 跳转
			onPageJump(url) {
				uni.navigateTo({
					url: url
				});
			},
			// 获取一级分类
			getOneLevel() {
				this.$http
					.post('book/shopcategory/getOneLevel')
					.then(res => {
						//console.log(res,'一级分类')
						this.oneLevel = res.list
						// this.current = e.type
						this.getTowLevel(this.oneLevel[0])
					})
			},
			// 点击一级分类
			getTowLevel(e) {
				this.utabs = false
				// this.twocurrent = 0; 	
				uni.showLoading()
				this.$http
					.post(`book/shopcategory/getTwoLevel?catId=${e.catId}`)
					.then(res => {
						//console.log(res,'二级分类')
						this.towLevel = res.list
						if (this.towLevel == '') {
							this.commodityList = []
						} else {
							let newo = {
								catId:0,
								name:'全部',
								parentCid:e.catId
							}
							this.towLevel.splice(0,0,newo)
							// this.getCategoryList(res.list[0])
							// console.log(this.towLevel, 'towLevel')
							this.getCategoryList(res.list[0])
						}
						uni.hideLoading()
						this.utabs = true
						uni.stopPullDownRefresh();
					})
			},

			// 点击二级分类
			getCategoryList(e) {
				// console.log(e)
				// return false
				// this.highlight = index			
				this.$http
					.post('book/shopproduct/appGetCategoryList', {
						'catId': e.catId
					})
					.then(res => {
						// console.log(res,'二级分类')
						this.commodityList = res.list
					})
			},
			// 加入购物车
			addShopCar(e) {
				this.$http
					.post(`book/ordercart/getCartList?userId=${this.userInfo.id}`)
					.then(res => {
						//  获得用户的购物车列表信息
						this.cartList = res.cartList
						// 统计商品信息
						let data = {
							"userId": this.userInfo.id,
							"productId": e.productId,
							"productAmount": 1,
							"price": e.price
						}
						// 判断列表是否为空
						if (this.cartList.length > 0) {
							let flag = ''
							let shagnpin = {}
							// 循环购物车列表
							flag = this.cartList.some((item, index) => {
								if (item.productId == data.productId) {
									shagnpin = item
									shagnpin.productAmount = item.productAmount + 1
									return true
								}
							})
							if (flag) {
								// 已在购物车中添加
								$http.request({
									url: "book/ordercart/update",
									method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
									data: shagnpin,
									header: { //默认 无 说明：请求头
										'Content-Type': 'application/json'
									}
								}).then(res => {
									if (res.code == 0) {
										uni.showToast({
											title: '加入购物车成功',
											duration: 1000,
										});
									}
								})
							} else {
								// 加入购物车
								$http.request({
									url: "book/ordercart/save",
									method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
									data,
									header: { //默认 无 说明：请求头
										'Content-Type': 'application/json'
									},
								}).then(res => {
									if (res.code == 0) {
										uni.showToast({
											title: '加入购物车成功',
											duration: 1000,
										});
									}
								})
							}

						} else {
							// 购物车列表为空时直接加入购物车
							$http.request({
								url: "book/ordercart/save",
								method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
								data,
								header: { //默认 无 说明：请求头
									'Content-Type': 'application/json'
								},
							}).then(res => {
								if (res.code == 0) {
									uni.showToast({
										title: '加入购物车成功',
										duration: 1000,
									});
								}
							})
						}
					})
			},
			// 商品内容跳转
			toDetail(id) {
				uni.navigateTo({
					url: `./commodityDetail?id=${id}`
				})
			}			
		},
		onPullDownRefresh(){
			// console.log('refresh');
			this.commodityList = []
			this.getOneLevel()			
		}
	}
</script>

<style lang="scss" scoped>
	.publierInfo {
		display: inline-block;
		background-color: #f1f1f1;
		flex-direction: row;
		border-radius: 10px;
		vertical-align: middle;
		padding: 0 12rpx;
		line-height: 32rpx;
	}

	.c999 {
		color: #999;
	}

	.f24 {
		font-size: 24rpx;
	}

	.search_box {
		width: 90%;
		height: 64upx;
		background-color: #fff;
		border-radius: 32upx;
		display: flex;
		align-items: center;
		padding: 0upx 40upx;
		position: relative;
		margin: 30rpx 0 15rpx -46%;
		left: 50%;
		box-shadow: 0 0px 10px 1px #54a96633;

		.prompt {
			color: #cccccc;

		}

		.icon_search {
			background-image: url('@/static/icon/map_ic_search.png');
			background-position: center center;
			background-repeat: no-repeat;
			background-size: cover;
			width: 29upx;
			height: 28upx;
			margin-right: 20upx;
		}
	}

	.oneBox {
		margin: 10rpx auto;

		.oneLevel {}
	}

	.twoBox {
		width: 95%;
		margin: 0 auto;
	}

	.classfyBody {
		margin: 5rpx auto;
		// width: 100%;
		height: 100%;



		.towLevel {
			width: 100%;
			height: 100%;
			display: flex;

			.towLevelTitle {
				width: 28%;
				height: auto;
				text-align: center;

				.titleItem {
					font-size: 35rpx;
					padding: 20rpx 10rpx;
				}

				.active {
					background-color: #fff;
					border-left: solid 10rpx #eba00b;
					font-weight: bold;
				}
			}

			.towLevelContent {
				display: flex;
				flex-wrap: wrap;
				padding: 10rpx 20rpx;
				width: 100%;
				align-items: stretch;
				// align-content:center;
				align-content:start;
				.commodityItem {
					width: 50%;
					// background-color: #fff;					
					padding: 10rpx;

					.box {
						background-color: #fff;
						padding: 10rpx;
						border-radius: 20rpx !important;
						overflow: hidden;
						box-shadow: 0 0px 10px 1px #54a96633;
					}

					.commodityTitle {
						font-size: 32rpx;
						margin: 20rpx 0 10rpx 0;
					}

					image {
						width: 100%;
						border-radius: 10rpx;
						height: 300rpx;
						margin-right: 20rpx;
					}

					.commodityContent {
						flex: 1;
						font-size: 16px;

						display: flex;
						flex-direction: column;
						justify-content: space-between;

						.commodityPrice {
							width: 100%;
							position: relative;
							margin: 0 0 3rpx 0;

							.price {
								vertical-align: middle;
								color: #ffa200;

								.priceTag {
									flex-direction: row;
									color: #999;
									display: inline-block;
									zoom: .8;
									margin-left: 6rpx;
									margin-bottom: 6px;
								}
							}

							.SoldNumber {
								font-size: 24rpx;
								color: #999;
								float: right;
								margin-top: 16rpx;
							}

							.icon {
								background-color: #fbf6ec;
								border-radius: 50rpx;
								padding: 5rpx;
								position: absolute;
								right: 0;
								bottom: -20rpx;
							}
						}
					}
				}
			}
		}
	}
</style>
