<template>
  <div>
    <!-- 杭州新增的确认弹窗 -->
    <div
      class="authorize-hz"
      v-if="isShow == 1 && !isComfirHz && isHangzhou"
      catchtouchmove="ture"
    >
      <div class="mid">
        <div class="authorize-box">
          <div class="bold">亲爱的会员，</div>
          <div class="other">
            为更好的为您提供会员服务，2021年12月8日起，杭州嘉里中心会员系统将全新升级为Kerry+，您的权益及积分将同步至新系统，如您有任何疑问欢迎拨打客服电话0571-88118888或前往服务台咨询。杭州嘉里中心诚挚为您服务，祝您生活愉快！
          </div>
          <div class="checkBox">
            <checkbox-group @change="changeHZ">
              <checkbox
                style="transform: scale(0.8)"
                color="#8CC63F"
                value="protocol"
                :checked="checkedHZ"
              />
            </checkbox-group>
            <div style="color: #4d4d4d; font-size: 28px; text-align: justify">
              已确认<span class="popup-a" @click="showChangeDetail"
                >《会员变更细则》</span
              >，且老会员同意将原KerryOn会员账号信息同步至Kerry+杭州
            </div>
          </div>
        </div>
        <div class="authorize-footer">
          <button class="disagree_btn" @click="disagreeHZ">不同意</button>
          <button
            class="agree_btn"
            :class="!checkedHZ ? 'disabled' : ''"
            @click="confirmHzClick()"
            :disabled="!checkedHZ"
          >
            同意
          </button>
        </div>
      </div>
      <uni-popup ref="popupHZ" type="center" style="z-index: 999999">
        <div class="auth-popup">
          <div class="auth-popup__main" style="padding: 40px">
            <div
              style="
                margin-bottom: 37px;
                font-size: 28px;
                color: #666;
                font-weight: 500;
                text-align: justify;
              "
            >
              亲爱的会员，请返回确认《会员变更细则》，继续使用Kerry+小程序
            </div>
          </div>
          <div class="auth-popup__footer">
            <div class="cancel" @click="cancelComfire(0)">取消</div>
            <div
              style="flex: 1; border-left: 1px solid #f0f0f0"
              @click="backComfirHZ"
              >返回</div
            >
          </div>
        </div>
      </uni-popup>
    </div>
    <!-- KerryOn新增的确认弹窗 -->
    <div
      class="authorize-hz"
      v-else-if="isShow == 1 && !isComfirOn && isKerryOn"
    >
      <div class="mid">
        <div class="authorize-box">
          <div class="bold">亲爱的会员，</div>
          <div class="bold">KerryOn会员协议更新提示：</div>
          <div style="color: #666">
            2021年12月8日起，您在KerryOn积分参与商场将不包括原杭州嘉里中心，您的原先KerryOn账户会员积分和权益将不受影响，
            您2021年12月8日之后在静安嘉里中心、浦东嘉里中心、北京嘉里中心产生的KerryOn会员积分将不可用于杭州嘉里中心兑换。
            如您有任何疑问可拨{{ tel }}或去服务台咨询。
          </div>
        </div>
        <div class="authorize-footer">
          <button class="disagree_btn" @click="disagreeON">不同意</button>
          <button class="agree_btn" @click="isComfirOn = true">同意</button>
        </div>
      </div>
      <uni-popup ref="popupON" type="center" style="z-index: 999999">
        <div class="auth-popup">
          <div class="auth-popup__main" style="padding: 40px">
            <div
              style="
                margin-bottom: 37px;
                font-size: 28px;
                color: #666;
                font-weight: 500;
                text-align: justify;
              "
            >
              您确认不同意本次会员协议变更吗？在您未去线下处理之前小程序服务将暂不可用
            </div>
          </div>
          <div class="auth-popup__footer">
            <div class="cancel" @click="backComfirON">取消</div>
            <div
              style="flex: 1; border-left: 1px solid #f0f0f0"
              @click="cancelComfire(1)"
              >确认不同意</div
            >
          </div>
        </div>
      </uni-popup>
    </div>
    <div
      class="authorize"
      v-if="isShow == 1"
      :style="{ 'padding-top': paddingTop + 'px' }"
    >
      <div class="show-auth" v-if="isShowSQ == 1">
        <div class="authorize__head">
          <div class="head__info">
            <div class="head__logo">
              <img
                class="head__logo__img"
                :src="getLogo"
                mode="heightFix"
                @click="disagreeHZ"
              ></img>
            </div>
            <div class="head__text"
              >立刻成为<span>{{ brandInfo?.name }}</span
              >会员, 即可享受会员权益</div
            >
          </div>
        </div>
        <div class="authorization_button_wrap">
          <div class="authorize_btn authorize_btn--wx" @click="getUserProfile">
            <img
              src="~@/static/images/authorize/weixin-2.svg"
              mode=""
              style="width: 57px; height: 48px; margin-right: 13px"
            />微信一键登录/注册
          </div>
        </div>
        <div class="authorization_button_wrap">
          <button
            class="authorize_btn authorize_btn--phone"
            @click="toPhoneLogin"
          >
            手机验证码登录/注册
          </button>
        </div>
        <div class="authorization_button_wrap">
          <div style="margin: 0 30px">
            <div style="display: flex">
              <checkbox-group @change="protocolChange">
                <checkbox
                  style="transform: scale(0.8)"
                  color="#808080"
                  value="protocol"
                  :checked="protocolChecked"
                />
              </checkbox-group>
              <div v-if="brandInfo" style="color: #666666; font-size: 32px">
                已阅读并同意<span
                  style="color: #627ecf"
                  @click="gotoProtocol('protocol')"
                  >《{{ brandInfo.protocolName }}》</span
                >
                和<span
                  style="color: #627ecf"
                  @click="gotoProtocol('privacyPolicy')"
                  >《{{ brandInfo.privacyPolicyName }}》</span
                >
              </div>
              <div v-else> 已阅读并同意会员计划条款及细则和隐私策略 </div>
            </div>
          </div>
        </div>
      </div>
      <uni-popup ref="popup" type="center" style="z-index: 999999">
        <div class="auth-popup">
          <div class="auth-popup__head">
            <span>微信授权</span>
          </div>
          <div class="auth-popup__main">
            <div class="head__logo">
              <img
                class="head__logo__img"
                :src="getLogo"
                mode="heightFix"
              />
            </div>
            <div
              style="
                margin-bottom: 37px;
                font-size: 33px;
                color: #333;
                font-weight: 500;
              "
              >申请获取以下权限</div
            >
            <div
              style="
                margin-top: 38px;
                margin-bottom: 32px;
                border-top: 1px solid #f0f0f0;
                color: #999999;
                font-size: 32px;
                padding-top: 38px;
              "
              >获得你的公开信息(手机号等)</div
            >
          </div>
          <div class="auth-popup__footer">
            <div class="cancel" @click="closeAuthPhonePopup">取消</div>
            <div style="flex: 1; border-left: 1px solid #f0f0f0">
              <button
                class="phone-btn"
                open-type="getPhoneNumber"
                @getphonenumber="authorizePhone"
              >
                确认授权
              </button>
            </div>
          </div>
        </div>
      </uni-popup>
    </div>
    <PerfectInfo
      :isShow="infoIsshow"
      @closeInfo="closeInfo"
      v-if="custTypeId === 0 && infoIsshow"
    ></PerfectInfo>
    <BluePerfectInfo
      ref="bluePerfectInfo"
      :isShow="blueInfoIsShow"
      @closeBlueInfo="closeBlueInfo"
      v-if="custTypeId !== 0 && blueInfoIsShow"
    ></BluePerfectInfo>
  </div>
</template>
<script>
	import log from '@/utils/log.js'
	import md5 from '@/common/js/md5.js'
	import {
		kipUpdateWxMember,
		kipGetWxMember,
		kipOpenidLogin,
		kipWxAuthLogin,
		kipGetBrandInfo,
		kipMemberAddBrand,
		kipCheckToken,
		kipGetNewAccessTokenByRefreshToken,
	} from '@/utils/api-kip.js'
	import {
		crmGetMemberByKipProfileId,
		crmCreateNewMemberByBrand,
		crmGetOpenId,
		memberCertification,
	} from '@/utils/api-crm-member.js'
	import MemberCacheTool from '@/utils/member-cache-tool.js'
	import KipCacheTool from '@/utils/kip-cache-tool.js'
	// var app = getApp();
 const app = {}
	var self;
	import uniPop from '@/components/uni-popup/uni-popup.vue'
	import { mapState } from "vuex";
  import uni from '@/utils/uniHooks'
  import {
		getLogoByBrand,
		getUTMSource,
	} from '@/utils/utils.js'
	import CacheTool from '@/utils/cache-tool.js'
	import PerfectInfo from '@/components/info/perfectInfo.vue'
	import BluePerfectInfo from '@/components/info/blue-perfectinfo.vue'
	const {
		KERRY_ON_BRAND_ID,
		PUDONG_LBS_ID,
		JINGAN_LBS_ID,
		BEIJING_LBS_ID,
		HANGZHOU_LBS_ID,
	} = CacheTool.getCurEnvConst();
	export default {
		name: 'authorize',
		props: {
			page: {
				type: String,
				default: ''
			},
			isFull: {
				type: Boolean,
				default: false
			}
		},
		components: {
			uniPop,
			PerfectInfo,
			BluePerfectInfo
		},
		data() {
			return {
				isShow: 0,
				isShowSQ: 0,
				callbackFn: '',
				url: '',
				logoImg: '',
				protocolChecked: false,
				wxProfile: null,
				picUrl: this.$picUrl,
				baseUrl: this.$baseURL,
				globalData: app.globalData,
				brandInfo: null,
				curJsCode: null,
				needLogin: false,
				authInfo: null,
				paddingTop: 0,
				// new
				isComfirHz: false,
				checkedHZ: false,
				isComfirOn: false,
				checkedON: false,
				tel: '0512-87654321',
				isHangzhou: false,
				infoIsshow: false, // 是否显示
				blueInfoIsShow: false, // 上海完善页面是否显示
				preUrl: '',
				// optionsQuery: uni.getStorageSync('options_query')
			};
		},
		created() {
			// self = this;
			// console.log('===================', BEIJING_LBS_ID, HANGZHOU_LBS_ID)
			// self.isComfirHz = uni.getStorageSync('comfirHangzhou');
		},
		computed: {
			...mapState({
				custTypeId: state => state.custTypeId
			}),
			getLogo () {
				return getLogoByBrand(this.brandInfo)
			},
			// isHangzhou() {
			// 	return uni.getStorageSync('mallid') == HANGZHOU_LBS_ID;
			// },
			isKerryOn() {
				return false;
				// return app.globalData?.groupId == KERRY_ON_BRAND_ID;
				// return uni.getStorageSync('groupId') == KERRY_ON_BRAND_ID;
				// return uni.getStorageSync('mallid') == BEIJING_LBS_ID
				// 	|| uni.getStorageSync('mallid') == JINGAN_LBS_ID
				// 	|| uni.getStorageSync('mallid') == PUDONG_LBS_ID;
			}
		},
		mounted() {
			// this.getBrandInfo()
			console.log('==>========================登陆组件部分')
			// const token = KipCacheTool.getKipToken();
			// self.checkTokenOrRefreshToken(token);
			// self.memberCertification();
		},
		watch: {
			isShow (newValue, oldValue) {
				if (newValue) {
					this.getBrandInfo()
					this.isHangzhou = uni.getStorageSync('mallid') == HANGZHOU_LBS_ID;
					this.isComfirHz = uni.getStorageSync("comfirHangzhou") || false;
					this.isComfirOn = uni.getStorageSync('comfirKerryOn') || false
				}
			}
		},
		onShow() {
			this.checkedHZ = false;
			// if (uni.getStorageSync('memberChangeFile')) this.isShow = 1, uni.setStorageSync('memberChangeFile', false);
		},
		methods: {
			// 校验token
			checkTokenOrRefreshToken (token) {
				// console.log('==>在买个搭载登陆组件的页面进行token校验', token)
				// 判断token是否过期，过期后刷新token
				if (token) {
					const _this = this;
					kipCheckToken(token).then(resp => {
						if (resp && resp.statusCode == '401') {
							log.info(`access_token已过期，使用refresh_token刷新access_token，如果refresh_token过期则删除所有数据`)
							// token过期之后使用refresh_token刷新access_token，如果refresh_token过期则删除所有数据
							const kipRefreshToken = KipCacheTool.getKipRefreshToken();
							kipGetNewAccessTokenByRefreshToken(kipRefreshToken).then(resp => {
								const result = resp.data;
								if (result && result.code === '000000' && result.data.access_token) {
									KipCacheTool.setKipToken(result.data.access_token);
									log.info(`refreshToken获取成功，这是新的token:`, result.data.access_token)
								} else {
									uni.showToast({
										title: result.message,
										duration: 2000,
										icon: 'none'
									})
									console.warn("===>清除所有缓存1")
									log.info(`清除所有缓存1`)
									_this.cleanAll();
									_this.login();
								}
							}).catch(err => {
								console.warn("===>清除所有缓存2")
								log.info(`清除所有缓存2`)
								_this.cleanAll();
								_this.login();
							})
						}
					}).catch(err => {
						console.error(err)
						console.warn("===>清除所有缓存3")
						log.info(`refresh_token获取失败，清除所有缓存3`,err)
						_this.cleanAll();
					})
				}
			},
			memberCertification() {
				// 会员认证
				const _this = this;
				const member = app?.globalData?.member || uni.getStorageSync('member')
				if (member) {
                const params = {
					kipUserId: member.kipUserId,
					groupId: uni.getStorageSync('groupId'),
					mallid: uni.getStorageSync('mallid')
				}
				memberCertification(_this.$baseURL, params).then(resp => {
          const result = resp.data;
          if (result && result.code == '0') {
            console.log('result',result.data)
          } else {
						uni.showToast({
							title: result.message,
							duration: 2000,
							icon: 'none'
						})
					}
				}).catch(err => {
						console.error(err)
						log.info(`会员认证失败`,err)
					})
				}
			},
			cleanAll() {
				// 清除所有用户信息
				KipCacheTool.cleanKipCache();
				MemberCacheTool.cleanMemberCache(this);
			},
			/**
			 * 关闭vvip完善信息页面
			 */
			closeBlueInfo() {
				this.blueInfoIsShow = false
				this.$refs.bluePerfectInfo.closePerfectinfo()
				self.callbackFn && self.callbackFn()
			},
			/**
			 * 关闭完善信息页面
			 */
			closeInfo() {
				this.infoIsshow = false
				self.callbackFn && self.callbackFn()
			},
			closeAll() {
				this.isShow = 0
				this.isShowSQ = 0
				uni.redirectTo({
					url: '/pages/automatic/automaticIndex',
				})
			},
			openPhoneAuth: function() {
				// 打开手机号授权框
				this.isShowSQ = 1
				this.isShow = 1
				this.$refs.popup.open()
			},
			openWxProfileAuth: function() {
				// 打开微信信息授权框

					this.isShowSQ = 1
					this.isShow = 1
				if (this.isFull && this.isShow) {
					this.paddingTop = 200;
				}
				this.loginBefore()
			},
			closeAllAuth: function () {
				// 关闭手机号和微信信息授权框
				this.isShowSQ = 0
				this.isShow = 0
			},
			gotoProtocol(type) {
				const brandId = app.globalData?.groupId
				const lbsId = app.globalData?.mallid
				const isChecked = this.protocolChecked;
				this.sensorsClick('$ClickConsentAgreement', {
					redirect_url: '/pages/protocol/protocol',
				})
				this.$router.push({
					path: `/pages/protocol/protocol?type=${type}&brandId=${brandId}&lbsId=${lbsId}&isChecked=${isChecked}`
				})
			},
			// 埋点方法
			sensorsClick(eventName, params) {
				let optionsQuery = uni.getStorageSync('options_query')
				let fixedParams = {
					cta_itemno: '',
					cta_name: '',
					previous_url: this.preUrl || '',
					// 原previous_url: uni.getStorageSync('previousUrl') || ''
					// previous_url: 使用sdk预置参数$referrer,
					$brand_id:uni.getStorageSync('groupId'),
					$location: uni.getStorageSync('mallid'),
					$channel: optionsQuery.channel || '',
					// $utm_lbs: this.optionsQuery.utm_lbs || '',
					$utm_channel: optionsQuery.utm_channel || '',
					$utm_method: optionsQuery.utm_method || '',
					$utm_source: optionsQuery.utm_source || '',
					$utm_function: optionsQuery.utm_function || '',
					$utm_user: optionsQuery.utm_user || '',
				},
				finalParams = Object.assign(fixedParams, params)
				this.$sensors.track(eventName, finalParams)
			},
			protocolChange(e) {
				if (e.detail.value.length > 0) {
					this.protocolChecked = true;
				} else {
					this.protocolChecked = false;
				}
				// this.protocolChecked = !this.protocolChecked
			},
			changeHZ(e) {
				if (e.detail.value.length > 0) {
					this.checkedHZ = true;
				} else {
					this.checkedHZ = false;
				}
			},
			disagreeHZ() {
				this.$refs.popupHZ.open();
			},
			backComfirHZ() {
				this.$refs.popupHZ.close();
			},
			changeON(e) {
				if (e.detail.value.length > 0) {
					this.checkedON = true;
				} else {
					this.checkedON = false;
				}
			},
			disagreeON() {
				this.$refs.popupON.open();
			},
			backComfirON() {
				this.$refs.popupON.close();
			},
			cancelComfire(flag) {
				const curPages = getCurrentPages();
				// uni.setStorageSync("memberChangeFile", false);
				if (flag === 0) uni.setStorageSync("comfirHangzhou", false);
				else uni.setStorageSync("comfirKerryOn", false);
				if (curPages[curPages.length - 1].route == 'pages/automatic/automaticIndex') this.isShow = 0;
				else uni.navigateBack({ delta: curPages.length - 1 })
			},
			showChangeDetail() {
				this.$router.push({ path: '/pages/memberChange/index' });
			},
			login: function(url, callback) {
				console.log(`===> 授权登录 `, url, callback, this.isShow)
				this.url = url
				this.callbackFn = callback
				const kipAccessToken = KipCacheTool.getKipToken();

				if (!kipAccessToken) {
					this.openWxProfileAuth()
				} else {
					this.uniGetSetting()
				}
			},
			uniGetSetting: function() {
				const member = uni.getStorageSync("member");
				console.log(`==>当前会员信息: ${JSON.stringify(member)}`)
				if (!member) {
					this.openWxProfileAuth()
				} else {
					this.closeAllAuth();
					self.callbackFn && self.callbackFn()
				}
			},
			loginBefore: function () {
				const _this = this;
				uni.login({
					// #ifdef MP-WEIXIN
					provider: 'weixin',
					// #endif
					success: function(loginRes) {
						_this.curJsCode = loginRes.code;
						const params = {
							jsCode: _this.curJsCode,
							brandId: app.globalData?.groupId,
							lbsId: app.globalData?.mallid
						}
						kipOpenidLogin(params).then(resp => {
              console.log(612, resp)
							const result = resp.data;
							if (result.code == '000000' && result.data) {
								// 第一次返回: data.needLogin
								// app.globalData?.isNewUser = member.isNewUser;
								_this.needLogin = result.data.needLogin
								if (!_this.needLogin) {
									_this.authInfo = result.data;
									// 登录成功后将值存入localStorage中
									// if (_this.isHangzhou) {
									// 	uni.setStorageSync("comfirLocation", 'loginBefore---');
									// 	uni.setStorageSync("comfirHangzhou", true);
									// } else if (_this.isKerryOn) {
									// 	uni.setStorageSync("comfirLocation", 'loginBefore---');
									// 	uni.setStorageSync("comfirKerryOn", true);
									// }

								}
							} else {
								uni.showToast({
									title: result.message,
									duration: 2000,
									icon: 'none'
								})
								console.error(`登录失败，${result.message}`)
							}
						}).catch(err => {
							console.error(err);
						})
					}
				})
			},
			getUserProfile: function(e) {
				if (!this.protocolChecked) {
					uni.showModal({
						title: '请阅读并勾选下方的协议',
						showCancel: false,
					})
					return false;
				}
				const _this = this;
				self.isShowSQ = 1
				let headEmpty = false
				if(this.authInfo !=null){
					headEmpty = this.authInfo.headEmpty
				}
				if (this.needLogin) {
					uni.getUserProfile({
						desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
						success: (res) => {
							console.log(`===>拉取获取会员资料授权框`, res)
							self.wxProfile = res;
							self.openPhoneAuth()
						},
						fail: (res) => {
							self.getCrmOpenId();
							// self.closeAllAuth()
							// uni.redirectTo({
							// 	url: '../../pages/automatic/automaticIndex'
							// })
						},
					})
				} else {
					KipCacheTool.setKipCache(_this.authInfo);
					if (headEmpty) {
						this.getWxInfoAndModKipMemberInfo()
					} else {
						this.queryMemberAndUpdateMember()
					}

				}

			},
			queryMemberAndUpdateMember: function() {
				// 查询会员信息，如果不存在则更新，然后再次查询
				const _this = this;
				kipGetWxMember().then(resp => {
					const result = resp.data;
					if (result && result.code === '000000') {
						// 判断用户信息是否完整
						const member = result.data;
						if (!member || !member.nickName) {
							// 请求授权
							uni.getUserProfile({
								desc: '用于完善会员资料',
								success: (res) => {
									console.log(`===>拉取获取会员资料授权框`, res)
									self.wxProfile = res;
									_this.updateKipMemberByWxProfile(res);
								},
								fail: (res) => {
									self.closeAllAuth()
									uni.redirectTo({
										url: '../../pages/automatic/automaticIndex'
									})
								},
							})

						} else {
							// 存储用户信息
							const member = result.data;
							self.getKipMemberInfoAfter(member);
						}
					} else {
						KipCacheTool.cleanKipCache();
						MemberCacheTool.cleanMemberCache(app);
						console.error(`queryMemberAndUpdateMember,会员不存在: ${result.message}`)
						const message = result.message || '获取信息失败';
						uni.showToast({
							title: message,
							duration: 2000,
							icon: 'none'
						})
						uni.reLaunch({
							url: "/pages/automatic/automaticIndex"
						})
					}
				}).catch(err => {
					KipCacheTool.cleanKipCache()
					MemberCacheTool.cleanMemberCache(app);
					console.error(err);
				})
			},
			authorizePhone: function(res) {
				if (!res.detail.encryptedData) {
					uni.showToast({
						title: '请先授权手机号',
						duration: 2000,
						icon: 'none'
					})
					this.closeAllAuth()
					this.$router.push({
						path: '../../pages/automatic/automaticIndex'
					})
					return;
				}
				uni.showLoading({
					title: '正在授权'
				})
				self.wxAuthPhoneRegister(res);

			},
			wxAuthPhoneRegister: function(res) {
				// KIP微信授权登录流程,因为KIP后台会缓存jsCode所以不用checkSession
				this.$refs.popup.close();
				var params = {
					encryptedData: res.detail.encryptedData,
					iv: res.detail.iv,
					jsCode: this.curJsCode,
					brandId: app.globalData?.groupId,
					lbsId: app.globalData?.mallid
				}
				let _this = this;
				kipWxAuthLogin(params).then(resp => {
					uni.hideLoading()
					const result = resp.data;
					if ( result && result.code === '000000') {
						// 登录成功获取token
						const authInfo = result.data;
						KipCacheTool.setKipCache(authInfo);
						// 更新微信会员信息
						_this.updateKipMemberByWxProfile(_this.wxProfile)
						if (_this.isHangzhou) {
							uni.setStorageSync("comfirLocation", 'wxAuthPhoneRegister---');
							uni.setStorageSync("comfirHangzhou", true);
						} else if (_this.isKerryOn) {
							uni.setStorageSync("comfirLocation", 'wxAuthPhoneRegister---');
							uni.setStorageSync("comfirKerryOn", true);
							}
					} else {
						const message = result.message || '注册失败请重试';
						uni.showToast({
							title: message,
							duration: 2000,
							icon: 'none'
						})
						// 关闭手机号授权框，删除本地缓存
						console.error(result.message)
						_this.curJsCode = null
						_this.closeAuthPhonePopup()
						KipCacheTool.cleanKipCache()
						MemberCacheTool.cleanMemberCache(app);
						_this.loginBefore()
					}

				}).catch(err => {
					uni.hideLoading()
					console.error(err);
					_this.curJsCode = null
					_this.closeAuthPhonePopup()
					KipCacheTool.cleanKipCache()
					MemberCacheTool.cleanMemberCache(app);
				})
			},
			// 短信登录
			toPhoneLogin: function() {
				uni.redirectTo({
					url: '/pages/wxLogin/login?url=' + encodeURIComponent(JSON.stringify(self.url))
				});
			},
			closeAuthPhonePopup () {
				this.$refs.popup.close();
			},
			getBrandInfo () {
				// 获取当前brand的logo以及协议和隐私名称
				const HZ_BRAND_ID = app.globalData?.groupId
				const HZ_LBS_ID = app.globalData?.mallid
				const params = {
					id: HZ_BRAND_ID,
					lbsId: HZ_LBS_ID
				}
				kipGetBrandInfo(params).then(resp => {
					if (!resp || !resp.data || resp.data.code != '000000' ) {
						const message = resp.data.message || '服务不可用';
						uni.showToast({
							title: message,
							duration: 2000,
							icon: 'none'
						});
					} else {
						const brandArray = resp.data.data;
						if (brandArray && brandArray.length > 0 && brandArray[0]) {
							const brandInfo = brandArray[0].brand;
							self.brandInfo = brandInfo;
						}
					}

				}).catch(err => {
					console.error(err);
				})
			},
			getKipMemberInfoAfter (kipMemberInfo) {
				// 获取到kip会员之后的操作
				MemberCacheTool.setKipMember(app, kipMemberInfo)
				// 将kipMember转成crmMember
				const newMember = MemberCacheTool.handleKipMemberToCrmMember(kipMemberInfo)
				if (!newMember) {
					console.error("===> 会员不存在")
					uni.showToast({
						title: "会员转换错误",
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				const newGroupId = uni.getStorageSync("groupId");
				const newMallId = uni.getStorageSync("mallid");
				const params = {
					groupId: newGroupId,
					kipUserId: newMember.kipUserId
				}
				const _this = this;
				// 查询 crm 会员
				uni.showLoading({
					title: '正在加载',
					mask: true,
				})
				crmGetMemberByKipProfileId(this.$baseURL, params).then(resp => {
					uni.hideLoading()
					const result = resp.data;
					if (result && result.code == '0') {
						const {member, wxMember} = result.data;
						const optionsQuery = uni.getStorageSync('options_query') || {};
						if (member && member.groupId && member.openid) {
							// 这里埋点-登录过但是清空缓存
							console.log( '==>这里走埋---crmGetMemberByKipProfileId', member, wxMember )
							//  TODO: 埋点公共属性重新赋值
							// _this.$sensors.registerApp({
							// 	$open_id: _this.globalData?.member?.openId || wxMember.openid || '',
							// 	$profile_id: _this.globalData?.member?.kipUserId || member.kipUserId || '',
							// 	$member_id: _this.globalData?.member?.id || member.id || '',
							// 	$union_id: _this.globalData?.member?.unionid || wxMember.unionid || '',
							// 	// $location: _this.globalData?.mallid,
							// 	// $brand_id: _this.globalData?.groupId,
							// 	// $utm_source: JSON.stringify(uni.getStorageSync('options_query')) || '',
							// 	// $channel: optionsQuery?.channel || '',
							// 	$utm_lbs: optionsQuery?.utm_lbs || '',
							// 	// $utm_channel: optionsQuery?.utm_channel || '',
							// 	// $utm_method: optionsQuery?.utm_method || '',
							// 	// $utm_source: optionsQuery?.utm_source || '',
							// 	// $utm_function: optionsQuery?.utm_function || '',
							// 	// $utm_user: optionsQuery?.utm_user || '',
							// })
							MemberCacheTool.setMemberCache(app, {member, wxMember})
							_this.checkIsNewUser()
						} else {
							// 重新绑定brand或openId
							_this.kipMemberBindBrand(newMember, newGroupId, newMallId)
						}
					} else {
						_this.kipMemberBindBrand(newMember, newGroupId, newMallId)
					}

				}).catch(err => {
					uni.hideLoading()
					console.error(err)
					uni.showToast({
						title: "登录注册失败",
						duration: 2000,
						icon: 'none'
					})
					KipCacheTool.cleanKipCache()
					MemberCacheTool.cleanMemberCache(app)
				})
			},
			checkIsNewUser () {
				if (this.custTypeId == '0')  {
					const isNewUser = KipCacheTool.getKipIsNewUser();
					console.log(isNewUser)
					if (isNewUser) {
						self.closeAllAuth()
					//	const {path, query} = uni.getStorageSync('loginUser')
						// this.$router.push({
						// 	path: '/pages/personInfo/personInfo'
						// })
						this.infoIsshow = true
					} else {
						self.closeAllAuth()
						self.callbackFn && self.callbackFn()
					}
				} else {
					const member = app.globalData?.member;
					if (member && (!member.isCompleted || member.isCompleted == '0') ) {
						// this.$router.push({
						// 	path: '/pages/personInfo/bluePersonInfo'
						// })
						self.closeAllAuth()
						this.blueInfoIsShow = true
					} else {
						self.closeAllAuth()
						self.callbackFn && self.callbackFn()
					}
				}
			},
			kipMemberBindBrand (crmMember, newGroupId, newMallId) {
				// 将会员喝brand绑定
				const kipParams = {
					brandId: newGroupId,
					lbsId: newMallId
				}
				const _this = this;
				uni.showLoading({
					title:'正在加载',
					mask: true,
				})
				kipMemberAddBrand(kipParams).then(resp => {
					uni.hideLoading()
					const result = resp.data;
					if (result && result.code == '000000') {
						const data = result.data;
						if (data) {
							crmMember.groupId = newGroupId;
							crmMember.mallid = newMallId;
							// 创建会员信息
							_this.createCrmMember(crmMember);
						}
					} else {
						console.error(result.message);
						const message = result.message || '登录注册失败';
						uni.showToast({
							title: message,
							duration: 2000,
							icon: 'none'
						})
						KipCacheTool.cleanKipCache()
						MemberCacheTool.cleanMemberCache(app);
					}
				}).catch(err => {
					uni.hideLoading()
					console.error(err);
					uni.showToast({
						title: "登录注册失败",
						duration: 2000,
						icon: 'none'
					})
					KipCacheTool.cleanKipCache()
					MemberCacheTool.cleanMemberCache(app);
				})
			},
			createCrmMember (crmMember) {
				// 创建crm会员
				const _this = this;
				crmMember.source = `1`;
				uni.showLoading({
					title:'正在加载',
					mask: true,
				})
				const regSource = app.globalData?.regSource;
				if (regSource) {
					crmMember.registerSource = regSource.value;
					crmMember.registerSourceLabel = regSource.label;
				}

				const tpName = app.globalData?.tpName;
				const tpId = app.globalData?.tpId;
				if(tpName || tpId){
				    crmMember.registerSourceRemark = tpName+':'+tpId;
				}else{
				    crmMember.registerSourceRemark = '';
				}
				crmMember.regMemberSourceOriginalParams = JSON.stringify(getUTMSource());
				crmCreateNewMemberByBrand(this.$baseURL, crmMember).then(resp => {
					uni.hideLoading()
					const result = resp.data;
					if ( result && result.code == '0') {
						const {member, wxMember} = result.data;
						const optionsQuery = uni.getStorageSync('options_query') || {};
						if (member && wxMember) {
							// 这里埋点 注册、退出账号后走，重新对公共属性赋值
							console.log('==>这里走埋---createCrmMember', member, wxMember)
							// TODO: 埋点公共属性重新赋值
							// _this.$sensors.registerApp({
							// 	$open_id: _this.globalData?.member?.openId || wxMember.openid || '',
							// 	$profile_id: _this.globalData?.member?.kipUserId || member?.kipUserId || '',
							// 	$member_id: _this.globalData?.member?.id || member?.id || '',
							// 	$union_id: _this.globalData?.member?.unionid || wxMember.unionid || '',
							// 	// $location: _this.globalData?.mallid,
							// 	// $brand_id: _this.globalData?.groupId,
							// 	// $utm_source: JSON.stringify(uni.getStorageSync('options_query')) || '',
							// 	// $channel: optionsQuery?.channel || '',
							// 	$utm_lbs: optionsQuery?.utm_lbs || '',
							// 	// $utm_channel: optionsQuery?.utm_channel || '',
							// 	// $utm_method: optionsQuery?.utm_method || '',
							// 	// $utm_source: optionsQuery?.utm_source || '',
							// 	// $utm_function: optionsQuery?.utm_function || '',
							// 	// $utm_user: optionsQuery?.utm_user || '',
							// })
							KipCacheTool.setKipCache(_this.authInfo);
							MemberCacheTool.setMemberCache(app, {member, wxMember});
							_this.checkIsNewUser()
						} else {
							uni.showToast({
								title: "登录注册失败",
								duration: 2000,
								icon: 'none'
							})
							KipCacheTool.cleanKipCache()
							MemberCacheTool.cleanMemberCache(app);
						}
					} else {

						uni.showToast({
							title: "登录注册失败",
							duration: 2000,
							icon: 'none'
						})
						KipCacheTool.cleanKipCache()
						MemberCacheTool.cleanMemberCache(app);
					}
				}).catch(err => {
					uni.hideLoading()
					console.error(err)
					uni.showToast({
						title: "登录注册失败",
						duration: 2000,
						icon: 'none'
					})
					KipCacheTool.cleanKipCache()
					MemberCacheTool.cleanMemberCache(app);
				})
			},
			updateKipMemberByWxProfile (wxProfile) {
				uni.showLoading({
					title: '正在加载',
					mask: true,
				})
				const wxProfileParams = {
					encryptedData: wxProfile.encryptedData,
					iv: wxProfile.iv
				}
				const _this = this;
				// 根据微信授权更新kip会员信息
				kipUpdateWxMember(wxProfileParams).then(updateResp => {
					uni.hideLoading()
					const updateRespResult = updateResp.data;
					if (updateRespResult && updateRespResult.code === '000000' && updateRespResult.data) {
						uni.showLoading({
							title: '正在加载',
							mask: true,
						})
						kipGetWxMember().then(resp => {
							uni.hideLoading()
							const result = resp.data;
							if (result && result.code === '000000' && result.data) {
								// 存储用户信息
								const member = result.data;
								self.getKipMemberInfoAfter(member);
							} else {
								MemberCacheTool.cleanMemberCache(app);
								uni.showToast({
									title: result.message,
									duration: 2000,
									icon: 'none'
								})
							}
						}).catch(err => {
							uni.hideLoading()
							MemberCacheTool.cleanMemberCache(app);
							console.log(err);
						})
					} else {
						uni.hideLoading()
						const message = updateRespResult.message || '更新会员失败';
						uni.showToast({
							title: message,
							duration: 2000,
							icon: 'none'
						})
						_this.closeAll()
						_this.loginBefore()
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: '更新会员失败',
						duration: 2000,
						icon: 'none'
					})
					log.error('更新会员信息错误', err);
					_this.closeAll()
					_this.loginBefore()
				})
			},
			getCrmOpenId () {
				const _this = this;
				uni.login({
					success(e) {
						console.log(e);
						const { code, errMsg } = e || {};
						if (code) {
							const mallid = uni.getStorageSync("mallid");
							const params = {
								code,
								mallid
							}
							crmGetOpenId(_this.$baseURL, params).then(resp => {
								console.log(resp);
								const result = resp.data;
								if (result.code == '0' && result.data) {
									const jsonStr = result.data.weixinResult;
									if (jsonStr) {
										const weixinResult = JSON.parse(jsonStr)
										if (weixinResult && weixinResult.openid) {
											const openId = weixinResult.openid;
											MemberCacheTool.setOpenId(app, openId);
											self.closeAllAuth()
											self.callbackFn && self.callbackFn()
											return;
										}
									}
									uni.redirectTo({
										url: '/pages/automatic/automaticIndex'
									})
								}
							}).catch(err => {
								console.warn(err);
								uni.redirectTo({
									url: '/pages/automatic/automaticIndex'
								})
							})
						}
					},
					fail() {
						console.warn('===>授权失败');
					}
				})
			},
			confirmHzClick () {
				this.isComfirHz = true;
				uni.setStorageSync("comfirLocation", 'loginBefore---');
				uni.setStorageSync("comfirHangzhou", true);
			},
			getWxInfoAndModKipMemberInfo () {
				const _this = this;
				// 请求授权
				uni.getUserProfile({
					desc: '用于完善会员资料',
					success: (res) => {
						console.log(`===>拉取获取会员资料授权框`, res)
						const wxProfile = res;
						uni.showLoading({
							title: '正在加载',
							mask: true,
						})
						const wxProfileParams = {
							encryptedData: wxProfile.encryptedData,
							iv: wxProfile.iv
						}
						// 根据微信授权更新kip会员信息
						kipUpdateWxMember(wxProfileParams).then(updateResp => {
							uni.hideLoading()
							const updateRespResult = updateResp.data;
							if (updateRespResult && updateRespResult.code === '000000' && updateRespResult.data) {
								uni.showLoading({
									title: '正在加载',
									mask: true,
								})
								kipGetWxMember().then(resp => {
									uni.hideLoading()
									const result = resp.data;
									if (result && result.code === '000000' && result.data) {
										// 存储用户信息
										const member = result.data;
										_this.getKipMemberInfoAfter(member);
									} else {
										MemberCacheTool.cleanMemberCache(app);
										uni.showToast({
											title: result.message,
											duration: 2000,
											icon: 'none'
										})
									}
								}).catch(err => {
									uni.hideLoading()
									MemberCacheTool.cleanMemberCache(app);
									console.log(err);
								})
							} else {
								uni.hideLoading()
								const message = updateRespResult.message || '更新会员失败';
								uni.showToast({
									title: message,
									duration: 2000,
									icon: 'none'
								})
								_this.closeAll()
								_this.loginBefore()
							}
						}).catch(err => {
							uni.hideLoading()
							uni.showToast({
								title: '更新会员失败',
								duration: 2000,
								icon: 'none'
							})
							log.error('更新会员信息错误', err);
							_this.closeAll()
							_this.loginBefore()
						})
					},
					fail: (res) => {
						// TODO 请求授权失败或用户取消授权
						_this.closeAll()
						_this.loginBefore()
					},
				})
			},
		}
	}
</script>

<style lang="less">
.authorize {
  position: fixed;
  z-index: 998;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: #f4f7ff;

  .show-auth {
    position: relative;
    z-index: 20;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;

    .authorize__head {
      height: 100px;
      width: 100%;
      justify-content: center;
      align-items: center;
      display: flex;
      padding-top: 216px;
      margin-bottom: 94px;

      .head__info {
        padding-top: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
        flex-flow: column;

        .head__logo {
          height: 75px;
          margin-bottom: 40px;
          text-align: center;

          .head__logo__img {
            height: 100%;
          }
        }

        .head__text {
          font-size: 32px;
          color: #666666;
          margin-top: 12px;
        }
      }
    }
    .authorization_button_wrap {
      margin-top: 39px;
    }

    .authorize_btn {
      height: 100px;
      border-radius: 100px;
      line-height: 100px;
      font-size: 38px;
      margin: 0 30px;
    }

    .authorize_btn--wx {
      background: #07c160;
      border: none;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .authorize_btn--phone {
      border: 2px solid #333333;
      background-color: #f4f7ff;
    }
  }
}

.auth-popup {
  position: relative;
  display: flex;
  flex-direction: column;
  align-content: space-between;
  width: 600px;
  background-color: #ffffff;
  overflow: hidden;
  border-radius: 18px;

  .auth-popup__head {
    height: 90px;
    line-height: 90px;
    text-align: center;
    font-size: 34px;
    font-weight: 600;
    border-bottom: 1px solid #f0f0f0;
    font-family: PingFangSC-Medium, PingFang SC;
  }

  .auth-popup__main {
    text-align: center;

    .head__logo {
      height: 75px;
      margin-bottom: 40px;
      margin: 52px auto 27px auto;
      text-align: center;

      .head__logo__img {
        height: 100%;
      }
    }
  }

  .auth-popup__footer {
    display: flex;
    font-size: 34px;
    text-align: center;
    height: 92px;
    line-height: 92px;
    border-top: 1px solid #f0f0f0;

    .cancel {
      flex: 1;
      line-height: 92px;
    }

    .phone-btn {
      color: #6578c1;
      background-color: transparent;
      &::after {
        border: none;
      }
    }
  }
}

// new
.authorize-hz {
  z-index: 999;
  width: 750px;
  height: 100vh;
  background: rgba(0, 0, 0, 0.6);
  position: relative;
  .mid {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    width: 588px;
    background: #fff;
    border-radius: 17px;
    padding: 20px 36px;
    .authorize-box {
      width: 100%;
      .bold {
        font-weight: bold;
        color: #333333;
      }
      .other {
        text-indent: 60px;
        color: #666666;
      }
      .checkBox {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        margin-top: 40px;
        .popup-a {
          color: #4e99ff;
          text-decoration: underline;
        }
      }
    }
    .authorize-footer {
      display: flex;
      justify-content: space-between;
      color: #ffffff;
      margin-top: 40px;
      .disagree_btn {
        width: 176px;
        height: 68px;
        line-height: 68px;
        border: 2px solid #b3b3b3;
        border-radius: 34px;
        color: #999999;
        font-size: 30px;
      }
      .agree_btn {
        width: 286px;
        height: 68px;
        line-height: 68px;
        background: linear-gradient(90deg, #662d91 0%, #1b1464 100%);
        opacity: 0.83;
        border-radius: 34px;
        color: #ffffff;
        font-size: 30px;
      }
      .disabled {
        background: #999999;
      }
    }
  }
}
</style>


