<template>
	<view class="order-content">
		<view class="step">
			<uni-steps :options="[{title: '停车'}, {title: '检查'}, {title: '下单'}]" :active="stepIndex" active-color="rgb(255,0,0)"></uni-steps>
		</view>
		<view class="step-content">
			<!-- 停车 -->
			<view v-if="stepIndex===0" class="step-item step-one">
				<text>请确认车辆是否停到指定位置</text>
				<image src="/static/img/step-one.png" mode="aspectFit"></image>
			</view>
			<!-- 检查 -->
			<view v-if="stepIndex===1" class="step-item step-two">
				<view class="item top">
					<text class="item-text">-请完成以下操作-</text>
					<image src="/static/img/cztis.png" mode="aspectFit"></image>
					<view class="care">
						注意：洗车过程中禁止移动车辆和上下车
					</view>
				</view>
				<view class="item bottom">
					<text class="item-text">超高加装件不能清洗</text>
					<image src="/static/img/zyts.png" mode="aspectFit"></image>
				</view>
			</view>
			<!-- 下单 -->
			<view v-if="stepIndex===2" class="step-item step-three">
				<view class="choose">
					<view class="title">
						请选择服务模式
					</view>
					<view class="list">
						<view :class="['item', serverIndex==index ?'avtive':'']" @click="chooseItem(index)" v-for="(item,index) in itemList" :key="index">
							<text>{{item.itemName}}</text>
							<text class="price">￥{{item.currentPrice}}</text>
						</view>
					</view>
				</view>
				<view class="choose-content">
					<view class="choose-item">
						<view class="item" @click="intoChooseCoupon">
							<text>优惠卷</text>
							<view v-if="checkedCoupon" class="right">
								<u-icon name="gift" color="rgb(255,0,0)" size="32"></u-icon>
								<text class="coopon">9.8元洗车券（￥-9.8）</text>
								<u-icon name="arrow-right" color="rgb(255,0,0)" size="32"></u-icon>
							</view>
							<view v-else class="right">
								<text >暂无可用优惠券</text>
							</view>
						</view>
						<view class="item phone">
							<text>手机号码</text>
							<view class="right">
								<text >{{userPhone}}</text>
							</view>
						</view>
					</view>
					<view class="read">
						<u-radio-group v-model="isRead">
							<u-radio shape="square" :disabled="isRead!='read'" name="read" active-color="red" icon-size="28" label-size="28">
								点击阅读并同意
								<text>无人洗车</text>
								<text @click="intoAgreement">《注意事项及服务协议》</text>
							</u-radio>
						</u-radio-group>
					</view>
				</view>
			</view>
		</view>
		<view class="step-footer">
			<button class="next-button" @click="nextStep" v-if="stepIndex!=2" type="warn">下一步</button>
			<view v-else class="pay">
				<text>合计：</text>
				<text class="amount">￥{{finalAmount}}</text>
				<view class="">
					<button @click="handleSubmit" type="warn">去付款</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uniSteps from '@/components/uni-steps/uni-steps.vue'
	import {getUserInfo} from '@/api/login.js'
	import {getStoreItems, saveOrder, signPay} from '@/api/order.js'
	export default {
		components: {
			uniSteps
		},
		data() {
			return {
				userPhone: '',
				stepIndex: 0, // 当前步奏下标
				serverIndex: 0, // 选择服务下标
				itemList: [], // 服务类型
				isRead: '', // 是否同意协议
				couponList: [
						{
							id: 23432445,
							name: "满100减50",
							price: 100,
							yxTime: "2020-05-16",
							remarks: '优惠卷使用说明优惠卷使用说明优惠卷使用说明',
							checked: false
						},
						{
							id: 3544355,
							name: "满100减50",
							price: 100,
							yxTime: "2020-05-16",
							remarks: '优惠卷使用说明优惠卷使用说明优惠卷使用说明',
							checked: false
						},
						{
							id: 234234234,
							name: "满100减50",
							price: 100,
							yxTime: "2020-05-16",
							remarks: '优惠卷使用说明优惠卷使用说明优惠卷使用说明',
							checked: false
						},
						{
							id: 66264646,
							name: "满100减50",
							price: 100,
							yxTime: "2020-05-16",
							remarks: '优惠卷使用说明优惠卷使用说明优惠卷使用说明',
							checked: false
						},
						{
							id: 9794694698,
							name: "满100减50",
							price: 100,
							yxTime: "2020-05-16",
							remarks: '优惠卷使用说明优惠卷使用说明优惠卷使用说明',
							checked: false
						}
					], // 用户可用优惠券
				checkedCoupon: null, // 用户当前所选优惠券
				amount: 0, // 所选服务项目总金额
				couponAmount: 0, // 优惠券优惠金额
				finalAmount: 0, // 用户最终所需支付金额
			}
		},
		onLoad(option) {
			// 存储当前扫码的设备及网点id
			// if(options.scene){
			// 	let scene=decodeURIComponent(options.scene);
			// 	//&是我们定义的参数链接方式
			// 	let userId=scene.split("&")[0];
			// 	let recommendId=scene.split('&')[1];
			// 	//其他逻辑处理。。。。。
			//   }
			this.$store.state.vuex_orderInfo.bizId = option.bizId || '9898'
			this.$store.state.vuex_orderInfo.storeId = option.storeId || '100000'
			uni.removeStorageSync('stepIndex')
			// 注册全局监听事件
			uni.$once('read', this.read)
			this.getUserPhone()
			this.getServerList()
		},
		onUnload() {
			uni.removeStorageSync('stepIndex')
		},
		onShow() {
			const index = uni.getStorageSync('stepIndex')
			this.stepIndex = index ? index : 0
			console.log(this.stepIndex)
		},
		methods: {
			// 获取用户信息
			getUserPhone () {
				getUserInfo().then(res =>{
					console.log(res,'rrrrrrr')
					if(res.status == 200) {
						this.userPhone = res.data.mobile
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			// 获取服务列表
			getServerList () {
				let storeId = this.$store.state.vuex_orderInfo.storeId
				getStoreItems({storeId:storeId}).then(res =>{
					if (res.status == 200) {
						this.itemList = res.data 
						this.serverIndex = 0
						this.getFinalAmount()
					} else {
						this.itemList = []
						this.toashMsg(res.message)
					}
				})
			},
			// 选择服务项目
			chooseItem(index) {
				this.serverIndex = index
				this.getFinalAmount()
			},
			// 下一步
			nextStep() {
				this.stepIndex = this.stepIndex===0 ? 1 : 2
				uni.setStorageSync('stepIndex', this.stepIndex)
			},
			// 已阅读
			read (e) {
				this.isRead = e.msg
			},
			// 获取用户可用优惠券
			getCouponList () {
				
			},
			// 格式化优惠券数据 获取优惠金额最大的优惠券 couponType 优惠券类型：FULLSUB满减/DISCOUNT折扣券/VOUCHER代金券
			formatCouponData (){
			  let arr = []
			  let _this = this
			  this.couponList.map(item => {
			    let data = {}
			    data.id = item.couponReceivesId
			    if (item.couponType == 'DISCOUNT') {
			      console.log(_this.amount, '_this.amount')
			      data.subAmount = Number((_this.amount * (1 - item.subAmount)).toFixed(2))
			    } else {
			      data.subAmount = item.couponType == 'FULLSUB' ? item.subAmount : item.price
			    }
			    arr.push(data)
			  })
			  console.log(arr, 'arr')
			  // 比较数据中优惠金额最大的值 并返回该对象
			  let obj = arr.reduce((p, v) => p.subAmount < v.subAmount ? v : p)
			  console.log(obj)
			  let p = this.couponList.find(item => item.couponReceivesId == obj.id)
			  // 订单金额为0时，默认不使用优惠卷
			  if (this.amount != 0){
			   this.checkedCoupon = p
			   this.couponAmount = obj.subAmount > this.amount ? this.amount : obj.subAmount
			  } else {
			    this.checkedCoupon = null
			    this.couponAmount = 0
			  }
			  // 计算合计
			  this.getFinalAmount()
			},
			// 计算合计
			getFinalAmount () {
				this.amount = this.itemList[this.serverIndex].currentPrice
			    let ret = this.amount - this.couponAmount 
			    this.finalAmount = ret.toFixed(2)
			},
			// 选择优惠券
			intoChooseCoupon () {
				uni.navigateTo({
					url: `/pages/coupon/chooseCoupon/chooseCoupon?list=${encodeURIComponent(JSON.stringify(this.couponList))}`
				})
			},
			// 打开服务协议
			intoAgreement () {
				uni.navigateTo({
					url: '/pages/agreement/agreement'
				})
			},
			// 去付款 保存订单
			handleSubmit (){
				if(this.itemList.length==0){
					this.toashMsg('请先选择服务')
					return 
				}
				if (this.isRead !='read') {
					this.toashMsg('请先阅读并同意无人洗车《注意事项及服务协议》！')
					return 
				}
				uni.showLoading({
					title: '请求中...',
					mask: true
				})
				let item = this.itemList[this.serverIndex]
				let params = {
					"itemId": item.itemId, // 服务id
					"itemCode": item.itemCode, 
					"storeId": 100000, // 门店id
					"deviceId": 100000, // 设备id
					"orderTime": this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss'), 
					"payableAmount": this.amount, // 应付金额 即优惠前金额
					"paymentAmount": this.finalAmount // 实收金额 即优惠后金额
				}
				saveOrder(params).then(res =>{
					if (res.status==200) {
						let data = res.data
						// 保存成功后 请求预支付返回吊起微信支付所需参数
						this.getPayData(data)
						this.$store.state.vuex_orderInfo.itemCode = data.itemCode
						this.$store.state.vuex_orderInfo.orderNo = data.orderNo
						this.$store.state.vuex_orderInfo.duration = item.duration
					} else {
						uni.hideLoading()
						// 刷新服务项
						this.getServerList()
						this.toashMsg(res.message)
					}
				})
			},
			// 预支付 返回微信支付所需参数
			getPayData (orderData) {
				signPay({orderId:orderData.id}).then(res =>{
					console.log(res,'预支付')
					uni.hideLoading()
					if (res.status == 200) {
						let data = res.data
						// 0元订单直接支付成功,不用吊微信支付
						if (data.tradeStatus && data.tradeStatus=="PAID") {
							// 付款成功后开始洗车
							uni.redirectTo({
								url:`/pages/work/index/index`
							})
						} else {
							uni.requestPayment({
							    provider: 'wxpay',
							    timeStamp: data.timeStamp,
							    nonceStr: data.nonceStr,
							    package: data.package,
							    signType: data.signType,
							    paySign: data.paySign,
							    success: function (res) {
							        console.log('success:' + JSON.stringify(res));
									// 付款成功后开始洗车
									uni.redirectTo({
										url:`/pages/work/index/index`
									})
							    },
							    fail: function (err) {
							        console.log('fail:' + JSON.stringify(err));
							    }
							});
						}
					} else {
						this.toashMsg(res.message)
					}
				})
			}
			
		}
	}
</script>

<style lang="scss">
	page{
		height: 100%;
	}
	.order-content{
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		.step{
			padding: 40rpx 0;
		}
		.step-content{
			flex: 1;
			width: 100%;
			display: flex;
			flex-direction: column;
			.step-item{
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;
				flex: 1;
			}
			// 第一步
			.step-one{
				text{
					color: #999;
					margin: 40rpx 0;
				}
			}
			// 第二步
			.step-two{
				background-color: #F8F8F8;
				justify-content: space-around;
				.item{
					background-color: #fff;
					width: 80%;
					height: 45%;
					display: flex;
					flex-direction: column;
					align-items: center;
					image{
						width: 80%;
						flex: 1;
					}
					
				}
				.top{
					text{
						color: #df928e;
						font-size: 24rpx;
					}
					.item-text{
						padding-top: 20rpx;
					}
					.care{
						padding: 10rpx 20rpx;
						background-color: #ff805b;
						border-radius: 30rpx;
						color: #fff;
						font-size: 24rpx;
						margin-bottom: 20rpx;
					}
				}
				.bottom{
					text{
						font-size: 24rpx;
						color: #333;
					}
					.item-text{
						padding-top: 20rpx;
					}
				}
			}
			// 第三步 下单
			.step-three{
				.choose{
					width: 100%;
					height: auto;
					padding-bottom: 60rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					border-bottom: 1px solid #eee;
					.title{
						color: #666;
					}
					.list{
						width: 100%;
						display: flex;
						justify-content: space-around;
						padding: 0 20rpx;
						.item{
							width: 30%;
							height: 140rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
							border: 1px solid #eee;
							border-radius: 15rpx;
							margin-top: 30rpx;
							color: #999;
							.price{
								font-size: 34rpx;
								margin-top: 10rpx;
							}
						}
						.avtive{
							color: #333;
							border-color: rgb(255,0,0);
							.price{
								color: rgb(255,0,0);
							}
						}
					}
					
				}
				.choose-content{
					flex: 1;
					width: 100%;
					.choose-item{
						width: 100%;
						.item{
							padding: 0 30rpx;
						}
					}
					.item{
						width: 100%;
						height: 100rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						border-bottom: 1px solid #eee;
						.coopon{
							color: rgb(255,0,0);
						}
					}
					.phone{
						border-bottom: none;
					}
					.read{
						width: 100%;
						border-top: 1px solid #eee;
						padding-top: 40rpx;
						display: flex;
						justify-content: center;
						text{
							color: #999;
						}
						text:last-child{
							color: #ff9ba5;
						}
					}
				}
			}
		}
		.step-footer{
			width: 100%;
			background-color: #fff;
			.next-button{
				margin: 0;
				border-radius: 0;
				padding: 10rpx 0;
			}
			.pay{
				width: 100%;
				height: 100%;
				padding: 10rpx;
				border-top: 1px solid #eee;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				.amount{
					color: rgb(255,0,0);
					font-size: 36rpx;
					margin-right: 40rpx;
				}
				button{
					width: 200rpx;
				}
			}
		}
	}
</style>
