<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="showBalanceAuth&&subsidyAmount">
								<view class="flex align_center" v-if="storeAccount">抵扣（余额：￥{{storeAccount.giveBalance}}）</view>
								<view class="flex align_center" v-if="!disKdk" @click="hasKdk=!hasKdk">
									<uni-icons size="18" :type="hasKdk?'checkbox-filled':'checkbox'" color="#2196f3"></uni-icons> 
									<text>￥{{subsidyAmount}}</text>
								</view>
								<view class="flex align_center" v-else>
									<uni-icons size="18" type="circle-filled" color="#aaa"></uni-icons>
									<text>￥{{subsidyAmount}}</text>
								</view>
							</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 class="product-price-item">
								<text>合计：</text>
								<text class="price">￥{{settleAmount.join('.')}}</text>
							</view>
						</view>
						<view style="margin-top: 10px;">
							<payOptions v-model="payType" :hasBalancePay="hasBalancePay" :disableCz="disCzOption" :hasPay="shelfInfo&&shelfInfo.payOnlineFlag&&shelfInfo.payOnlineFlag=='1'" @change="v=>hasKdk=v!=2" :balance="storeAccount?storeAccount.rechargeBalance:0"></payOptions>
						</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 payOptions from '../components/payOptions.vue'
	import { purchaseSave, purchaseCheck, purchasePay } from '@/api/purchase.js'
	export default {
		components:{
			productItem,
			sklineHeader,
			payModal,
			payOptions
		},
		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, // 总优惠
				subsidyAmount:0, // 总可抵扣金额
				totalCoupon: 0, // 总代金券
				totalNum: 0, // 总数量
				screenWidth: 325, // 屏幕宽度
				screenHeight: 0, // 屏幕高度
				statusBarHeight: 44, // 状态栏高度
				safeAreaBottom: 0, // 底部安全区域高度
				showPopu: false, // 弹框
				payData: null ,// 付款参数
				payType: 0, // 支付方式，0抵扣、1微信，2线下
				hasKdk: false, // 是否使用抵扣金额
			}
		},
		watch: {
			hasBalancePay(v){
				this.payType = v ? 0 : (this.hasPay ? 1 : 2)
			}
		},
		computed: {
			...mapState(['hasLogin']),
			userInfo(){
				return this.$store.state.vuex_userInfo
			},
			// 结算金额
			settleAmount(){
				return Number(this.hasKdk?this.totalAmount-this.subsidyAmount:this.totalAmount).toFixed(2).toString().split('.')
			},
			// 货架经销商信息
			shelfInfo(){
				return this.$store.state.vuex_storeShelf
			},
			// 抵扣余额支付是否可用
			showBalanceAuth(){
				return this.$store.state.vuex_showBalanceAuth
			},
			// 充值余额支付是否显示，合计金额小于充值余额
			hasBalancePay(){
				return this.showBalanceAuth&&this.storeAccount&&!this.disCzOption
			},
			// 抵扣余额
			storeAccount(){
				return this.$store.state.vuex_storeAccount
			},
			// 禁用抵扣金额
			disKdk(){
				const kdk = this.storeAccount&&this.subsidyAmount>0&&this.subsidyAmount<=this.storeAccount.giveBalance
				return !kdk
			},
			// 禁用的支付选项
			disCzOption(){
				const ta = this.hasKdk&&this.totalAmount?this.totalAmount-this.subsidyAmount:this.totalAmount
				return ta>this.storeAccount.rechargeBalance
			},
			// 最小支付金额
			minPayAmount(){
				const shelfInfo = this.shelfInfo
				return shelfInfo&&shelfInfo.minAmount ? shelfInfo.minAmount : 0
			},
			//是否开启线上支付
			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){
					 if(this.hasPay && this.minPayAmount>this.totalAmount){
					 	uni.showModal({
							content: '支付金额不能小于'+this.minPayAmount+'元!',
							showCancel:false,
							confirmText:'知道了'
						})
					 }else{
						this.submitOrder()
					 }
				}else{
					uni.showToast({
						title: '请选择产品',
						icon: 'none',
						mask: true,
						duration: 3000
					})
				}
			},
			// 去结算
			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,
							promoProductSn: item.shopProductSubsidy&&item.shopProductSubsidy.productSubsidySn,
							resultValue: item.shopProductSubsidy&&item.shopProductSubsidy.subsidyAmount
						 })
						 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,
								promoProductSn: item.promoProductSn,
								resultValue: item.resultValue
							}
						})
						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,
					payOnlineType: this.payType == 0 ? 'RECHARGE_BALANCE' : this.payType == 1 ? 'PAY_WECHAT_ONLINE' : ''
				}).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:'SETTLE_BILL',
								payUserOpenId: this.$store.state.vuex_openid || uni.getStorageSync('openid'),
								settleType: this.payType == 0 ? 'RECHARGE_BALANCE' : 'PAY_WECHAT_ONLINE'
							}).then(ret=>{
								if(ret.status == 200){
									// 微信支付
									if(this.payType == 1){
										this.showPopu = true
										this.payData = ret.data?ret.data.payRequestRest:null
									}else{
										// 余额支付
										this.payComplete(null,true)
									}
								}else{
									uni.showToast({
										title: ret.message,
										icon: 'none'
									})
								}
							})
						}else{
							this.payComplete(null,true)
						}
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			// 订单详情页
			payComplete(data){
				// 创建成功，跳转到订单详情页
				uni.redirectTo({
					url: "/pagesB/procureOrder/orderDetail?purchaseSn="+this.$store.state.vuex_tempOrderData.purchaseSn
				})
			},
			// 计算总款数、合计、数量
			getChooseHeji(){
				this.totalAmount = 0
				this.totalDiscount = 0
				this.subsidyAmount = 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.shopProductSubsidy&&!item.shopPromoProduct){
							// 抵扣金额是否小于售价
							const isXPrice = item.shopProductSubsidy.subsidyAmount<=item.price
							this.subsidyAmount += isXPrice ? (item.shopProductSubsidy.subsidyAmount||0) * item.qty : 0
						}
						// 如果是返券类型
						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
					})
				})
				// 总可抵扣金额有余额支付权限，且总抵扣金额小于等于抵扣余额
				this.hasKdk = this.subsidyAmount>0&&this.storeAccount&&this.subsidyAmount<=this.storeAccount.giveBalance&&this.showBalanceAuth
				// 默认支付方式
				this.payType = this.hasBalancePay ? 0 : (this.hasPay ? 1 : 2)
			},
		}
	}
</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;
						}
						&:last-child{
							font-size: 28rpx;
							justify-content: flex-end;
							.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>
