<template>
	<view class="content">
		<view class="navbar" :style="{position:headerPosition,top:headerTop}">
			<view class="nav-item" :class="{current: filterIndex === 0}" @click="tabClick(0)">
				综合排序
			</view>
			<view class="nav-item" :class="{current: filterIndex === 1}" @click="tabClick(1)">
				销量优先
			</view>
			<view class="nav-item" :class="{current: filterIndex === 2}" @click="tabClick(2)">
				<text>价格</text>
				<view class="p-box">
					<text :class="{active: priceOrder === 1 && filterIndex === 2}" class="yticon icon-shang"></text>
					<text :class="{active: priceOrder === 2 && filterIndex === 2}" class="yticon icon-shang xia"></text>
				</view>
			</view>
			<!-- 跳到购物车 -->	
			<!-- <navigator url="/pages/cart/cart" open-type="switchTab"><text class=" cate-item yticon icon-gouwuche"></text></navigator> -->
		</view>
		<view class="goods-list">
			<view 
				v-for="(item, index) in goodsList" :key="index"
				class="goods-item">
				
				<view class="image-wrapper" @click="toGoods(item)">
					<image :src="item.img" mode="aspectFill"></image>
				</view>
				
				<text class="title clamp" @click="toGoods(item)">{{item.mc}}&nbsp;{{item.gg}}{{item.dw}}</text>
				<!-- <view>
					<text class="sdtext">{{ item.sdtext }}</text>
				</view> -->
				<view v-if="item.inputnum">
					<input style="font-size: 28upx;color: #41A863;" type="text" :value="item.bz" @input="inputchangeBz($event,item.bz,item.id,item.kcnum)" placeholder="输入备注">
					<input style="font-size: 28upx;color: #41A863;" type="text" :value="item.fudw" @input="inputchangeFudw($event,item.fudw,item.id,item.kcnum)" placeholder="输入副单位">
				</view>
				<view class="price-box">
					<view class="info">
						<view class="price">{{ item.price }}{{item.dw}}</view>
						<view class="slogan">库存&nbsp;{{ item.kcnum }}</view>
					</view>
					<view style="display: flex; justify-content: space-between; width: 100%;">
						<!-- <view v-if="item.kcnum==0" class="cart"><cjl-icon color="#909399" size='50'>&#xe60f;</cjl-icon></view> -->
						
						<!-- <view v-if="item.kcnum" @click="addshopcat(item.id)" class="cart"><cjl-icon color="#3883FA" size='50'>&#xe60f;</cjl-icon></view>
						<text class="checknum" v-if="item.shownum">{{item.shownum}}</text>
						-->
						<view class="p-b-btn" :class="{active: item.iscollect}" @click="toFavorite(item.id,index)">
							<text class="yticon icon-shoucang"></text>
						</view> 
						<view class="number" v-if="item.kcnum">
							<view class="sub" @tap.stop="sub(item.id)" >
								<view class="jian">-</view>
							</view>
							<view class="input" @tap.stop="discard" >
								<input type="digit" v-model="item.inputnum==0?'':item.inputnum" @input="inputchange($event,item.inputnum,item.id,item.kcnum,0)" />
							</view>
							<view class="add" @tap.stop="add(item.id,0)">
								<view class="jia">
									<image src="../../static/img/addicon.png"></image>
								</view>
							</view>
						</view>
						
					</view>
				</view>
				<view class="shouqinimg" v-if="item.kcnum==0">
					<image src="/static/img/nocknum.png" ></image>
				</view>
			</view>
		</view>
		<uni-load-more :status="loadingType"></uni-load-more>
		
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	export default {
		components: {
			uniLoadMore	
		},
		data() {
			return {
				cateMaskState: 0, //分类面板展开状态
				headerPosition:"fixed",
				headerTop:"0px",
				loadingType: 'more', //加载更多状态
				filterIndex: 0, 
				cateId: 0, //已选三级分类id
				priceOrder: 0, //1 价格从低到高 2价格从高到低
				goodsList: [],
				favorite: true,
				cartlist:[],
				dflid:0
			};
		},
		onBackPress(options) {
						console.log(55555,options);
			if (options.from === 'navigateBack') {
				return false;
			}
			// 这里使用重定向
			uni.redirectTo({ 
				url: '/pages/category/categoryjiad'
			})
			return true;

		},
		onLoad(options){
			// #ifdef H5
			this.headerTop = document.getElementsByTagName('uni-page-head')[0].offsetHeight+'px';
			// #endif
			this.cateId = options.fid;
			this.dflid=options.dflid;
			this.keyword=options.keyword
			this.loadData();
			//this.getgoodlist();
		},
		onShow(){
			this.checkshownum()
		},
		onPageScroll(e){
			//兼容iOS端下拉时顶部漂移
			if(e.scrollTop>=0){
				this.headerPosition = "fixed";
			}else{
				this.headerPosition = "absolute";
			}
		},
		
		//下拉刷新
		onPullDownRefresh(){
			this.loadData('refresh');
		},
		//加载更多
		onReachBottom(){
			this.loadData();
		},
		methods: {
			//减操作
			sub(id) {
				let getcartlist = uni.getStorageSync('cartlistjiad');
				let isexit = this.findidfromstor(id);
				let delid = 0;
				for (let i = 0; i < getcartlist.length; i++) {
					if (isexit.id == getcartlist[i].id) { //找到商品一样的商品
						getcartlist[i].num--; //数量减
						if (getcartlist[i].num <= 0) {
							//删除当前商品缓存
							getcartlist.splice(i, 1);
							uni.setStorageSync('cartlistjiad', getcartlist)
							break; //跳出循环
						} else {
							getcartlist[i].total = parseFloat((getcartlist[i].num * getcartlist[i].price) * 100) / 100
							uni.setStorageSync('cartlistjiad', getcartlist)
							break; //跳出循环
						}
			
					}
				}
			
				this.checkshownum();
			},
			// 增加数量,type 0-推荐商品，1-猜你喜欢商品
			add(id, type) {
				let getcartlist = uni.getStorageSync('cartlistjiad');
				//首次加购物车
				if (getcartlist == '') {
					this.goodsLists = [];
					this.goodsLists.push(this.findarrbyid(id));
					//计算每个商品的总价格
					this.goodsLists.map((item, index) => {
						item.total = parseFloat((item.price * item.num) * 100) / 100
					});
					uni.setStorageSync('cartlistjiad', this.goodsLists);
			
				} else {
					//已有商品在购物车
					let isexit = this.findidfromstor(id);
					if (!isexit) {
						//购物车中还没当前商品
						//不存在
						getcartlist.push(this.findarrbyid(id));
						for (let i = 0; i < getcartlist.length; i++) {
							if (id == getcartlist[i].id) {
								getcartlist[i].total = parseFloat((getcartlist[i].num * getcartlist[i].price) * 100) / 100
							}
						}
						uni.setStorageSync('cartlistjiad', getcartlist);
			
					} else {
						//存在
						for (let i = 0; i < getcartlist.length; i++) {
							if (isexit.id == getcartlist[i].id) { //找到商品一样的商品
								getcartlist[i].num++; //数量自增
								if (getcartlist[i].num > getcartlist[i].kcnum) {
									uni.showToast({
										title: '库存不足！',
										icon: 'none'
									})
									break; //跳出循环
								} else {
									getcartlist[i].total = parseFloat((getcartlist[i].num * getcartlist[i].price) * 100) / 100
									uni.setStorageSync('cartlistjiad', getcartlist)
									break; //跳出循环
								}
							}
						}
					}
				}
				this.checkshownum();
				//更新本地储存
			},
			// input框直接加入购物车
			inputadd(id, type,inputnum) {
				let getcartlist = uni.getStorageSync('cartlistjiad');
				//首次加购物车
				if (getcartlist == '') {
					this.goodsLists = [];
					this.goodsLists.push(this.findarrbyid(id));
					//计算每个商品的总价格
					this.goodsLists.map((item, index) => {
						// item.total = parseFloat((item.price * item.num) * 100) / 100;
						item.total = parseFloat((item.price * inputnum) * 100) / 100;
						item.num = parseFloat(inputnum);
					});
					uni.setStorageSync('cartlistjiad', this.goodsLists);
			
				} else {
					//已有商品在购物车
					let isexit = this.findidfromstor(id);
					if (!isexit) {
						//购物车中还没当前商品
						//不存在
						getcartlist.push(this.findarrbyid(id));
						for (let i = 0; i < getcartlist.length; i++) {
							if (id == getcartlist[i].id) {
								//getcartlist[i].total = parseFloat((getcartlist[i].num * getcartlist[i].price) * 100) / 100;
								getcartlist[i].total = parseFloat((inputnum * getcartlist[i].price) * 100) / 100;
								getcartlist[i].num = parseFloat(inputnum);
							}
						}
						uni.setStorageSync('cartlistjiad', getcartlist);
			
					} else {
						//存在
						for (let i = 0; i < getcartlist.length; i++) {
							if (isexit.id == getcartlist[i].id) { //找到商品一样的商品
								getcartlist[i].num=inputnum; //数量自增
								if (getcartlist[i].num > getcartlist[i].kcnum) {
									uni.showToast({
										title: '库存不足！',
										icon: 'none'
									})
									break; //跳出循环
								} else {
									getcartlist[i].total = parseFloat((getcartlist[i].num * getcartlist[i].price) * 100) / 100
									uni.setStorageSync('cartlistjiad', getcartlist)
									break; //跳出循环
								}
							}
						}
					}
				}
				this.checkshownum();
			},
			inputchange(inputsl,inputnum, id, kcnum,type) {
				inputnum=parseFloat(inputsl.detail.value);
				let getcartlist = uni.getStorageSync('cartlistjiad');
				if (inputnum > 0) {
					if (inputnum > kcnum) {
						uni.showToast({
							title: '库存不足',
							icon: 'none'
						})
						return;
					}
					this.inputadd(id,type,inputnum);//input框直接添加购物车
				} else {
					for (let i = 0; i < getcartlist.length; i++) {
						if (id == getcartlist[i].id) { //找到商品一样的商品
							getcartlist[i].num = 0;
							uni.setStorageSync('cartlistjiad', getcartlist)
							break; //跳出循环
						}
					}
					this.checkshownum();
				}
			},
			//初始化购物车数据
			checkshownum(){
				let getcartlist=uni.getStorageSync('cartlistjiad');
				let carid=[];let carbz=[];let carfudw=[];
				for(let i=0;i<getcartlist.length;i++){
					carid[getcartlist[i]['id']]=getcartlist[i]['num'];
					carbz[getcartlist[i]['id']] = getcartlist[i]['bz'];
					carfudw[getcartlist[i]['id']] = getcartlist[i]['fudw'];
				}
				for(let i=0;i<this.goodsList.length;i++){
					if(carid[this.goodsList[i]['id']]){
						this.$set(this.goodsList[i],'shownum',carid[this.goodsList[i]['id']])
						this.$set(this.goodsList[i],'inputnum',carid[this.goodsList[i]['id']])
						this.$set(this.goodsList[i], 'bz', carbz[this.goodsList[i]['id']])
						this.$set(this.goodsList[i], 'fudw', carfudw[this.goodsList[i]['id']])
					}else{
						this.$set(this.goodsList[i],'shownum',0)
						this.$set(this.goodsList[i],'inputnum',0)
						this.$set(this.goodsList[i], 'bz', '')
						this.$set(this.goodsList[i], 'fudw', '')
					}
				}
			},
			inputchangeBz(inputsl,inputnum, id, kcnum) {
				inputnum=inputsl.detail.value;
				let getcartlist = uni.getStorageSync('cartlistjiad');
				let isbz=0;
				for (let i = 0; i < getcartlist.length; i++) {
					if (id == getcartlist[i].id) { //找到商品一样的商品
						getcartlist[i].bz = inputnum;
						uni.setStorageSync('cartlistjiad', getcartlist)
						isbz=1;
						break; //跳出循环
					}
				}
				if(isbz==0){
					uni.showToast({title:'请您输入数量后再填备注',icon:'none'});
					return;
				}
				this.checkshownum();
			},
			inputchangeFudw(inputsl,inputnum, id, kcnum) {
				inputnum=inputsl.detail.value;
				let getcartlist = uni.getStorageSync('cartlistjiad');
				let is=0;
				for (let i = 0; i < getcartlist.length; i++) {
					if (id == getcartlist[i].id) { //找到商品一样的商品
						getcartlist[i].fudw = inputnum;
						uni.setStorageSync('cartlistjiad', getcartlist)
						is=1;
						break; //跳出循环
					}
				}
				if(is==0){
					uni.showToast({title:'请您输入数量后再填副单位',icon:'none'});
					return;
				}
				this.checkshownum();
			},
			//加载商品 ，带下拉刷新和上滑加载
			async loadData(type='add', loading) {
				//没有更多直接返回
				if(type === 'add'){
					if(this.loadingType === 'nomore'){
						return;
					}
					this.loadingType = 'loading';
				}else{
					this.loadingType = 'more'
				}
				let userinfo=uni.getStorageSync('userinfo');
				let getdata;
				if(this.dflid>0){
					//一级分类
					getdata = await this.$api.getgoodlist({action:'goodlist2',uid:userinfo.uid,aid:userinfo.aid,dflid:this.dflid,keywords:this.keyword});
				}else{
					//二级分类
					getdata = await this.$api.getgoodlist({action:'goodlist2',uid:userinfo.uid,aid:userinfo.aid,fid:this.cateId,keywords:this.keyword});
				}
				let goodsList=getdata.data;
			
				if(type === 'refresh'){
					this.goodsList = [];
				}
				console.log(this.cateId,'得到的类id')
				//筛选，测试数据直接前端筛选了
				if(this.filterIndex === 1){
					goodsList.sort((a,b)=>b.sellnum - a.sellnum)
				}
				if(this.filterIndex === 2){
					goodsList.sort((a,b)=>{
						if(this.priceOrder == 1){
							return a.price - b.price;
						}
						return b.price - a.price;
					})
				}
				
				this.goodsList = this.goodsList.concat(goodsList);
				
				this.checkshownum();
				//判断是否还有下一页，有是more  没有是nomore(测试数据判断大于20就没有了)
				//this.loadingType  = this.goodsList.length > 20 ? 'nomore' : 'more';
				this.loadingType  = 'nomore';
				if(type === 'refresh'){
					if(loading == 1){
						uni.hideLoading()
					}else{
						uni.stopPullDownRefresh();
					}
				}
			},
			//筛选点击
			tabClick(index){
				if(this.filterIndex === index && index !== 2){
					return;
				}
				this.filterIndex = index;
				if(index === 2){
					this.priceOrder = this.priceOrder === 1 ? 2: 1;
				}else{
					this.priceOrder = 0;
				}
				uni.pageScrollTo({
					duration: 300,
					scrollTop: 0
				})
				this.loadData('refresh', 1);
				uni.showLoading({
					title: '正在加载'
				})
			},
			stopPrevent(){},
			async addcollection(id, index) {
				let userinfo=uni.getStorageSync('userinfo');
				let type=!this.goodsList[index].iscollect;
				if(userinfo){
					let redata=await this.$api.addcollection({action:'addcollection',type:type,uid:userinfo.uid,aid:userinfo.aid,id:id});
					uni.showToast({
						title:redata.msg,icon:'none'
					})
					if(redata.code==1){
						this.goodsList[index].iscollect=!this.goodsList[index].iscollect;
					}
				}else{   
					uni.navigateTo({
						url:'/pages/user/login'
					})
				}
			},
			//收藏
			toFavorite(id,index){
				this.addcollection(id,index);
			},
			//添加浏览记录
			async add_read_record(id,uid,aid) {
				await this.$api.add_read_record({action:'add_read_record',cpid:id,uid:uid,aid:aid});
			},
			addshopcat(id){
				let getcartlist=uni.getStorageSync('cartlistjiad');
				let userinfo=uni.getStorageSync('userinfo');
				if(userinfo.uid>0){
					this.add_read_record(id,userinfo.uid,userinfo.aid)
				}
				if(getcartlist==''){
					this.cartlist.push(this.findarrbyid(id));
					this.cartlist.map((item,index)=>{
						item.total=parseFloat((item.price*item.num)*100)/100
					});
					uni.setStorageSync('cartlistjiad',this.cartlist);
				}else{
					let isexit=this.findidfromstor(id);
					if(!isexit){
						//不存在
						getcartlist.push(this.findarrbyid(id));
						for(let i=0;i<getcartlist.length;i++){
							if(id==getcartlist[i].id ){
								getcartlist[i].total=parseFloat((getcartlist[i].num*getcartlist[i].price)*100)/100 
							}
						}
						uni.setStorageSync('cartlistjiad',getcartlist);
					}else{
						//存在
						for(let i=0;i<getcartlist.length;i++){
								if(isexit.id==getcartlist[i].id )
								{	//找到商品一样的商品
									getcartlist[i].num++;//数量自增
									if(getcartlist[i].num>getcartlist[i].kcnum){
										uni.showToast({
											title:'库存不足！',icon:'none'
										})
										break;//跳出循环
									}else{
										getcartlist[i].total=parseFloat((getcartlist[i].num*getcartlist[i].price)*100)/100
										uni.setStorageSync('cartlistjiad',getcartlist)
										break;//跳出循环
									}
									
								}
							}
					}
				}
				this.checkshownum();
			},
			//根据数组指定key获取当前数组
			findarrbyid(id){
				let arr=this.goodsList;
				for(let i=0;i<arr.length;i++){
					if(arr[i]['id']==id){
						return arr[i];
						break;//跳出循环
					}
				}
			},
			//从本地存储中根据id获取数组
			findidfromstor(id){
				let arr=uni.getStorageSync('cartlistjiad');
				for(let i=0;i<arr.length;i++){
						if(arr[i]['id']==id){
							return arr[i];
							break;//跳出循环
						}
				}
				
			},
			
			//跳详情页
			// toGoods(good){
			// 	uni.navigateTo({
			// 		url:'../product/detail?gid='+good.id+"&price="+good.price
			// 	})
			// }
			
		},
	}
</script>

<style lang="scss">
	page, .content{
		background: $page-color-base;
	}
	.content{
		padding-top: 96upx;
	}
	.info {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		width: 100%;
		padding: 10upx 4% 10upx 0;
	
		.price {
			color: #e65339;
			font-size: 30upx;
			font-weight: 600;
		}
	
		.slogan {
			color: #807c87;
			font-size: 24upx;
		}
	}
	.number {
		display: flex;
		justify-content: flex-end;
		margin-right: 30upx;
		margin-bottom: 10upx;
	
		.input {
			width: 70upx;
			height: 45upx;
			margin: 0 10upx;
			// background-color: #f3f3f3;
			border-bottom: 1upx #ADADAD solid;
	
			input {
				width: 60upx;
				height: 60upx;
				display: flex;
				justify-content: center;
				align-items: center;
				text-align: center;
				font-size: 26upx;
			}
		}
	
		.sub,
		.add {
			width: 45upx;
			height: 45upx;
			border-radius: 5upx;
		}
	
		.jia {
			display: flex;
			width: 45upx;
			height: 45upx;
			justify-content: center;
			justify-items: center;
			align-items: center;
			background-color: #41A863;
			color: #fff;
			border-radius: 50%;
	
			image {
				width: 40upx;
				height: 40upx;
				padding: 7upx;
			}
		}
	
		.jian {
			display: flex;
			width: 45upx;
			height: 45upx;
			justify-content: center;
			justify-items: center;
			align-items: center;
			background-color: #41A863;
			color: #fff;
			border-radius: 50%;
			padding-bottom: 10upx;
		}
	}
	

	.navbar{
		position: fixed;
		left: 0;
		top: var(--window-top);
		display: flex;
		width: 100%;
		height: 80upx;
		background: #fff;
		box-shadow: 0 2upx 10upx rgba(0,0,0,.06);
		z-index: 10;
		.nav-item{
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 30upx;
			color: $font-color-dark;
			position: relative;
			&.current{
				color: #3883FA;
				&:after{
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 120upx;
					height: 0;
					border-bottom: 4upx solid #3883FA;
				}
			}
		}
		.p-box{
			display: flex;
			flex-direction: column;
			.yticon{
				display: flex;
				align-items: center;
				justify-content: center;
				width: 30upx;
				height: 14upx;
				line-height: 1;
				margin-left: 4upx;
				font-size: 26upx;
				color: #888;
				&.active{
					color: #2C74E5;
				}
			}
			&.active, &.active .yticon{
				color: $uni-color-primary;
			}
			.xia{
				transform: scaleY(-1);
			}
		}
		.cate-item{
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			width: 100upx;
			position: relative;
			font-size: 44upx;
			&:after{
				content: '';
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				border-left: 1px solid #ddd;
				width: 0;
				height: 36upx;
			}
		}
	}
	
	/* 商品列表 */
	.goods-list{
		display:flex;
		flex-wrap:wrap;
		padding: 0 30upx;
		background: #fff;
		.goods-item{
			display:flex;
			flex-direction: column;
			width: 48%;
			padding-bottom: 40upx;
			&:nth-child(2n+1){
				margin-right: 4%;
			}
			.sdtext{
				padding: 2upx 8upx;
				border: 1upx #DBDBDB solid;
				border-radius: 5upx;
				color: #B9B9B9;
				font-size: 25upx;
				margin-top: 3upx;
				
			}
			.sellnum{
				font-size: 25upx;
				padding-left: 15upx;
				color: #B9B9B9;
			}
		}
		.shouqinimg{
			position: relative;
			image{
				width: 250upx;
				height: 250upx;
				position: absolute;
				bottom: 200upx;
				right: 40upx;
				z-index: 100;
			}
		}
		.image-wrapper{
			width: 100%;
			height: 330upx;
			border-radius: 3px;
			overflow: hidden;
			image{
				
				width: 100%;
				height: 100%;
				opacity: 1;
			}
		}
		.title{
			font-size: $font-lg;
			color: $font-color-dark;
			line-height: 80upx;
		}
		.price-box{
			display: flex;
			align-items: center;
			// justify-content: space-between;
			flex-direction: column;
			// padding-right: 10upx;
			font-size: 24upx;
			color: $font-color-light;
			.waitsell{
				font-size: 24upx;
				color: #F2F5F2;
				padding: 5upx;
				border-radius: 3upx;
				background-color: #B7B7B7;
				text-align: center;
			}
			.btright{
				display: flex;
				align-items: center;
				.nosell{
						display: flex;
						justify-content: flex-end;
						text{
							position: relative;
							right: 5upx;
							padding: 5upx;
							background-color: #EAEAEA;
							color: white;
							font-size: 28upx !important;
						}
						}
				.cart{
					padding-right: 15upx;
				}
				.checknum{
					width: 38upx;
					height: 38upx;
					border-radius: 50%;
					color: #FFFFFF;
					background-color: #FF393B;
					position: relative;
					text-align: center;
					right: 15upx;
					bottom: 25upx;
				}
			}
			.p-b-btn{
				display:flex;
				flex-direction: column;
				align-items: flex-start;
				justify-content: flex-start;
				font-size: 24upx;
				color: $font-color-base;
				// width: 96upx;
				height: 80upx;
				.yticon{
					font-size: 40upx;
					line-height: 48upx;
					color: #F0EAE5;
				}
				&.active, &.active .yticon{
					color: $uni-color-primary;
				}
				.icon-fenxiang2{
					font-size: 42upx;
					transform: translateY(-2upx);
				}
				.icon-shoucang{
					font-size: 50upx;
				}
			}
		}
		.price{
			font-size: $font-lg;
			color: $uni-color-primary;
			line-height: 1;
			&:before{
				content: '￥';
				font-size: 26upx;
			}
		}
	}
	

</style>
