import Vue from 'vue/types/umd';
<!--  -->
<template>
  <div class="login">
    <div class="login-con">
      <div class="login-bg-img">
        <van-image width="100%" height="400" :src="bgImgPath" fit="contain" />
      </div>
      <div class="login-btn">
        <van-button type="primary" size="large" round @click="onWxAutoLogin" :color="$green" class="login-text"
          >用户一键登录</van-button
        >
      </div>
    </div>
    <van-popup v-model="show" round position="bottom" :style="{ height: '50%' }">
      <div class="popup">
        <van-cell-group>
          <van-field
            v-model="phone"
            type="tel"
            maxlength="12"
            placeholder="请输入监护人手机号码"
            :error-message="errPhoneMsg"
          >
            <template #left-icon> </template>
          </van-field>
          <van-field
            v-model="verificacode"
            type="digit"
            maxlength="6"
            placeholder="请输入短信验证码"
            :error-message="errCodeMsg"
          >
            <template #button>
              <van-button size="small" round :color="$green" @click="sendCode" :disabled="sendMsgDisabled">{{
                sendMsgDisabled ? '已发送(' + codeTime + ')' : '发送验证码'
              }}</van-button>
            </template>
          </van-field>
        </van-cell-group>
        <van-button size="large" round @click="onLogin" :color="$green" class="login-text">注册/登录</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import APIUser from '@/api/user';
import NotifyService from '@/services/notify-service';
import AppId from '@/config/appId';
import APIWx from '@/api/wx';
export default {
  data() {
    const time = 120;
    return {
      bgImgPath: require('../../assets/com-imges/55_06.png'),
      show: false,
      verificacode: '',
      phone: '',
      errPhoneMsg: '',
      errCodeMsg: '',
      codeTime: time, //倒计时间
      codeInterval: time, //倒计时间
      sendMsgDisabled: false,
      verificationCode: ' '
    };
  },
  created() {},
  mounted() {
    // TODO 获取code再拿code获取openId
    this.getCode();
  },
  methods: {
    getCode() {
      let url = window.location.href;
      if (url.indexOf('code') > -1) {
        let codeUrl = window.location.href.split('?code=');
        console.log('获取code的url', codeUrl);
        if (codeUrl) {
          let timeStamp = new Date().getTime();
          let code = codeUrl[1].split('&')[0];
          if (this.$own.isNotNull(code)) {
            this.$store.commit('code', `${code}-${timeStamp}`);
            this.checkedRegister(code);
          }
        }
      }
    },
    // 通过code拿去openId
    checkedRegister(code) {
      if (code) {
        let reqBody = {
          loginCode: code.split('-')[0],
          appId: AppId
        };
        APIWx.checkIsNewCustomer(reqBody).then(res => {
          if (res.data.stateCode === 1 || res.data.stateCode === 2) {
            this.$store.commit('openId', res.data.wxOpenId);
          }
        });
      }
    },
    sendCode() {
      // 验证是否输正确的手机号码，
      let reg = /^1[3456789]\d{9}$/;
      if (this.$own.isNull(this.phone)) {
        console.log('手机号码为空');
        this.errPhoneMsg = '手机号码不能为空';
      } else if (!reg.test(this.phone)) {
        console.log('手机号码为空222');
        this.errPhoneMsg = '请输入正确的手机号码';
      } else {
        this.errPhoneMsg = '';
        // 调取发送/获取验证码接口
        this.getVerificationCode();
      }
    },
    getVerificationCode() {
      let reqBody = {
        mobile: this.phone,
        validateType: 2 // 登录页面 后端约定为 2
      };
      APIUser.getVerificationCode(reqBody)
        .then(res => {
          let item = res.data;
          if (item.stateCode === 1 && item.code !== null) {
            NotifyService.notify({ message: '已发送验证码到该手机', type: 'success' });
            this.verificationCode = item.code;
            this.sendMsgDisabled = true;
            this.countDown();
          }
          if (item.stateCode === 0 && item.code === null) {
            //this.notify('请勿频繁获取，验证码5分钟内有效');
            NotifyService.notify({ message: item.message });
          }
        })
        .catch(() => {
          NotifyService.notify({ message: '获取验证码过于频繁.请稍后再试', type: 'warning' });
        })
        .finally(() => (this.canSendVerificationCode = true));
    },
    countDown() {
      let codeInterval = window.setInterval(() => {
        if (--this.codeTime <= 0) {
          this.codeTime = this.codeInterval;
          this.sendMsgDisabled = false;
          window.clearInterval(codeInterval);
        }
      }, 1000);
    },
    onLogin() {
      // 一键登录之前调取登录接口查询是否是旧用户，如果是旧用户直接登录无需再输入手机号码和验证码登录，否则需要
      // 现在模拟是新用户，待接口完成
      let reg = /^1[3456789]\d{9}$/;
      if (this.phone === '' || !reg.test(this.phone)) {
        this.errPhoneMsg = '请输入正确的手机号码';
      } else if (this.verificacode === '') {
        this.errCodeMsg = '请输入正确的验证码';
      } else {
        // 格式正确
        this.errPhoneMsg = '';
        this.loginRequest();
      }
    },
    // 使用微信code得到的openId 自动登录
    onWxAutoLogin() {
      let reqBody = {
        appId: AppId,
        openId: /* this.$store.getters.openId || */ 'o7Z9t0zyOyZxojWy0VwsLNChddzs'
      };
      APIUser.wxAutoLogin(reqBody)
        .then(res => {
          if (res.data.stateCode === 1) {
            if (res.data) {
              let item = res.data;
              this.$store.commit('authToken', item.authToken);
              this.$store.commit('userId', item.userId);
              this.$store.commit('code', '');
              this.$store.commit('openId', item.wxOpenId || '');
              NotifyService.notify({ message: '登录成功！正在为您跳转...', type: 'success' });
              this.$store.commit('isLogin', 'true');
              setTimeout(() => {
                this.$router.push({ name: 'Index' });
              }, 1000);
            }
          } else {
            this.show = true;
          }
        })
        .catch(e => {
          console.log(e);
          NotifyService.notify({ message: `${e.message}` });
        });
    },
    loginRequest() {
      /* let reqBody = {
        phoneNumber: this.phone,
        loginCode: this.$store.getters.openId,
        appId: AppId,
        loginType: 2,
        verificationCode: this.verificacode
      }; */
      let reqBody = {
        loginName: /* this.phone */ '18664272743',
        password: /* this.password */ '123456',
        loginCode: /* this.$store.getters.openId */ 'ofTDa6FWgxD-HKoeYtJcrr_9StlE',
        appId: AppId
      };
      APIUser.wxLogin(reqBody)
        .then(res => {
          let item = res.data;
          if (item.stateCode === 0) {
            NotifyService.notify({ message: item.message });
          } else if (item.stateCode === 1) {
            this.$store.commit('authToken', item.authToken);
            this.$store.commit('userId', item.userId);
            this.$store.commit('code', '');
            NotifyService.notify({ message: '登录成功！正在为您跳转...', type: 'success' });
            this.$store.commit('isLogin', 'true');
            setTimeout(() => {
              this.$router.push({
                name: 'personInfos',
                query: {
                  from: 'login',
                  toRouter: 'Index'
                }
              });
            }, 1000);
          } else {
            NotifyService.notify({ message: '获取openId失败，请您重新进入公众号' });
          }
        })
        .catch(e => {
          console.log(e);
          NotifyService.notify({ message: '请求失败，请联系系统管理员' });
        });
    }
  }
};
</script>
<style scoped lang="scss">
/* @import url(); 引入css类 */
@import './login.scss';
</style>
