<template>
	<view class="pages">
		<!-- head -->
		<view class="scrollPage-header">
			<view :style="{height:statusBarHeight+'px'}"></view>
			<view class="header-title">
				<view class="header-left" @click="goBack">
					<image style="width: 16px; height: 16px;margin-right:3px;" mode="aspectFit" src="../static/arrow-left.png"></image>
					<text>返回</text>
				</view>
				<view class="header-title"><text class="ellipsis-one" overflow="ellipsis">购物车</text></view>
				<view class="header-right"></view>
			</view>
		</view>
		<view class="cart-body">
				<!-- 内容 -->
				<scroll-view 
				scroll-y 
				class="cart-list" 
				type="custom" 
				@scrolltolower="onreachBottom">
					<sticky-header>
						 <!-- 头部 -->
						 <view class="cart-head" v-if="total>0">
						 	<view class="cart-head-left">共<text>{{total}}</text>款商品</view>
						 	<view class="cart-head-right">
								<view class="cart-head-btton blue" @click="editAll">
									<text>{{editFlag?'完成':'编辑'}}</text>
								</view>
							</view>
						 </view>
					</sticky-header>
					<productItem
					v-for="(item, index) in list"
					:key="index"  
					:index="index"
					:list="item" 
					@changeQty="changeQty" 
					@check="chooseItem"
					@remove="removeCart">
					</productItem>
					<!-- loading -->
					<view class="loading-bar" v-if="total>0 && status!='loading'">{{noDataText}}</view>
					<view class="empty-bar" v-if="total==0 && status!='loading'">
						<image mode="aspectFit" :src="empty.imgUrl"></image>
						<view>{{empty.tip}}</view>
					</view>
				</scroll-view>
				<!-- 底部 -->
				<view class="cart-footer" v-if="total>0">
					<view class="cart-footer-box">
						<view class="cart-footer-left">
								<view class="cart-footer-left-all" @click="chooseAll">
									<view class="cart-footer-left-all-icon">
										<uni-icons v-if="allDisabled&&!editFlag" type="circle-filled" size="24" color="#ccc"></uni-icons>
										<uni-icons v-else :type="allChecked?'checkbox-filled':'circle'" size="24" :color="allChecked?'#dd0000':'#666'"></uni-icons>
									</view>
									<view class="cart-footer-left-all-text">
										<text>全选</text>
									</view>
								</view>
						</view>
						<view class="cart-footer-right">
							<view class="cart-footer-left-price" v-if="!editFlag && totalAmount">
								<view class="cart-footer-left-price-text">
									<text>合计：</text>
								</view>
								<view class="cart-footer-left-price-num">
									<text>￥{{Number(totalAmount).toFixed(2)}}</text>
								</view>
							</view>
							<!-- <view class="cart-head-btton red" v-if="editFlag" @click="clearAll">
								<text>清空购物车</text>
							</view> -->
							<view class="cart-footer-right-button">
								<button class="btns" :loading="loading" v-if="!editFlag" type="warn" size="mini" @click="settlement">去结算({{totalNum}})</button>
								<button v-else class="btns" type="warn" plain size="mini" @click="batchRemove">删除</button>
							</view>
						</view>
					</view>
					<view :style="{height:safeAreaBottom+'px'}"></view>
				</view>
		</view>
	</view>
</template>

<script>
	import {
	    mapState,
	    mapMutations,
	} from 'vuex'
	import productItem from '@/pagesB/cart/productitem.vue'
	import { getCartList, updateCart, deleteCart } from '@/api/cart.js'
	import { purchaseSave } from '@/api/purchase.js'
	export default {
		components:{
			productItem
		},
		onLoad() {
			// 计算区域高度
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			this.screenWidth = uni.getSystemInfoSync().windowWidth
			this.screenHeight = uni.getSystemInfoSync().windowHeight
			this.safeAreaBottom = uni.getSystemInfoSync().safeAreaInsets.bottom
			// 获取列表数据
			this.pageInit()
		},
		data() {
			return {
				loading: false,
				status: 'loading',
				noDataText: '暂无产品',
				empty: {
					tip: '暂无产品',
					imgUrl: '/static/nodata.png'
				},
				// 查询条件
				pageNo: 1,
				pageSize: 5,
				list: [],
				total: 0,
				totalAmount: 0,
				totalNum: 0,
				editFlag: false,
				allChecked: false,
				screenWidth: 325,
				screenHeight: 0,
				statusBarHeight: 44,
				safeAreaBottom: 0,
			}
		},
		computed: {
			...mapState(['hasLogin']),
			userInfo(){
				return this.$store.state.vuex_userInfo
			},
			allDisabled(){
				let ret = false
				if(!this.editFlag){
					this.list.forEach(key => {
						ret = key.every(item => item.status==0||item.dealerScopeFlag==0)
					})
				}
				return ret
			}
		},
		methods: {
			goBack(){
				uni.navigateBack()
			},
			pageInit(){
				this.pageNo = 1
				this.list = []
				this.getRow()
			},
			// 查询列表
			getRow (pageNo) {
			  let _this = this
			  if (pageNo) {
			    this.pageNo = pageNo
			  }
			  let params = {
			    pageNo: this.pageNo,
			    pageSize: this.pageSize,
				queryWord: this.queryWord
			  }
			  this.status = "loading"
			  getCartList(params).then(res => {
				if (res.status == 200) {
				  const list = res.data.list
				  const ret = []
				  list.forEach(key => {
						ret.push({
							id: key.id,
							checked: this.allChecked,
							cartSn: key.cartSn,
							price: key.price,
							qty: key.qty,
							productSn: key.productSn,
							productName: key.productEntity.productName,
							productImage: key.productEntity.images,
							productCode: key.productEntity.code,
							productOrigCode: key.productEntity.origCode,
							unit: key.productEntity.unit,
							status: key.status,
							dealerScopeFlag: key.dealerScopeFlag
						})
				  })
				  _this.list.push(ret)
				  _this.total = res.data.count || 0
				  _this.status = _this.total>=_this.list.length ? "nomore" : 'loadmore'
				  _this.noDataText = _this.total>=_this.list.length ? '没有更多了' : '加载更多'
				} else {
				  _this.list = []
				  _this.total = 0
				  _this.status = 'loadmore'
				  _this.noDataText = res.message
				}
			  })
			},
			// scroll-view到底部加载更多
			onreachBottom() {
				// 判断是否最后一页
				const maxPages = Math.ceil(this.total / this.pageSize)
				if(this.pageNo >= maxPages){
					this.status = "nomore"
					this.noDataText = '没有更多了'
				}else{
					this.pageNo += 1
					this.getRow()
				}
			},
			// 根据cartSn查找
			getItemById(cartSn){
				const a = this.list.findIndex(k => k.find(s=> s.cartSn == cartSn))
				const b = a>=0 ? this.list[a].findIndex(s=> s.cartSn == cartSn) : -1
				return {p:a,s:b}
			},
			// 已选产品变更数量
			changeQty(val,cartSn){
				uni.showLoading({
					title: '加载中'
				})
				updateCart({
					cartSn: cartSn,
					qty: val
				}).then(res => {
					if(res.status == 200){
						const crow = this.getItemById(cartSn)
						if(crow.p>=0&&crow.s>=0){
							this.list[crow.p][crow.s].qty = val
							this.list[crow.p].splice()
							// 合计
							this.getChooseHeji()
						}
					}
					uni.hideLoading()
				})
			},
			// 单选择
			chooseItem(cartSn){
				const crow = this.getItemById(cartSn)
				if(crow.p>=0&&crow.s>=0){
					this.list[crow.p][crow.s].checked = !this.list[crow.p][crow.s].checked
					// 合计
					this.getChooseHeji()
					// 判断是否全选
					this.isAllChecked()
				}
			},
			// 判断是否全选
			isAllChecked(){
				if(this.editFlag){
					this.allChecked = this.list.every(key => key.every(item => item.checked))
				}else{
					this.allChecked = this.list.every(key => key.every(item => item.checked && (item.status==1||item.dealerScopeFlag==1)))
				}
			},
			// 编辑
			editAll(){
				this.editFlag = !this.editFlag
				this.list.forEach(key => {
					key.forEach(item => {
						item.edit = this.editFlag
						if(item.status==0||item.dealerScopeFlag==0){
							item.checked = false
						}
					})
				})
				// 合计
				this.getChooseHeji()
				// 判断是否全选
				this.isAllChecked()
			},
			// 清空购物车
			clearAll(){
				const _this = this
				uni.showModal({
					title: '提示',
					content: '确定清空购物车？',
					confirmText: '确定',
					success(res) {
						if(res.confirm){
							uni.showLoading({
								title: '正在清空...',
								mask: true
							})
							
						}
					}
				})
			},
			// 全选
			chooseAll(){
				if(this.allDisabled){
					return
				}
				this.allChecked = !this.allChecked
				this.list.forEach(key => {
					key.forEach(item => {
						if(item.status == 1 || item.dealerScopeFlag == 1){
							item.checked = this.allChecked
						}
					})
				})
				// 合计
				this.getChooseHeji()
			},
			//单个删除
			removeChoose(cartSn,isBatch){
				// 删除项
				const crow = this.getItemById(cartSn)
				if(crow.p>=0&&crow.s>=0){
					this.list[crow.p].splice(crow.s, 1);
					this.total = this.total - 1
					// 合计
					if(!isBatch){
						this.getChooseHeji()
						// 判断是否全选
						this.isAllChecked()
					}
				}
			},
			// 批量删除
			batchRemove(){
				if(this.totalNum==0){
					uni.showToast({
						title: '请选择产品',
						icon: 'none'
					})
					return false
				}
				const _this = this
				uni.showModal({
					title: '提示',
					content: '确定删除商品吗？',
					confirmText: '确定',
					success(res) {
						if(res.confirm){
							const snList = []
							 _this.list.forEach(item => {
							 	item.filter(k=>k.checked).forEach(s=>{
							 		snList.push(s.cartSn)
							 	})
							 })
							  
							 // 删除购物车
							 _this.removeCart(snList,true)
						}
					}
				})
			},
			// 删除商品
			removeCart(snList,isBatch){
				const _this = this
				uni.showLoading({
					title: '删除中'
				})
				deleteCart({cartSns:snList}).then(ret => {
					 if(ret.status == 200){
						 uni.showToast({
							 title: '删除成功',
							 icon: 'none'
						 })
						 snList.forEach(sn => {
							 _this.removeChoose(sn,isBatch)
						 })
						 // 合计,批量操作
						 if(isBatch){
							 // 如果全选
							 if(_this.allChecked){
								 _this.list = []
								 _this.allChecked = false
							 }
							 _this.getChooseHeji()
							 // 判断是否全选
							 this.isAllChecked()
						 }
					 }
					 uni.hideLoading()
				})
			},
			// 去结算
			settlement(){
				if(this.totalAmount>0){
					 this.submitOrder()
				}else{
					uni.showToast({
						title: '请选择产品',
						icon: 'none'
					})
				}
			},
			// 去结算
			submitOrder(){
				const _this = this
				// 获取已选商品
				const detailList = []
				const cartSn = []
				const soldOutSn = []
				const sellOutSn = []
				this.list.forEach(key => {
					key.filter(item=>item.checked).forEach(item => {
						// 已下架产品提示
						if(item.status == 0){
							soldOutSn.push(item.productCode)
						}
						//售罄产品提示
						else if(item.dealerScopeFlag == 0){
							sellOutSn.push(item.productCode)
						}else{
							detailList.push({
								productSn:item.productSn,
								productCode:item.productCode,
								qty: item.qty,
								price:item.price,
							})
							cartSn.push(item.cartSn)
						}
					})
				})
				
				// 提示信息
				if(soldOutSn.length || sellOutSn.length){
					uni.showModal({
						title: '提示',
						content: (soldOutSn.length ? `产品${soldOutSn.join(',')}已下架，`:'')+(sellOutSn.length?`产品${sellOutSn.join(',')}已售罄，`:'')+`不可采购。是否继续采购其他产品？`,
						success(res) {
							if(res.confirm){
								_this.submitForm(detailList,cartSn)
							}
						}
					})
					return
				}
				
				// 提交
				this.submitForm(detailList,cartSn)
			},
			// 确认提交
			submitForm(){
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				this.loading = true
				purchaseSave({
					detailList: detailList
				}).then(res => {
					this.loading = false
					uni.hideLoading()
					if(res.status == 200){
						// 删除已提交产品
						this.removeCart(cartSn,true)
						res.data.detailList = []
						this.$store.state.vuex_tempData = res.data
						uni.navigateTo({
							url: "/pagesB/procureOrder"
						})
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			// 计算总款数、合计、数量
			getChooseHeji(){
				this.totalAmount = 0
				this.totalNum = 0
				this.list.forEach(key => {
					key.filter(item=>item.checked).forEach(item => {
						this.totalAmount += item.price * item.qty // 总金额
						this.totalNum += item.qty // 总数量
					})
				})
			},
		}
	}
</script>

<style lang="less">
.pages{
	height: 100vh;
	display: flex;
	flex-direction: column;
	.scrollPage-header{
		z-index: 1;
		.header-title{
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 10px;
			height: 44px;
			background-color: #FFFFFF;
			box-shadow: 0px 1px 0px 0px #E6E6E6;
			.header-title{
				font-size: 16px;
				color: #333333;
				max-width: 70%;
			}
			.header-left{
				display: flex;
				align-items: center;
				text{
					font-size: 14px;
					color: #333333;
					margin-left: 5px;
				}
			}
			.header-right{
				width: 50px;
			}
		}
	}
	.cart-body{
		position: relative;
		flex-grow: 1;
		display: flex;
		flex-direction: column;
		.cart-head{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 20rpx;
			background-color: #FFFFFF;
			height: 40px;
			.cart-head-left{
				display: flex;
				align-items: center;
				font-size: 28rpx;
				color: #333333;
				height: 100%;
				text{
					color: #d81e06;
					margin: 0 10rpx;
				}
			}
			.cart-head-right{
				display: flex;
				align-items: center;
			}
			.red{
				color: #d81e06;
			}
			.blue{
				color: #2196F3;
			}
			.cart-head-btton{
				height: 100%;
				font-size: 28rpx;
				margin-right: 10px;
			}
		}
		.cart-list{
			flex-grow: 1;
			background-color: #F5F5F5;
			width: 100%;
			.loading-bar{
				text-align: center;
				padding: 10px 0;
				color: #999999;
			}
			.empty-bar{
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 20px 0;
				image{
					width: 100px;
					height: 100px;
				}
				view{
					font-size: 14px;
					color: #999999;
					margin-top: 10px;
				}
			}
		}
		.cart-footer{
			width: 100%;
			background-color: #FFFFFF;
			.cart-footer-box{
				width: 100%;
				height: 100rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
			.cart-footer-left{
				display: flex;
				align-items: center;
				padding: 0 20rpx 0 36rpx;
				.cart-footer-left-all{
					display: flex;
					align-items: center;
					.cart-footer-left-all-text{
						margin-left: 10rpx;
						font-size: 28rpx;
						color: #333333;
					}
				}
			}
			.cart-footer-right{
				padding: 0 20rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.cart-footer-left-price{
					display: flex;
					align-items: center;
					.cart-footer-left-price-text{
						font-size: 28rpx;
						color: #333333;
					}
					.cart-footer-left-price-num{
						font-size: 28rpx;
						color: #d81e06;
					}
				}
				.red{
					color: #d81e06;
				}
				.cart-head-btton{
					height: 100%;
					font-size: 28rpx;
					color: #333333;
				}
				.cart-footer-right-button{
					display: flex;
					align-items: center;
					margin-left: 20rpx;
					text-align: right;
					.btns{
						border-radius: 100rpx;
						height: 36px;
					}
				}
			}
		}
	}
}
</style>
