<template>
  <view
    v-if="openModal"
    class="wx-authorization-modal"
  >
    <view
      class="wam__mask"
      @touchmove.prevent=""
      @tap.stop="closeModal"
    ></view>
    
    <!-- 内容区域 -->
    <view class="wam__wrapper">
      <!-- 关闭按钮 -->
      <view class="wam__close-btn" @tap.stop="closeModal">
        <text class="tn-icon-close"></text>
      </view>
      <!-- 标题 -->
	  <!-- #ifdef MP-WEIXIN -->
      <view class="wam__title">获取您的昵称、头像</view>
      <!-- tips -->
      <view class="wam__sub-title">
        获取用户头像、昵称，主要用于向用户提供具有辨识度的用户中心界面
      </view>
      <!-- #endif -->
	  <!-- #ifdef H5 -->
	  <view class="wam__title">获取您的手机号</view>
	  <!-- tips -->
	  <view class="wam__sub-title">
	    获取用户手机号，主要用于向用户提供具有辨识度的用户中心界面
	  </view>
	  <!-- #endif -->
      <!-- 头像选择 -->
	  <!-- #ifdef MP-WEIXIN -->
      <view class="wam__avatar">
        <view class="button-shadow">
          <button
            class="button"
            open-type="chooseAvatar"
            @chooseavatar="chooseAvatarEvent"
          >
            <view v-if="userInfo.avatar" class="avatar__image">
              <image class="image" :src="userInfo.avatar" mode="aspectFill"></image>
            </view>
            <view v-else class="avatar__empty">
              <image class="image" src="" mode="aspectFill"></image>
            </view>
            <view class="avatar--icon">
              <view class="tn-icon-camera-fill"></view>
            </view>
          </button>
        </view>
      </view>
      <!-- #endif -->
      <!-- 昵称输入 -->
      <view class="wam__nickname">
		  <!-- #ifdef MP-WEIXIN -->
        <view class="nickname__data">
          <input class="input" type="nickname" maxlength="13" v-model="userInfo.nickname" placeholder="请输入昵称" placeholder-style="color: #AAAAAA;">
        </view>
		 <!-- #endif -->
		<!-- #ifdef H5 -->
			<view class="nickname__data">
			  <input class="input" type="number"  v-model="userInfo.phone" placeholder="请输入手机号" placeholder-style="color: #AAAAAA;">
			</view>
			<view class="nickname__data tn-flex align-center justify-between">
			  <input class="input" style="width: 145px;" type="number"  v-model="userInfo.code" placeholder="请输入验证码" placeholder-style="color: #AAAAAA;">
			  <view @tap="getCode" class="getcode">{{tips}}</view>
			</view>
		<!-- #endif -->
		
      </view>
      
      <u-code :seconds="seconds" @end="end" @start="start" ref="uCode"
      @change="codeChange"></u-code>
	  <!-- #ifdef MP-WEIXIN -->
	  <view class="wam__button">
		  <!-- 保存按钮 -->
	  	<view
	  	  class="wam__submit-btn"
	  	 
	  	  hover-class="tn-btn-hover-class"
	  	  :hover-stay-time="150"
	  	  @tap.stop="submitUserInfo"
	  	>
		<!-- :class="[{
		  'disabled': !userInfo.avatar || !userInfo.nickname
		}]" -->
	  	  授 权 登 录
	  	</view>
	  	<!-- <button v-if="platform == 'wxMiniProgram'&&userInfo.avatar&&userInfo.nickname" class="getbuttons" open-type="getPhoneNumber" @getphonenumber="getphone"></button> -->
	  </view>
      <!-- #endif -->
     <!-- #ifdef H5 -->
     <view class="wam__button">
     		  <!-- 保存按钮 -->
     	<view
     	  class="wam__submit-btn"
     	 :class="[{
     	   'disabled': !userInfo.phone || !userInfo.code
     	 }]"
     	  hover-class="tn-btn-hover-class"
     	  :hover-stay-time="150"
     	  @tap.stop="binding"
     	>
     		
     	  授 权 登 录
     	</view>
     </view>
     <!-- #endif -->
    </view>
  </view>
</template>

<script>
	import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
	import wechat from '@/common/wechat/wechat';
  import { apiurl } from '@/common/request/request';
  import platform from '@/common/platform/index';
  export default {
    options: {
      // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
      virtualHost: true
    },
    props: {
      value: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
		  tips: '获取验证码',
		seconds: 60,
        openModal: false,
        userInfo: {
          avatar: '',
          nickname: ''
        },
		platform:platform.get()
      }
    },
    watch: {
      value: {
        handler(val) {
          this.openModal = val
        },
        immediate: true
      }
    },
	computed: {
		...mapGetters(['appInfo','isLogin'])
	},
    methods: {
      ...mapActions(['getUserInfo']),
      // 头像选择
      chooseAvatarEvent(e) {
		var that = this;
		uni.uploadFile({
			url: apiurl('common/upload'),
			filePath: e.detail.avatarUrl,
			name: 'file',
			formData: {
				accept: 'image'
			},
			success: res2 => {
				let a = JSON.parse(res2.data);
				if (a.code == 0) {
					that.userInfo.avatar = a.data.path
				}else{
					uni.showToast({
						title:'上传头像失败',
						icon:'none'
					})
				}
			}
		});
      },
      // 绑定手机号
      async getphone(e) {
      	let that = this;
      		let res = await wechat.getPhoneNumber(e.detail);
      		if(res.code === 0){
      			// uni.showToast({
      			// 	title:that.cur?'绑定成功':'登录成功',
      			// 	duration:1500
      			// })
      			// that.whether = true;
      			// that.$store.commit('userInfo',res.data)
      			// uni.navigateTo({
      			// 	url:'/pages/public/webview?url=https://y.iduomi.cc/api/wechat_login.html'
      			// })
				uni.showToast({
					icon:'loading',
					title:'授权登录中...'
				})
				that.userprofile()
      		}				
      },
	  getCode(){
		  var that = this;
		  if(!that.userInfo.phone){
			  // uni.$u.toast('请输入手机号');
			  // return;
			  return uni.showToast({
			    icon: 'none',
			    title: '请输入手机号'
			  })
		  }else if(!uni.$u.test.mobile(that.userInfo.phone)){
			  // uni.$u.toast('请输入正确的手机号');
			  // return;
			 return uni.showToast({
			   icon: 'none',
			   title: '请输入正确的手机号'
			 }) 
		  }
		  if(that.$refs.uCode.canGetCode) {
		  					// 模拟向后端请求验证码
		  					uni.showLoading({
		  						title: '正在获取验证码'
		  					})
							that.$http('common.sendMobileCode',{mobile:that.userInfo.phone,event:'register'}).then(res=>{
								if(res.code == 0){
									setTimeout(() => {
										uni.hideLoading();
										// 这里此提示会被that.start()方法中的提示覆盖
										// uni.$u.toast('验证码已发送');
										uni.showToast({
										  icon: 'none',
										  title: '验证码已发送'
										})
										// 通知验证码组件内部开始倒计时
										that.$refs.uCode.start();
									}, 2000);
								}
							})
		  				} else {
		  					// uni.$u.toast('倒计时结束后再发送');
							uni.showToast({
							  icon: 'none',
							  title: '倒计时结束后再发送'
							})
		  				}
	  },
	  end() {
	  				// uni.$u.toast('倒计时结束');
					uni.showToast({
					  icon: 'none',
					  title: '倒计时结束'
					})
	  			},
	  			start() {
	  				// uni.$u.toast('倒计时开始');
					uni.showToast({
					  icon: 'none',
					  title: '倒计时开始'
					})
	  			},
	  codeChange(text){
		  // console.log(text);
		  this.tips = text;
	  },
      // 更新用户信息
      submitUserInfo() {
		  // console.log(platform.get());
        // 判断是否已经选择了用户头像和输入了用户昵称
        if (!this.userInfo.avatar) {
          return uni.showToast({
            icon: 'none',
            title: '请上传头像'
          })
        }else if(!this.userInfo.nickname){
			return uni.showToast({
			  icon: 'none',
			  title: '请输入昵称'
			})
		}else if(!uni.$u.test.rangeLength('abc', [1, 13])){
			return uni.showToast({
			  icon: 'none',
			  title: '昵称过长'
			})
		}else{
			uni.showToast({
				icon:'loading',
				title:'授权登录中...'
			})
			this.userprofile()
		}
        
        // 更新完成事件
        // this.$emit('updated', this.userInfo)
        
      },
      userprofile(){
		  this.$http('user.profile',{nickname: this.userInfo.nickname,avatar: this.userInfo.avatar}).then( res => {
		  	if(res.code == 0){
		  		
		  		this.$store.dispatch('getUserInfo')
		  		setTimeout(function() {
		  		uni.showToast({
		  			title:'登录成功',
		  		})
				setTimeout(function() {
					uni.navigateBack()
				}, 1500);
		  		}, 1500);
		  	}else{
		  		that.$u.toast('登录失败，请重试');
		  	}
		  })
	  },
      // 关闭弹框
      closeModal() {
        this.$emit('input', false)
      },
      // 绑定手机号
      binding(){
      	let that = this;
		
		if(!that.userInfo.phone){
					  // uni.$u.toast('请输入手机号');
					  // return;
					  return uni.showToast({
					    icon: 'none',
					    title: '请输入手机号'
					  })
		}else if(!uni.$u.test.mobile(that.userInfo.phone)){
					  // uni.$u.toast('请输入正确的手机号');
					  // return;
					 return uni.showToast({
					   icon: 'none',
					   title: '请输入正确的手机号'
					 }) 
		}else if(!that.userInfo.code){
			return uni.showToast({
			  icon: 'none',
			  title: '请输入验证码'
			})
		}
		uni.showToast({
			icon:'loading',
			title:'授权登录中...'
		})
      	that.$http(
      		'wechat.authBindindPhoneCode',
      		{
      			phone: that.userInfo.phone,
      			code: that.userInfo.code
      		},
      		// '中...'
      	).then(res => {
      		if (res.code === 0) {
      			uni.showToast({
      				title:'登录成功',
      				duration:1500
      			})
      			setTimeout(function(){
      				// uni.navigateBack({
      				// })
					// this.$emit('updated', that.userInfo)
					uni.switchTab({
						url:'/pages/user/user'
					})
      			},1500);
      			that.$store.commit('userInfo',res.data)
      		} else {
      			that.$u.toast(res.msg);
      		}
      	});
      },
      
    }
  }
</script>

<style lang="scss" scoped>
  
  @import '../../static/iconfont/tuniao.css';
  
  .wx-authorization-modal {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    // z-index: 99998;
    
    view {
      box-sizing: border-box;
    }
    
    .image {
      width: 100%;
      height: 100%;
      border-radius: inherit;
    }
    
    .wam {
      /* mask */
      &__mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        opacity: 0;
        animation: showMask 0.25s ease 0.1s forwards;
      }
      
      /* close-btn */
      &__close-btn {
        position: absolute;
        top: 30rpx;
        right: 30rpx;
        // z-index: 99999;
      }
      
      /* wrapper */
      &__wrapper {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        background-color: #FFFFFF;
        border-radius: 20rpx 20rpx 0rpx 0rpx;
        padding: 40rpx;
        padding-top: 60rpx;
        padding-bottom: 40rpx;
        padding-bottom: calc(constant(safe-area-inset-bottom) + 40rpx);
        padding-bottom: calc(env(safe-area-inset-bottom) + 40rpx);
        transform-origin: center bottom;
        transform: scaleY(0);
        animation: showWrapper 0.25s ease 0.1s forwards;
        // z-index: 99999;
      }
      
      /* title */
      &__title {
        font-size: 34rpx;
      }
      /* sub-title */
      &__sub-title {
        font-size: 26rpx;
        color: #AAAAAA;
        margin-top: 16rpx;
        padding-bottom: 30rpx;
      }
      
      /* 头像选择 */
      &__avatar {
        width: 100%;
        margin-top: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .button-shadow {
          border: 8rpx solid rgba(255,255,255,0.05);
          box-shadow: 0rpx 0rpx 80rpx 0rpx rgba(0, 0, 0, 0.15);
          border-radius: 50%;
        }
        
        .button {
          position: relative;
          width: 160rpx;
          height: 160rpx;
          border-radius: 50%;
          overflow: visible;
          background-image: repeating-linear-gradient(45deg, #E4E9EC, #F8F7F8);
          color: #FFFFFF;
          background-color: transparent;
          padding: 0;
          margin: 0;
          font-size: inherit;
          line-height: inherit;
          border: none;
          &::after {
            border: none;
          }
        }
        
        .avatar {
          &__empty, &__image {
            width: 100%;
            height: 100%;
            border-radius: inherit;
          }
          
          &--icon {
            position: absolute;
            right: -10rpx;
            bottom: -6rpx;
            width: 60rpx;
            height: 60rpx;
            // transform: translate(50%, 50%);
            background-color: #1D2541;
            color: #FFFFFF;
            border-radius: 50%;
            border: 6rpx solid #FFFFFF;
            line-height: 1;
            font-size: 36rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
      }
      
      /* 昵称 */
      &__nickname {
        margin-top: 40rpx;
        
        .nickname {
          
          &__data {
            margin-top: 26rpx;
            width: 100%;
            // padding: 26rpx 46rpx;
			padding: 26rpx 26rpx 26rpx 46rpx;
            border-radius: 16rpx;
            background-color: #F8F7F8;
            
            .input {
              color: #080808;
            }
          }
        }
      }
      
      /* 保存按钮 */
      &__submit-btn {
        width: 100%;
        background-color: #05C160;
        color: #FFFFFF;
        margin-top: 60rpx;
        border-radius: 16rpx;
        padding: 25rpx;
        font-size: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &.disabled {
          background-color: #E6E6E6;
        }
      }
      
      
    }
  }
  
  .tn-btn-hover-class {
    box-shadow: inset 10rpx 2rpx 40rpx 0rpx rgba(0, 0, 0, 0.05);
  }
  
  @keyframes showMask {
    0% {
      opacity: 0;
    }
    100% {
      opacity: 1;
    }
  }
  @keyframes showWrapper {
    0% {
      transform: scaleY(0);
    }
    100% {
      transform: scaleY(1);
    }
  }
  .wam__button{
	  position: relative;
	  font-weight: bold;
	  .getbuttons{
	  	position: absolute;
	  	width: 100%;
	  	height: 88rpx;
	  	opacity: 0;
		top: 0;
	  }
  }
  .getcode{
	  color: #fff;
	  background: #05C160;
	  padding: 8rpx 26rpx;
	  border-radius: 12rpx;
	  font-size: 24rpx;
  }
</style>