<template>
  <div class="login_bg">
    <div class="logo">
      <a href="/">
        <span class="logo_text">
          <img src="../assets/logo1.png" height="40px" v-if="$isMobile" />
          <img src="../assets/logo.png" height="40px" v-else />
        </span>
      </a>
    </div>
    <div>
      <div class="login_content">
        <h2 style="text-align: center; font-weight: 400; color: #4a4c6d">
          用户注册
        </h2>
        <el-radio-group v-model="labelPosition" class="radioGroup" size="small" @change="clickChange">
          <el-radio-button label="mailbox">邮箱注册</el-radio-button>
          <el-radio-button label="phone">手机号注册</el-radio-button>
        </el-radio-group>
        <el-form
          size="medium"
          :model="registerForm"
          :rules="rules"
          ref="registerForm"
          class="login_form">
          <el-form-item v-if="labelPosition==='mailbox'" prop="email" label="">
            <el-input
              v-model="registerForm.email"
              prefix-icon="el-icon-postcard"
              placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item v-if="labelPosition==='mailbox'" prop="code" label="">
            <div style="display: flex; gap: 20px">
              <div style="flex: 1">
                <el-input
                  v-model="registerForm.code"
                  prefix-icon="el-icon-message"
                  placeholder="请输入邮箱验证码"></el-input>
              </div>
              <div>
                <el-button
                  class="get-code-button"
                  style="width: 112px"
                  :disabled="getCodeDisabled"
                  :class="getCodeDisabled ? 'disabled' : 'code-btn'"
                  @click="verCode">
                  {{
                    codeCountDown === 0 ? '获取验证码' : `${codeCountDown}秒`
                  }}
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item v-if="labelPosition==='phone'" prop="phone" label="">
            <el-input
              v-model="registerForm.phone"
              prefix-icon="el-icon-phone"
              placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item v-if="labelPosition==='phone'" prop="verifyKey" label="">
            <div style="display: flex; gap: 20px; margin-bottom: -10px;">
              <div style="flex: 1">
                <el-input
                  v-model="registerForm.verifyKey"
                  prefix-icon="el-icon-postcard"
                  placeholder="请输入验证码,区分大小写">
                </el-input>
              </div>
              <div @click="getVerifycode">
                <img
                  style="width: 100px; height: 80%"
                  :src="VerifyUrl">
                </img>
              </div>
            </div>
          </el-form-item>
          <el-form-item  v-if="labelPosition==='phone'" prop="code" label="">
            <div style="display: flex; gap: 20px">
              <div style="flex: 1">
                <el-input
                  v-model="registerForm.code"
                  prefix-icon="el-icon-message"
                  placeholder="请输入短信验证码"></el-input>
              </div>
              <div>
                <el-button
                  class="get-code-button"
                  style="width: 112px"
                  :disabled="getCodeDisabled"
                  :class="getCodeDisabled ? 'disabled' : 'code-btn'"
                  @click="verPhonecode">
                  {{
                    codeCountDown === 0 ? '获取验证码' : `${codeCountDown}秒`
                  }}
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="password" label="">
            <el-input
              type="password"
              v-model="registerForm.password"
              prefix-icon="el-icon-lock"
              placeholder="请输入密码"
              autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="checkPass" label="">
            <el-input
              type="password"
              prefix-icon="el-icon-lock"
              v-model="registerForm.checkPass"
              placeholder="请再次输入密码"
              autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="companyName" label="">
            <el-input
              v-model="registerForm.companyName"
              prefix-icon="el-icon-s-home"
              placeholder="请输入公司名称"></el-input>
          </el-form-item>
          <el-form-item prop="job" label="">
            <el-input
              v-model="registerForm.job"
              prefix-icon="el-icon-s-order"
              placeholder="请输入职务"></el-input>
          </el-form-item>
        </el-form>
        <div class="agree-terms" :class="agreeAnimate ? 'agree-animate' : ''">
          <el-checkbox v-model="isRead" label="" :indeterminate="false" />
          <span class="tos-link">
            阅读并同意
            <a class="link" href="/protocol/term" target="_blank">
              《九猫ERP条款与协议》
            </a>
            <span>和</span>
            <a class="link" href="/protocol/privacy" target="_blank">
              《隐私协议》
            </a>
          </span>
        </div>
        <div style="text-align: center">
          <button class="register-btn" type="primary" @click="onRegister">
            立即注册
          </button>
        </div>
        <div style="margin-top: 20px; font-size: 14px; text-align: center">
          已有账号？
          <router-link class="link" to="/login">马上登录</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { get, post } from '../utils/axios'
import md5 from 'js-md5'
import {mapState} from "vuex";
export default {
  name: 'register',
  components: {},
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      VerifyUrl:'',
      verifyKeyTime:'',
      labelPosition: 'mailbox',
      registerForm: {},
      isRead: false,
      agreeAnimate: false,
      codeCountDown: 0,
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3,4,5,6,7,8,9][0-9]{9}$/,
            message: "请输入正确手机号码",
            trigger: ['blur', 'change'],
          }
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        verifyKey: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        checkPass: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' },
        ],
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
        ],
        job: [{ required: true, message: '请输入职务', trigger: 'blur' }],
      },
      showPwd: false,
    }
  },
  computed: {
    getCodeDisabled() {
      return this.codeCountDown > 0
    },
  },
  mounted(){
    this.getVerifycode()
  },
  methods: {
    async verCode() {
      try {
        await new Promise((resolve, reject) => {
          this.$refs.registerForm.validateField('email', (m) => {
            m ? reject() : resolve()
          })
        })
      } catch {
        return
      }
      try {
        const res = await get('business/user/emailcode', {
          email: this.registerForm.email
        })
        this.codeCountDown = 60
        this.timer = setInterval(() => {
          this.codeCountDown--
          if (this.codeCountDown <= 0) {
            clearInterval(this.timer)
          }
        }, 1000)
        this.$message.success(res.message)
      } catch (e) {
        console.error(e)
      }
    },
    async verPhonecode(){
      try {
        await new Promise((resolve, reject) => {
          this.$refs.registerForm.validateField('phone', (m) => {
            m ? reject() : resolve()
          })
        })
      } catch {
        return
      }
      try {
        const res = await post('business/user/phonecode', {
          account: this.registerForm.phone,
          verifyKey: this.verifyKeyTime,
          verifyCode: this.registerForm.verifyKey
        })
        this.codeCountDown = 60
        this.timer = setInterval(() => {
          this.codeCountDown--
          if (this.codeCountDown <= 0) {
            clearInterval(this.timer)
          }
        }, 1000)
        this.$message.success(res.message)
      } catch (e) {
        this.getVerifycode()
        console.error(e)
      }
    },
    onRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          if (!this.isRead) {
            this.agreeAnimate = true
            setTimeout(() => {
              this.agreeAnimate = false
            }, 700)
            return
          }
          const { code, companyName, email, job, password, phone, verifyKey } = this.registerForm
          const hash = md5.create()
          hash.update(password)

          const passwordHash = hash.hex()
          post('business/user/register', {
            code: code,
            companyName: companyName,
            email: email,
            job: job,
            password: passwordHash,
            account: email ? email : phone
          }).then((res) => {
            this.$message.success(res.message)
            if (res.code === 200) {
              this.registerForm = {}
              this.$router.push('/')
            }
          })
        }
      })
    },
    getVerifycode(){
      this.verifyKeyTime = new Date().getTime();
      get('business/user/verifycode',{
        verifyKey: this.verifyKeyTime
      }).then((res)=>{
        if(res.code === 200){
          this.VerifyUrl = res.message
        }
      })
    },
    clickChange(lab){
      this.registerForm = {}
    }
  },
}
</script>
<style scoped>
.login_bg {
  width: 100%;
  height: 100%;
  position: relative;
  background: url(../assets/register.jpg) center / cover no-repeat;
}

.login_bg::v-deep .el-input__inner {
  background-color: #fff;
}

.el-form--inline .el-form-item {
  margin-right: 0px;
}
.login_content {
  padding: 40px;
  background: #fff;
  position: absolute;
  top: 50%;
  left: 70%;
  border-radius: 6px;
  transform: translate(-50%, -50%);
  box-sizing: border-box;
  background-position: top right, center;
  background-repeat: no-repeat;
}

.login_content::v-deep .el-form-item__content {
  white-space: nowrap;
}

.login_form {
  padding: 20px 0px 0px 0px;
}

.agree-terms {
  margin-bottom: 30px;
}

.get-code-button:disabled:hover {
  background-color: #d0d2d8;
  color: #666;
}

.tos-link {
  font-size: 14px;
}

@keyframes shake {
  0% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-2.57rem);
  }
  50% {
    transform: translateX(0);
  }
  75% {
    transform: translateX(2.57rem);
  }
  100% {
    transform: translateX(0);
  }
}
.agree-animate {
  animation: shake 0.4s;
}

.register-btn {
  width: 100%;
  height: 38px;
  display: block;
  margin: 0 auto;
  background: #006eff;
  box-shadow: 0 4px 8px 0 rgb(26 90 216 / 32%);
  border-radius: 4px;
  font-size: 16px;
  color: #fff;
  cursor: pointer;
}

.code-btn {
  margin-left: 10px;
  background: linear-gradient(180deg, #319af2 0%, #2386ee 100%);
  color: #fff;
}
.disabled {
  background-color: #d0d2d8;
  color: #666;
  margin-left: 10px;
}

.logo {
  position: absolute;
  top: 7%;
  left: 8%;
}
.radioGroup{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

@media screen and (max-width: 1100px) {
  .login_bg {
    background: unset;
  }

  .logo {
    position: unset;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .login_content {
    position: unset;
    transform: unset;
    padding: 20px;
  }
}
</style>
