<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
// import { useRoute, useRouteQuery, useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import { Lock, Message, User } from '@element-plus/icons-vue'
import Cookies from 'js-cookie'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { countStore } from '@/store'

const router = useRouter()
interface LoginForm {
  username: string
  password: string
  rememberMe: boolean
  code: string
  uuid: string
}
interface CodeImgResponse {
  captchaEnabled?: boolean
  img: string
  uuid: string
}
interface LoginRes {
  code: Number
  msg: string
  token: string
}
interface InfoRes {
  msg: string
  code: Number
  user: {
    userId: Number
    nickName: string
  }
}

const loginRef = ref<FormInstance>()
const loginForm = ref<LoginForm>({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
})

const loginRules = reactive<FormRules<LoginForm>>({
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  // code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
})

const codeUrl = ref<string>('')
const loading = ref<boolean>(false)
const captchaEnabled = ref<boolean>(true)
// const register = ref<boolean>(false);
// const redirect = ref<string | undefined>();

// 监听路由变化
// watch(() => route.query, (newQuery) => {
//   redirect.value = newQuery.redirect as string | undefined;
// }, { immediate: true });

// 登录处理
const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl)
    return
  formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      handleRememberMe()
      executeLogin()
    }
    else {
      getCode()
      // console.log("error submit!", fields);
    }
  })
}

// 记住密码处理
const handleRememberMe = (): void => {
  if (loginForm.value.rememberMe) {
    Cookies.set('username', loginForm.value.username, { expires: 30 })
    Cookies.set('password', loginForm.value.password, { expires: 30 })
    Cookies.set('rememberMe', String(loginForm.value.rememberMe), {
      expires: 30,
    })
  }
  else {
    Cookies.remove('username')
    Cookies.remove('password')
    Cookies.remove('rememberMe')
  }
}
const info = countStore()
// 执行登录操作
const executeLogin = async () => {
  try {
    const response = await axios.post<LoginRes>(
      `${import.meta.env.VITE_APP_API_BASE_URL}/login`,
      {
        username: loginForm.value.username,
        password: loginForm.value.password,
        code: loginForm.value.code,
        uuid: loginForm.value.uuid,
      },
    )
    if (response.data.code == 200) {
      Cookies.set('Admin-Token', response.data.token)
      try {
        const res = await axios.get<InfoRes>(
          `${import.meta.env.VITE_APP_API_BASE_URL}/getInfo`,
          {
            headers: {
              Authorization: `Bearer ${Cookies.get('Admin-Token')}`,
            },
          },
        )
        if (res.data.code == 200) {
          Cookies.set('nickName', res.data.user.nickName)
          info
            .setNameAId(res.data.user.userId, res.data.user.nickName)
            .then(() => {
              router.replace('/chat').catch(() => {})
            })
        }
      }
      catch (error) {
        console.error('Error loading user:', error)
      }
      finally {
        loading.value = false
      }
    }
    else {
      ElMessage({
        showClose: true,
        message: response.data.msg,
        type: 'error',
      })
      getCode()
    }
  }
  catch (error) {
    console.error('Error loading user:', error)
  }
  finally {
    loading.value = false
  }
}
const getCode = async () => {
  try {
    const response = await axios.get<CodeImgResponse>(
      `${import.meta.env.VITE_APP_API_BASE_URL}/captchaImage`,
    )
    captchaEnabled.value = response.data.captchaEnabled ?? true
    if (captchaEnabled.value) {
      codeUrl.value = `data:image/gif;base64,${response.data.img}`
      loginForm.value.uuid = response.data.uuid
    }
  }
  catch (error) {
    console.error('Error loading user:', error)
  }
  finally {
    loading.value = false
  }
}
// 读取Cookie
const getCookie = (): void => {
  loginForm.value = {
    username: Cookies.get('username') || loginForm.value.username,
    password: Cookies.get('password')
      ? Cookies.get('password')!
      : loginForm.value.password,
    rememberMe: Cookies.get('rememberMe')
      ? Cookies.get('rememberMe') === 'true'
      : false,
    code: '',
    uuid: '',
  }
}

// 生命周期钩子
onMounted(() => {
  getCode()
  getCookie()
})
</script>

<template>
  <div class="login">
    <el-form
      ref="loginRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">
        极创科技DeepSeek
      </h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="账号"
        >
          <template #prefix>
            <el-icon><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleLogin"
        >
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
<!--      <el-form-item v-if="captchaEnabled" prop="code">-->
<!--        <el-input-->
<!--          v-model="loginForm.code"-->
<!--          size="large"-->
<!--          auto-complete="off"-->
<!--          placeholder="验证码"-->
<!--          style="width: 63%"-->
<!--          @keyup.enter="handleLogin"-->
<!--        >-->
<!--          <template #prefix>-->
<!--            <el-icon><Message /></el-icon>-->
<!--          </template>-->
<!--        </el-input>-->
<!--        <div class="login-code">-->
<!--          <img :src="codeUrl" class="login-code-img" @click="getCode">-->
<!--        </div>-->
<!--      </el-form-item>-->
      <el-checkbox
        v-model="loginForm.rememberMe"
        style="margin: 0px 0px 25px 0px"
      >
        记住密码
      </el-checkbox>
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width: 100%;background: linear-gradient(90deg, #4C7FFF, #1329FF)!important"
          @click.prevent="handleLogin(loginRef)"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <!-- <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../../../assets/背景图.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-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;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
