<template>
  <div class="container">
    <div class="loginContent">
      <div class="login-title">
        羊小咩欢迎您！
      </div>
      <cr-form
        ref="loginForm"
        class="login-form"
        show-error
        validate-trigger="onBlur"
        :show-error-message="false"
        @submit="login"
        @failed="onFormFailed"
      >
        <cr-field
          v-model="formData.phoneNo"
          name="phoneNo"
          type="tel"
          label=""
          class="input"
          placeholder="请填写您的手机号"
          :rules="validOptions[0]"
        />
        <cr-field
          v-if="captchaShow && captchaUrl"
          v-model="formData.captcha"
          class="send-sms-field input"
          name="captcha"
          type="digit"
          label=""
          placeholder="请填写图片验证码"
          :rules="validOptions[1]"
        >
          <template slot="button">
            <img :src="captchaUrl" class="captchaUrl" @click="getCaptcha()" />
          </template>
        </cr-field>
        <cr-field
          v-show="type === 'fast'"
          v-model="formData.verifyCode"
          class="send-sms-field input"
          name="verifyCode"
          type="tel"
          :max-length="6"
          label=""
          placeholder="请填写验证码"
          :rules="[{ required: type === 'fast', message: '请填写短信验证码' }]"
        >
          <template slot="button">
            <p v-show="gtShow && gtVcode && !noAllowSend" id="captcha-box" class="get-catpha" />
            <a v-if="!showCount" href="javascript:;" class="login-form-send" @click="getCode">
              获取验证码
            </a>
            <span v-else class="login-form-send count">{{ count }}s</span>
          </template>
        </cr-field>
        <cr-field
          v-if="type === 'password'"
          v-model="formData.password"
          name="password"
          type="password"
          label=""
          class="input"
          placeholder="请填写密码"
        />
        <div class="checkbox-content">
          <cr-checkbox v-model="isAgreement" icon-size="14px" shape="round" class="agreement">
            <span class="text">我已阅读并同意 </span>
          </cr-checkbox>
          <a :href="$config.privacyRreaty.url" class="link">《{{ $config.privacyRreaty.label }}》</a
          ><a :href="$config.registerRreaty.url" class="link"
            >《{{ $config.registerRreaty.label }}》</a
          >
        </div>

        <cr-button
          shape="circle"
          block
          type="primary"
          native-type="submit"
          class="login-form-submit"
        >
          登录/注册
        </cr-button>
      </cr-form>
      <div class="login-change" @click="changeType">
        {{ type === 'password' ? '验证码登录' : '密码登录' }}
      </div>
    </div>
  </div>
</template>

<script>
import {
  friendLogin as loginByPhone,
  smsCode as getCaptchaSms,
  captcha,
  captchaType,
  loginByPassword
} from '@/api/user.api';
import { isPhone } from '@/service/utils.service';
import { mapMutations } from 'vuex';
import { getUserInfo } from '@/service/userInfo.service';
import initGeetest from '@/service/lib/jy';
// import { sStorage } from '@/service/sessionStorage.service';
import localStorage from '@/service/localStorage.service';
import cfg from '@/config';
import { smTrackEvent } from '@/service/shumei.service';

export default {
  name: 'Login',
  data() {
    return {
      type: 'password',
      show: true,
      showCount: false,
      count: '',
      timer: null,
      captchaUrl: '',
      captchaShow: false,
      captchaId: '',
      captcha: '',
      gtShow: false,
      gtVcode: true,
      isAgreement: false,
      gt: {
        clientType: 'h5',
        verifyType: 'gt',
        geetest_challenge: '',
        geetest_validate: '',
        geetest_seccode: '',
        phoneNo: ''
      },
      verifyType: '',
      backUrl: '',
      uniqueKey: '',
      formData: {
        phoneNo: '',
        verifyCode: '',
        captcha: '',
        password: ''
      },
      validOptions: [
        [
          { required: true, message: '请填写您的手机号' },
          { validator: isPhone, message: '请填写正确的手机号码' }
        ],
        [{ required: true, message: '请填写图形验证码' }],
        [{ required: true, message: '请填写短信验证码' }]
      ]
    };
  },
  computed: {
    noAllowSend() {
      return !isPhone(this.formData.phoneNo);
    }
  },
  mounted() {
    const { backUrl = '', vccChannel = '' } = this.$route.query || {};
    this.backUrl = backUrl;
    this.registerFrom = vccChannel;
    this.verifyMode();
  },
  methods: {
    ...mapMutations(['CHANGE_TOKEN']),
    changeType() {
      this.type = this.type === 'password' ? 'fast' : 'password';
    },
    onFormFailed(errorInfo) {
      const { errors } = errorInfo;
      this.$toast({ message: errors[0].message });
    },
    resetJyState(captchaObj = {}) {
      this.gtVcode = false;
      captchaObj['reset'] && captchaObj.reset();
    },
    getJyParam(res) {
      var vm = this;
      initGeetest(
        {
          width: '100%',
          gt: res.gt,
          challenge: res.challenge,
          offline: !res.success,
          product: 'popup'
        },
        function(captchaObj) {
          // 这里可以调用验证实例 captchaObj 的实例方法
          captchaObj.appendTo('#captcha-box');
          captchaObj.onReady(function() {
            vm.isReady = true;
          });
          captchaObj.onSuccess(function() {
            var result = captchaObj.getValidate();
            vm.gt.geetest_challenge = result.geetest_challenge;
            vm.gt.geetest_validate = result.geetest_validate;
            vm.gt.geetest_seccode = result.geetest_seccode;
            vm.getCode(captchaObj);
          });
          captchaObj.onError(function() {
            vm.$toast('尝试过多，请点击重试');
          });
        }
      );
    },

    async getCaptcha() {
      const [res] = await captcha();
      this.captchaUrl = res.image;
      this.captchaId = res.imageId;
    },
    async login() {
      if (!this.isAgreement) {
        this.$toast.fail('请勾选协议');
        return;
      }
      const { phoneNo, verifyCode, password } = this.formData;
      console.log(verifyCode, 'verifyCode');
      const smTrackData = {
        eventId: 'login',
        phone: phoneNo,
        type: this.type === 'password' ? 'phonePassword' : 'phoneMessage'
      };
      const [res] =
        this.type === 'password'
          ? await loginByPassword({
              loginName: phoneNo,
              password,
              captchaId: this.captchaId,
              captchaValue: this.formData.captcha
            })
          : await loginByPhone({
              loginName: phoneNo,
              smsCode: verifyCode,
              captchaId: this.captchaId,
              captchaValue: this.formData.captcha
              // uuid: this.$route.query.uuid
            });
      // console.log(smTrackData);
      if (res) {
        this.$toast.success('登录成功');
        this.CHANGE_TOKEN(res.token);
        this.$track.run('loginSa', res.uuid);
        localStorage.set('userPhoneNo', res.phoneNo);
        await getUserInfo();
        smTrackEvent(smTrackData);
        setTimeout(() => {
          window.location.href = `${cfg.zimuLink}?token=${res.token}&registerFrom=${this.registerFrom}&tenantId=560761&appName=xinyongqianbao&appChannel=214`;
        }, 1000);
        return;
      }
      smTrackEvent(smTrackData);
    },
    async getCode(captchaObj) {
      if (!this.gtShow && !this.captchaShow) {
        this.captchaShow = true;
        this.getCaptcha();
        return;
      }
      const TIME_COUNT = 60;
      const { phoneNo } = this.formData;
      if (this.timer) return;
      if (!isPhone(phoneNo)) {
        this.$toast('请填写正确的手机号码');
        return;
      }
      let params = {};
      if (this.gtShow) {
        this.gt.phoneNo = phoneNo;
        params = { ...this.gt, verifyType: 'gt', uniqueKey: this.uniqueKey };
      } else {
        params = {
          phoneNo,
          captchaValue: this.formData.captcha,
          captchaId: this.captchaId
        };
        if (this.$config.yxm) {
          params.verifyType = 'qg';
          params.clientType = 'h5';
        }
      }
      try {
        const [res] = await getCaptchaSms(params);

        if (!res) return;
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.showCount = true;
          if (this.gtShow) {
            this.resetJyState(captchaObj);
          }
          this.$toast('短信验证码已发送，请注意查收');
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.showCount = false;
              clearInterval(this.timer);
              this.timer = null;
              this.gtVcode = true;
            }
          }, 1000);
        }
      } catch (error) {
        if (this.gtShow) {
          this.resetJyState(captchaObj);
        }
      }
    },
    async verifyMode() {
      const [res] = await captchaType({ phoneNo: this.phone, clientType: 'h5' });
      this.uniqueKey = res.uniqueKey;
      this.verifyType = res.verifyType;
      if (res.verifyType === 'gt') {
        this.getJyParam(res);
        this.gtShow = true;
        return;
      } else {
        this.captchaShow = true;
        this.getCaptcha();
      }
    }
  }
};
</script>

<style lang="less" scoped>
// background: #DCDCDC;
.input {
  height: 60px;
  border-bottom: 0.5px solid @gray-2;
  padding: 0 !important;
  // padding-bottom: 15px !important;
}
.agreement {
  .text {
    font-size: 12px;
    color: @gray-5;
  }
}
.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  background: @white;
  padding-top: 30px;
  box-sizing: border-box;
  .loginContent {
    width: 315px;
    height: auto;
  }
}
.login-title {
  .text-size(24);
  color: @black;
  // font-weight: @font-weight-bold;
  padding: 40px 0 68px;
}
.checkbox-content {
  display: flex;
  margin-top: 67px;
  .link {
    font-size: 12px;
  }
}
.login-form {
  .cr-field--error-message {
    display: none;
  }
  .cr-cell {
    &__value {
      overflow: initial;
    }
    &-group {
      &::after {
        display: none;
      }
    }

    // background: rgb(249, 249, 249);
    // border-radius: @border-radius-max;
    // margin-bottom: 12px;
    align-items: center;
    // padding: 12.5px 16px;
    &::after {
      display: none;
    }
    &__title {
      color: #333333;
      display: flex;
      align-items: center;
    }
  }
  &-btn {
    width: 90px;
    position: relative;
  }
  &-send {
    width: 104px;
    box-sizing: border-box;
    text-align: left;
    padding-left: 20px;
    border-left: 1px solid @gray-2;
    color: @black;
    .text-size(16);
    &.count {
      padding: 0;
      text-align: center;
      color: @gray-4;
    }
  }
  &-submit {
    margin-top: 15px;
    height: 40px;
    font-size: 16px;
  }
}
.login-change {
  font-size: 14px;
  display: flex;
  justify-content: flex-end;
  color: #666;
  margin-top: 20px;
}
.get-catpha {
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
  opacity: 0;
}
::v-deep {
  .cr-field--control-in {
    color: #333333;
    .text-size(16);
  }
  .cr-field--control-error::placeholder {
    color: #999 !important;
  }
}
.captchaUrl {
  margin-bottom: -(@padding-unit + 2);
}
</style>
