<template>
  <div class="login-dialog">
    <div class="login_el_dialog__body">
      <h3 class="flex items-center">
        <img src="@/assets/logo/logo.svg" alt="">
      </h3>
      <el-form
        class="login-form"
        :rules="rule"
        :model="loginForm"
        ref="loginFormRef"
        @keyup.enter="handelLogin"
      >
        <div class="mb-20">
          <el-form-item prop="name">
            <el-input
              size="large"
              class="input-item"
              v-model="loginForm.username"
              placeholder="请输入账号"
            >
            </el-input>
          </el-form-item>
        </div>
        <div style="margin-bottom: 58px">
          <el-form-item prop="password">
            <el-input
              type="password"
              size="large"
              class="input-item"
              v-model="loginForm.password"
              placeholder="请输入密码"
              show-password
              @click.stop
            >
            </el-input>
          </el-form-item>
        </div>
        <el-form-item class="remember-item">
          <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
        </el-form-item>
        <el-button
          size="large"
          type="primary"
          class="w-full btn_login"
          @click="handelLogin"
          :loading="loading"
          >登录</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import useStore from '@/stores'
import { aesEncrypt, aesDecrypt } from '@/utils/crypto'
import { MsgError } from '@/utils/message'

const { dada } = useStore()
const router = useRouter()

defineOptions({ name: 'IndexLogin' })

const loading = ref<boolean>(false)
const loginFormRef = ref<FormInstance>()
const loginForm = ref<any>({
  username: '',
  password: ''
})

const rememberMe = ref(false)
const isCodeDisabled = ref(false)

const rule: any = ref<FormRules<any>>({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const handelLogin = () => {
  passwordLogin()
}

/**
 * 登录方法
 */
const login = async (data: any) => {
  loading.value = true
  const password = aesEncrypt(data.password)
  // 密码登录
  const param: any = {
    grantType: 'CAPTCHA',
    username: data.username,
    password,
    code: '123456', // 验证码固定写死6位
    loginType: 'APP',
    key: '25673794041173B71A7A902D1741742602540'
  }
  dada
    .login(param)
    .then((res: any) => {
      // 账号密码登录-记住密码
      if (rememberMe.value) {
        localStorage.setItem(
          'loginCredentials',
          JSON.stringify({
            username: loginForm.value.username,
            encryptedPwd: password
          })
        )
      } else {
        localStorage.removeItem('loginCredentials')
      }
      if (res) {
        router.push({ name: 'home' })
      }
    })
    .catch((err) => {
      MsgError(err.message || err)
    })
    .finally(() => (loading.value = false))
}

/**
 * 通过账号密码登录
 */
const passwordLogin = async () => {
  loginFormRef.value?.validate().then(async () => {
    loading.value = true
    // 密码登录
    let data: any = {
      username: loginForm.value.username,
      password: loginForm.value.password
    }
    await login(data)
  })
}

const getLocaUserInfo = () => {
  const saved = localStorage.getItem('loginCredentials')
  if (saved) {
    const { username, encryptedPwd } = JSON.parse(saved)
    loginForm.value = {
      username,
      password: aesDecrypt(encryptedPwd)
    }
    rememberMe.value = true
  }
}

onMounted(() => {
  isCodeDisabled.value = true

  getLocaUserInfo()

  nextTick(() => {
    const dom = document.querySelector('.el-input__suffix')
    if (dom) {
      dom.addEventListener('click', (event) => {
        event.preventDefault()
        const input = dom.closest('.el-input')?.querySelector('input')
        if (input) {
          input.setSelectionRange(0, 0)
        }
        return false
      })
    }
  })
})
</script>

<style lang="scss" scope>
.login-dialog {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-color: #fff;

  padding: 0;
  border-radius: 12px;
  .login_el_dialog__body {
    padding: 40px 40px 50px 40px;
    width: 440px;
    position: relative;
    h3 {
      line-height: 36px;
      height: 36px;
      font-size: 24px;
      color: #333;
      margin-bottom: 32px;
    }
    .btn_login {
      height: 40px;
      border-radius: 6px;
    }
  }
}

.login-form {
  .el-input__append {
    padding: 0;
    .el-button {
      width: 100px;
    }
  }
}

/* 记住密码*/
.remember-item {
  bottom: 94px;
  margin-bottom: 0;
  position: absolute;
}
</style>
