<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">
					<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">
								<text class="red" style="font-size: 24rpx;">供货价</text>
								<text class="price">¥ <text class="price-num">{{item.patchPrice}}</text></text>
							</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">
						<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 {
				downOption: {},
				// 上拉加载的配置(可选, 绝大部分情况无需配置)
				upOption: {
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						tip: '暂无相关数据'
					}
				},
				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;
					price = item.patchPrice
				  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.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); //追加新数据
					// 请求成功,隐藏加载状态
					//方法一(推荐): 后台接口有返回列表的总页数 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 => {
					item.checked = selectAll
					// if(item.quantity<=item.stock){
					// 	item.checked = selectAll
					// }
				})
			},
			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({cartId:id,num:num,type:0}).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);
				this.cansubmit = false;
				let param = {};
				param.goodsList = this.selectGoods.map(item=>{
					return {goodsId:item.goodsId,quantity:item.quantity}
				})
				param.ifCartSubmint = true;
				
				this.$u.api.submitOrder(param).then(res=>{
					uni.$u.route('/shopping/paysuccess');
					this.cansubmit = true;
				}).catch(err=>{
					console.log('getAddrList',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;
		}
	}
	.product:last-child{
		margin-bottom: 0;
		border-bottom: 0;
		padding-right: 0;
	}
	.til{
		position: sticky;
		background-color: #fff;
		z-index: 999;
		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;
		.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>