<template>
  <view class="all-container">
    <view class="logo">
      <view class="logo_top">
        <image style="width: 100%;height: 100%" :src="configInfo.minLogo1" mode=""></image>
      </view>
      <view class="logo_bottom">
        {{configInfo.minAppName || ' '}}
      </view>
    </view>
    <view class="loginForm">
      <!-- #ifdef H5 -->
      <u--form labelPosition="left" :model="model" :rules="rules" ref='model'>
        <u-form-item label="" prop="mobile">
          <u--input clearable shape='circle' placeholder="请输入手机号" v-model="model.mobile">
            <view class="" style="" slot='prefix'>
              <text class="iconfont icon-shouji"></text>
            </view>
          </u--input>
        </u-form-item>
        <u-form-item label="" prop="code">
          <u--input clearable shape='circle' placeholder="请输入验证码" v-model="model.code">
            <view class="" style="" slot='prefix'>
              <text class="iconfont icon-yanzhengma"></text>
            </view>
            <view class="" slot='suffix' @click="getImgV">
              {{countDown?countDown+'S':'获取验证码'}}
            </view>
          </u--input>
        </u-form-item>
      </u--form>
      <u-button @click='loginFn' type="primary" shape="circle" size="" text="登录" class="mt40"></u-button>
      <!-- #endif -->
      <!-- #ifdef MP-WEIXIN -->
      <u-button type="primary" size="large" shape="circle" text="手机号快捷登录" open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumber">
      </u-button>
      <!-- #endif -->
    </view>
    <!-- #ifdef H5 -->
    <zjDialogVerification ref="verification" :isShow="isShowCodeDialog" :top="codeObj.yHeight" :bgImg="codeObj.bigImage"
      :maskImg="codeObj.smallImage" :isSuccess="codeObj.isSuccess" :isFail="codeObj.isFail"
      @close="isShowCodeDialog = false" @refresh="refresh" @finish="finish">
    </zjDialogVerification>
    <!-- #endif -->
  </view>
</template>

<script>
  import zjDialogVerification from "@/components/zj-dialog/zj-dialog-verification.vue";

  export default {
    components: {
      zjDialogVerification
    },
    data() {
      return {
        configInfo: {},
        isShowCodeDialog: false,
        codeObj: {
          bigImage: '',
          smallImage: '',
          key: '',
          yHeight: '',
          isSuccess: false,
          isFail: false,
        },
        model: {
          mobile: '',
          code: '',
        },
        rules: {
          mobile: {
            type: 'string',
            required: true,
            message: '手机号不能为空',
            trigger: ['blur', 'change']
          },
          code: {
            type: 'string',
            required: true,
            message: '验证码不能为空',
            trigger: ['blur', 'change']
          },
        },
        countDown: 0,
        pageObj:null
      }
    },
    watch: {
      countDown() {
        if (this.countDown > 0) {
          setTimeout(() => {
            this.countDown--
          }, 1000)
        }
      }
    },
    async onLoad({
      pageObj
    }) {
      if (pageObj) {
        this.pageObj = JSON.parse(decodeURIComponent(pageObj))
      }
      this.configInfo = await this.$getConfigInfo();
    },
    methods: {
      // 获取手机号
      getPhoneNumber(e) {
        if (!e.detail.iv) {
          return this.$toast('获取手机号失败');
        }
        uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            this.$api.post('/user/auth', {
              code: loginRes.code,
              phoneCode: e.detail.code,
            }).then(async res => {
              this.$store.commit("user/set_token", res.data.token)
              this.$store.commit("user/set_openId", res.data.openId)
              this.$store.commit("user/set_name", res.data.nickName)
              this.$store.commit("user/set_avatar", res.data.avatar)
              this.$store.commit("user/set_userId", res.data.userId)
              this.$store.commit("user/set_mobile", res.data.mobile)
              if(!res.data.avatar || !res.data.nickName) {
              	await this.saveUserInfo(res.data);
              }
              if (this.pageObj) {
                this.$navToPage(this.pageObj, "redirectTo")
              } else {
                this.$navToPage({
                  url: "/pages/index/index"
                }, "switchTab")
              }
            })
          }
        });
      },

      // 保存用户信息
      async saveUserInfo(userInfo) {
      	return new Promise((resolve, reject) => {
      		this.$api.post('/user/userinfo/save', {
            userId: this.$store.state.user.userId,
            avatarUrl: this.configInfo.minLogo3,
            nickName: `微信用户_${userInfo.mobile.slice(7, 11)}`,
      		}).then(res => {
      			resolve(res.data);
      		})
      	})
      },

      async getImgV() {
        try {
          if (this.countDown == 0) {
            this.$refs.model.validateField("mobile", (res) => {
              if (!res.length) {
                this.$api.get('/admin/user/getVerifi').then(res => {
                  this.codeObj = res.data;
                  this.isShowCodeDialog = true
                })
              }
            })
          }
        } catch (e) {}
      },
      refresh() {
        this.getImgV()
      },
      finish(val) {
        this.$api.post('/admin/user/smsCode', {
          mobile: this.model.mobile,
          code: this.codeObj.key,
          codeValue: parseInt(val),
        }).then(res => {
          this.isShowCodeDialog = false
          this.codeObj = {
            bigImage: '',
            smallImage: '',
            key: '',
            yHeight: '',
            isSuccess: false,
            isFail: false,
          }
          this.countDown = 60
        })
      },
      //登录
      async loginFn() {
        try {
          await this.$refs.model.validate()
          let params = {
            "mobile": this.model.mobile,
            "code": this.model.code,
          }
          await this.$store.dispatch('user/login', params)
          await this.$store.dispatch('user/getInfo')
          await this.$Prompt.toast({
            title: '登陆成功',
            icon: 'success'
          })
          this.$Router.push({
            name: 'learn'
          })
        } catch (e) {}
      },
    }
  }
</script>

<style lang="scss" scoped>
  .all-container {
    background-color: #fff;
    height: 100vh;
    box-sizing: border-box;
    padding-top: 1rpx;
  }

  .logo {
    width: 100vw;
    height: 500rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .logo_top {
      width: 240rpx;
      height: 240rpx;
    }

    .logo_bottom {
      font-size: 40rpx;
      font-weight: 700;
      color: #333;
      padding-top: 38rpx;
    }
  }

  .loginForm {
    padding: 0 60rpx;
    .iconfont {
      color: $theme-color;
      font-size: 36rpx;
      font-weight: 600;
      margin: 0 8rpx;
    }
  }
</style>
