<script>
import { get, post } from '../../utils/request'
import EyeClose from '@/components/icon/eye_close.vue'
import EyeOpen from '@/components/icon/eye_open.vue'
import Loading from '@/components/icon/loading.vue'
import Error from '@/components/icon/error.vue'
import Email from '@/components/icon/email.vue'
import AsideInfo from '@/components/asideInfo.vue'

export default {
  components: { EyeClose, EyeOpen, Loading, Error, Email, AsideInfo },
  created() {
    if (!this.$route.query.code) {
      this.$router.push('/404')
    }
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback('Please confirm password.')
      } else if (value !== this.ruleForm.password) {
        callback("Confirm password doesn't match password")
      } else {
        callback()
      }
    }
    return {
      loading: false,
      checked: false,
      checkBox: false,
      passwordType: false,
      passwordConfirmType: false,
      teamIds: '',
      EmailCodeError: false,
      verificationCodeError: false,
      CountDown: 60, //倒计时
      buttonName: 'send', //按钮初始化文字
      isDisabled: false, //是否禁用按钮
      ruleForm: {
        email: '',
        verificationCode: '',
        userName: '',
        password: '',
        passwordConfirm: ''
      },
      rules: {
        email: [
          {
            required: true,
            message: 'Email Address is required',
            trigger: ['']
          },
          {
            type: 'email',
            message: 'Please enter a valid Email Address',
            trigger: ['']
          }
        ],
        verificationCode: [
          { required: true, message: 'Verification Code is required', trigger: [''] }
        ],
        userName: [
          { required: true, message: 'User name is required', trigger: [''] }
        ],
        password: [
          { required: true, message: 'Password is required', trigger: [''] },
          { min: 6, max: 24, message: 'Password must between 6-24 characters', trigger: [''] }
        ],
        passwordConfirm: [
          { required: true, validator: validatePass2, trigger: 'blur' },
          { min: 6, max: 24, message: 'Password must between 6-24 characters', trigger: ['blur'] }
        ]
      }
    }
  },
  watch: {
    checked: {
      handler(val) {
        if (this.checked !== '') {
          this.checkBox = false
        } else {
          this.checkBox = true
        }
      }
    }
  },
  methods: {
    createAccount() {
      this.verificationCodeError = false
      this.$refs['ruleForm'].validate((valid) => {
        if (!this.checked) {
          this.checkBox = true
          this.$message.error({
            duration: 5000,
            message: 'Please read and confirm PRIVACY POLICY and TERMS OF USE first'
          })
        }
        if (valid && this.checked) {
          this.loading = true
          if (this.$route.query.teamIds) {
            this.teamIds = this.$route.query.teamIds.split(',')
          }
          let teamIds = this.teamIds || null
          post('/pdf-tech/vppMember/create', {
            email: this.ruleForm.email,
            verifyCode: this.ruleForm.verificationCode,
            username: this.ruleForm.userName,
            password: this.ruleForm.password,
            confirmPassword: this.ruleForm.passwordConfirm,
            industry: this.ruleForm.industry,
            company: this.ruleForm.company,
            inviteEmailCode: this.$route.query.code,
            teamIds: teamIds
          }).then((res) => {
            this.loading = false
            if (
              res.data.code === 700 &&
              res.data.msg === 'False Code，please check again'
            ) {
              this.verificationCodeError = true
              this.$message.error({
                duration: 5000,
                message: 'Verification Code Error'
              })
            } else if (
              res.data.code === 700 &&
              res.data.msg === 'The inviteEmailCode is error'
            ) {
              this.verificationCodeError = true
              this.$message.error({
                duration: 5000,
                message: 'Invited users only'
              })
            } else if (
              res.data.code === 700 &&
              res.data.msg === 'Password must between 6-24 characters'
            ) {
              this.$message.error({
                duration: 5000,
                message: 'Password must be 6-24 characters'
              })
            } else if (
              res.data.code === 700 &&
              res.data.msg === 'Different Password'
            ) {
              this.$message.error({
                duration: 5000,
                message: "Confirm password doesn't match password"
              })
            } else if (
              res.data.code === 700 &&
              res.data.msg === 'Email has been created'
            ) {
              this.EmailCodeError = true
              this.$message.error({
                duration: 5000,
                message: 'Account already exist, log in or change email?'
              })
            } else if (res.data.code === 200 && res.data.msg === '注册成功') {
              this.$message({
                duration: 5000,
                message: 'Create Successfully',
                type: 'success'
              })
              this.$router.push('/login?freeEmail=' + this.ruleForm.email)
            }
          })
        }
      })

    },
    sendEmail() {
      const regEmail = /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/
      if (!regEmail.test(this.ruleForm.email)) {
        this.$message({
          message: 'Invalid Email Addresses',
          type: "error"
        })
      } else {
        if (!this.isDisabled) {
          this.isDisabled = true
          //发送邮件
          get(
            '/pdf-tech/auth/getVerifyCode?action=0&type=0&receiver=' +
            this.ruleForm.email
          ).then((res) => {
            if (res.data.code === 200) {
              this.$message({
                message: 'Email sent successfully',
                type: "success"
              })
              let timerId = setInterval(() => {
                this.CountDown--
                this.isDisabled = true
                this.buttonName = this.CountDown + 's'
                if (this.CountDown <= 0) {
                  clearInterval(timerId)
                  this.buttonName = 'send'
                  this.CountDown = 60
                  this.isDisabled = false
                }
              }, 1000)
            } else if (
              res.data.code === 700 &&
              res.data.msg === 'Email has been created'
            ) {
              this.EmailCodeError = true
              this.isDisabled = false
              this.$message.error({
                duration: 5000,
                message: 'Account already exist, log in or change email?'
              })
            } else {
              this.isDisabled = false
            }
          })
        }
      }
    },
    changeEmail() {
      this.EmailCodeError = false
      this.ruleForm = {
        email: '',
        verificationCode: '',
        userName: '',
        password: '',
        passwordConfirm: ''
      }
    },
    clear(val) {
      this.$refs["ruleForm"].clearValidate([val])
      if (val === 'verificationCode') {
        this.verificationCodeError = false
      }
    },
  }
}
</script>

<template>
  <div class="bg w-full min-h-100vh flex justify-center items-center">
    <div v-show="loading" class="
        absolute
        z-100
        flex
        justify-center
        items-center
        h-100vh
        w-full
        bg-[#fff]
        opacity-60
      ">
      <Loading class="z-100" />
    </div>
    <div class="flex w-1184px py-40px">
      <AsideInfo />
      <div class="w-704px bg-[#fff] flex justify-center rounded-r-16px">
        <div class="w-592px h-auto m-auto rounded-8px p-24px bg-[#fff] loginBox">
          <h1 class="text-24px font-bold mt-24px mb-8px">Sign up</h1>
          <div class="text-16px leading-24px text-[#404653] pb-8px border-b-1px border-[#E2E3E5]">
            Create
            <span class="text-[#12B76A]">a team administrator</span>
            account
          </div>
          <el-form :model="ruleForm" ref="ruleForm" :rules="rules">
            <el-form-item prop="email">
              <div class="mt-8px text-[#404653] text-16px leading-24px mb-8px">
                Email
                <span class="text-[#F04438]">*</span>
              </div>
              <div class="flex items-center relative">
                <el-input v-model.trim="ruleForm.email" placeholder="Please enter email address." @focus="clear('email')">
                </el-input>
                <button type="button" :class="isDisabled || ruleForm.email === '' ? 'bgColor' : ''" :disabled=isDisabled
                  @click="sendEmail()"
                  class="absolute top-0.5px right-0px w-80px h-39px bg-[#0773ED] text-center rounded-tr-4px rounded-br-4px font-500 text-[16px] text-[#fff] leading-32px hover:bg-[#3091FF] cursor-pointer">
                  {{ buttonName }}
                </button>
              </div>
            </el-form-item>
            <el-form-item prop="verificationCode">
              <div class="text-[#404653] text-16px leading-24px mb-8px">
                Verification Code
                <span class="text-[#F04438]">*</span>
              </div>
              <div class="flex items-center">
                <el-input v-model="ruleForm.verificationCode" placeholder="Verification Code"
                  @focus="clear('verificationCode')">
                </el-input>
                <Error class="w-14px h-14px block ml-10px absolute right-10px"
                  :class="verificationCodeError ? 'block' : 'hidden'" />
              </div>
            </el-form-item>
            <el-form-item prop="userName">
              <div class="text-[#404653] text-16px leading-24px mb-8px">
                User Name
                <span class="text-[#F04438]">*</span>
              </div>
              <div class="flex items-center">
                <el-input v-model.trim="ruleForm.userName" autocomplete="off" placeholder="User Name"
                  @focus="clear('userName')">
                </el-input>
              </div>
            </el-form-item>
            <el-form-item prop="password">
              <div class="text-[#404653] text-16px leading-24px mb-8px">
                Password
                <span class="text-[#F04438]">*</span>
              </div>
              <div class="flex items-center">
                <el-input v-model.trim="ruleForm.password" placeholder="Password" :type="passwordType ? '' : 'password'"
                  @focus="clear('password')" autocomplete="off">
                </el-input>
                <span v-show="ruleForm.password !== ''" class="show-password"
                  :class="passwordType ? 'eye-open' : 'eye-close'" @click="passwordType = !passwordType">
                  <EyeOpen v-show="passwordType" />
                  <EyeClose v-show="!passwordType" />
                </span>
              </div>
            </el-form-item>
            <el-form-item prop="passwordConfirm" class="mt-4px">
              <div class="text-[#404653] text-16px leading-24px mb-8px">
                Password Comfirm
                <span class="text-[#F04438]">*</span>
              </div>
              <div class="flex items-center">
                <el-input v-model.trim="ruleForm.passwordConfirm" autocomplete="off" placeholder="Confirm Password"
                  :type="passwordConfirmType ? '' : 'password'" @focus="clear('passwordConfirm')">
                </el-input>
                <span v-show="ruleForm.passwordConfirm !== ''" class="show-password"
                  :class="passwordConfirmType ? 'eye-open' : 'eye-close'"
                  @click="passwordConfirmType = !passwordConfirmType">
                  <EyeOpen v-show="passwordConfirmType" />
                  <EyeClose v-show="!passwordConfirmType" />
                </span>
              </div>
            </el-form-item>
          </el-form>
          <div class="flex justify-between">
            <button type="button" @click="createAccount()" class="
              w-[48%]
              h-48px
              bg-[#1460F3]
              text-[#fff]
              font-bold
              rounded-8px
              hover:opacity-80
            ">
              Sign up
            </button>
            <button type="button" @click="$router.push('/login')" class="
              w-[48%]
              h-48px
              text-[#3091FF]
              font-bold
              border-[#3091FF] border-1px
              rounded-8px
              hover:opacity-80
            ">
              Back
            </button>
          </div>
          <div class="flex items-start mt-8px">
            <input type="checkbox" v-model="checked" name="type" />
            <span class="ml-8px text-12px leading-14px" :class="checkBox ? 'text-[#FF5054]' : 'text-[#101828]'">Read and
              Agree to
              <a href="https://www.pdfreaderpro.com/privacy-policy" target="_blank" class="text-[#0773ED]">PRIVACY
                POLICY </a>
              and
              <a href="https://www.pdfreaderpro.com/terms_of_service" target="_blank" class="text-[#0773ED]"> TERMS OF
                USE</a>
            </span>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="" :visible.sync="EmailCodeError" width="376px" top="30vh" center :show-close="false">
      <Email class="inline-block" />
      <div class="mt-16px text-16px leading-24px text-[#232A40]">
        <p>Email has been created</p>
        <p>sign in now or change your email?</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeEmail">Change Email</el-button>
        <el-button type="primary" @click="$router.push(`/login?freeEmail=${ruleForm.email}`)">Sign in</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.bgColor {
  background-color: rgba(20, 96, 243, 0.2);
  border: none;
  cursor: not-allowed;
}

.bg {
  font-family: Ubuntu;
  background: #e7eaee url('@/assets/images/background.png') center center/100% 100% no-repeat;
}

.el-input::v-deep input {
  border: 1px solid #d9d9d9 !important;
  border-radius: 4px !important;
}

.el-form::v-deep .el-form-item {
  margin-bottom: 28px;
}

.show-password {
  display: inline-block;
  position: absolute;
  right: 23px;
  top: 43px;
  width: 14px;
  height: 14px;
  cursor: pointer;
}
</style>

