<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]"
        />
        <transition name="slide-fade">
          <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>
        </transition>
        <cr-field
          v-model="formData.verifyCode"
          class="send-sms-field input"
          name="verifyCode"
          type="tel"
          :max-length="6"
          label=""
          placeholder="请填写验证码"
          :rules="validOptions[2]"
        >
          <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>
        <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 v-if="operater && operater != 'CT'" class="oneKeyLoginBtn" @click="jVerify(true)">
        一键登录
      </div>
    </div>
  </div>
</template>

<script>
import {
  friendLogin as loginByPhone,
  smsCode as getCaptchaSms,
  captcha,
  captchaType,
  apiLoginSuccessPage
} 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 { smTrackEvent } from '@/service/shumei.service';
import JverifyAuthLoginMixins from '@/mixins/JverifyAuthLogin.mixin';
export default {
  name: 'Login',
  mixins: [JverifyAuthLoginMixins],
  data() {
    return {
      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: ''
      },
      validOptions: [
        [
          { required: true, message: '请填写您的手机号' },
          { validator: isPhone, message: '请填写正确的手机号码' }
        ],
        [{ required: true, message: '请填写图形验证码' }],
        [{ required: true, message: '请填写短信验证码' }]
      ],
      jumpNewUserPage: ['user'] // 目前首页、我的页面新用户登录之后进入新用户专享页；
    };
  },
  computed: {
    noAllowSend() {
      return !isPhone(this.formData.phoneNo);
    }
  },
  async mounted() {
    const { backUrl = '' } = this.$route.query || {};
    this.backUrl = backUrl;
    if (this.$config.qinghai) {
      this.captchaShow = true;
      this.getCaptcha();
    }
    if (this.$config.yxm) {
      this.verifyMode();
    }
    this.jVerify();
  },
  methods: {
    ...mapMutations(['CHANGE_TOKEN']),
    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() {
      // H5_LoginBtnClick
      this.$track.registeredEvents('H5_LoginBtnClick', {
        le_channel_code: localStorage.get('vccChannel') || '',
        le_login_type: '验证码登录'
      });
      if (!this.isAgreement) {
        this.$toast.fail('请勾选协议');
        return;
      }
      const { phoneNo, verifyCode } = this.formData;

      const [res] = await loginByPhone({
        loginName: phoneNo,
        smsCode: verifyCode
        // uuid: this.$route.query.uuid
      });
      const smTrackData = {
        eventId: 'login',
        phone: phoneNo,
        type: 'phoneMessage'
      };
      if (res) {
        this.$toast.success('登录成功');
        this.CHANGE_TOKEN(res.token);
        this.$track.run('loginSa', res.uuid);
        localStorage.set('userPhoneNo', res.phoneNo);
        this.saUploadLoginEvent(true);
        const params = {};
        [
          'adv_utm_campaign',
          'adv_utm_content',
          'adv_utm_medium',
          'adv_utm_source',
          'adv_utm_term'
        ].forEach(param => {
          params[param] = sStorage.getItem(param) || '';
        });
        this.$track.registeredEvents('H5_Adv_LoginPageLoginBtnClick', {
          adv_url: window.location.href,
          ...params
        });
        smTrackEvent(smTrackData);
        await getUserInfo();
        let [newUserRes] = await apiLoginSuccessPage();
        if (newUserRes && newUserRes.newUser) {
          let pageArr = this.backUrl.split('/');
          let pages = pageArr.splice(pageArr.length - 1, 1);
          // pageArr.length === 3 首页 没有路径
          if (
            (pageArr.length === 3 || this.jumpNewUserPage.includes(pages[0])) &&
            newUserRes.nextUrl
          ) {
            this.goBack(newUserRes.nextUrl);
            return false;
          } else {
            this.goBack(this.backUrl);
            return false;
          }
        } else {
          this.goBack(this.backUrl);
        }
        return;
      }
      this.saUploadLoginEvent(false);
      // 登录不管成功与否，上报数美
      smTrackEvent(smTrackData);
    },
    // 登录回调
    goBack(backUrl) {
      setTimeout(() => {
        if (backUrl) {
          location.replace(backUrl);
          return;
        }
        this.$router.go(-1);
      }, 500);
    },
    saUploadLoginEvent(loginSuccess, failCode, failMessage) {
      this.$track.registeredEvents('H5_LoginEvent', {
        le_is_login_success: loginSuccess,
        le_channel_code: localStorage.get('vccChannel') || '',
        le_login_type: '验证码登录',
        le_failure_code: failCode || '',
        le_failure_message: failMessage || ''
      });
    },
    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 58px;
}
.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;
  }
}

.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);
}

.slide-fade-enter-active {
  animation: show 0.3s;
}

.slide-fade-leave-active {
  animation: hide 0.3s;
}

.slide-fade-enter-from {
  height: 0;
}
.slide-fade-leave-to {
  height: 0;
}
@keyframes show {
  0% {
    opacity: 0;
    height: 0;
  }
  100% {
    opacity: 1;
    height: 60px;
  }
}
@keyframes hide {
  0% {
    opacity: 1;
    height: 60px;
  }
  100% {
    opacity: 0;
    height: 0;
  }
}
.oneKeyLoginBtn {
  .text-size(16);
  color: @gray-5;
  text-align: center;
  margin-top: @padding-unit * 5;
}
</style>
