<template>
	<view class="pages">
		<!-- head -->
		<sklineHeader title="确认采购订单"></sklineHeader>
		<view class="cart-body">
				<!-- 内容 -->
				<scroll-view 
				scroll-y 
				class="cart-list" 
				type="custom" 
				:bounces="false"
				>
					<sticky-header>
						 <!-- 头部 -->
						 <view class="cart-head" v-if="total>0">
						 	<view class="cart-head-left">商品列表</view>
						 	<view class="cart-head-right">
								共<text>{{total}}</text>款<text>{{totalNum}}</text>件商品
							</view>
						 </view>
					</sticky-header>
					<productItem
					v-for="(item, index) in list"
					:key="index"  
					:list="item" 
					type="views"
					>
					</productItem>
					<!-- loading -->
					<view class="loading-bar" v-if="total>0 && status!='loading'">{{noDataText}}</view>
					<view class="empty-bar" v-if="total==0 && status!='loading'" @click="goBack">
						<view>{{empty.tip}}</view>
					</view>
					<!-- 商品总计 -->
					<view class="product-price">
						<view>
							<view class="product-price-item">
								<text>合计</text>
								<text class="price">￥{{Number(totalAmount).toFixed(2)}}</text>
							</view>
							<view class="product-price-item" v-if="totalDiscount">
								<text>优惠金额</text>
								<text class="price">￥{{Number(totalDiscount).toFixed(2)}}</text>
							</view>
							<view class="product-price-item" v-if="totalCoupon">
								<text>代金券</text>
								<text class="price">￥{{Number(totalCoupon).toFixed(2)}}</text>
							</view>
						</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-price-num">
								￥<text>{{settleAmount[0]}}</text>.{{settleAmount[1]}}
							</view>
						</view>
						<view class="cart-footer-right">
							<view></view>
							<view class="cart-footer-right-button">
								<button class="btns" :loading="loading" type="warn" size="mini" @click="settlement">提交订单</button>
							</view>
						</view>
					</view>
					<view :style="{height:safeAreaBottom+'px'}"></view>
				</view>
		</view>
		<!-- 付款弹框 -->
		<payModal v-if="hasPay" :showPopu="showPopu" :payInfo="payInfo" :payData="payData" @close="showPopu=false" @payComplete="payComplete"></payModal> 
	</view>
</template>

<script>
	import {
	    mapState,
	    mapMutations,
	} from 'vuex'
	import productItem from '@/pagesB/cart/productitem.vue'
	import sklineHeader from '../../components/skline/sklineHeader.vue'
	import payModal from '../components/payModal.vue'
	import { purchaseSave, purchaseCheck, purchasePay } from '@/api/purchase.js'
	export default {
		components:{
			productItem,
			sklineHeader,
			payModal
		},
		onLoad() {
			// 计算区域高度
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			this.screenWidth = uni.getSystemInfoSync().windowWidth
			this.screenHeight = uni.getSystemInfoSync().windowHeight
			this.safeAreaBottom = uni.getSystemInfoSync().safeAreaInsets.bottom
			// 列表原始数据
			this.list = this.$store.state.vuex_tempData||[]
			this.getChooseHeji()
		},
		onUnload() {
			this.$store.state.vuex_tempData = null
		},
		onShow() {
		},
		data() {
			return {
				loading: false,
				status: 'loading',
				noDataText: '暂无产品',
				empty: {
					tip: '暂无产品',
				},
				// 查询条件
				list: [], // 列表数据
				total: 0, // 总款数
				totalAmount: 0, // 总金额
				totalDiscount:0, // 总优惠
				totalCoupon: 0, // 总代金券
				totalNum: 0, // 总数量
				screenWidth: 325, // 屏幕宽度
				screenHeight: 0, // 屏幕高度
				statusBarHeight: 44, // 状态栏高度
				safeAreaBottom: 0, // 底部安全区域高度
				showPopu: false, // 弹框
				payData: null ,// 付款参数
			}
		},
		computed: {
			...mapState(['hasLogin']),
			userInfo(){
				return this.$store.state.vuex_userInfo
			},
			// 结算金额
			settleAmount(){
				return Number(this.totalAmount).toFixed(2).toString().split('.')
			},
			// 货架经销商信息
			shelfInfo(){
				return this.$store.state.vuex_storeShelf
			},
			//是否开启线上支付
			hasPay(){
				const shelfInfo = this.shelfInfo
				return shelfInfo&&shelfInfo.payOnlineFlag&&shelfInfo.payOnlineFlag=='1'
			},
			// 付款信息
			payInfo(){
				return this.$store.state.vuex_tempOrderData
			}
		},
		methods: {
			goBack(){
				uni.navigateBack()
			},
			// 去结算
			settlement(){
				if(this.totalAmount>0){
					 this.submitOrder()
				}else{
					uni.showToast({
						title: '请选择产品',
						icon: 'none'
					})
				}
			},
			// 去结算
			submitOrder(){
				const _this = this
				// 获取已选商品
				const detailList = []
				const cartSn = []
				_this.list.forEach(key => {
					key.filter(item=>item.checked).forEach(item => {
						 detailList.push({
						 	productSn:item.productSn,
						 	productCode:item.productCode,
						 	qty: item.qty,
						 	price:item.orginPrice,
							promoSn: item.promoSn
						 })
						 cartSn.push({
							 cartSn: item.cartSn,
							 productSn:item.productSn
						 })
					})
				})
				
				// 校验并提示信息
				purchaseCheck({detailList:detailList}).then(res => {
					if(res.status == 200){
						const promoChangeFlag = res.data.promoChangeFlag
						// 活动变更
						if(promoChangeFlag){
							uni.showModal({
								title: '提示',
								content: '促销活动已变更，请返回购物车重新选择？',
								confirmText:'确定刷新',
								success(ret) {
									if(ret.confirm){
										_this.goBack()
										uni.$emit('refashCartList')
									}
								}
							})
							return
						}
						const successList = res.data.successList.map(item => {
							return {
								productSn:item.productSn,
								productCode: item.productCode,
								qty: item.qty,
								price: item.price,
								promoSn: item.promoSn
							}
						})
						const delSn = cartSn.filter(item => successList.find(k => k.productSn == item.productSn)).map(item => item.cartSn)
						const removeList = res.data.removeList.map(item => item.productCode)
						const selloutList = res.data.selloutList.map(item => item.productCode)
						console.log(successList,delSn)
						console.log(removeList,selloutList)
						// 有已下架或已售罄产品提示
						if(removeList.length || selloutList.length){
							uni.showModal({
								title: '提示',
								content: (removeList.length ? `产品${removeList.join(',')}已下架，`:'')+(selloutList.length?`产品${selloutList.join(',')}已售罄，`:'')+`不可采购。`+(successList.length?'是否继续采购其他产品？':''),
								showCancel: successList.length,
								confirmText: successList.length?'确定':'知道了',
								success(ret) {
									if(ret.confirm && successList.length){
										_this.submitForm(successList,delSn)
									}
								}
							})
						}else{
							// 提交
							_this.submitForm(successList,delSn)
						}
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			// 确认提交
			submitForm(detailList,cartSn){
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				this.loading = true
				purchaseSave({
					detailList: detailList
				}).then(res => {
					this.loading = false
					uni.hideLoading()
					if(res.status == 200){
						// 删除已提交产品
						uni.$emit('removeCatGood',cartSn,true,false)
						res.data.detailList = []
						this.$store.state.vuex_tempOrderData = res.data
						// 这里判断是否开通支付，如果开通打开确认付款弹框
						if(this.hasPay){
							purchasePay({
								bizSn:res.data.purchaseSn,
								bizNo:res.data.purchaseNo,
								bizType:'PURCHASE',
								payUserOpenId: this.$store.state.vuex_openid || uni.getStorageSync('openid')
							}).then(res=>{
								this.showPopu = true
								this.payData = res.data?res.data.payRequestRest:null
							})
						}else{
							this.payComplete(null,true)
						}
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			// 订单详情页
			payComplete(data){
				// 创建成功，跳转到订单详情页
				this.showPopu = false
				uni.navigateBack()
				setTimeout(()=>{
					uni.navigateTo({
						url: "/pagesB/procureOrder/orderDetail?purchaseSn="+this.$store.state.vuex_tempOrderData.purchaseSn
					})
				},150)
			},
			// 计算总款数、合计、数量
			getChooseHeji(){
				this.totalAmount = 0
				this.totalDiscount = 0
				this.totalCoupon = 0
				this.total = 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 // 总数量
						this.total += 1 // 总款数
						// 如果是返券类型
						if(item.promoType=='BUY_PROD_GIVE_VALID'){
							this.totalCoupon += item.resultValue * item.qty
						}
						// 特价
						if(item.promoType=='PROMO_PROD'){
							this.totalDiscount += (item.orginPrice - item.conditionValue) * item.qty
						}
						// 满赠
						item.giftQty = item.promoType=='BUY_PROD_GIVE_PROD' ? Math.floor(item.qty / item.conditionValue)*item.resultValue : 0
					})
				})
			},
		}
	}
</script>

<style lang="less">
.pages{
	height: 100vh;
	display: flex;
	flex-direction: column;
	.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%;
			}
			.cart-head-right{
				display: flex;
				align-items: center;
				font-size: 24rpx;
				color: #666;
				height: 100%;
				text{
					color: #d81e06;
					margin: 0 10rpx;
				}
			}
		}
		.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;
				margin-top: 20vh;
				image{
					width: 100px;
					height: 100px;
				}
				view{
					font-size: 14px;
					color: #999999;
					margin-top: 10px;
				}
			}
			.product-price{
				padding:0 6px;
				margin: 6px 0;
				> view{
					background: #fff;
					padding: 10px;
					border-radius: 10px;
					.product-price-item{
						display:flex;
						align-items: center;
						justify-content: space-between;
						padding: 6px 0;
						font-size: 24rpx;
						.price{
							color: #333;
						}
						&:first-child{
							font-size: 28rpx;
							.price{
								color: #d81e06;
								font-weight: bold;
							}
						}
					}
				}
			}
		}
		.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: baseline;
				padding: 0 20rpx 0 36rpx;
				font-size: 24rpx;
			}
			.cart-footer-left-price-num{
				display: flex;
				align-items: baseline;
				font-size: 24rpx;
				color: #d81e06;
				text{
					font-size: 36rpx;
				}
			} 
			.cart-footer-right{
				padding: 0 20rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				flex-grow:1;
				.cart-footer-right-button{
					display: flex;
					align-items: center;
					margin-left: 20rpx;
					text-align: right;
					.btns{
						border-radius: 100rpx;
						height: 36px;
						padding: 0 10px;
						min-width: 80px;
					}
				}
			}
		}
	}
}
</style>
