<template>
  <view class="container-mine">
    <!-- <navbar ref="navbar" :config="config"></navbar> -->
    <uv-navbar title="登录" placeholder bgColor="#F9F9F9" @leftClick="goBack"></uv-navbar>
    <view class="top">
      <view class="title">手机号一键登录</view>
      <view class="tig">首次登录将为您注册</view>
    </view>
    <view class="body">
      <view class="btnBox">
        <uv-button type="primary" custom-style="background:#FF6600;border-color:#FF6600;" hover-class="hoverClass" @click="login">一键登录</uv-button>
      </view>
    </view>

    <view class="loginBox">
      <!-- <u-divider half-width="50" @click="toOtherLogin">切换其它登录方式</u-divider> -->
      <uv-button class="otherClass" custom-style="background:#fff;border:none" @click="toOtherLogin">切换其它登录方式</uv-button>
    </view>

    <view class="agreementCls">
      <uv-checkbox-group size="26rpx" v-model="checked">
        <uv-checkbox shape="circle" active-color="#56CBD9" name="1">
          <view>
            我已阅读同意 <text @click.stop="goAgreement('user_protocol')">《服务协议》</text>和<text @click.stop="goAgreement('privacy_protocol')">《隐私政策》</text>
          </view>
        </uv-checkbox>
      </uv-checkbox-group>
    </view>
  </view>
</template>

<script>
export default {
  data () {
    return {
      mobile: '',
      checked: [],
      osVersion: "",
      platform: "",
      isInstallWx: true, //是否安装微信
      isInstallZfb: true, //是否安装支付宝
      isOneClickLogin: false
    }
  },
  onLoad () {
    uni.removeStorageSync('shop')
    // 先判断 系统版本
    uni.getSystemInfo({
      success: (res) => {
        this.osVersion = res.osVersion.split('.')[0]
        this.platform = res.platform;
      }
    })
    // #ifdef APP || APP-PLUS
    plus.push.getClientInfoAsync((info) => {
      let cid = info["clientid"];
      console.log('cid', cid)
      uni.setStorageSync('cid', cid)
      this.cid = cid
    });
    uni.preLogin({
      provider: 'univerify',
      success: (res) => { //预登录成功
        // 显示一键登录选项
        console.log('预登录===>', res)
        if (res.errMsg == 'preLogin:ok') {
          this.isOneClickLogin = true
          this.$nextTick(() => {
            this.checked = ['1']
            this.oneClickLogin()
          })
        }
      },
      fail: (fail) => { // 预登录失败
        // 不显示一键登录选项（或置灰）
        // 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
        console.log(fail)
        this.preError(fail)
        // this.$u.toast(fail.errMsg);
      }
    })
    // #endif
  },
  methods: {
    login () {
      if (this.checked.length <= 0) {
        uni.showToast({
          title: '请阅读并同意相关协议',
          duration: 1500,
          icon: "none"
        });
        return
      }
      this.oneClickLogin()
    },
    goAgreement (val) {
      uni.navigateTo({
        url: "/pages/protocol/index?code=" + val
      })
    },
    // 一键登录
    oneClickLogin () {
      uni.login({
        provider: 'univerify',
        univerifyStyle: {
          fullScreen: true
        },
        success: res => {
          console.log('res==>', res)
          if (res.errMsg == 'login:ok') {
            const authResult = res.authResult
            // 在得到access_token后，通过callfunction调用云函数
            uniCloud.callFunction({
              name: 'getYGPhoneNumber', // 你的云函数名称
              data: {
                'access_token': authResult.access_token, // 客户端一键登录接口返回的access_token
                'openid': authResult.openid // 客户端一键登录接口返回的openid
              }
            }).then(data => {
              console.log('data===>', data)
              const dataVal = data.result
              this.oneLogin({
                mobile: dataVal.phoneNumber,
                cid: this.cid
              })
              // 登录成功，可以关闭一键登录授权界面了
            }).catch(err => {
              uni.closeAuthView()
              // 处理错误
              console.log('errr===>', err)
              uni.showToast({
                title: err,
                duration: 1500,
                icon: "none"
              });
              // this.$u.toast(err);

            })
          }
        },
        fail: fail => {
          uni.closeAuthView()
          console.log('fail===>', fail)
          // this.$u.toast(fail);
          uni.showToast({
            title: fail,
            duration: 1500,
            icon: "none"
          });
        }
      })
    },
    preError (fail) {
      const {
        code,
        errMsg
      } = fail
      if (code == 30005) {
        if (fail.metadata) {
          if (fail.metadata.status == 102001) {
            uni.showToast({
              title: "请保证数据流量开启",
              duration: 1500,
              icon: "none"
            });
            return

          }
          uni.showToast({
            title: fail.metadata.message,
            duration: 1500,
            icon: "none"
          });
        } else {
          // this.$u.toast("请检查手机是否有SIM卡、是否启用数据流量")
          uni.showToast({
            title: "请检查手机是否有SIM卡、是否启用数据流量",
            duration: 1500,
            icon: "none"
          });
        }
      }
    },

    oneLogin (data) {
      this.$yghttp.post('/user/login/mobile', data).then(res => {
        if (res && res.code == 200) {
          // this.$u.toast('登录成功');
          uni.showToast({
            title: "登录成功",
            duration: 1500,
          });
          uni.setStorageSync('apiToken', res.data.token);
          uni.closeAuthView()
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/tabtar/home"
            });
          }, 500)
        } else {
          // this.$u.toast('登录失败');
          uni.showToast({
            icon: "none",
            title: "登录失败",
            duration: 1500,
          });
        }
      })
    },

    onBackPress () {
      uni.switchTab({
        url: "pages/tabtar/home"
      })
      return true
    },
    toOtherLogin () {
      uni.navigateTo({
        url: '/pages/login/otherLogin'
      })
    }
  }
}
</script>

<style>
page {
  background-color: #f9f9f9;
}
</style>
<style lang="scss" scoped>
::v-deep .hx-navbar__icon {
  color: #303133 !important;
}

::v-deep .u-divider {
  background-color: #f9f9f9 !important;
}

.lgoin-nav {
  width: 100%;
  background-color: #fff;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 0;
}

.top {
  text-align: center;
  padding: 50rpx 0 100rpx;
  font-size: 28rpx;

  .title {
    font-size: 60rpx;
    margin-bottom: 10rpx;
    font-weight: 700;
  }

  .tig {
    font-size: 30rpx;
  }
}

.body {
  margin: auto;
  width: 615rpx;
  margin-bottom: 30rpx;

  .inpBox {
    background: #fff;
    border-radius: 20rpx;
    padding: 20rpx 30rpx;
    display: flex;
  }

  image {
    width: 36rpx;
    height: 44rpx;
    margin-right: 30rpx;
  }

  .uni-input {
    height: 40rpx;

    .uni-input-placeholder {
      color: #bebebe;
    }
  }

  .login-btn {
    background-color: #4095e5;
    color: #fff;
    margin-top: 100rpx;
  }
}

.agreementCls {
  position: absolute;
  bottom: 200rpx;
  width: 100%;
  // padding: 0 30rpx;
  font-size: 26rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;

  ::v-deep .u-checkbox__label {
    margin-right: 0rpx;
    font-size: 26rpx;
  }

  text {
    color: #56cbd9;
  }
  ::v-deep .uv-checkbox-group--row {
    justify-content: center;
  }
}

.loginBox {
  // width: 100%;
  width: 615rpx;
  margin: auto;
  .loginBox_b {
    width: 615rpx;
    display: flex;
    justify-content: space-around;
    margin: auto;
    margin-top: 60rpx;

    > view {
      text-align: center;

      image {
        width: 82rpx;
        height: 82rpx;
        border-radius: 50%;
      }

      > view {
        font-size: 26rpx;
        color: #333333;
      }
    }
  }
}

.btnBox {
  width: 100%;
  margin-top: 60rpx;
}

.u-btn {
  width: 615rpx;
  border-radius: 10rpx;
  background: #ff6600;
  font-size: 30rpx;
  font-weight: 700;
  margin: auto;
  font-family: Microsoft YaHei, Microsoft YaHei-Bold;
  background: linear-gradient(6deg, #56d9ee 0%, #3ebcd0 100%) #3c66d9;
}

.hoverClass {
  background: linear-gradient(6deg, #56d9ee 0%, #3ebcd0 100%) #3c66d9;
}

.otherClass {
  margin-top: 50rpx;
  color: #909399;
  font-weight: normal;
  font-size: 30rpx;
  background: #fff;
  border-color: #4095e5;
}
</style>