<template>
	<view>
		<view class='mask' v-if='isShowAuth && code' @click='close'></view>
		<view class='Popup' :class="{'privacyPoupon' : canGetPrivacySetting }" v-if='isShowAuth && code' :style="'top:'+top+'px;'">
      <!--登录弹框 - logo-->
			<view class="logo-auth">
				<image class="image" :src='routine_logo' mode="aspectFit"></image>
			</view>
      <!--登录弹框 - 标题-->
      <template>
        <!--#ifdef H5-->
        <view v-if="isWeixin" class='title'>授权提醒</view>
        <view v-else class='title'>{{title}}</view>
        <!--#endif-->
        <!--#ifdef APP-PLUS-->
        <view class='title'>用户登录</view>
        <!--#endif-->
        <!--#ifdef MP-->
        <view class='title'>{{title}}</view>
        <!--#endif-->
      </template>
      <!--登录弹框 - 提示-->
      <template>
        <!--#ifdef H5-->
        <view v-if="isWeixin" class='tip'>请授权用户信息，以便为您提供更好的服务！</view>
        <view v-else class='tip'>{{info}}</view>
        <!--#endif-->
        <!--#ifdef APP-PLUS-->
        <view class='tip'>请登录，将为您提供更好的服务！</view>
        <!--#endif-->
        <!--#ifndef MP-->
        <view class='tip'>{{info}}</view>
        <!--#endif-->
        <!--#ifdef MP-WEIXIN-->
        <view class="popup_box">
          <view class="info">
            <button class="userAvatar" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
              <image class="avatar" :src="avatar"></image>
            </button>
            <view class="row">
              <view class="text1">昵称：</view>
              <input type="nickname" class="weui-input" :value="nickname" placeholder="请输入昵称" @change="changeNickname"/>
            </view>




          </view>
        </view>
        <!--#endif-->
      </template>
      <!--操作按钮-->
			<view class='bottom flex'>
				<view class='item' @click='close'>随便逛逛</view>
				<!-- #ifdef MP -->
				<button class="item grant" hover-class="none" @tap="getUserProfile">
          <view class="text">授权登录</view>
        </button>
				<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<button class="item grant" @tap="toWecahtAuth">
					<view class="text">去登录</view>
				</button>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<button class="item grant" @tap="toWecahtAuth">
					<view v-if="isWeixin" class="text">去授权</view>
					<view v-else class="text">去登录</view>
				</button>
				<!-- #endif -->
			</view>
		</view>
		<!-- #ifdef MP -->
		<privacyAgreementPopup ref="privacyAgreement" v-if="canGetPrivacySetting" @onclose="onclose"  @onReject="close" @onAgree="onAgree"></privacyAgreementPopup>
		<!-- #endif -->
		<!-- #ifdef MP -->
		<editUserModal :isShow="editModal" @closeEdit="closeEdit" @editSuccess="editSuccess"></editUserModal>
		<!-- #endif -->
	</view>
</template>
<script>

	const app = getApp();
  import Cache from '../utils/cache';
  import {commonAuth} from '../api/public';
  import {EXPIRES_TIME, USER_INFO} from '../config/cache';
  import {mapGetters} from 'vuex';
  import Routine from '../libs/routine';
  import {configMap} from '@/utils/index';
  import {toLogin} from '../libs/login';
  // #ifdef MP
  import editUserModal from '@/components/eidtUserModal/index.vue'
  import privacyAgreementPopup from '@/components/privacyAgreementPopup/index.vue'
  // #endif
	export default {
		name: 'Authorize',
		props: {
			isAuto: {
				type: Boolean,
				default: true
			},
			isGoIndex: {
				type: Boolean,
				default: true
			},
			isShowAuth: {
				type: Boolean,
				default: false
			}
		},
		components: {
			// #ifdef MP
			editUserModal,
			privacyAgreementPopup
			// #endif
		},
		data() {
			return {
				title: '用户登录',
				info: '请登录，将为您提供更好的服务！',
				//#ifdef H5
				isWeixin: this.$wechat.isWeixin(),
				//#endif
				//#ifdef MP
				title: '授权提醒',
				info: '请授权头像等信息，以便为您提供更好的服务！',
				//#endif
				canUseGetUserProfile: false,
				code: null,
				top: 0,
				mp_is_new: this.$Cache.get('MP_VERSION_ISNEW') || false,
				editModal: false, // 编辑头像信息
				canGetPrivacySetting: false,
        // 用户信息
        avatar: '',
        nickname: '',
			}
		},
		computed: {
			...mapGetters(['isLogin', 'userInfo', 'viewColor']),
			...configMap(['routine_logo','first_avatar_switch','wechat_phone_switch'])
		},
		watch: {
			isLogin(n) {
				n === true && this.$emit('onLoadFun', this.userInfo);
			},
			isShowAuth(n) {
				this.getCode(this.isShowAuth)
			}
		},
		created() {
			this.top = uni.getSystemInfoSync().windowHeight/2-70
			if (wx.getUserProfile) {
				this.canUseGetUserProfile = true
			}
			this.setAuthStatus();
			this.getCode(this.isShowAuth)
		},
		methods: {
			onclose(){
				this.canGetPrivacySetting = false;
			},
			onAgree() {
				let self = this;
				self.canUseGetUserProfile = false;
				Routine.getUserProfile()
					.then(res => {
						let userInfo = res.userInfo;
						userInfo.code = self.code;
						userInfo.spread = app.globalData.spid; //获取推广人ID
						userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID
            userInfo.new_nickname = self.nickname;
            userInfo.new_avatar = self.avatar;
						commonAuth({auth: {type:'routine', auth: userInfo}}).then(res=>{
							if(res.data.status == 200){
								let time = res.data.result.expires_time - Cache.time();
								self.$store.commit('UPDATE_USERINFO', res.data.result.user);
								self.$store.commit('LOGIN', {token:res.data.result.token, time:time});
								self.$store.commit('SETUID', res.data.result.user.uid);
								Cache.set(EXPIRES_TIME,res.data.result.expires_time,time);
								Cache.set(USER_INFO,res.data.result.user,time);
								self.$emit('onLoadFun', res.data.result.user);
								if(res.data.result.user.isNew && self.mp_is_new && self.first_avatar_switch==1 && self.wechat_phone_switch == 1){
									self.editModal = true;
								}
							}else{
								uni.setStorageSync('auth_token',res.data.result.key);
								return uni.navigateTo({
									url:'/pages/users/login/index'
								})
							}
						}).catch(res => {
							uni.hideLoading();
							uni.showToast({
								title: res.message,
								icon: 'none',
								duration: 2000,
							});
						});
					})
					.catch(res => {
            console.log('Routine.getUserProfile catch',res);
						uni.hideLoading();
					});
			},
			// #ifdef MP
			editSuccess() {
				this.editModal = false
				this.$emit('onLoadFun', this.userInfo);
			},
			closeEdit() {
				this.editModal = false
			},
			// #endif
			setAuthStatus() {
				//#ifdef MP
				Routine.authorize().then(res => {
					if (res.islogin === false)
						this.$emit('onLoadFun', this.userInfo);
				}).catch(res => {
					if (this.isAuto)
						this.$emit('authColse', true);
				})
				//#endif
			},
			getCode(n){
				// #ifdef MP
				if (n) {
					uni.showLoading({
						title: '正在登录中'
					});
					Routine.getCode().then(code => {
						uni.hideLoading();
						this.code = code;
					}).catch(e => {
						uni.hideLoading();
						uni.showToast({
							title: '登录失败',
							duration: 2000
						});
					})
				} else {
					this.code = null;
				}
				// #endif
				// #ifndef MP
				if(n){
					this.code = 1;
				}
				// #endif
			},
			toWecahtAuth(){
				toLogin(true);
			},
			getUserProfile() {
				if (wx.getPrivacySetting) {
					wx.getPrivacySetting({
						success: res => {
							if (res.needAuthorization) {
								// 需要弹出隐私协议
								this.canGetPrivacySetting = true
								this.$nextTick(()=>{
									this.$refs.privacyAgreement.showPoupon(res.privacyContractName)
								})
							}else{
								this.onAgree()
							}
						},
						fail: (err) => {
              console.log('wx.getPrivacySetting Fail',err);
            },
						complete: () => {}
					})
				}else{
					this.onAgree()
				}
			},
			close() {
				let pages = getCurrentPages(),
					currPage = pages[pages.length - 1];
					this.$emit('authColse', false);
					this.canGetPrivacySetting = false;
				// if (this.isGoIndex) {
				// 	uni.switchTab({
				// 		url: '/pages/index/index'
				// 	});
				// } else {
				// 	this.$emit('authColse', false);
				// }
			},


      // 微信头像获取
      onChooseAvatar(e) {
        const {avatarUrl} = e.detail
        this.$util.uploadImgs('upload/image', avatarUrl, (res) => {
          this.avatar = res.data.path
        }, (err) => {
          console.log(err)
        })
      },
      changeNickname(e){
        this.nickname = e.detail.value || e.target.value;
      }

		}
	}
</script>

<style scoped lang='scss'>
	.Popup {
    --logo-auth-size-: 180rpx;

    width: 80%;
    background-color: #fff;
    position: fixed;
    top: 500rpx;
    left: 10%;
    z-index: 900;
    padding:calc(var(--logo-auth-size-) / 2) 20rpx 20rpx 20rpx;
    border-radius: 15rpx;

		.logo-auth {
      position: absolute;
      top: calc(0rpx - (var(--logo-auth-size-) + 8rpx) / 2);
      left: calc((100% - 180rpx) / 2);
      width: var(--logo-auth-size-);
      height: var(--logo-auth-size-);
      border: 8rpx solid #fff;
      border-radius: 50%;
      background: #fff;
      display: inline-flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: center;
      align-items: center;
      .image {
        height: var(--logo-auth-size-);
        margin-top: -30rpx;
      }
		}
    .title {
      width: 100%;
      height: 60rpx;
      line-height: 60rpx;
      text-align: center;
      font-size: 32rpx;
      color: #000;
    }
    .tip {
      width: 100%;
      line-height: 50rpx;
      font-size: 28rpx;
      color: #555;
      padding: 20rpx 0;
      text-align: left;
    }
    .bottom{
      width: 100%;
      height: 80rpx;
      margin-top: 50rpx;
      display: inline-flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-around;
      align-items: center;

      .item {
        width: 200rpx;
        height: 80rpx;
        line-height: 80rpx;
        background-color: #eeeeee;
        text-align: center;
        font-size: 26rpx;
        color: #666;
        .text{
          font-size: 26rpx;
          color: #666;
        }
      }
      .item.on {
        width: 500rpx;
      }
      .item.grant {
        font-weight: bold;
        background-color: #E93323;
        /* background-color: var(--view-theme); */
        border-radius: 0;
        padding: 0;
        .text{
          font-size: 28rpx;
          color: #fff;
        }
      }
    }
	}
	.flex {
		display: flex;
		flex-direction: row;
	}
	.mask {
		position: fixed;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.65);
		z-index: 99;
	}

  .popup_box {
    width: 100%;
    background-color: #fff;
    border-radius: 35rpx;
    display: flex;
    flex-direction: column;

    .h1 {
      width: 100%;
      position: fixed;
      top: 0;
      background: #fff;
      font-size: 36rpx;
      height: 100rpx;
      line-height: 100rpx;
      display: -ms-flexbox;
      display: flex;
      -ms-flex-pack: justify;
      justify-content: space-between;
      padding: 0 28rpx;
      box-sizing: border-box;
    }
    .h1 icon {
      font-size: 32rpx;
      color: #c9c9c9;
    }
    .info {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    }
    .info .userAvatar {
      width: 130rpx;
      height: 130rpx;
      border-radius: 100%;
      overflow: hidden;
      padding: 0;
      margin-top: 45px;
      background-color: #fff;
      border: 2rpx solid #cccccc;
    }
    .info .userAvatar .avatar {
      display: block;
      width: 130rpx;
      height: 130rpx;
    }
    .info .row {
      border-bottom: 1px solid #ccc;
      display: flex;
      align-items: center;
      height: 80rpx;
      padding-left: 20rpx;
    }
    .info .row.text1 {
      flex: 2;
    }
    .info .row.weui-input {
      flex: 6;
    }
    .btn {
      position: fixed;
      bottom: 0;
      width: 100%;
      background: #fff;
      align-items: center;
      justify-content: center;
      display: flex;
      padding-top: 20rpx;
      padding-bottom: 20rpx;
    }
    .btn .button {
      width: 90%;
      height: 84rpx;
      border-radius: 64rpx;
      background: #f15353;
      color: #fff;
      font-size: 36rpx;
      border: none;
      text-align: center;
      line-height: 84rpx;
    }
  }
</style>
