<template>
  <view class="app-container">
    <view class="main-container">
      <view class="header">
        <image :src="configInfo.minLogo1"></image>
        <view>{{ configInfo.minAppName }}</view>
      </view>
      <view class="bottom">
        <view class="content">
          <view>申请获取以下权限</view>
          <text>获取你的公开信息(昵称，头像、地区等)</text>
        </view>
        <button class="button" type="primary" @tap="wxLogin">授权登录</button>
        <!-- <view class="tips">登录即代表同意<text @tap="toAgreement(1)">《用户协议》</text>和<text @tap="toAgreement(2)">《隐私声明》</text></view> -->
      </view>
    </view>

    <u-popup :round="10" :show="isShowPhoneDialog">
      <view class="phone-dialog">
        <view class="content">
          <view>申请获取以下权限</view>
          <text>获得你的公开信息(手机号码)</text>
        </view>
        <view class="btn">
          <button @tap="isShowPhoneDialog = false">取消</button>
          <button type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">确定授权</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      configInfo: {},
      userId: null,
      isNotOpenid: false, // 是否因为 支付前没有openid 进入的登录页

      isShowPhoneDialog: false // 是否显示获取手机号授权弹窗
    }
  },
  async onLoad({ isNotOpenid }) {
    this.isNotOpenid = isNotOpenid ? true : false
    this.configInfo = await this.$getConfigInfo()

    if (this.$getStorage('is_qywx') !== true && this.$getStorage('is_qywx') !== false) {
      console.log('重新获取系统信息')
      uni.getSystemInfo({
        success: function (e) {
          console.log(e)
          if (e.environment == 'wxwork') {
            this.$setStorage('is_qywx', true)
          } else {
            this.$setStorage('is_qywx', false)
          }
        }
      })
    }
  },
  methods: {
    wxLogin() {
      console.log('是否从企业微信端进入：' + this.$getStorage('is_qywx'))
      // 没有openid
      if (this.isNotOpenid == true) {
        console.log('没有openid')

        wx.login({
          provider: 'weixin',
          success: loginRes => {
            console.log(loginRes)
            this.$axios({
              url: '/user/auth',
              params: {
                code: loginRes.code,
                work: this.$getStorage('is_qywx'),
                serviceId: this.$getStorage('is_qywx') ? this.$store.state.userId : ''
              }
            }).then(res => {
              this.userId = res.data.userId
              this.mobile = res.data.mobile
              this.$setStorage('token', res.data.token)

              if (!this.mobile) {
                return (this.isShowPhoneDialog = true)
              }

              this.loginSuccess()
            })
          }
        })
      }

      // 企业微信端
      else if (this.$getStorage('is_qywx') == true) {
        console.log('从企业微信端进入')
        wx.qy.login({
          success: loginRes => {
            console.log(loginRes)
            if (loginRes.code) {
              this.$axios({
                url: '/user/auth',
                params: {
                  code: loginRes.code,
                  work: true
                }
              }).then(res => {
                this.userId = res.data.userId
                this.mobile = res.data.mobile
                this.$setStorage('token', res.data.token)

                if (!this.mobile || this.$getStorage('isActiveLogout')) {
                  return (this.isShowPhoneDialog = true)
                }

                this.loginSuccess()
              })
            } else {
              console.log('登录失败！' + loginRes.errMsg)
            }
          }
        })
      }

      // 微信端
      else if (this.$getStorage('is_qywx') == false) {
        console.log('从微信端进入')
        wx.login({
          provider: 'weixin',
          success: loginRes => {
            console.log(loginRes)
            this.$axios({
              url: '/user/auth',
              params: {
                code: loginRes.code,
                work: false
              }
            }).then(res => {
              this.userId = res.data.userId
              this.mobile = res.data.mobile
              this.$setStorage('token', res.data.token)

              if (!this.mobile || this.$getStorage('isActiveLogout')) {
                return (this.isShowPhoneDialog = true)
              }

              this.loginSuccess()
            })
          }
        })
      }
      return false
    },

    // 获取配置信息
    async getConfigInfo() {
      return new Promise((resolve, reject) => {
        this.$axios({
          url: '/common/config/get',
          method: 'get'
        }).then(res => {
          resolve(res.data)
        })
      })
    },

    // 保存用户信息
    async saveUserInfo(userInfo) {
      const configInfo = await this.getConfigInfo()

      return new Promise((resolve, reject) => {
        this.$axios({
          url: '/user/userinfo/save',
          params: {
            userId: this.userId,
            avatarUrl: configInfo.minLogo3,
            nickName: `微信用户_${userInfo.mobile.slice(7, 11)}`
          }
        }).then(res => {
          resolve(res.data)
        })
      })
    },

    // 获取手机号
    getPhoneNumber(e) {
      this.$axios({
        url: '/user/mobile/grant',
        params: {
          userId: this.userId,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        }
      }).then(res => {
        this.$setStorage('token', res.data.token)
        this.$setStorage('isActiveLogout', false)
        this.isShowPhoneDialog = false

        this.loginSuccess()
      })
    },

    // 登录成功
    async loginSuccess() {
      const userInfo = await this.$getUserInfo(this.userId)

      if (!userInfo.avatar || !userInfo.nickName) {
        await this.saveUserInfo(userInfo)
      }

      this.$store.commit('changeIsLogin', true)
      this.$setStorage('isLogin', true)
      this.$successToast('登录成功')
      this.$isResolve()
      this.$backPage(1, 1000)
    },

    toAgreement(type) {
      this.$navToPage({
        url: '/pages/login/agreement?type=' + type
      })
    }
  }
}
</script>

<style lang="scss">
.app-container {
  background: #ffffff;
  box-sizing: border-box;
}
.main-container {
  .header {
    border-bottom: 1px solid #ccc;
    text-align: center;
    height: 400rpx;
    margin-bottom: 50rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    view {
      font-size: 38rpx;
      margin-top: 30rpx;
    }
    image {
      width: 200rpx;
      height: 200rpx;
    }
  }

  .bottom {
    padding: 0 50rpx;
    .content {
      font-size: 28rpx;
      margin-bottom: 90rpx;
      text {
        display: block;
        color: #9d9d9d;
        margin-top: 30rpx;
      }
    }
    .button {
      border-radius: 80rpx;
      margin: 70rpx 0 30rpx;
      font-size: 35rpx;
    }
    .tips {
      font-size: 26rpx;
      color: #666666;
      text {
        color: #ff3f42;
      }
    }
  }
}

.phone-dialog {
  padding: 40rpx;
  box-sizing: border-box;
  .content {
    margin-top: 30rpx;
    margin-bottom: 30rpx;
    line-height: 50rpx;
    text {
      color: #9d9d9d;
    }
  }
  .btn {
    display: flex;
    justify-content: center;
    margin-top: 60rpx;
    button::after {
      border: none;
    }
    button {
      width: 180rpx;
      height: 70rpx;
      line-height: 70rpx;
      margin: 0;
      font-size: 28rpx;
      margin: 0 30rpx;
      &:first-child {
        background: #f5f5f5;
        color: #00ba5c;
      }
    }
  }
}
</style>
