<template>
	<view class="page">

		<view class="flex flex-column header">
			<!-- 未登录显示 -->
			<view v-if="!isLogin" class="flex flex-column no-login">
				<view class="no-login-text">登录后查看个人信息</view>
				<button class="no-login-btn" @click="$utils.toLogin">立即登录</button>
			</view>
			
			<!-- 登录后显示用户信息 -->
			<view v-else class="flex flex-column user" @click="$utils.navigateTo('/pages_order/auth/wxUserInfo')">
				<image class="user-avatar" :src="userInfo.headImage" mode="aspectFill"></image>
				<view class="user-name">{{ userInfo.nickName }}</view>
			</view>

			
			<view class="member">
				<template v-if="role">
					<image class="member-bg" src="/pages_order/static/center/member-bg.png" mode="widthFix" ></image>
					<view class="flex member-overview" :class="[role ? 'is-member' : '']">
						<image class="icon icon-crown" src="" mode="widthFix"></image>
						<image v-if="role" class="icon icon-role" :src="vipInfo.massageVipCombo.imageVip" mode="widthFix"></image>
						<text v-if="vipInfo.validTime" class="member-tips">{{ `将于${$dayjs(vipInfo.validTime).format('YYYY-MM-DD')}到期` }}</text>
					</view>
				</template>
				<template v-else>
					<image class="member-bg" src="/pages_order/static/center/member-not-bg.png" mode="widthFix" ></image>
					<button plain class="btn member-btn" @click="$utils.navigateTo('/pages_order/mine/memberCenter')">立即开通</button>
				</template>
			</view>

			<view class="member" v-if="false">
				<image class="member-bg" src="/pages_order/static/center/member-bg.png" mode="widthFix" ></image>
				<view class="flex member-overview" :class="[role ? 'is-member' : '']">
					<template v-if="role">
						<!-- todo: 缺切图 "皇冠" -->
						<image class="icon icon-crown" src="" mode="widthFix"></image>
						<image v-if="role" class="icon icon-role" :src="vipInfo.massageVipCombo.imageVip" mode="widthFix"></image>
						<text v-if="vipInfo.validTime" class="member-tips">{{ `将于${$dayjs(vipInfo.validTime).format('YYYY-MM-DD')}到期` }}</text>
					</template>
					<template v-else>
						<view class="flex">
							<!-- todo: 缺切图 "皇冠" -->
							<image class="icon icon-crown" src="" mode="widthFix"></image>
							<!-- todo: 缺切图 "会员" -->
							<image class="icon icon-member" src="" mode="widthFix"></image>
							<text class="member-tips">成为会员可获得会员卡，享受会员福利哟~</text>
						</view>
						<button plain class="btn member-btn" @click="$utils.navigateTo('/pages_order/mine/memberCenter')">立即开通</button>
					</template>
				</view>
			</view>
		</view>

		<!-- 账户信息 - 登录后显示 -->
		<view class="card flex account">
			<view class="flex flex-column">
				<view class="account-value">{{ userInfo.price || 0 }}<text class="account-unit">元</text></view>
				<view class="account-label">我的余额</view>
			</view>
			<view class="flex flex-column">
				<view class="account-value">{{ userCenterData.score || 0 }}</view>
				<view class="account-label">我的积分</view>
			</view>
			<view class="flex flex-column">
				<view class="account-value">{{ userInfo.recommendAmount || 0 }}<text class="account-unit">元</text></view>
				<view class="account-label">推广佣金</view>
			</view>
			<view class="flex flex-column">
				<view class="account-value">{{ couponCount || 0 }}<text class="account-unit">张</text></view>
				<view class="account-label">优惠券</view>
			</view>
		</view>

		<view class="card fun-common">
			<view v-if="isMerchants" class="fun-header">
				<cardTitle>常用功能</cardTitle>
			</view>
			<view class="fun-content fun-common-content">
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/mine/memberCenter')">
					<image class="fun-common-icon" src="@/static/image/center/icon-member-center.png" mode="widthFix"></image>
					<text class="fun-common-label">会员中心</text>
				</view>
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/mine/partner')">
					<image class="fun-common-icon" src="@/static/image/center/icon-team.png" mode="widthFix"></image>
					<text class="fun-common-label">我的团队</text>
				</view>
				
				<!-- #ifdef MP-WEIXIN -->
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/mine/promotion')">
				<!-- #endif -->
				
				<!-- #ifdef H5 -->
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/mine/promotionH5')">
				<!-- #endif -->
					
					<image class="fun-common-icon" src="@/static/image/center/icon-invite.png" mode="widthFix"></image>
					<text class="fun-common-label">邀请好友</text>
				</view>
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/mine/coupon')">
					<image class="fun-common-icon" src="@/static/image/center/icon-coupon.png" mode="widthFix"></image>
					<text class="fun-common-label">优惠券</text>
				</view>
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/mine/voucher')">
					<image class="fun-common-icon" src="@/static/image/center/icon-voucher.png" mode="widthFix"></image>
					<text class="fun-common-label">代金券</text>
				</view>
				<!-- todo: check -> @click="openServicePopup" -->
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/home/contact')">
					<image class="fun-common-icon" src="@/static/image/center/icon-service.png" mode="widthFix"></image>
					<text class="fun-common-label">联系客服</text>
				</view>
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/mine/signIn')">
					<image class="fun-common-icon" src="@/static/image/center/icon-sign-in.png" mode="widthFix"></image>
					<text class="fun-common-label">每日签到</text>
				</view>
				<view class="flex flex-column" @click="$utils.navigateTo('/pages_order/mine/cooperation')">
					<image class="fun-common-icon" src="@/static/image/center/icon-cooperation.png" mode="widthFix"></image>
					<text class="fun-common-label">商家合作</text>
				</view>
			</view>
		</view>

		<view v-if="isMerchants" class="card fun-merchant">
			<view class="fun-header">
				<cardTitle>商家功能</cardTitle>
			</view>
			<view class="flex fun-content fun-merchant-content">
				<view class="left" @click="$utils.navigateTo('/pages_order/mine/verifyRecord')">
					<image class="left-bg" src="/static/image/center/bg-verify.png"></image>

					<view class="flex left-content">
						<text>核销明细</text>
						<image class="left-icon" src="/static/image/center/icon-arrow.png" mode="widthFix"></image>
					</view>
				</view>

				<view class="right" @click="onScan">
					<image class="right-bg" src="/static/image/center/bg-scan.png"></image>
				</view>
			</view>
		</view>
	
		<customerServicePopup ref="customerServicePopup" />

		<tabber select="center" />
	</view>
</template>

<script>
	import cardTitle from '@/components/base/cardTitle.vue'
	import tabber from '@/components/base/tabbar.vue'
	import { mapGetters, mapState } from 'vuex'
	import customerServicePopup from '@/components/config/customerServicePopup.vue'

	export default {
		components: {
			cardTitle,
			tabber,
			customerServicePopup,
		},
		computed: {
			...mapGetters(['role']),
			...mapState(['userInfo', 'userCenterData', 'vipInfo', 'riceInfo']),
			isMerchants() {
				return this.userInfo.isMerchants === '1'
			},
			isLogin() {
				return this.userInfo && this.userInfo.id
			}
		},
		data() {
			return {
				couponCount: 0,
			}
		},
		onShow() {
			if(uni.getStorageSync('token')){
				this.$store.commit('getUserInfo')
				this.$store.commit('getUserCenterInfo')
				this.$store.commit('getRiceInfo')
				this.fetchCouponData()
			}
		},
		onPullDownRefresh() {
			if(uni.getStorageSync('token')){
				this.$store.commit('getUserInfo')
				this.$store.commit('getUserCenterInfo')
				this.$store.commit('getRiceInfo')
				this.fetchCouponData()

				setTimeout(() => {
					uni.stopPullDownRefresh();
				}, 300)
			}
		},
		methods: {
			// #ifdef H5
			// 检查是否在微信环境
			isInWechat() {
				const ua = navigator.userAgent.toLowerCase()
				return ua.indexOf('micromessenger') !== -1
			},
			// #endif
			clickNo() {
				uni.showModal({
					title: '暂未开放',
				})
			},
			logout(){
                uni.showModal({
                    title: '确认退出登录吗',
                    success : (r) => {
                        if (r.confirm) {
                            this.$store.commit('logout', true)
                        }
                    }
                })
			},
			openServicePopup(phone, title) {
				// todo 
				this.$refs.customerServicePopup.open(phone, title)
			},
			onScan() {
				// #ifdef H5
				// H5环境下使用微信JSSDK扫码
				if (!this.isInWechat()) {
					uni.showToast({
						title: '请在微信中打开',
						icon: 'none'
					})
					return
				}
				
				if (this.$jWeixin) {
					this.$jWeixin.ready(() => {
						this.$jWeixin.scanQRCode({
							needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果
							scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
							success: (res) => {
								console.log('H5扫码结果：', res);
								if (res.resultStr) {
									// 处理扫码结果
									const [id, type] = res.resultStr.split(',')
									console.log('扫码结果：', res.resultStr);

									this.$fetch('overOrder', {
										orderId : id,
										type, // type区分，0-订单核销 1-代金券核销
									}).then(() => {
										uni.showToast({
											title: '核销成功',
											icon: 'none'
										})
									}).catch(err => {
										uni.showToast({
											title: '核销失败',
											icon: 'none'
										})
									})
								}
							},
							fail: (err) => {
								console.error('H5扫码失败：', err);
								uni.showToast({
									title: '扫码失败',
									icon: 'none'
								})
							}
						})
					})
					
					this.$jWeixin.error((res) => {
						console.error('微信配置失败:', res)
						uni.showToast({
							title: '微信配置失败',
							icon: 'none'
						})
					})
				} else {
					uni.showToast({
						title: '微信环境异常',
						icon: 'none'
					})
				}
				// #endif
				
				// #ifdef MP-WEIXIN
				// 小程序环境下使用uni.scanCode
				uni.scanCode({
					success: (res) => {
						console.log(res);
						if (res.result) {
							// 处理扫码结果
							const [id, type] = res.result.split(',')
							console.log('扫码结果：', res.result);

							this.$fetch('overOrder', {
								orderId : id,
								type, // type区分，0-订单核销 1-代金券核销
							}).then(() => {
								uni.showToast({
									title: '核销成功',
									icon: 'none'
								})
							}).catch(err => {
								uni.showToast({
									title: '核销失败',
									icon: 'none'
								})
							})
						}
					},
					fail: (err) => {
						console.error('扫码失败：', err);
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						})
					}
				});
				// #endif
			},
			async fetchCouponData() {
				try {
					const { total } = await this.$fetch('queryVouchersList', { type: 0 })

					this.couponCount = total
				} catch (err) {

				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.page {
		background-color: #F5F5F5;

		.header {
			height: 550rpx;
			background-image: linear-gradient(#84A73F, #D8FF8F);
			justify-content: flex-end;
			position: relative;
		}
	}

	.user {
		margin-top: 123rpx;

		&-avatar {
			width: 115rpx;
			height: 115rpx;
			border-radius: 50%;
		}
		&-name {
			margin-top: 4rpx;
			color: $uni-text-color-inverse;
			font-size: 30rpx;
			text-align: center;
		}
	}
	
	.no-login {
		margin-top: 123rpx;
		align-items: center;
		
		&-img {
			width: 115rpx;
			height: auto;
			margin-bottom: 20rpx;
		}
		
		&-text {
			color: #FFFFFF;
			font-size: 28rpx;
			margin-bottom: 40rpx;
		}
		
		&-btn {
			padding: 16rpx 60rpx;
			background-color: #FFFFFF;
			color: #84A73F;
			font-size: 28rpx;
			font-weight: bold;
			border-radius: 40rpx;
			box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
		}
	}

	.member {
		width: calc(100vw - 8rpx);
		height: 241rpx;
		// position: absolute;
		// bottom: 0;
		// left: 13rpx;
		position: relative;
		margin-top: 37rpx;
    transform: translateY(10rpx);

		color: #F5F5F5;
		font-size: 22rpx;

		// background-color: #2B2C30;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;

		&-bg {
			width: 100%;
			height: 100%;
		}

		&-overview {
			position: absolute;
			top: 10rpx;
			left: 30rpx;
			min-height: 81rpx;
			justify-content: space-between;

			&.is-member {
				justify-content: flex-start;
			}
		}

		.icon {
			height: auto;

			&-crown {
				width: 35rpx;
				margin-left: 20rpx;
			}

			&-member {
				width: 62rpx;
			}

			&-role {
				width: 156rpx;
				margin-right: 15rpx;
			}

			&-rights {
				width: 56rpx;
				margin-right: 11rpx;
			}
		}

		&-btn {
			display: inline-block;
			position: absolute;
			top: 26rpx;
			right: 28rpx;
			padding: 14rpx 20rpx;
			color: #000000;
			font-size: 22rpx;
			border: none;
		}

		&-tips {
			margin-left: 6rpx;
		}
	}

	.card {
		margin: 20rpx 13rpx 0 13rpx;
	}

	.account {
		padding: 40rpx 40rpx 23rpx 40rpx;
		justify-content: space-between;

		&-label {
			color: #666666;
			font-size: 28rpx;
			margin-top: 9rpx;
		}

		&-value {
			color: #000000;
			font-size: 32rpx;
		}

		&-unit {
			color: #666666;
			font-size: 18rpx;
			margin-left: 2rpx;
		}
	}

	.fun {

		&-header {
			text-align: left;
			padding-left: 12rpx;
			margin-bottom: 19rpx;

			/deep/ .title__view {
				display: inline-flex;
			}
		}

		&-content {
			margin-top: 24rpx;			
		}

		&-common {
			padding: 30rpx 40rpx 67rpx 40rpx;

			&-content {
				display: grid;
				grid-template-columns: repeat(4, 1fr);
				grid-column-gap: 71rpx;
				grid-row-gap: 81rpx;
			}

			&-icon {
				width: 66rpx;
				height: auto;
			}

			&-label {
				color: #000000;
				font-size: 28rpx;
				margin-top: 5rpx;
			}
		}

		&-merchant {
			padding: 33rpx 30rpx 28rpx 30rpx;
			margin-bottom: 10rpx;

			&-content {
				justify-content: space-between;
			}

			.left {
				width: 198rpx;
				height: 139rpx;
				position: relative;

				&-bg {
					width: 100%;
					height: 100%;
				}

				&-content {
					position: absolute;
					top: 13rpx;
					left: 14rpx;

					color: $uni-text-color-inverse;
					font-size: 28rpx;
				}

				&-icon {
					width: 23rpx;
					height: auto;
					margin-left: 9rpx;
				}
			}

			.right {
				width: 429rpx;
				height: 164rpx;
				margin-top: -25rpx;
				&-bg {
					width: 100%;
					height: 100%;
				}
			}
		}
	}
</style>