<template>
  <div class="container">
    <div class="register">
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
        <h3 class="title">智能机具管理系统</h3>

        <el-form-item prop="nickName">
          <el-input v-model="registerForm.nickName" type="text" auto-complete="off" placeholder="请输入姓名">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>

        <el-form-item prop="mobile">
          <el-input v-model="registerForm.mobile" type="text" auto-complete="off"
                    :placeholder="`请输入${config.registersConfig.phoneRegisters ? '手机号' : ''}${config.registersConfig.emailRegisters ? '/邮箱' : ''}`">
          <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleRegister"
            show-password
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            auto-complete="off"
            placeholder="确认密码"
            @keyup.enter.native="handleRegister"
            show-password
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>

        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
            v-model="registerForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleRegister"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
          </el-input>
          <div class="register-code">
            <img :src="codeUrl" @click="getCode" class="register-code-img"/>
          </div>
        </el-form-item>

        <el-form-item v-show="config.registersConfig.verificationCode" prop="verificationCode">
          <el-input v-model="registerForm.verificationCode" :readonly="!isSendingCode" placeholder="请输入验证码">
            <template slot="append">
              <el-button
                type="primary"
                @click="sendCode"
                :disabled="isSendingCode || captchaEnabled?!registerForm.code:false"
                class="send-code-button"
              >
                {{ isSendingCode ? `${countdown}s` : '获取验证码' }}
              </el-button>
            </template>
            <svg-icon slot="prefix" icon-class="message" class="el-input__icon input-icon"/>
          </el-input>
        </el-form-item>

        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleRegister"
          >
            <span v-if="!loading">注 册</span>
            <span v-else>注 册 中...</span>
          </el-button>
          <div style="float: right;">
            <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
          </div>
        </el-form-item>
      </el-form>
      <!--  底部  -->
      <div class="el-register-footer">
        <span>Copyright © 2018-2024 bonus.vip All Rights Reserved.</span>
      </div>
    </div>
  </div>
</template>

<script>
import { getCodeImg, register } from '@/api/login'
import { validateNewPassword } from '@/utils/validate'
import { decryptCBC } from '@/utils/aescbc'

export default {
  name: 'Register',
  computed: {
    LOGIN() {
      return LOGIN
    },
    config() {
      return JSON.parse(localStorage.getItem('systemConfig')) || {registersConfig: {
          phoneRegisters: true,
          emailRegisters: true,
          verificationCode:true
        }}; // 获取 JSON 对象
    },
  },
  data() {
    // 验证姓名是否符合要求
    const validateNickName = (rule, value, callback) => {
      const regex = /^[\u4e00-\u9fa5]{2,4}$/
      if (!value) {
        callback(new Error('请输入姓名'))
      } else if (!regex.test(value)) {
        callback(new Error('名字必须是2到4个汉字'))
      } else {
        callback()
      }
    }

    // 验证密码是否一致
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      codeUrl: '',
      isSendingCode: false,
      countdown: 0,
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        verificationCode: '',
        mobile: '',
        nickName: '',
        code: '',
        uuid: '',
        phoneUuid: '',
        mobileCodeType: 'REGISTER'
      },
      registerRules: {
        nickName: [
          { required: true, trigger: 'blur', validator: validateNickName }
        ],
        mobile: [
          { required: true, message: '请输入手机号/邮箱', trigger: 'blur' },
          { validator: this.validateContact, trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '请输入您的密码' },
          { validator: validateNewPassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', message: '请再次输入您的密码' },
          { required: true, validator: equalToPassword, trigger: 'blur' }
        ],
        code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
      },
      loading: false,
      captchaEnabled: true
    }
  },

  created() {
    this.getCode()
  },
  methods: {
    // 获取验证码图片
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.registerForm.uuid = res.uuid
        }
      })
    },

    // 处理注册请求
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          register(this.registerForm).then(res => {
            const username = this.registerForm.username
            this.$alert(`<font color="red">恭喜你，您的账号 ${username} 注册成功！</font>`, '系统提示', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            }).then(() => {
              this.$router.push('/login')
            }).catch(() => {
            })
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    },

    // 发送验证码
    sendCode() {
      if (!this.registerForm.mobile) {
        this.$message.error('请先填写手机号')
        return
      }
      this.$store.dispatch('GetPhoneCode', this.registerForm)
        .then(res => {
          console.log(res)
          this.isSendingCode = true
          this.countdown = 60
          const timer = setInterval(() => {
            this.countdown -= 1
            if (this.countdown <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        })
        .catch(() => {
          this.loading = false
          if (this.captchaEnabled) {
            this.getCode()
          }
          this.isSendingCode = false
          this.countdown = 0
        })
    },

    // 验证手机号或邮箱格式
    validateContact(rule, value, callback) {
      const phoneRegex = /^1[3-9]\d{9}$/
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

      if (!value) {
        return callback(new Error('请输入电子邮件或电话号码'))
      }

      if (!phoneRegex.test(value) && !emailRegex.test(value)) {
        return callback(new Error('必须是有效的电子邮件或电话号码'))
      }

      callback()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/bg.png");
  background-size: cover;
}

.register {
  width: 42%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.register-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.register-code-img {
  height: 38px;
}
</style>
