<template>
	<view class="container-box">
		<navigation-bar-vue title="急招券" style="width: 100%;" background-color="#ffffff"
			title-color="#000000"></navigation-bar-vue>
		<view class="content">
			<!-- 操作按钮 -->
			<view class="dl-opt-box">
				<view class="dl-menu-box" v-for="(item,index) in menus">
					<view @click="itemClick(index,item)" class="dl-menu"
						:class="index==menuIndex?'dl-menu click':'dl-menu'">{{item}}</view>
				</view>
			</view>
			<view style="width: 100%;" v-if="0==menuIndex">
				<view class="coupon-list-box">
					<view class="top-text">剩余<text>{{ coupon }}</text>张</view>
					<view :class="['coupon-item-box',index==couponIndex?'click':'']" v-for="(item,index) in dataList"
						@click="chooseCoupon(index)">
						<view class="left-dom">
							<image src="@/static/mine/coupon/coupon.png" mode="aspectFit"></image>
							<uni-icons type="closeempty" color="#FC1F3E" size="14"></uni-icons>
							<view style="margin-left: 15rpx;">{{item.couponNum}}张</view>
						</view>
						<view class="right-dom">
							<text>¥</text>{{item.price}}
						</view>
					</view>
					<!-- 购买 -->
					<!-- #ifdef H5 -->
					<view class="button-dom" @click="toOrder()">购买</view>
					<!-- #endif -->
					<!-- 调整h5 -->
					<!-- #ifdef MP-WEIXIN -->
					<view class="button-dom" @click="openVip()">购买</view>

					<!-- #endif -->

				</view>
				<view class="item-field" style="align-items: center;">
					<view class="my-suggest-dom" @click="viewRichText()">
						<text>查看《急招券购买协议》</text>
					</view>
				</view>
			</view>
			<view style="width: 100%;" v-if="1==menuIndex">
				<view class="buy-list-box">
					<scroll-view style="height: 100%;" scroll-y="true" @scrolltolower="onReachBottomCus"
						refresher-enabled @refresherrefresh="onRefresherrefresh" :refresher-triggered="isTriggered">
						<view class="item-box" v-for="(item,index) in byList">
							<view class="top-title-box">
								<view class="order-no">订单编号：{{item.orderNo}}</view>
								<view :class="['order-status',item.isPay==1?'payed':'no-pay']">
									{{item.isPay==1?'已支付':'未支付'}}
								</view>
							</view>
							<view class="detail-item">
								<view class="left-dom">急招券</view>
								<view class="right-dom">*{{item.goodsNum}} 张</view>
							</view>
							<view class="detail-item" style="border-bottom:1rpx solid #F4F4F4;padding-bottom: 25rpx;">
								<view class="left-dom">金额</view>
								<view class="right-dom">{{item.goodsPrice}} 元</view>
							</view>
							<view class="bottom-item">
								下单时间：{{item.createTime}}
							</view>
						</view>
						<view style="text-align: center" v-if="byList.length==0">
							<image class="" src="@/static/images/nothing.png"></image>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import navigationBarVue from '@/components/navigation/navigationBar.vue';
	import {
		initCouponList
	} from '@/api/business/base.js'
	import {
		saveOrder,
		getOrderList,
		prepayment,
		getMemberCoupon
	} from '@/api/business/member.js'
	import {
		toast
	} from '@/utils/common.js'
	import constant from '@/utils/constant';
	import {
		getJSONData
	} from '@/utils/auth.js'
	import {
		getCodeUrl,
		getWebAccessTokenAndOpenid,
		gzhLogin
	} from '@/api/wxApi'
	import {
		getToken
	} from '@/utils/auth'
	export default {
		components: {
			navigationBarVue
		},
		data() {
			return {
				globalConfig: getApp().globalData.config,
				menus: ['急招券', '购买记录'],
				menuIndex: 0,
				coupon: 0,
				//选中的急招券下标
				couponIndex: 0,
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					orderType: '02',
          isPay:'1',
					userId: null,
				},
				total: 0,
				//下来刷新状态
				isTriggered: false,
				dataList: [],
				//购买记录
				byList: []
			}
		},
		onLoad(option) {
			this.menuIndex = option.index || 0
			this.initCoupon();
			this.initOrder()
			//获取url中的search
			if (location.search) {
				let search = location.search.slice(1);
				let arr = search.split("&");
				let result = {};
				arr.forEach(function(item) {
					let itemArr = item.split('=');
					result[itemArr[0]] = itemArr[1];
				})
				if (result.code) {
					let that = this
					getWebAccessTokenAndOpenid(result.code).then(res => {
						that.$store.dispatch('GzhLogin', res).then(() => {
							that.initCoupon();
							that.initOrder()
							that.loginSuccess()
							that.initMyCoupon()
						}).catch((e) => {
							uni.showToast({
								icon: 'error',
								duration: 2000,
								title: e
							});
						})
					})
				} else {
					this.toLogin()
				}
			}
		},
		onShow() {
			if (getToken()) {
				this.initMyCoupon()
			}
		},
		methods: {
			initMyCoupon() {
				getMemberCoupon().then(res => {
					this.coupon = res.data
				})
			},
			openVip() {
				// 在你想触发跳转的地方
				wx.openOfficialAccountProfile({
					username: 'tonggaokuaijie', // 此处填写公众号的微信号
					success: res => {},
					fail: res => {}
				})

			},
			// 登录成功后，处理函数
			loginSuccess(result) {
				// 设置用户信息
				this.$store.dispatch('GetInfo').then(res => {

				})
			},
			toLogin() {
				/*#ifdef APP-PLUS*/
				// App端特有的逻辑
				console.log('Running on App-Plus');
				/*#endif*/
				/*#ifdef H5*/
				// 在浏览器端（H5）执行的逻辑

				//未登录状态
				getCodeUrl("01", "pages/mine/coupon/my-coupon").then(res => {
					window.location.href = res.codeUrl;
				})

				/*#endif*/
				/*#ifdef MP-WEIXIN*/
				// 微信小程序端执行的逻辑
				console.log('Running on WeChat Mini Program');
				/*#endif*/

			},
			/**
			 * 菜单点击
			 * @param {Object} index
			 * @param {Object} item
			 */
			itemClick(index, item) {
				this.menuIndex = index

			},

			/**查询卡券*/
			initCoupon() {
				if (getToken()) {
					this.dataList = []
					initCouponList().then(res => {
						this.dataList = res.data
					})
				}

			},

			/**初始化订单数据*/
			initOrder() {
				if (getToken()) {
					this.queryParams.userId = getJSONData(constant.userInfo).userId
					getOrderList(this.queryParams).then(res => {
						this.isTriggered = false
						if (res.code == 200) {
							if (this.queryParams.pageNum == 1) {
								this.byList = res.data.records
							} else {
								this.byList = this.byList.concat(res.data.records)
							}
							this.total = res.data.total
						}
					})
				}
			},

			/**生成订单*/
			async toOrder() {
				let data = {
					userType: '01',
					orderType: '02',
					goodsId: this.dataList[this.couponIndex].id,
					goodsNum: this.dataList[this.couponIndex].couponNum,
					goodsPrice: this.dataList[this.couponIndex].price,
					goodsCycle: '04'
				}
				let that = this
				saveOrder(data).then(res => {
					if (res.code == 200) {
						//吊起支付
						let payData = {
							orderNo: res.data.orderNo
						}
						prepayment(payData).then(paymentData => {
							that.wxpay(paymentData)
						})
					}
				}).catch((e) => {
					uni.showToast({
						icon: 'error',
						duration: 2000,
						title: e
					});
				})
			},

			/**
			 * 选中的优惠券
			 * @param {Object} index
			 */
			chooseCoupon(index) {
				this.couponIndex = index
			},

			viewRichText() {
				this.$tab.navigateTo(
					`/pages/common/richview/index?title=${this.globalConfig.appInfo.agreements[6].title}&code=${this.globalConfig.appInfo.agreements[6].code}`
				)
			},



			/**
			 * 上滑加载数据
			 */
			onReachBottomCus() {
				//判断 如果页码*页容量大于等于总条数，提示该页数据加载完毕
				if (this.queryParams.pageNum * this.queryParams.pageSize >= this.total) {
					toast("没有更多数据了")
					return
				}
				//页码+1,调用获取数据的方法获取第二页数据
				this.queryParams.pageNum++
				this.initOrder()
			},
			/**
			 * 下拉刷新数据
			 */
			onRefresherrefresh() {
				this.isTriggered = true
				this.queryParams.pageNum = 1
				this.total = 0
				this.initOrder()
			},
			// 检测支付环境中的 WeixinJSBridge
			wxpay(data) {
				if (typeof WeixinJSBridge == "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', onBridgeReady(data), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', onBridgeReady(data));
						document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(data));
					}
				} else {
					this.onBridgeReady(data);
				}
			},

			onBridgeReady(data) {

				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						// 传入第一步后端接口返回的核心参数
						"appId": data.appId, //公众号
						"timeStamp": data.timeStamp, //时间戳
						"nonceStr": data.nonceStr, //随机串
						"package": data.packageVal, //prepay_id
						"signType": data.signType, //微信签名方式RSA
						"paySign": data.paySign //微信签名
					},
					function(res) {
						// 支付成功
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
						}
						// 支付过程中用户取消
						if (res.err_msg == "get_brand_wcpay_request:cancel") {

						}
						// 支付失败
						if (res.err_msg == "get_brand_wcpay_request:fail") {

						}
						/**
						 * 其它
						 * 1、请检查预支付会话标识prepay_id是否已失效
						 * 2、请求的appid与下单接口的appid是否一致
						 * */
						if (res.err_msg == "调用支付JSAPI缺少参数：total_fee") {

						}
					});
			}
		}
	}
</script>

<style lang="scss">
	.container-box {
		padding-top: calc(90rpx + var(--status-bar-height));
		border-top: 1rpx solid #F4F4F4;
		background-color: white;
		width: 100%;
		color: #363636;
		font-size: 30rpx;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: self-start;
		justify-content: center;
		position: relative;

		.content {
			border-top: 1rpx solid #F4F4F4;
			height: calc(100vh - var(--status-bar-height) - var(--window-bottom) - 95rpx);
			overflow-y: scroll;
			width: 100%;
			background-color: #F2F2F2;
			border-radius: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: self-start;
			justify-content: start;
			position: relative;

			.dl-opt-box {
				background-color: white;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;

				.dl-menu-box {
					color: #929292;
					display: flex;
					flex: 1;
					align-items: center;
					justify-content: center;
					width: 100%;
					padding-top: 20rpx;

					.dl-menu {
						width: 120rpx;
						font-size: 30rpx;
						margin: 0 20rpx;
						padding-bottom: 15rpx;
						text-align: center;
					}

					.click {
						color: #FF434E;
						font-weight: bold;
						border-bottom: 2px solid #FF434E;
					}
				}

				.seting {
					font-size: 30rpx;
					width: 180rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					image {
						width: 30rpx;
						height: 30rpx;
						margin-right: 10rpx;
					}
				}
			}

			.buy-list-box {
				height: calc(100vh - var(--status-bar-height) - var(--window-bottom) - 174rpx);
				width: 100%;
				padding: 20rpx 30rpx 0 30rpx;
				background-color: #F2F2F2;
				border-radius: 20rpx;
				display: flex;
				flex-direction: column;
				align-items: self-start;
				justify-content: start;
				position: relative;

				.item-box {
					margin-bottom: 20rpx;
					background-color: white;
					border-radius: 15rpx;
					padding: 25rpx;
					width: 100%;
					display: flex;
					flex-direction: column;
					align-items: self-start;
					justify-content: start;

					.top-title-box {
						padding-top: 10rpx;
						padding-bottom: 20rpx;
						margin-bottom: 15rpx;
						width: 100%;
						display: flex;
						align-items: center;
						justify-content: start;
						border-bottom: 1rpx solid #F4F4F4;

						.order-no {
							flex: 1;
							font-weight: bold;
							display: flex;
							align-items: center;
							justify-content: start;
						}

						.order-status {
							font-size: 27rpx;
							padding: 5rpx 15rpx;
							border-radius: 25rpx;
							color: white;
						}

						.no-pay {
							background-color: #929292;
						}

						.payed {
							background-color: #FC1F3E;
						}
					}

					.detail-item {
						width: 100%;
						padding: 10rpx 0;
						display: flex;
						align-items: center;
						justify-content: start;

						.left-dom {
							display: flex;
							align-items: center;
							justify-content: start;
							width: 200rpx;
						}

						.right-dom {
							display: flex;
							align-items: center;
							justify-content: flex-end;
							flex: 1;
						}
					}

					.bottom-item {
						padding-top: 15rpx;
						font-size: 26rpx;
						color: #929292;
					}
				}
			}

			.coupon-list-box {
				margin-top: 20rpx;
				background-color: white;
				border-radius: 20rpx;
				padding: 30rpx 20rpx;
				margin-left: 30rpx;
				margin-right: 30rpx;
				width: calc(100% - 60rpx);
				flex-direction: column;
				display: flex;
				align-items: self-start;
				justify-content: center;

				.top-text {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					padding-bottom: 30rpx;

					text {
						color: #FB2B43;
						padding: 0 10rpx;
					}
				}

				.coupon-item-box {
					width: 100%;
					padding: 30rpx 40rpx 30rpx 20rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 20rpx;
					background-color: #FFE9EC;
					border: 2rpx solid #FFE9EC;
					border-radius: 15rpx;
					color: #FC1F3E;

					.left-dom {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: flex-start;


						image {
							width: 60rpx;
							height: 60rpx;
							margin-right: 15rpx;
						}

					}

					.right-dom {
						width: 200rpx;
						display: flex;
						align-items: baseline;
						justify-content: flex-end;
						font-weight: bold;
						font-size: 36rpx;

						text {
							font-weight: normal;
							margin-right: 8rpx;
							font-size: 18rpx;
						}
					}
				}

				.click {
					border: 2rpx solid #FC1F3E !important;
				}

				.button-dom {
					margin-top: 30rpx;
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 20rpx 0;
					background-image: linear-gradient(to right, #F9605A, #FB2B43);
					color: white;
					border-radius: 40rpx;
					font-size: 33rpx;
				}
			}

			.item-field {
				color: #929292;
				width: 100%;
				display: flex;
				align-items: self-start;
				justify-content: center;

				.my-suggest-dom {
					margin: 0 30rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24rpx;
					margin-top: 20rpx;
				}
			}
		}
	}
</style>