<template>
    <view class="">
		<u-navbar
			title="购物车"
			:placeholder="true"
			@leftClick="leftClick"
			:autoBack="false"
			 :safeAreaInsetTop="true"
		>
		</u-navbar>
        <view class="product-list">
			<view class="til u-flex u-row-between" :style="{top:navHeight+'px'}">
				<u-checkbox-group @change="allCheckboxChange">
					<u-checkbox shape="circle" :checked="allChecked" :name="allCheckbox.name" label="商品列表"></u-checkbox>
				</u-checkbox-group>
				<text class="delbtn" @click="delSelect" v-if="selectGoods.length>0">删除</text>
			</view>
			<mescroll-body class="" ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
				<u-checkbox-group placement="column" @change="checkboxChange" >
				<view v-for="(item,index) in dataList" :key="item.id" class="product">
					<view class="u-flex logistics">
						<text v-for="(logis,logisIndex) in item.logisticsTypeList" :key="logisIndex">
							{{logis|filterLogisticsType}} 
							<text style="margin: 0 5px;" v-if="logisIndex<item.logisticsTypeList.length-1">/</text>
						</text>
					</view>
					<u-swipe-action>
					<u-swipe-action-item :show="item.show" :index="index" @click="swipeClick(index)" :options="options">
					<view class="swipe-action">
					<view class="swipe-action__content u-flex">
					<u-checkbox shape="circle" :disabled="item.quantity>item.stock" activeColor="#00A447" :key="index" :name="item.name" :checked="item.checked" @change="toggleCheck(index)" class="checkbox" />
					<u--image @click="$u.route('/shopping/productdetails',{id:item.goodsId})" :showLoading="true" :src="item.mainImg" width="180rpx" height="180rpx"></u--image>
					<view class="text">
						<view class="name ellipsis-2" @click="$u.route('/shopping/productdetails',{id:item.goodsId})">{{item.goodsName}}</view>
						<view class="u-flex u-row-between">
							<view class="left">
								<view class="up">
									<!-- <view class="" v-if="vuex_member_info.priceType>1">
										<text class="price">¥ <text class="price-num">{{item.vipPrice}}</text></text>
										<text class="vip-icon">VIP</text>
									</view>
									<view class="" v-else>
										<text class="price">¥ <text class="price-num">{{item.salePrice}}</text></text>
									</view> -->
									<view class="">
										<text class="price">¥ <text class="price-num">{{item.levelPrice}}</text></text>
									</view>
								</view>
								<view class="down">
									<!-- <text class="discount">8.8折</text> -->
									<text v-if="item.salePrice!=item.levelPrice" class="original-price gray line-through">¥ {{item.salePrice}}</text>
									<!-- <text class="sales gray">销量999+</text> -->
								</view>
							</view>
							<u-number-box 
								v-model="item.quantity" 
								:max="item.stock" 
								:asyncChange="true"
								@change="changeQuantity(index, $event)" integer>
							</u-number-box>
						</view>
					</view>
					
					</view>
					</view>
					<view class="tip" v-if="item.quantity>item.stock">库存不足</view>
					</u-swipe-action-item>
					</u-swipe-action>
				</view>
				</u-checkbox-group>
			</mescroll-body>
			
        </view>
	<!-- 	<view class="recommend" v-if="dataList.length>=total">
			<view class="til u-flex">
				<u-icon name="heart" color="#FF3C3F" size="28"></u-icon>
				<text class="text">为你推荐</text>
			</view>
			<view class="half-product u-flex u-flex-wrap u-row-between">
				<view class="half-product-item" v-for="data in 10" :key="data">
					<u--image :showLoading="true" src="http://placekitten.com/340/340" width="340rpx" height="340rpx"></u--image>
					<view class="down">
						<view class="name ellipsis-2">
							贵州特色酒习酒·百亿纪念酒53度500ML
						</view>
						<view class="u-flex u-row-between">
							<text class="price red">¥ <text class="price-num">{{data+1000}}</text></text>
							<u--image :showLoading="false" :src="staticUrl+'/img/add.png'" width="48rpx" height="48rpx"></u--image>
						</view>
					</view>
				</view>
			</view>
		</view> -->
		<view class="cart-bottom">
			<view class="inner u-flex u-row-between">
				<view class="left u-flex">
					<view class="checkbox" @click="checkboxClick" style="padding: 10px;">
						<u-checkbox-group @change="allCheckboxChange">
							<u-checkbox shape="circle" :checked="allChecked" :name="allCheckbox.name" label="全选"></u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="total-price">
						合计:{{totalPrice}}
					</view>
				</view>
				<view class="btn active" v-if="selectGoods.length>0&&cansubmit" @click="submitorder">去结算</view>
				<view class="btn" v-else>去结算</view>
			</view>
		</view>
		<u-toast ref="uToast"></u-toast>
    </view>
</template>
<script>
	import { systemInfo } from "@/mixin.js";
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
    export default {
		mixins: [MescrollMixin,systemInfo], // 使用mixin
        data() {
            return {
				cansubmit:true,
				hasAddr:false,
				buyNowId:null,//立即购买id
				buyNowName:'',//立即购买商品
				staticUrl:this.$commonConfig.staticUrl,
				allCheckbox:{name: '全选'},
				options:[
					{
						text: '删除',
						style: {
							backgroundColor: '#FF3C3F',
							'padding-left':'10px'
						}
					}
				],
                // 购物车列表
                dataList: [],
				total:10,
				deleteArr:[],
            }
        },
		watch:{
			// 'tabbarIndexProps': {
			// 	handler(newVal, oldVal) {
			// 		this.tabbarValue = newVal
			// 	},
			// 	immediate: true
			// }
		},
        computed: {
            // 是否全选
            allChecked() {
                return this.dataList.every(item => item.checked)
            },
            // 商品合计价格
            selectGoods() {
				let selectGoods = [];
                this.dataList.forEach(item => {
                    if (item.checked) {
                       selectGoods.push(item)
                    }
                })
                return selectGoods
            },
			totalPrice() {
			  let that = this;
			  return this.dataList.reduce((total, item) => {
				if (item.checked) {
					let price = null;
					// if(that.vuex_member_info.priceType>1){
					// 	price = item.vipPrice
					// }else{
					// 	price = item.salePrice
					// }
					price = item.levelPrice
				  total += price * item.quantity;
				}
				return total;
			  }, 0).toFixed(2);
			}
        },
		onLoad(page) {
			this.getSystemInfo();
			this.buyNowId = page.buyNowId;
			this.buyNowName = page.buyNowName;
		},
		onShow() {
			this.getAddrList();
		},
        methods: {
			/*下拉刷新的回调, 重置列表为第一页 (此处可删,mixins已默认)
			downCallback(){
				this.mescroll.resetUpScroll();
			},
			/*上拉加载的回调*/
			upCallback(page) {
				// 此处可以继续请求其他接口
				// if(page.num == 1){
				// 	// 请求其他接口...
				// }
			
				// 如果希望先请求其他接口,再触发upCallback,可参考以下写法
				// if(!this.hasTypeId){
				// 	this.shopNewsType();
				// 	return // 此处return,先获取xx
				// }
			
				let pageNum = page.num; // 页码, 默认从1开始
				let pageSize = page.size; // 页长, 默认每页10条
			
				let params = {
					pageNum : page.num,
					pageSize :  page.size,
				}
				//如果从立即购买中过来
				if(this.buyNowName){
					params.goodsName = this.buyNowName
				}
				// console.log('this.params',params);
				this.$u.api.cartList(params).then(data => {
					console.log('data',JSON.parse(JSON.stringify(data)));
					// 接口返回的当前页数据列表 (数组)
					let curPageData = data.data.rows;
					curPageData = curPageData.map( item =>{
						item.logisticsTypeList = item.logisticsType?.split(",")||[]
						item.checked = false
						return  item
					})
					// console.log('curPageData',JSON.parse(JSON.stringify(curPageData)));
					// 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
					let curPageLen = curPageData.length; 
					// 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
					// let totalPage =  data.data.data.totalPage; 
					// 接口返回的总数据量(如列表有26个数据,每页10条,共3页; 则totalSize=26)
					let totalSize = data.data.total; 
					this.total = totalSize;
					// 接口返回的是否有下一页 (true/false)
					// let hasNext = data.xxx; 
					// console.log('totalPage',totalPage,'curPageLen',curPageLen);
					//设置列表数据
					if(page.num == 1) this.dataList = []; //如果是第一页需手动置空列表
					this.dataList = this.dataList.concat(curPageData); //追加新数据
					// console.log('dataList',this.dataList);
					// 请求成功,隐藏加载状态
					//方法一(推荐): 后台接口有返回列表的总页数 totalPage
					// this.mescroll.endByPage(curPageLen, totalPage); 
					//方法二(推荐): 后台接口有返回列表的总数据量 totalSize
					this.mescroll.endBySize(curPageLen, totalSize); 
				}).catch(err => {
					this.mescroll.endErr()
					console.log(err)
				});	
			
			},
			/*若希望重新加载列表,只需调用此方法即可(内部会自动page.num=1,再主动触发up.callback)*/
			reloadList() {
				this.mescroll.resetUpScroll();
			},
			leftClick(e){
				uni.reLaunch({url: '/pages/index/index'});
				console.log('leftClick',e);
			},
			// 切换全选状态
			allCheckboxChange(n){
				// console.log('allCheckboxChange',n[0]);
				console.log('allCheckboxChange',n);
				let selectAll = n[0]?true:false;
				this.dataList.forEach(item => {
					if(item.quantity<=item.stock){
						item.checked = selectAll
					}
				})
			},
			checkboxClick(){
				// console.log('checkboxClick',this.allChecked);
				this.dataList.forEach(item => {
					if(item.quantity<=item.stock){
						item.checked = !this.allChecked
					}
				})
			},
			checkboxChange(n){
				// console.log('checkboxChange',n);
			},
            // 切换商品选中状态
            toggleCheck(index) {
				// console.log('toggleCheck',index);
                this.dataList[index].checked = !this.dataList[index].checked
            },
            // 改变商品数量
            changeQuantity(index, value) {
				this.changeQuantityApi(this.dataList[index].id,value.value,index)
            },
			changeQuantityApi(id,num,index){
				this.$u.api.updateQuantity({id:id,quantity:num}).then(res=>{
					this.dataList[index].quantity = num;
					console.log('res',res.data);
					}).catch(err=>{
					console.log('changeQuantityApi',err.data);
				})
			},
            // 结算
            checkout() {
                // TODO: 跳转到支付页面
            },
			swipeClick(index){
				let that = this;
				console.log('swipeClick',index);
				// console.log('swipeClick',this.dataList[index]);
				let item = this.dataList[index];
				uni.showModal({
					title: '温馨提示',
					content: '确定要删除吗？',
					success: res => {
						if (res.confirm) {
							// console.log('',that);
							that.deleteArr = [];
							that.deleteArr.push(item.id);
							that.deleteCarts();
						}
					},
					complete:()=>{}
				})
			},
			deleteCarts(){
				this.$u.api.deleteCarts(this.deleteArr).then(res=>{
					this.reloadList()
					}).catch(err=>{
					console.log('deleteCarts',err.data);
				})
			},
			submitorder(){
				// console.log('submitorder',this.selectGoods);
				
				// 判断是否有相同的收货方式
				let logis = [];
				this.selectGoods.forEach(item=>{
					logis.push(item.logisticsTypeList)
				})
				// console.log('logis',logis);
				const referenceArray = logis[0];
				// 使用some()方法遍历数组，并判断每个子数组是否存在与参照数组相同的值
				const result = logis.some(subArray => {
				  // 遍历参照数组的每个元素，判断是否包含在子数组中
				  return referenceArray.some(element => {
				    return subArray.includes(element);
				  });
				});
				if (result) {
				  // console.log("每个子数组中至少存在一个相同的值");
				} else {
				  // console.log("每个子数组中都没有相同的值");
				  uni.$u.toast('只有相同提货方式的商品才能一起结算哦')
				  return false
				}
				// 判断是否有相同的收货方式结束

				this.cansubmit = false;
				let param = {};
				if(!this.hasAddr){
					// this.$refs.uToast.show({
					// 	type: 'error',
					// 	title: '提示',
					// 	message: "请先去'我的-地址管理'设置收货地址！",
					// 	duration:3000
					// })
					uni.showModal({
						title: '温馨提示',
						content: '请先设置地址！',
						success: res => {
							if (res.confirm) {
								uni.$u.route('/center/addrlist', {
									from: 'cart',
									backUrl:'/shopping/cart'
								});
							}
						}
					})
					return
				}
				param.goodsList = this.selectGoods.map(item=>{
					return {goodsId:item.goodsId,quantity:item.quantity}
				})
				this.$u.vuex('cartGoods', param.goodsList);
				uni.$u.route('/shopping/submitorder', {});
				this.cansubmit = true;
				// // console.log('param',param);取消在这个获取订单结算详情
				// this.$u.api.getSettlement(param).then(res=>{
				// 	console.log('submitorder',res.data);
				// 	// return
				// 	uni.$u.route('/shopping/submitorder', {
				// 		selectGoods: JSON.stringify(res.data),
				// 	});
				// }).catch(err=>{
				// 	console.log('getSettlement',err.data);
				// })
			},
			delSelect(){
				let that = this;
				let delArr = [];
				delArr = this.selectGoods.map(item=>{
					return item.id;
				});
				uni.showModal({
					title: '温馨提示',
					content: '确定要删除吗？',
					success: res => {
						if (res.confirm) {
							// console.log('',that);
							that.deleteArr = [];
							that.deleteArr = delArr
							that.deleteCarts();
						}
					}
				})
			},
			getAddrList(){
				this.$u.api.addrList().then(res=>{
					// this.dataList = res.data.rows;
					if( res.data.total>0){
						this.hasAddr = true;
					}else{
						this.hasAddr = false;
					}
				}).catch(err=>{
					console.log('getAddrList',err.data);
				})
			},
        }
    }
</script>
<style>
	page{
		background-color: #F5F5F5;
		/* padding-top: 50px; */
	}
</style>
<style lang="scss" scoped>
.product-list{
	background-color: #fff;
	margin-bottom: 60rpx;
	padding: 30rpx;
	.product{
		.text{
			margin-left: 20rpx;
		}
		.logistics{
			font-size: 24rpx;
			color: #ccc;
			margin-bottom: 10rpx;
		}
	}
	.product:last-child{
		margin-bottom: 0;
		border-bottom: 0;
		padding-right: 0;
	}
	.til{
		position: sticky;
		background-color: #fff;
		z-index: 1001;
		padding-bottom: 10rpx;
		margin-bottom: 20rpx;
		min-height: 30px;
		.delbtn{
			font-size: 26rpx;
			border: 1px solid #999;
			color: #666;
			padding: 5rpx 20rpx;
			border-radius: 20rpx;
		}
	}
	.tip{
		text-align: right;
		margin-top: 20rpx;
		color: #999;
	}
}
.recommend{
	padding: 0 20rpx 20rpx;
	color: #666;
	.til{
		margin-bottom: 20rpx;
		.text{margin-left: 10rpx;}
	}
	
}
.cart-bottom{
	position: relative;
	z-index: 1001;
	height: 98rpx;
	.inner{
		position: fixed;
		background-color: #fff;
		height: 98rpx;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 0 20rpx;
		padding-left: 0;
		.total-price{
			font-size: 30rpx;
			color: #333;
			font-weight: 600;
			margin-left: 30rpx;
		}
		.btn{
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 50rpx;
			padding: 0 50rpx;
			background-color: #eee;
			color: #333;
			text-align: center;
			&.active{
				background-color: #FF3C3F;
				color: #fff;
			}
		}
	}
}
</style>