<template>
  <div v-loading="loading">
    <el-form label-width="80px" style="width:400px;" :rules="rules" :model="emailBindingForm" :ref="emailBindingForm">
      <el-form-item label="新邮箱号" prop="email">
        <el-input v-model="emailBindingForm.email"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="verifyCode">
        <el-input placeholder="验证码内容" v-model="emailBindingForm.verifyCode" class="input-with-select">
          <el-button slot="append" @click="getVerifyCode" :disabled="hasVerifyCode">{{hasVerifyCode ? codeTime : '获取验证码'}}</el-button>
        </el-input>
        <span v-if="hasVerifyCode">验证码已发送到您邮箱上</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain  @click="reBindingMail">完成绑定</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
  import Http from '@/js/http.js'
  import {logout, storageGet} from '@/js/index'
  import {notify} from '@/constants/index'

  export default {
    name: "ReBindingMail",
    data() {
      let isEmail = (rule, value, callback) => {
        if (!value) {
          callback();
        } else {
          const reg = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;
          const email = reg.test(value);
          if (!email) {
            callback(new Error("请输入正确的邮箱格式，注意去掉前后的空格"));
          } else {
            callback();
          }
        }
      };
      return {
        active: 0,
        user: {},
        loading: false,
        emailBindingForm: {
          email: '',
          verifyCode: ''
        },
        hasVerifyCode: false,
        codeTime: 60,
        rules: {
          verifyCode: [
            {required: true, message: '请输入验证码', trigger: 'blur'},
              {min:6, max: 6, message: '验证码长度为6个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            { validator: isEmail, trigger: "blur" }
          ],
        },
      }
    },
    methods: {
      setUserInfo() {
        let userId = storageGet('user') && storageGet('user').userVO.id;
        Http.get(`/api/user/${userId}`).then(res => {
          this.user = res.userVO
        })
      },
      reBindingMail() {
        this.showLoading();
        let params = {
          "id": this.user.id,
          "email": this.emailBindingForm.email,
          "verifyCode": this.emailBindingForm.verifyCode
        };
        Http.put('/api/user/email', params).then((res) => {
          this.hideLoading();
          if (res.msg == "ERROR") {
            notify('error', '绑定失败：' + res.data);
            this.codeTime = 60;
            this.hasVerifyCode = false;
          } else {
            // notify('success', '绑定成功');
            window.alert('邮箱修改成功, 请重新登录');
            logout().then((res) => {
              window.location.href = process.env.LOGIN_URL;
              // this.$router.push('/home')
            })
          }
        })

      },
      getVerifyCode() {
        let params = {
          id: this.user.id,
          email: this.emailBindingForm.email
        }
        Http.put('/api/verify/email', params).then((res) => {
          let _this = this;
          if (res.msg == "ERROR") {
            notify('error', '验证码获取失败：' + res.data);
          }else{
            this.hasVerifyCode = true;
            notify('success', res.data);
            let codeTimer = setInterval(function () {
              if (_this.codeTime > 0) {
                _this.codeTime--;
              } else {
                clearInterval(codeTimer);
                _this.hasVerifyCode = false;
                this.codeTime = 10;
              }
            }, 1000)
          }
        }).catch(err => {
          notify('error', '获取验证码失败:' + err.data);
        })
      },
      showLoading() {
        this.loading = true
      },
      hideLoading() {
        this.loading = false
      },
    },

    mounted() {
      this.setUserInfo();
    }
  }
</script>

<style scoped>

</style>
