<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" @click="lookMore">
					<view class="item-text">
						<text>超高加装件不能清洗</text>
						<view class="right">
							<text>查看更多</text>
							<u-icon name="arrow-right" size="28"></u-icon>
						</view>
					</view>
					<image src="/static/img/zyts.png" ></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>
						<u-empty text="暂无服务项目" img-width="120" v-if="itemList.length==0 && status!='loading'" mode="list"></u-empty>
					</view>
				</view>
				<view class="choose-content">
					<view class="choose-item">
						<view class="item" @click="intoChooseCoupon">
							<text>优惠卷</text>
							<view v-if="couponList.length" class="right">
								<u-icon name="gift" color="rgb(255,0,0)" size="32"></u-icon>
								<text class="coopon">{{checkedCoupon?(checkedCoupon.couponTitle+'(￥-'+checkedCoupon.couponAmount+')'):''}}</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" @click="intoAgreement">
						<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>《注意事项及服务协议》</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 :disabled="disabledPay" @click="handleSubmit" type="warn">去付款</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {couponEnable} from '@/api/coupon.js'
	import uniSteps from '@/components/uni-steps/uni-steps.vue'
	import {
		getUserInfo
	} from '@/api/login.js'
	import {
		getStoreItems,
		saveOrder,
		signPay
	} from '@/api/order.js'
	import {
		getStoreStatus
	} from '@/api/store.js'
	export default {
		components: {
			uniSteps
		},
		data() {
			return {
				status: 'loadmore',
				disabledPay: false,
				userPhone: '',
				stepIndex: 0, // 当前步奏下标
				serverIndex: 0, // 选择服务下标
				itemList: [], // 服务类型
				isRead: '', // 是否同意协议
				couponList: [], // 用户可用优惠券
				checkedCoupon: null, // 用户当前所选优惠券
				amount: 0, // 所选服务项目总金额
				couponAmount: 0, // 优惠券优惠金额
				finalAmount: 0, // 用户最终所需支付金额
			}
		},
		onLoad(options) {
			// 存储当前扫码的设备及网点id
			if (options.scene) {
				let scene = decodeURIComponent(options.scene);
				//&是我们定义的参数链接方式
				let storeId = scene.split(",")[0];
				let bizId = scene.split(',')[1];
				//其他逻辑处理。。。。。
				this.$u.vuex('vuex_bizId',bizId)
				this.$u.vuex('vuex_storeId',storeId)
				// 判断当前门店是否已运营
				this.getStoreStatus(storeId,bizId)
			} else {
				// 判断是否扫码过
				if (this.$store.state.vuex_bizId != '') {
					this.dataInit()
				} else {
					// 返回首页
					uni.reLaunch({
						url: "/pages/index/index"
					})
				}
			}
		},
		onUnload() {
			uni.removeStorageSync('stepIndex')
			uni.$off('couponChoose', this.couponChoose)
		},
		onShow() {
			const index = uni.getStorageSync('stepIndex')
			this.stepIndex = index ? index : 0
			console.log(this.stepIndex)
		},
		methods: {
			// 查询基础数据
			dataInit(){
				// 监听点击已阅读事件
				uni.$once('read', this.read)
				// 监听用户选择的优惠券
				uni.$on('couponChoose', this.couponChoose)
				// 获取用户信息
				this.getUserPhone()
				// 获取服务项目
				this.getServerList()
			},
			// 获取网点营业状态
			getStoreStatus(storeId, bizId) {
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				getStoreStatus({
					storeId: storeId,
					deviceNo: bizId
				}).then(res => {
					uni.hideLoading()
					console.log(res,'---------')
					if(res.status != 200 && res.status != 401) {
						uni.showModal({
						    title: '提示',
						    content: res.message,
							showCancel: false,
						    success: function (res) {
						        if (res.confirm) {
									uni.reLaunch({
										url:'/pages/index/index'
									})
						        }
						    }
						});
					}else{
						this.dataInit()
					}
				})
			},
			// 获取用户信息
			getUserPhone() {
				getUserInfo().then(res => {
					console.log(res, 'rrrrrrr')
					if (res.status == 200) {
						this.userPhone = res.data.mobile
					} else {
					}
				})
			},
			// 查看更多注意事项
			lookMore() {
				uni.navigateTo({
					url: '/pages/careMore/careMore'
				})
			},
			// 获取服务列表
			getServerList() {
				this.status = 'loading'
				let storeId = this.$store.state.vuex_storeId
				getStoreItems({
					storeId: storeId
				}).then(res => {
					this.status = 'loadmore'
					if (res.status == 200) {
						this.itemList = res.data
						this.serverIndex = 0
						// 获取用户可用优惠券
						this.getCouponList()
					} else {
						this.itemList = []
					}
				})
			},
			// 选择服务项目
			chooseItem(index) {
				this.serverIndex = index
				// 获取用户可用优惠券
				this.getCouponList()
			},
			// 下一步
			nextStep() {
				this.stepIndex = this.stepIndex === 0 ? 1 : 2
				uni.setStorageSync('stepIndex', this.stepIndex)
			},
			// 已阅读
			read(e) {
				this.isRead = e.msg
			},
			// 获取用户选择的优惠券
			couponChoose (e) {
				this.checkedCoupon = e.curCoupon
				// 计算合计
				this.getFinalAmount()
			},
			// 获取用户可用优惠券
			getCouponList() {
				let item = this.itemList[this.serverIndex]
				let params = {
					consumAmount: item.currentPrice, //服务金额
					itemId: item.itemId  // 服务id
				}
				uni.showLoading({
					title: '正在查询可用优惠券...',
					mask: true
				})
				couponEnable(params).then(res=> {
					uni.hideLoading()
					if (res.status == 200) {
						this.couponList = res.data
						this.checkedCoupon = this.couponList[0]
						// 计算合计
						this.getFinalAmount()
					} else {
						this.couponList = []
						this.checkedCoupon = null
					}
				})
			},
			
			// 计算合计
			getFinalAmount() {
				this.amount = this.itemList[this.serverIndex].currentPrice
				this.couponAmount = (this.checkedCoupon && this.checkedCoupon.couponAmount > this.amount) ? this.amount : (this.checkedCoupon ?this.checkedCoupon.couponAmount : 0)
				let ret = this.amount - this.couponAmount
				this.finalAmount = ret.toFixed(2)
			},
			// 选择优惠券
			intoChooseCoupon() {
				this.couponList.map((item)=> {
					item.checked = (this.checkedCoupon && item.id == this.checkedCoupon.id) ? true : false
				})
				uni.navigateTo({
					url: `/pages/coupon/chooseCoupon/chooseCoupon?list=${encodeURIComponent(JSON.stringify(this.couponList))}&curCoupon=${encodeURIComponent(JSON.stringify(this.checkedCoupon))}`
				})
			},
			// 打开服务协议
			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 storeId = this.$store.state.vuex_storeId
				let deviceNo = this.$store.state.vuex_bizId
				let params = {
					"itemId": item.itemId, // 服务id
					"itemCode": item.itemCode,
					"storeId": storeId, // 门店id
					"deviceNo": deviceNo, // 设备编号
					"orderTime": this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss'),
					"payableAmount": this.amount, // 应付金额 即优惠前金额
					"paymentAmount": this.finalAmount, // 实收金额 即优惠后金额
					"couponAmount": this.couponAmount, // 优惠金额
				}
				if (this.checkedCoupon) {
					params.couponReceivesList = [{id:this.checkedCoupon.id}]
				}
				this.disabledPay = true
				saveOrder(params).then(res => {
					if (res.status == 200) {
						let data = res.data
						// 保存成功后 请求预支付返回吊起微信支付所需参数
						this.getPayData(data)
						this.$u.vuex('vuex_itemCode',data.itemCode)
						this.$u.vuex('vuex_orderNo',data.orderNo)
					} else {
						uni.hideLoading()
						this.toashMsg(res.message)
						this.disabledPay = false
						setTimeout(()=>{
							// 刷新服务项
							this.getServerList()
						},2000)
					}
				})
			},
			// 预支付 返回微信支付所需参数
			getPayData(orderData) {
				let _this = this
				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") {
							this.paySuccess()
						} 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));
									_this.paySuccess()
								},
								fail: function(err) {
									console.log('fail:' + JSON.stringify(err));
									_this.payFail(err)
									_this.disabledPay = false
								}
							});
						}
					} else {
						this.toashMsg(res.message)
						this.disabledPay = false
					}
				})
			},
			// 付款成功后
			paySuccess(){
				this.$u.vuex('vuex_orderStatus','PAID')
				this.$u.vuex('vuex_orderDjs',0)
				this.$u.vuex('vuex_workStep',0)
				this.$u.vuex('vuex_workStatus','linking')
				 
				// 付款成功后开始洗车
				uni.redirectTo({
					url: `/pages/work/index/index`
				})
				
				this.disabledPay = false
			},
			// 付款失败或取消
			payFail(err){
				this.$u.vuex('vuex_orderStatus','FAIL')
				let content = '支付失败，请重试'
				if(err.errMsg.indexOf("cancel")>=0){
					content = '支付取消'
				}
				this.toashMsg(content)
			}
		}
	}
</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;
			overflow-y: scroll;
			.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: 92%;
					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 {
						width: 100%;
						padding: 0 40rpx;
						display: flex;
						justify-content: space-between;
						padding-top: 20rpx;
					}
					image {
						margin-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>
