<template>
  <v-container class="register-for-invite pa-0" fluid :class="`type-${type}`">
    <div class="box1">
      <validation-observer ref="observer" class="mlr10" slim>
        <v-form @submit.prevent="submit()">
          <validation-provider v-slot="{ errors }" ref="providerPhome" name="手机号码" rules="phone" slim>
            <div style="display: flex;">
              <div class="label-item">
                手机号
              </div>
              <v-text-field v-model="form.phone" v-mask="$mask.phone" background-color="#F6F6F6" name="phone" required :error-messages="errors" placeholder="请输入11位手机号" solo type="tel" flat maxlength="11" @blur="makePoint(form.channelCode + '_Promotion _activities_输入手机号')" />
            </div>
          </validation-provider>
          <validation-provider v-slot="{ errors }" name="短信验证码" rules="code" slim>
            <div style="display: flex;">
              <div class="label-item">
                验证码
              </div>
              <v-text-field ref="code" v-model="form.code" v-mask="'######'" class="w220" background-color="#F6F6F6" label="" :error-messages="errors" name="code" maxlength="6" required placeholder="请输入验证码" solo flat type="tel" @blur="makePoint(form.channelCode + '_Promotion _activities_输入验证码')">
                <template #append>
                  <v-btn :loading="codeSending" :disabled="codeTime > 0" small depressed color="#1E3ADE" plain class="text-base" @click="sendSmsCode()">
                    <template v-if="codeTime > 0">{{ codeTime }}s后重新获取</template>
                    <template v-else>获取验证码</template>
                  </v-btn>
                </template>
              </v-text-field>
            </div>
          </validation-provider>
          <div class="submit-btn-box">
            <v-btn type="submit" :loading="submitting" class="submit-btn" rounded>注册并下载APP</v-btn>
          </div>
        </v-form>
      </validation-observer>
    </div>
  </v-container>
</template>

<script>
import { Toast } from 'vant';
import { registerForInvite } from '~/api/user/client.js';
import { sendSmsCode } from '~/api/message/phone.js';
export default {
  auth: false,
  name: 'RegisterForInvite',
  data() {
    return {
      form: {
        phone: '',
        code: '',
        invitationUserName: null,
        activityId: null,
        invitationType: 5
      },
      codeSending: false,
      codeTime: 0,
      submitting: false,
      client: 1
    };
  },
  fetch() {
    this.form.invitationUserName = this.$route.query.invitationUserName;
    this.form.activityId = this.$route.query.activityId;
    if (this.$userAgent.isSzx && this.$userAgent.isAndroid) {
      this.client = 1;
    } else if (this.$userAgent.isSzx && this.$userAgent.isIos) {
      this.client = 2;
    } else if (this.$userAgent.isMiniProgram) {
      this.client = 5;
    } else {
      this.client = 7;
    }
  },
  head: {
    title: '注册',
  },
  computed: {
    type() {
      return 2;
    },
  },
  mounted() {
    this.makePoint('activity_download_PV')
    this.makePoint('activity_download_UV')
  },
  methods: {
    maskPhone(value) {
      return [/\d/, /\d/];
    },
    makePoint(positionButton) {
      this.$axios.$post('/public/v5/buriedPointRecord/reportRecords', [
        {
          client: this.client,
          eventCode: '28_分享活动',
          userName: '',
          positionButton,
          operationTime: this.getCurrentTime(),
          phoneNumber: '',
          deviceId: ''
        },
      ]);
    },
    getCurrentTime() {
      const date = new Date(); // 当前时间
      const year = date.getFullYear() // 年
      const month = this.repair(date.getMonth() + 1); // 月
      const day = this.repair(date.getDate()); // 日
      const hour = this.repair(date.getHours()); // 时
      const minute = this.repair(date.getMinutes()); // 分
      const second = this.repair(date.getSeconds()); // 秒
      // 当前时间 
      const curTime = year + "-" + month + "-" + day +
        " " + hour + ":" + minute + ":" + second;
      return curTime;
    },
    repair(i) {
      if (i >= 0 && i <= 9) {
        return "0" + i;
      } else {
        return i;
      }
    },
    async submit() {
      try {
        this.makePoint('activity_Share_注册并下载app按钮')
        this.submitting = true;
        const valid = await this.$refs.observer.validate();
        if (valid) {
          this.$tongji.trackEvent('活动', '注册', '', 0);
          await registerForInvite(this, this.form);
          Toast({
            message: '注册成功',
            position: 'top',
            duration: 3000
          });
          this.openSzxApp();
        }
      } catch (error) {
        Toast({
          message: error.message,
          position: 'top',
          duration: 3000
        });
        if(error.response.data.status === 1114) {
          this.openSzxApp();
        }
      } finally {
        this.submitting = false;
      }
    },
    openSzxApp() {
      this.$callSzx.open({ param: {}, path: '' });
    },
    async sendSmsCode() {
      try {
        this.codeSending = true;
        const validationResult = await this.$refs.providerPhome.validate();

        if (validationResult.valid) {
          this.$tongji.trackEvent('活动', '发送短信', '', 0);
          this.makePoint('activity_Share_获得验证码')
          const res = await sendSmsCode(this, {
            type: 'common',
            authorizationType: 5,
            phone: this.form.phone,
          });
          this.codeTime = 60;
          this.codeInterval = setInterval(
            () => --this.codeTime <= 0 && clearInterval(this.codeInterval),
            1000,
          );
          Toast({
            message: res.msg,
            position: 'top',
            duration: 3000
          });
        }
      } catch (error) {
        Toast({
          message: error.message,
          duration: 3000
        });
      } finally {
        this.codeSending = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.mlr10 {
  margin: 4px;
  border: 1px solid #FDAF7D;
  border-radius: 18px 18px 18px 18px;
  overflow: hidden;
  width: 344px;
  height: 227px;
  box-sizing: border-box;
  padding: 25px 19px 23px 18px;
}

.register-for-invite {
  color: #333;
  background-size: 100% auto;
  // background-position-y: -44px;
  overflow: hidden;
  padding-bottom: 30px;
  min-height: 880px;

  &.type-1 {
    background-image: url('~/assets/image/activity/invite-user/bg@2x.png');
  }

  &.type-2 {
    background-image: url('~/assets/image/activity/invite-user/bj@2x.png');
  }

  &.type-3 {
    background-image: url('~/assets/image/activity/invite-user/bg-3@2x.png');
  }
}

.box1 {
  margin: 265px auto 0;
  width: 350px;
  height: 234px;
  background: #FFFFFF;
  border-radius: 18px 18px 18px 18px;
  overflow: hidden;
}

.submit-btn-box {
  // 解决百度APP广告屏蔽导致按钮被隐藏
  display: flex !important;
  justify-content: center;
}

.submit-btn {
  display: block;
  width: 308px !important;
  height: 40px !important;
  background: linear-gradient(0deg, #F34927 0%, #FDAF7D 100%);
  border-radius: 20px;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  color: #FFFFFF !important;
  line-height: 40px;
}

.label-item {
  width: 64px;
  font-size: 14px;
  color: #333;
  height: 12.8vw;
  line-height: 12.8vw;
  text-align: center;
}

.w220 {
  width: 220px;
}
</style>
