<template>
  <div
    class="absolute top-0 right-0 bottom-0 left-0 bg-[#f5f7f9] flex justify-center items-center overflow-auto"
  >
    <n-card class="w-[500px] shadow rounded-lg" :bordered="false">
      <template #header>
        <h2 class="text-center">冷链验证报告生成系统</h2>
      </template>
      <n-form
        ref="formRef"
        :rules="rules"
        :model="formValue"
        size="large"
        label-placement="left"
      >
        <n-form-item path="username">
          <n-input v-model:value="formValue.username" :maxlength="8" clearable>
            <template #prefix>
              <n-icon :component="UserOutlined" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item path="password">
          <n-input
            v-model:value="formValue.password"
            type="password"
            show-password-on="click"
            :maxlength="8"
            clearable
          >
            <template #prefix>
              <n-icon :component="LockOutlined" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item path="role">
          <n-select
            v-model:value="formValue.role"
            :options="generalOptions"
            clearable
          />
        </n-form-item>
        <n-form-item>
          <n-button type="primary" block @click="handleSubmit">登录</n-button>
        </n-form-item>
      </n-form>
    </n-card>
  </div>
</template>

<script setup>
import { UserOutlined, LockOutlined } from "@vicons/antd";
import { login } from "@/api";
import md5 from "md5";
import { setToken } from "@/utils/storage/sessionToken";

const loadingBar = useLoadingBar();

const formRef = ref(null);

const router = useRouter();

const message = useMessage();

// 验证表项的规则
const rules = {
  username: { required: true, message: "不能为空", trigger: "blur" },
  password: { required: true, message: "不能为空", trigger: "blur" },
  role: { required: true, message: "不能为空", trigger: ["blur", "change"] },
};

// 登录表单
const formValue = reactive({
  username: "",
  password: "",
  role: "",
});

// 角色列表
const generalOptions = ["管理员", "用户"].map((v) => ({
  label: v,
  value: v,
}));

const handleSubmit = async () => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      try {
        loadingBar.start();
        const { data: res } = await login(
          {
            bzd_username: formValue.username,
            bzd_password: md5(formValue.password),
          },
          formValue.role
        );
        if (res.Code === 200) {
          router.replace("/");
          message.success(res.Msg);
          setToken(res.Data);
        }
      } finally {
        loadingBar.finish();
      }
    } else {
      message.error("验证失败，请填写完整信息");
    }
  });
};
</script>

<style lang="scss" scoped></style>
