<template>
	<view class="scrollPage">
		<!-- 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">{{title}}</text></view>
				<view class="header-right"></view>
			</view>
		</view>
		<!-- body -->
		<scroll-view 
		class="scrollPage-body" 
		:style="{height: (screenHeight - statusBarHeight - safeAreaBottom - 94) + 'px'}" 
		scroll-y="true" 
		type="custom" 
		:bounces="false"
		@scrolltolower="reachBottom">
			<!-- 搜索，吸顶 -->
			<sticky-header>
				<view class="search-head">
					<uni-search-bar radius="100" placeholder="请输入产品名称/轮胎规格" clearButton="auto" cancelButton="none" @confirm="searchList" @clear="searchList" />
				</view>
			</sticky-header>
			<!-- 产品列表 -->
			<productItem
			v-for="(item,index) in list"
			:key="index" 
			:list="item" 
			:index="index"
			:itemWidth="(screenWidth*0.94-screenWidth*0.03)*0.5"
			:gap="screenWidth*0.03"
			@chooseProduct="chooseProduct"
			></productItem>
			<!-- loading -->
			<view class="loading-bar" v-if="list.length && (loading||loadEnd)">{{loadText}}</view>
			<view class="empty-bar" v-if="total==0&&!loading">
				<image mode="aspectFit" :src="empty.imgUrl"></image>
				<view>{{empty.tip}}</view>
			</view>
		</scroll-view>
		<!-- footer -->
		<view class="scrollPage-footer">
			<view>
				<view class="bottom-bar-left">
					<view class="bottom-bar-left-item">
						<view class="bottom-bar-left-item-icon" @click="openChoose">
							<image style="width: 20px; height: 20px;" mode="aspectFit" src="./static/cart.png"></image>
							<text class="badge" v-if="totalNum">{{totalNum>99?'99+':totalNum}}</text>
						</view>
					</view>
					<view class="bottom-bar-left-item">
						<!-- 合计：<view class="price-txt">￥<text>{{totalAmount}}</text></view> -->
					</view>
				</view>
				<view :class="'bottom-bar-right'" @click="submitOrder">
					<view class="bottom-bar-right-item">去结算</view>
				</view>
			</view>
			<view :style="{height:safeAreaBottom+'px'}"></view>
		</view>
		<!-- 已选产品 -->
		<page-container
		:show="showChoosePopu" 
		:round="true"
		:z-index="10"
		position="bottom" 
		custom-style="height:80%"
		@afterenter="openRender"
		@afterleave="closePopu">
			<view class="popup-body" v-if="showSwipeAction">
				<scroll-view 
				:style="{width:screenWidth + 'px',height:'100%'}" 
				scroll-y="true" 
				type="custom"
				>
						<sticky-header>
							<view class="choose-title">
								<view class="choose-left">
									<view>已选<text class="p-nums">{{chooseLength}}</text>款产品</view>
									<!-- <button @click="claerChoose" size="mini" type="warn" plain>清空列表</button> -->
									<!-- <button class="editBtn" @click="handleEditChoose" size="mini" type="primary" plain>{{editChoose?'完成':'编辑'}}</button> -->
									<view class="clearBtn" @click="claerChoose">
										<text>清空列表</text>
									</view>
									<view class="editBtn" @click="handleEditChoose">
										<text>{{editChoose?'完成':'编辑'}}</text>
									</view>
								</view>
								<view class="choose-close" @click="showChoosePopu=false">
									<uni-icons type="closeempty" size="28"></uni-icons>
								</view>
							</view>
						</sticky-header>
						<chooseProductItem 
						v-for="(item, index) in showList"
						:key="item.id"  
						:index="index"
						:list="item" 
						:edit="editChoose" 
						@changeQty="changeQty" 
						@remove="removeChoose">
						</chooseProductItem>
						<view style="min-height: 180rpx;"></view>
				</scroll-view>
				<view class="choose-footer">
					<view>
						<view class="choose-footer-left">
							<view class="choose-footer-left-item">
								<!-- 总数：<view><text class="p-nums">{{totalNum}}</text></view> -->
							</view>
							<view class="choose-footer-left-item">
								合计：<view class="price-txt">￥<text>{{totalAmount}}</text></view>
							</view>
						</view>
						<view class="choose-footer-right bg-1" @click="submitOrder">
							<view class="choose-footer-right-item">确认采购</view>
						</view>
					</view>
					<view :style="{height:safeAreaBottom+'px'}"></view>
				</view>
			</view>
		</page-container>
	</view>
</template>

<script>
	import {
	    mapState,
	    mapMutations,
	} from 'vuex'
	import { queryPromoProductByPage } from '@/api/video.js'
	import { purchaseSave } from '@/api/purchase.js'
	import productItem from '@/pagesB/components/productItemSkline.vue'
	import chooseProductItem from '@/pagesB/components/chooseProductItemSkline.vue'
	export default {
		components:{
			productItem,
			chooseProductItem
		},
		data() {
			return {
				title: '促销产品列表',
				pageNo:1,
				pageSize:16,
				total:0,
				list:[],
				loading:false,
				loadEnd: false,
				loadText: '加载中...',
				empty: {
					tip: '暂无产品',
					imgUrl: '/static/nodata.png'
				},
				queryWord:'',
				promoActiveSn:'',
				screenWidth: 750,
				screenHeight: 0,
				statusBarHeight: 44,
				safeAreaBottom: 0,
				// 已选弹框
				showChoosePopu: false,
				showSwipeAction: false,
				chooseList:[],
				editChoose: false,
				choosePageSize: 12,
				// 数量，合计
				chooseLength: 0, //已选产品总款数
				totalAmount: 0, //已选产品总金额
				totalNum: 0, //已选产品总数量
			};
		},
		computed: {
			...mapState(['hasLogin']),
			userInfo(){
				return this.$store.state.vuex_userInfo
			},
			fristLength(){
				return this.chooseList.length > 0 ? this.chooseList[0].length : 0
			},
			showList(){
				return this.showSwipeAction ? this.chooseList : []
			}
		},
		onLoad(opts) {
			this.title = opts.title||'促销产品列表'
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			this.screenWidth = uni.getSystemInfoSync().windowWidth
			this.screenHeight = uni.getSystemInfoSync().windowHeight
			this.safeAreaBottom = uni.getSystemInfoSync().safeAreaInsets.bottom
			 
			// 清空临时数据
			this.$store.state.vuex_tempData = null
			this.promoActiveSn = opts.promoActiveSn
			
			// 查询列表
			this.getList()
			
			this.chooseList = this.getCacheList()
			this.getChooseHeji()
		},
		onUnload(){
			// 存储已选列表值
			const hasCache = this.$store.state.vuex_cartList.find(k => k.sn == this.promoActiveSn)
			if(hasCache){
				hasCache.list = this.chooseList
			}else{
				this.$store.state.vuex_cartList.push({sn:this.promoActiveSn,list: this.chooseList})
			}
			this.$u.vuex('vuex_cartList', this.$store.state.vuex_cartList)
			
			// 清空数据
			this.chooseList = null
			this.list = null
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			// 从缓存获取数据
			getCacheList(){
				const cacheList = this.$store.state.vuex_cartList.find(k => k.sn == this.promoActiveSn)
				return cacheList ? JSON.parse(JSON.stringify(cacheList.list)) : []
			},
			// 滚动到底部
			reachBottom() {
				if(!this.loading && !this.loadEnd){
					this.pageNo++
					this.getList()
				}
			},
			// 搜索
			searchList(event){
				this.loadEnd = false
				this.loadText = '加载中...'
				this.queryWord = event.value
				this.list = []
				this.pageNo = 1
				this.getList()
			},
			// 列表查询
			getList(){
				this.loading = true
				queryPromoProductByPage({
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					queryWord: this.queryWord,
					promoActiveSn: this.promoActiveSn
				}).then(res => {
					this.loading = false
					if(res.status == 200){
						this.total = res.data.count
						if(this.total){
							const list = res.data.list || []
							const ret = []
							// 更新已选状态
							list.forEach(k => {
							  // 如果筛选或分页后，更新页面列表产品数量
							  const row = this.getChooseItemById(k.id)
							  const hasChecked = row.p>=0 && row.s>=0
							  ret.push({
								  id: k.id,
								  cost: k.cost,
								  checked: hasChecked ? true : false,
								  qty: hasChecked ? this.chooseList[row.p][row.s].qty : 0,
								  productCode: k.productCode,
								  productSn: k.productSn,
								  productImage: k.productImage,
								  productName: k.productName,
								  productOrigCode: k.productOrigCode,
								  promoActiveSn: k.promoActiveSn,
								  promoRuleSn: k.promoRuleSn,
								  promoRuleValue: k.promoRuleValue,
								  promoRuleType: k.promoRuleType,
							  })
							})
							// 追加数据
							this.list.push(ret)
							// 判断是否最后一页
							const maxPages = Math.ceil(this.total / this.pageSize)
							if(this.pageNo >= maxPages){
								this.loadEnd = true
								this.loadText = '没有更多了'
							}
						}else{
							this.loadEnd = false
							this.loadText = '暂无产品'
						}
					}
				}).catch(err => {
					this.loading = false
				})
			},
			// 根据id查找chooseList
			getChooseItemById(id){
				const a = this.chooseList.findIndex(k => k.find(s=> s.id == id))
				const b = a>=0 ? this.chooseList[a].findIndex(s=> s.id == id) : -1
				return {p:a,s:b}
			},
			// 计算总款数、合计、数量
			getChooseHeji(){
				this.chooseLength = 0
				this.totalAmount = 0
				this.totalNum = 0
				this.chooseList.forEach(key => {
					this.chooseLength += key.length // 总款数
					key.forEach(item => {
						this.totalAmount += item.cost * item.qty // 总金额
						this.totalNum += item.qty // 总数量
					})
				})
			},
			// 选择产品
			chooseProduct(item,index){
				const rowItem = this.list[index].find(k => k.id == item.id)
				// 新加
				if(!rowItem.checked){
					rowItem.checked = true
					rowItem.qty = 1
					// 存入二维数组中
					const chooselens = this.chooseList.length
					if(chooselens){
						const firstRow = this.chooseList[0]
						if(firstRow.length<this.choosePageSize){
							firstRow.unshift(this.$u.deepClone(rowItem))
						}else{
							this.chooseList.unshift([this.$u.deepClone(rowItem)])
						}
					}else{
						this.chooseList.unshift([this.$u.deepClone(rowItem)])
					}
				}else{
					rowItem.qty = rowItem.qty + 1
					// 已添加，则增加已选列表中的数量
					const row = this.getChooseItemById(rowItem.id)
					if(row.p>=0 && row.s>=0){
						this.chooseList[row.p][row.s].qty = this.chooseList[row.p][row.s].qty + 1
						this.chooseList[row.p].splice()
					}
				}
				// 合计
				this.getChooseHeji()
			},
			// 打开已选产品列表
			openChoose(){
				this.submitOk = false
				if(this.chooseLength){
					uni.showLoading({
						title:'加载中...',
						mask: true
					})
					this.showChoosePopu = true
				}else{
					this.$u.toast(`请选择产品`);
				}
			},
			// 渲染已选产品列表
			openRender(){
				this.showSwipeAction = true
				setTimeout(()=>{
					uni.hideLoading()
				},300)
			},
			// 关闭后
			closePopu(){
				setTimeout(()=>{
					this.showSwipeAction = false
				},300)
				
				this.showChoosePopu = false
				this.editChoose = false
				uni.hideLoading()
				
				// 提交成功
				if(this.submitOk){
					uni.navigateTo({
						url: "/pagesB/procureOrder"
					})
				}
			},
			// 确定清空已选列表
			claerChoose(){
				const _this = this
				uni.showModal({
					title: '提示',
					content: '确定清空已选列表？',
					confirmText: '确定',
					success(res) {
						if(res.confirm){
							uni.showLoading({
								title: '正在清空...',
								mask: true
							})
							_this.clearChooseData()
						}
					}
				})
			},
			// 清空已选数据
			clearChooseData(){
				this.showChoosePopu = false
				this.chooseList = []
				// 合计
				this.getChooseHeji()
				
				// 重置已选状态
				this.list.forEach(key => {
					key.filter(item => item.checked).forEach(item=>{
						item.checked = false
						item.qty = 0
					})
				})
			},
			// 编辑已选产品
			handleEditChoose(){
				this.editChoose=!this.editChoose
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				this.$nextTick(()=>{
					uni.hideLoading()
				})
			},
			// 根据id 获取页面list项
			getListItemById(id){
				const aindex = this.list.findIndex(key => key.find(a => a.id == id))
				const aindex2 = aindex >=0 ? this.list[aindex].findIndex(a => a.id == id) : -1
				return {p:aindex,s:aindex2}
			},
			// 已选产品变更数量
			changeQty(val,id){
				const crow = this.getChooseItemById(id)
				if(crow.p>=0&&crow.s>=0){
					this.chooseList[crow.p][crow.s].qty = val
					this.chooseList[crow.p].splice()
					// 合计
					this.getChooseHeji()
				}
				
				// 更新页面产品数据
				const row = this.getListItemById(id)
				if(row.p>=0 && row.s>=0){
					this.list[row.p][row.s].qty = val
					this.list[row.p].splice()
				}
			},
			//已选产品删除
			removeChoose(id){
				// 删除项
				const crow = this.getChooseItemById(id)
				if(crow.p>=0&&crow.s>=0){
					this.chooseList[crow.p].splice(crow.s, 1);
					// 合计
					this.getChooseHeji()
				}
				
				// 如果没有数据了
				if(this.chooseList.length==0){
					this.clearChooseData()
				}
				
				// 更新列表已选状态
				const row = this.getListItemById(id)
				if(row.p>=0 && row.s>=0){
					this.list[row.p][row.s].qty = 0
					this.list[row.p][row.s].checked = false
					this.list[row.p].splice()
				}
			},
			// 去结算
			submitOrder(){
				if(this.showChoosePopu){
					uni.showLoading({
						title: '提交中...',
						mask: true
					})
					// 展开成一维数组
					const detailList = []
					this.chooseList.forEach(key => {
						key.forEach(item => {
							detailList.push({
									promoActiveSn: this.promoActiveSn,
									promoRuleSn:item.promoRuleSn,
									productSn:item.productSn,
									productCode:item.productCode,
									qty:item.qty,
									price:item.cost,
									giveAmount:item.promoRuleValue
							})
						})
					})
					purchaseSave({
						promoActiveSn: this.promoActiveSn,
						detailList: detailList
					}).then(res => {
						if(res.status == 200){
							res.data.detailList = []
							this.$store.state.vuex_tempData = res.data
							this.clearChooseData()
							this.submitOk = true
						}else{
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					})
				}else{
					this.openChoose()
				}
			}
		}
	}
</script>

<style lang="less">
/* 显示一行省略号 */
.ellipsis-one{
	white-space: nowrap;
	text-overflow: ellipsis;
	overflow: hidden;
	word-break: break-all;
}
.scrollPage{
	height: 100vh;
	display: flex;
	flex-direction: column;
	.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;
		}
	}
	.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;
			}
		}
	}
	.scrollPage-body{
		flex-grow: 1;
		height: 100%;
		.search-head{
			background: #fff;
		}
	}
	.scrollPage-footer{
		background: #fff;
		z-index: 200;
		> view{
			height: 50px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 32upx;
		}
		.bottom-bar-left{
			padding: 0 30upx;
			flex-grow: 1;
			display: flex;
			align-items: center;
		}
		.bottom-bar-left-item{
			padding-right: 20rpx;
			font-size: 24rpx;
			display: flex;
			align-items: center;
			.price-txt{
				color: red;
				display: flex;
				align-items: center;
				text{
					font-size: 36rpx;
				}
			}
		}
		.bottom-bar-left-item-icon{
			position: relative;
			background: #2196F3;
			width: 80rpx;
			height: 80rpx;
			border-radius: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			.badge{
				background: #f44336;
				color: #fff;
				position: absolute;
				left: 50rpx;
				top: -3px;
				font-size: 12px;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50rpx;
				padding: 0 10rpx;
			}
		}
		.bottom-bar-right{
			width: 35%;
			height: 100%;
			background: #066cff;
			display: flex;
			align-items: center;
			justify-content: center;
			.bottom-bar-right-item{
				color: #fff;
			}
		}
		.bg-0{
			background: #066cff;
		}
		.bg-1{
			background: #f44336;
		}
	}
	
	.choose-title{
		display: flex;
		align-items:center;
		justify-content: space-between;
		background: #fff;
		width: 100%;
		border-bottom: 1px solid #eee;
		border-radius: 40rpx 40rpx 0 0;
		> view{
			padding: 20rpx 30rpx;
		}
		.choose-left{
			display: flex;
			align-items:center;
			flex-grow: 1;
			> view{
				display: flex;
				align-items:center;
				flex-grow: 1;
			}
			button{
				padding: 0 10px;
				height: auto;
				font-size: 12px;
				margin-left: 10px;
			}
			.editBtn{
				color: #2196F3;
				justify-content: center;
			}
			.clearBtn{
				color: #ff0000;
				justify-content: center;
			}
		}
		.p-nums{
			color: #2196F3;
			margin: 0 6rpx;
		}
	}
	.popup-body{
		height: 100%;
		position: relative;
	}
	.choose-footer{
		position: fixed;
		bottom: 0;
		left: 0;
		background: #fff;
		z-index: 100;
		width: 100%;
		> view{
			width: 100%;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		.choose-footer-left{
			flex-grow: 1;
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			> view{
				font-size: 28rpx;
			}
			.choose-footer-left-item{
				display: flex;
				align-items: center;
				margin-right: 10px;
				.price-txt{
					color: red;
					display: flex;
					align-items: center;
					text{
						font-size: 36rpx;
					}
				}
			}
		}
		.choose-footer-right{
			width: 35%;
			height: 100%;
			background: #2196F3;
			display: flex;
			align-items: center;
			justify-content: center;
			.choose-footer-right-item{
				color: #fff;
			}
		}
		.bg-1{
			background: #f44336;
		}
	}
}
</style>
