<template>
	<view class="container">
		<!-- 禁用弹窗 -->
		<restrictedTip ref="restrictedOrCanelTip" :showCode="showCode" confirmText="前往首页"
			:content="restrictedOrCanelContent" @confirm="gotoIndex()" />
		<image class="imgbox" src="../assets/images/bg1.jpg" mode="widthFix"></image>
		<view class="wapper">
			<view style="flex: 1;">
				<view class="header">
					<view class="headerLeft">
						<view class="one">
							合伙人加盟
						</view>
						<view class="two">
							优质资源，专业服务
						</view>
					</view>
					<view class="headerRight">
						<image class="headerImg" src="@/static/suplogo.png" mode="widthFix"></image>
					</view>
				</view>
				<view class="applyBox">
					<view style="height: 550rpx;">
						<view class="inputBox">
							<view class="txt">
								<text class="require">*</text>昵称 <text class="desTxt">（用于邀请好友及统计业绩显示）</text>
							</view>
							<view class="">
								<input class="user-input" maxlength="10" type="text" placeholder="请输入2~10个字符"
									v-model="form.nickName" />
							</view>
						</view>
						<view class="inputBox">
							<view class="txt">
								<text class="require">*</text>手机号码 <text class="desTxt">（账号唯一标识）</text>
							</view>
							<view class="codeBox">
								<input type="number" class="user-input" name="mobileNo" placeholder="请输入手机号"
									v-model="form.mobile" maxlength="11" :disabled="editMobile" />
								<view :class="{'grey':disabledSendBtn}" @click="sendMessage()"
									v-if="showVerificationCode">
									{{sendCodeHtml}}
								</view>
							</view>
						</view>
						<view class="inputBox" v-if="showVerificationCode">
							<view class="txt">
								<text class="require">*</text>验证码
							</view>
							<view class="">
								<input type="number" class="user-input" name="mobileNo" placeholder="请输入短信验证码"
									v-model="form.code" maxlength="6" />
							</view>
						</view>
						<view class="protol">
							<view class="empty" v-if="!agreeFlag" @click="agreeFlag=true"></view>
							<text v-else class="iconfont icon-icon_duihao-mian" @click="agreeFlag=false"></text>
							<text style="color: #666;">我已阅读并同意</text>
							<text style="color: #20269B;" @click="getFile(1)">服务协议</text>
							<text style="color: #666666;">和</text>
							<text style="color: #20269B;" @click="getFile(2)">隐私条款</text>
						</view>
					</view>
					<view class="btnBox" @click="gotoApply">
						{{loginType=='codelogin'?'确认加盟':'注册并加盟'}}
					</view>
				</view>
			</view>
			<view class="footer">
				银盾家办
			</view>
		</view>
		<!-- 已加盟为合伙人提示弹窗组件 -->
		<everyJoinPopup ref="everyJoinPopup" @continue="jumpPage" :showCanel="false" />
		<!-- 成功加盟为合伙人提示弹窗组件 -->
		<everyJoinPopup ref="successJoinPopup" @continue="jumpPage(e)" content="您已加盟为银盾家办合伙人"
			twoContent='购买一单"财务健康智能体检"即可升级为新锐合伙人,享受组织利益' continueText="前往购买" cancelText="暂不购买，继续浏览" fontColor="#20279B"
			:maskClick="false" icon="icon-dianzan" iconSize='80rpx' :showCanel="true" />
	</view>
</template>

<script>
	import everyJoinPopup from "@/components/commonPopup/everyJoinPopup.vue";
	import api from '@/api/api';
	import * as environment from "@/environments/environment";
	import common from '@/common/common';
	import dataHandling from "@/util/dataHandling";
	import { initJssdkShare, setWechatShare } from '@/util/fiveshare';
	import restrictedTip from '@/components/commonPopup/restrictedTip.vue';
	
	export default {
		components: {
			everyJoinPopup,
			restrictedTip
		},
		data() {
			return {
				companyInfo: environment.companyInfo,
				shareURL: environment.shareURL,
				form: {
					mobile: '',
					nickName: '',
					code: ''
				},
				agreeFlag: false,
				sendCodeHtml: '发送验证码',
				disabledSendBtn: false,
				timer: null,
				remainTimes: 60,
				loginType: uni.getStorageSync('loginType'),
				userInfo: '',
				userId: uni.getStorageSync('cffp_userId'), //本人id,
				InviteeUserId: '', //被邀请人id
				inviteUserId: '', //邀请人id,
				editNickName: false,
				editMobile: false,
				shareId: '', //邀请人分享得id
				invitationCode: '', //邀请码
				showCode: false, //弹窗是否展示客服二维码
				restrictedOrCanelContent: '', //禁用/注销展示文本
				sharePosterObj: { invitationCode: '', inviteUserId: '' }, //通过分享海报进来
				showVerificationCode: false, //验证码是否展示，

			}
		},

		onLoad(options) {
			if (uni.getStorageSync('loginType')) {
				this.loginType = uni.getStorageSync('loginType')
			}
			this.inviteUserId = ''
			if (options.inviteUserId) {
				this.inviteUserId = options.inviteUserId
			}
			if (options.invitationCode) {
				this.invitationCode = options.invitationCode
			}
			// 邀请链接进来的统一走注册加盟
			if (options.shareId) {
				this.shareId = options.shareId
				this.getqueryById(options.shareId)
				// uni.clearStorageSync()
				// uni.setStorageSync('loginType', 'visitor')
			}

		},

		onShow() {
			if (uni.getStorageSync('loginType')) {
				this.loginType = uni.getStorageSync('loginType')
			}
			if (uni.getStorageSync('cffp_userInfo')) {
				this.userInfo = JSON.parse(uni.getStorageSync('cffp_userInfo'))
			}
			if (uni.getStorageSync('cffp_userId')) {
				this.userId = uni.getStorageSync('cffp_userId')
			}
			if (!uni.getStorageSync('loginType') || this.loginType == 'visitor') {
				this.loginType = 'visitor'
				this.checkToken()
			}
			// 非邀请状态
			if (!this.shareId && this.loginType == 'codelogin' && this.userInfo.mobile) {
				this.form.mobile = this.userInfo.mobile
				this.editMobile = true
				this.showVerificationCode = false
			}
			// 非邀请状态
			if (!this.shareId && this.loginType == 'codelogin' && !this.form.nickName) {
				this.queryInfo()
			}
			// 登录状态 非邀请
			if (this.loginType == 'codelogin' && !this.shareId) {
				// #ifdef H5
				initJssdkShare(() => {
					setWechatShare();
				}, window.location.href);
				// #endif
			} else {
				this.showVerificationCode = true
			}

		},
		methods: {
			gotoIndex() {
				uni.switchTab({
					url: '/pages/index/index'
				})
				this.$refs.restrictedOrCanelTip.close()
			},
			// 未登录状态下需要重新获取token
			checkToken() {
				api.checkToken().then(res => {
					if (res['success']) {} else {
						api.obtainToken().then(res => {
							if (res.success) {
								uni.setStorageSync('uni-token', res.data['token']);
								// #ifdef H5
								initJssdkShare(() => {
									setWechatShare();
								}, window.location.href);
								// #endif
							}
						})
					}
				})
			},
			getqueryById(shareId) {

				api.queryById({ id: shareId }).then(res => {
					this.form.nickName = res.data.data.name
					this.form.mobile = res.data.data.mobileNumber
					this.editNickName = this.editMobile = true
					// 手机号一致的没做判断，以后可能要做判断
					// if(this.userInfo&&(this.userInfo.mobile !==this.form.mobile )){
					// 	this.showVerificationCode = true
					// 	uni.setStorageSync('loginType', 'visitor')
					// 	return
					// }
					// 之前登录过，但和申请加盟的账号不一致
					if (this.userInfo && (this.userInfo.mobile !== this.form.mobile)) {
						this.showVerificationCode = true
						uni.setStorageSync('loginType', 'visitor')
						this.loginType = 'visitor'

						return
					}
					if (res.data.data.isPartner && this.loginType == 'codelogin') {
						this.$refs.successJoinPopup.open()
					}
				})
			},
			jumpPage(e) {
				// e===1时，前往购买；e===2暂不购买；目前全部跳转到首页，不进行判断
				uni.switchTab({
					url: '/pages/index/index'
				})
				this.$refs.successJoinPopup.close()
				this.$refs.everyJoinPopup.close()
			},
			getFile(type) {
				let typeName = type == 1 ? '服务协议' : type == 2 ? '隐私条款' : ''
				dataHandling.pocessTracking(
					'查看协议',
					`查看${typeName}`,
					'点击',
					2,
					'申请加盟',
					'pages/saleCourseLists/saleCourseLists'
				)
				uni.navigateTo({
					url: `/myPackageA/ruleAndContract/clause?type=${type}`
				})
			},
			c_agreeFlag() {
				this.agreeFlag = !this.agreeFlag;
			},

			delayTime() {
				this.disabledSendBtn = true;
				this.timer = setInterval(() => {
					this.remainTimes--;
					this.sendCodeHtml = `${this.remainTimes}(S)`;
					if (this.remainTimes <= 0) {
						this.sendCodeHtml = '获取验证码';
						this.remainTimes = 60;
						this.disabledSendBtn = false;
						clearInterval(this.timer);
					}
				}, 1000);
			},
			sendMessage() {
				const params = {
					mobileNo: this.form.mobile,
					type: "1",
					source: "cffp"
				}
				if (common.mobileNoValid(this.form.mobile)) {
					if (!this.disabledSendBtn) {
						api.verificationCode(params).then((res) => {
							if (res['success']) {
								this.delayTime()
							} else {
								common.errorDialog(2, res['message'])
							}
						})
					}
				} else {
					common.errorDialog(2, '请填写手机号')
				}
			},
			gotoApply: dataHandling.debounce(function () {
				uni.showLoading({
				  title: '申请中...'
				});
				if (uni.getStorageSync('sharePosterObj')) {
					this.sharePosterObj = uni.getStorageSync('sharePosterObj')
				}
				console.log('this.sharePosterObj', this.sharePosterObj)
				// 登录并且是禁用状态
				if (this.loginType == 'codelogin' && this.userInfo.userIsActive == 2) {
					this.showCode = true
					this.restrictedOrCanelContent = '您的账号处在不可用状态，请扫码添加客服咨询情况'
					this.$refs.restrictedOrCanelTip.open()
					return
				}
				// 登录并且是注销状态 前端不判断，通过申请加盟的接口判断
				if (!this.form.nickName) {
					common.errorDialog(1, '请输入昵称');
					return false;
				}
				if (this.form.nickName && this.form.nickName.length < 2) {
					common.errorDialog(1, '昵称长度为2~10个字符');
					return
				}
				if (!this.form.mobile) {
					common.errorDialog(1, '请输入手机号');
					return false;
				}
				if (!common.mobileNoValid(this.form.mobile)) {
					common.errorDialog(2, '手机号格式填写错误');
					return false;
				}
				if (!this.loginType || this.loginType === 'visitor') {
					if (!this.form.code) {
						common.errorDialog(1, '请输入验证码');
						return false;
					}
				}
				if (!this.agreeFlag) {
					uni.showToast({
						title: '请阅读并勾选' + `${this.companyInfo.companyFullName}` + '服务协议和隐私条款',
						duration: 3000,
						icon: 'none'
					})
					return false;
				}
				const params = {
					loginType: '3',
					...this.form,
					visitorUuid:uni.getStorageSync('visitorUuid')?uni.getStorageSync('visitorUuid'):dataHandling.uuid()
				}
				if (this.loginType == 'codelogin') {
					this.getApply()
					uni.hideLoading()
					return
				}
				if (!this.loginType || this.loginType == 'visitor') {
					api.loginVerification(params).then((res) => {
						uni.hideLoading()
						if (res['success']) {
							// 不能登录并且是禁用状态
							if (res.data.userIsActive == 2) {
								this.showCode = true
								this.restrictedOrCanelContent = '您的账号处在不可用状态，请扫码添加客服咨询情况'
								this.$refs.restrictedOrCanelTip.open()
								return
							}
							this.userId = String(res['data']['userId']);
							uni.setStorageSync('isLogin', '1');
							uni.setStorageSync('loginType', 'codelogin');
							uni.setStorageSync('cffp_userId', this.userId);
							uni.setStorageSync('uni-token', res.data['token']);
							uni.setStorageSync('visitorUuid', res.data['visitorUuid']);
							this.queryInfo()
							// 禁用和注销状态并存，以禁用为准  
							// 已经进行过注销操作的， 弹窗提示90天内不可再次申请加盟为合伙人
							//  partnerIsActive 合伙人状态：1签约，2解约，3为加盟 ；解约过的合伙人状态一直为解约，直到下次签约成功才会改变
							// 登录并且是注销状态 前端不判断，通过申请加盟的接口判断
							// if(res.data.partnerIsActive==2){
							// 	this.showCode = false
							// 	this.restrictedOrCanelContent = '90天内不可再次申请加盟为合伙人'
							// 	this.$refs.restrictedOrCanelTip.open()
							// 	return
							// }
							// 是合伙人就不让在加盟
							if (res.data.isPartner && res.data.partnerIsActive == 1) {
								this.$refs.everyJoinPopup.open()
								return
							}
							// 不是合伙人就加盟
							if (!res.data.isPartner && res.data.partnerIsActive != 1) {
								this.getApply()
							}

						} else {
							uni.showToast({
								title: res['message'],
								duration: 2000,
								icon: 'none'
							})
						}
					})

				}

			}, 500),
			

			queryInfo() {
				api.queryInfo({ userId: uni.getStorageSync('cffp_userId') }).then(res => {
					// 保存用户得个人信息
					if (res['success']) {
						this.form.nickName = res['data']['nickName']
						if (this.form.nickName) {
							this.editNickName = true
						} else {
							this.editNickName = false
						}
						delete res.data.commonResult
						const cffp_userInfo = {
							...res.data
						}
						uni.setStorageSync('cffp_userInfo', JSON.stringify(cffp_userInfo))
						uni.setStorageSync('user_mobile', cffp_userInfo.mobile)

					} else {
						uni.setStorageSync('loginType', 'visitor')
						this.loginType = 'visitor'
					}

				})
			},
			// 申请加盟
			getApply() {
				console.log('login状态', this.loginType);
				let params = {}
				if (this.shareId) {
					params = {
						applyType: '1',
						applyUserId: this.userId,
						applyMobile: this.form.mobile,
						inviteUserId: this.inviteUserId,
						nickName: this.form.nickName,
						inviterInvitationCode: this.invitationCode,
						shareId: this.shareId
					}
				} else {
					params = {
						applyType: '2',
						applyUserId: this.userId,
						applyMobile: this.form.mobile,
						nickName: this.form.nickName,
						inviteUserId: this.sharePosterObj.inviteUserId,
						invitationCode: this.sharePosterObj.invitationCode
					}
				}
				api.newSaveApplyInfo(params).then((res) => {
					if (res['success']) {
						// 是合伙人就不让在加盟
						if (res.data.isPartner) {
							this.$refs.everyJoinPopup.open()
							return
						}
						dataHandling.pocessTracking(
							'加盟',
							`已成功加盟为合伙人`,
							'点击',
							2,
							'申请加盟',
							'pages/saleCourseLists/saleCourseLists'
						)
						this.$refs.successJoinPopup.open()
					} else {
						// 由于注销需求，依据后端报错展示弹窗
						this.showCode = false
						this.restrictedOrCanelContent = res['message']
						this.$refs.restrictedOrCanelTip.open()

					}
				})
			},

		},

	}
</script>

<style lang="scss" scoped>
	::v-deep .uni-radio-input {
		// background-color: #20279B !important;
		// border-color: #20279B !important;
	}

	.container {
		position: relative;
		box-sizing: border-box;

		.imgbox {
			display: block;
		}

		.wapper {
			// background-color: pink;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			position: absolute;
			top: 0;
			left: 0;
			height: 100%;
			width: 100%;
			padding: 0 50rpx;
			// .header{
			// 	color: #333333;
			// 	margin-top: 140rpx;
			// 	.one{
			// 		font-size: 60rpx;
			// 		font-weight: 700;

			// 	}
			// 	.two{
			// 		font-size: 30rpx;
			// 		font-weight: 500;
			// 	}
			// }
			.header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				color: #333333;

				margin-top: 30rpx;

				.one {
					font-size: 60rpx;
					font-weight: 700;
					margin-bottom: 20rpx;

				}

				.two {
					font-size: 30rpx;
					font-weight: 500;
				}

				.headerRight {
					width: 300rpx;
				}

			}

			.headerImg {
				width: 300rpx;
				height: 300rpx;
				opacity: .5;
			}

			.applyBox {
				background-color: #fff;
				padding: 30rpx;
				border-radius: 20rpx;
				// margin-top: 100rpx;
				box-sizing: border-box;

				.inputBox {
					margin-bottom: 20rpx;
					padding-bottom: 10rpx;
					border-bottom: 1rpx solid #E8E8E8;

					.require {
						font-size: 24rpx;
						color: red;
					}

					.desTxt {
						font-size: 24rpx;
						color: #333333;
					}

					.user-input {
						color: black;
						font-size: 26rpx;
						margin-top: 15rpx;
					}

					.codeBox {
						display: flex;
						align-items: center;
						justify-content: space-between;
						color: #20279B;
						font-size: 26rpx;

						.grey {
							color: rgba(32, 39, 155, 0.5);
							/* 50% 透明 */
						}
					}
				}

				.agreeBox {
					padding-top: 20rpx;
					font-size: 26rpx;
					color: #20279B;

				}

				.protol {
					display: flex;
					align-items: center;
					font-size: 26rpx;

					.empty {
						width: 30rpx;
						height: 30rpx;
						border: 1rpx solid #20269B;
						border-radius: 50%;
						margin-right: 5rpx;
					}

					.icon-icon_duihao-mian {
						font-size: 30rpx;
						color: #20269B;
						margin-right: 5rpx;
					}
				}

				.btnBox {
					box-sizing: border-box;
					width: 80%;
					text-align: center;
					padding: 20rpx;
					border-radius: 50rpx;
					background-color: #20279B;
					color: #fff;
					font-size: 28rpx;
					margin: 0rpx 50rpx 30rpx 50rpx;
				}
			}

			.footer {
				font-size: 28rpx;
				color: rgba(0, 0, 0, .5);
				width: 100%;
				text-align: center;
				margin-bottom: 20rpx;
				margin-top: auto;
				letter-spacing: 8rpx;
			}
		}
	}
</style>