<script setup lang="ts">
import { useRouter } from 'vue-router'
import ErrorTips from './components/ErrorTips.vue'

const router = useRouter()
const loginForm = ref({
  username: 'ra.admin',
  password: 'abc123456789',
  email: '',
  code: ''
})

const status = ref('login')
watch(status, () => {
  loginForm.value = {
    username: 'ra.admin',
    password: 'abc123456789',
    email: '',
    code: ''
  }
  loginError.value = {
    username: false,
    password: false,
    email: false,
    code: false
  }
  verificationCode.value = ''
  getCode()
})

const loginError: any = ref({
  username: false,
  password: false,
  email: false,
  code: false
})
const verificationCode = ref()
// 获取验证码
const getCode = () => {
  $api.getVerifcationCode().then((res: any) => {
    if (res.code === 200) {
      verificationCode.value = `data:image/png;base64,${res.data.imagePngBase64}`
    } else {
      verificationCode.value = ''
    }
  })
}
getCode()

// 验证当前用户是否存在
const handleCheckUser = () => {
  if (!loginForm.value.username) {
    return
  }
  // 这里是验证用户是否存在的逻辑
  $api.isUserNameExit({ uname: loginForm.value.username }).then((res: any) => {
    if (res.code === 200) {
      if (res.data.msg !== 'no_exist') {
        isUserNameExit.value = true
      } else {
        loginError.value.username = true
        isUserNameExit.value = false
      }
    } else {
      isUserNameExit.value = false
    }
  })
}

// 点击登录按钮
const handleLogin = () => {
  // 这里是登录逻辑
  $api
    .login({
      uname: loginForm.value.username,
      psw: loginForm.value.password,
      verifcation_code: loginForm.value.code
    })
    .then((res: any) => {
      if (res.code === 200) {
        const { data } = res
        if (data.msg === 'today') {
          ElMessageBox.alert('Your password will expire today, please reset', 'Prompt', {
            confirmButtonText: 'OK',
            type: 'warning',
            confirmButtonClass: 'el-button--dark'
          })
        } else if (data.msg === 'last') {
          ElMessageBox.alert(
            `Your password will expire in${data.data}days, please reset`,
            'Prompt',
            {
              confirmButtonText: 'OK',
              type: 'warning',
              confirmButtonClass: 'el-button--dark'
            }
          )
        }
        router.push('/')
      } else if (res.code === 400) {
        // 验证码错误
        if (res.data.msg === 'password_error') {
          loginError.value.password = true
        } else if (res.data.msg === 'verifcation_error') {
          loginError.value.code = true
        } else if (res.data.msg === 'error_times') {
          errorTipsRef.value.openDialog()
        }
      }
    })
    .finally(() => {
      getCode()
    })
}

const isUserNameExit = ref(false)

const handleForgot = () => {
  status.value = 'reset'
  isUserNameExit.value = false
  handleDeleteEmailTips()
}
const handleSendPassword = () => {
  // 这里是发送密码逻辑
  $api
    .forgotPassword({
      login: loginForm.value.username,
      email: loginForm.value.email
    })
    .then((res: any) => {
      if (res.code === 200) {
        isEmailTips.value = true
      }
    })
}

const isEmailTips = ref(false)
const handleDeleteEmailTips = (type?: any) => {
  isEmailTips.value = false
  if (type) {
    loginError.value[type] = false
  }
}

const errorTipsRef = ref()
</script>

<template>
  <div class="login">
    <el-card class="login-card" v-if="status === 'login'">
      <div class="title">
        <span class="welcome">Welcome to KLN Portal</span>
        <span class="tips">Login to your account</span>
      </div>
      <div class="send-email-tips" :style="{ display: isEmailTips ? 'block' : 'none' }">
        <span class="font_family icon-icon_confirm_b success-icon"></span>
        New Password sent to registered email.
        <span
          @click="handleDeleteEmailTips"
          class="font_family icon-icon_reject_b delete-icon"
        ></span>
      </div>
      <div class="login-form">
        <div class="label">
          <span>User Name</span>
        </div>
        <el-input
          ref="userNameRef"
          :class="{ 'is-error': loginError.username }"
          v-model="loginForm.username"
          class="user-name"
          placeholder="Please input user name"
          @focus="handleDeleteEmailTips('username')"
          @change="handleCheckUser"
        >
          <template #prefix>
            <span class="font_family icon-icon_username_b"></span>
          </template>
          <template #suffix>
            <span v-if="isUserNameExit" class="font_family icon-icon_confirm_b confirm-icon"></span>
          </template>
        </el-input>
        <div class="error" v-if="loginError.username">This account does not exist.</div>
        <div class="label">
          <span>Password</span>
          <span class="forgot-password" @click="handleForgot">Forgot Password?</span>
        </div>
        <el-input
          ref="passWordRef"
          :class="{ 'is-error': loginError.password }"
          v-model="loginForm.password"
          type="password"
          placeholder="Please input password"
          show-password
          @focus="handleDeleteEmailTips('password')"
          ><template #prefix>
            <span class="font_family icon-icon_password_b"></span>
          </template>
        </el-input>
        <div class="error" v-if="loginError.password">Incorrect password. Please try again.</div>
        <el-input
          ref="codeRef"
          :class="{ 'is-error': loginError.code }"
          class="verification-code"
          v-model="loginForm.code"
          placeholder="Verification Code"
          @focus="handleDeleteEmailTips('code')"
        >
          <template #append>
            <img class="verification-code-img" :src="verificationCode" alt="" />
          </template>
        </el-input>
        <div class="error" v-if="loginError.code">Incorrect verification code.</div>
        <el-button @click="handleLogin" class="el-button--dark login-btn">Login</el-button>
      </div>
      <template #footer>
        <div class="license">
          <span>© 2024 KTreker from <span class="company">Kerry Logistics</span></span>
          <span>Version 0.67</span>
        </div>
      </template>
    </el-card>
    <el-card class="login-card" v-else>
      <div class="title">
        <span class="welcome">Password Retrieval</span>
        <span class="tips">We'll send you new password in email</span>
      </div>
      <div class="login-form">
        <div class="label">
          <span>User Name</span>
        </div>
        <el-input
          ref="userNameRef"
          :class="{ 'is-error': loginError.username }"
          v-model="loginForm.username"
          class="user-name"
          placeholder="Please input user name"
          @focus="handleDeleteEmailTips('username')"
        >
          <template #prefix>
            <span class="font_family icon-icon_username_b"></span>
          </template>
          <template #suffix>
            <span v-if="isUserNameExit" class="font_family icon-icon_confirm_b confirm-icon"></span>
          </template>
        </el-input>
        <div class="error" v-if="loginError.username">
          This is the prompt information given by the verification
        </div>
        <div class="label">
          <span>Email Address</span>
        </div>
        <el-input
          ref="passWordRef"
          :class="{ 'is-error': loginError.email }"
          v-model="loginForm.email"
          placeholder="Please input your email address"
          @focus="handleDeleteEmailTips('email')"
          ><template #prefix>
            <span class="font_family icon-icon_email_b"></span>
          </template>
        </el-input>
        <div class="error" v-if="loginError.password">
          This is the prompt information given by the verification
        </div>
        <el-input
          ref="codeRef"
          :class="{ 'is-error': loginError.code }"
          class="verification-code"
          v-model="loginForm.code"
          placeholder="Verification Code"
          @focus="handleDeleteEmailTips('code')"
          ><template #append>
            <img class="verification-code-img" :src="verificationCode" alt="" /> </template
        ></el-input>
        <div class="error" v-if="loginError.code">
          This is the prompt information given by the verification
        </div>
        <el-button @click="handleSendPassword" class="el-button--dark login-btn"
          >Send Password</el-button
        >
        <div @click="status = 'login'" class="back-text">
          <span class="font_family icon-icon_back_b"></span>
          <span class="text"> Back to login</span>
        </div>
      </div>
      <template #footer>
        <div class="license">
          <span>© 2024 KTreker from <span class="company">Kerry Logistics</span></span>
          <span>Version 0.67</span>
        </div>
      </template>
    </el-card>
    <ErrorTips ref="errorTipsRef" @forget-password="status = 'reset'"></ErrorTips>
  </div>
</template>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: url(../src/image/bg-image.png) no-repeat center center;
  background-size: cover;
}

.login-card {
  width: 400px;

  .title {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 24px;

    .welcome {
      margin-bottom: 16px;
      font-size: 24px;
      font-weight: 700;
    }
  }

  .send-email-tips {
    display: flex;
    align-items: center;
    height: 40px;
    padding: 12px;
    padding-left: 14px;
    background-color: #e5f6f1;
    border-radius: 6px;
    color: var(--color-success);

    .success-icon {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      height: 16px;
      width: 16px;
      margin-right: 4px;
      font-size: 14px;
      color: #fff;
      background-color: var(--color-success);
      border-radius: 50%;
    }

    .delete-icon {
      margin-left: 6px;
      color: var(--color-success);
      cursor: pointer;
    }
  }

  :deep(.el-card__body) {
    padding: 40px;
    padding-bottom: 16px;
  }

  .login-btn {
    width: 100%;
    height: 40px;
    margin-top: 16px;
  }
}

.login-form {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .el-input {
    height: 40px;
    .confirm-icon {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      height: 16px;
      width: 16px;
      margin-right: 4px;
      font-size: 14px;
      color: #fff;
      background-color: var(--color-success);
      border-radius: 50%;
    }

    &.is-error {
      :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 1px var(--color-danger) inset;
      }
    }

    :deep(.el-input__prefix) {
      margin: 0 4px;
      background-color: transparent;
    }
  }
  .verification-code {
    margin-top: 16px;
    .verification-code-img {
      width: 130px;
      height: 38px;
      object-fit: cover;
    }
    :deep(.el-input-group__append) {
      padding: 0;
      padding-right: 1px;
    }
  }
  .el-input.user-name {
    :deep(.el-input__wrapper) {
      padding-right: 6px;
    }
  }

  .label {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-top: 16px;
    font-size: 12px;
    line-height: 18px;

    span {
      color: var(--color-neutral-2);
    }

    .forgot-password {
      color: var(--color-theme);
      cursor: pointer;
    }
  }

  .error {
    font-size: 12px;
    color: var(--color-danger);
    line-height: 14px;
  }

  .back-text {
    width: 100%;
    height: 20px;
    margin-top: 24px;
    margin-bottom: 8px;
    text-align: center;
    cursor: pointer;

    span {
      color: var(--color-theme);
    }

    .text {
      display: inline-block;
      transform: translateY(-2px);
      font-size: 12px;
    }
  }
}

.license {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;

  .company {
    color: var(--color-theme);
  }

  span {
    color: var(--color-neutral-2);
  }
}
</style>
