<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-position="top" hide-required-asterisk="false">
    <el-form-item label="账号" prop="username">
      <el-input class="no-border" v-model="loginForm.username" placeholder="请输入账号" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input class="no-border"  v-model="loginForm.password" type="password" placeholder="请输入密码" show-password autocomplete="new-password"/>
    </el-form-item>
    <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
  </el-form>
  <div class="login-btn">
    <el-button style="width: 100%;" size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, onBeforeUnmount, computed} from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
// import { getTimeState } from "@/utils";
import {Login, Platform} from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "md5";
import {getPlatformList} from "@/api/modules/allData";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  rememberMe: false,
  username: "",
  password: ""
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;

    if (loginForm.rememberMe) {
      localStorage.setItem('username', String(loginForm.username));
      localStorage.setItem('password', String(loginForm.password));
      localStorage.setItem('rememberMe', String(loginForm.rememberMe));
    } else {
      // 否则移除
      localStorage.removeItem('username');
      localStorage.removeItem('password');
      localStorage.removeItem('rememberMe');
    }

    localStorage.setItem('username2', String(loginForm.username));
    localStorage.setItem('password2', String(loginForm.password));

    try {
      // 1.执行登录接口
      const { data } = await loginApi({ ...loginForm, password: loginForm.password });
      if(!data.user){
        ElNotification({
          title: "提示",
          message: "账号密码错误!",
          type: "error",
          duration: 5000
        });
        return;
      }

      userStore.setToken(Date.now().toString());
      userStore.setUserInfo(data.user)
      userStore.setAsInfo(data.asInfo)
      getStationsList();

      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: "地面气象观测系统",
        message: "欢迎登录",
        type: "success",
        duration: 5000
      });
    } finally {
      loading.value = false;
    }
  });
};

// 站号列表更新
const getStationsList = async () => {
  const userStore = useUserStore();
  const user = computed(() => userStore.userInfo);
  const Info = computed(() => userStore.asInfo);

  // 查询自动站列表
  const queryas = ref<Platform>({ pageSize: 20000, pageNum: 1 });
  const { data } = await getPlatformList(queryas.value);
  const array2 = data.list;

  if (user.value.role_id === '管理员') {
    userStore.setStations(array2);
  } else {
    const codesToMatch = Info.value.map(item => item.as_code);
    const filteredArray = array2.filter(item => codesToMatch.includes(item.as_code));
    userStore.setStations(filteredArray);
  }
};
const getLoginData = () => {
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.username = username === null ? String(loginForm.username) : username
  loginForm.password = password === null ? String(loginForm.password) : String(password)
  loginForm.rememberMe = rememberMe === null ? false : Boolean(rememberMe)
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
  getLoginData()
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});

</script>

<style scoped lang="scss">
@import "../index.scss";
::v-deep .no-border .el-input__wrapper  {
  box-shadow: 0 0 0 0px!important;
  background-color: #F2F2F2;
}

</style>
