<template>
  <div class="contain">
    <el-card class="box-card" shadow="always">
      <template #header>
        <div class="flex-c">欢迎登录</div>
      </template>
      <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm">
        <el-form-item label="账号" prop="account">
          <el-input :prefix-icon="User" v-model="ruleForm.account" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input :prefix-icon="Lock" v-model="ruleForm.password" />
        </el-form-item>
      </el-form>
      <div class="flex-s">
        <div>
          <el-checkbox v-model="state.isRemember">记住密码</el-checkbox>
        </div>
        <div style="color: #606266; font-size: 14px">忘记密码？</div>
      </div>
      <div class="flex-c mt30">
        <el-button
          type="primary"
          @click="submitForm(ruleFormRef)"
          :loading="state.loading"
          style="width: 100%"
          >登录</el-button
        >
      </div>
    </el-card>
  </div>
</template>
<script lang="ts" setup>
import { reactive, getCurrentInstance, ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

import { userLogin } from "@/utils/api.ts";

const { appContext } = getCurrentInstance();

const router = useRouter();
const proxy = appContext.config.globalProperties;
const ruleFormRef = ref();
const ruleForm = reactive({
  account: "",
  password: "",
});
const state = reactive({
  loading: false,
  isRemember: false,
});
const rules = reactive<FormRules<ruleForm>>({
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const {
        code,
        body: { token },
      } = await userLogin(ruleForm);
      if (code == 200) {
        localStorage.setItem("token", token);
      }
      ElMessage.success("登录成功")
      router.push("/");
    } else {
      ElMessage.error("请完善信息")
    }
  });
};
</script>
<style>
.contain {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box-card {
  width: 400px;
}
</style>
