<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
// import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg_cz, leftLogo_cz } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
// import update from "./components/update.vue";
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  toRaw,
  nextTick
} from "vue";
// import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";

// import dayIcon from "@/assets/svg/day.svg?component";
// import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/icon-park-outline/lock";
import User from "@iconify-icons/icon-park-outline/user";
import PreviewClose from "@iconify-icons/icon-park-outline/preview-close";
import PreviewOpen from "@iconify-icons/icon-park-outline/preview-open";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
// const checked = ref(false);
// const currentPage = computed(() => {
//   return useUserStoreHook().currentPage;
// });

const { initStorage } = useLayout();
initStorage();

// const { dataTheme, dataThemeChange } = useDataThemeChange();
// dataThemeChange();
// const { title } = useNav();

const ruleForm = reactive({
  username: "admin",
  password: "admin123"
});

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      useUserStoreHook()
        .loginByUsername({
          username: ruleForm.username,
          password: ruleForm.password
        })
        .then(res => {
          if (res.success) {
            // 获取后端路由
            initRouter().then(() => {
              router.push(getTopMenu(true).path);
              message("登录成功", { type: "success" });
            });
          } else {
            message("登录失败", { type: "error" });
          }
        })
        .catch(() => {
          loading.value = false;
          message("登录失败", { type: "error" });
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};
const passwordType = ref("password");
const refInput = ref();
/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

function showPass() {
  if (passwordType.value === "password") {
    passwordType.value = "text";
  } else {
    passwordType.value = "password";
  }
  nextTick(() => {
    refInput.value.focus();
  });
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <div class="image_bg">
      <!-- <img :src="bg" class="wave" /> -->
      <img :src="bg_cz" class="wave" />
    </div>
    <!-- <div class="logo-small">
      <component :is="toRaw(sst)" />
    </div> -->
    <!-- <img :src="sst" class="logo-small" /> -->
    <!-- <div class="flex-c absolute right-5 top-3"> -->
    <!-- 主题 -->
    <!-- <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      /> -->
    <!-- </div> -->
    <div class="login-container">
      <div class="img">
        <!-- <div class="platform-logo">
          <img :src="sst" />
        </div> -->
        <!-- <component :is="toRaw(leftLogo)" /> -->
        <component :is="toRaw(leftLogo_cz)" />
        <!-- <component :is="toRaw(illustration)" /> -->
      </div>
      <div class="login-box">
        <div class="login-form">
          <!-- <avatar class="avatar" /> -->
          <Motion>
            <h2
              class="outline-none"
              style="font-size: 32px; font-weight: 400; text-align: center"
            >
              {{ "欢迎登录执法视频智能解析系统" }}
            </h2>
          </Motion>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  placeholder="账号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  ref="refInput"
                  :type="passwordType"
                  v-model="ruleForm.password"
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                >
                  <template #suffix>
                    <el-icon
                      class="el-icon el-input__icon el-input__password"
                      @click="showPass"
                    >
                      <IconifyIconOffline
                        :icon="
                          passwordType == 'password'
                            ? PreviewClose
                            : PreviewOpen
                        "
                      />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </Motion>
            <Motion :delay="250">
              <!-- <div class="w-full h-[20px] flex justify-between items-center">
                <el-checkbox v-model="checked">
                  {{ "记住密码" }}
                </el-checkbox>
                <el-button link class="btn-color" type="primary">
                  {{ "忘记密码？" }}
                </el-button>
              </div> -->
              <!-- <el-button
                class="w-full mt-7 login-btn"
                size="default"
                type="primary"
                color="#0457A9"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button> -->
              <el-button
                class="w-full mt-7 login-btn"
                size="default"
                type="primary"
                color="#004FB2"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>
          </el-form>
          <!-- 忘记密码 -->
          <!-- <update v-if="currentPage === 4" /> -->
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.login-btn {
  height: 40px;
  font-weight: 600;
  // font-family: "PingFang SC";
  color: #fff;
  cursor: pointer;
}

.btn-color {
  color: #0457a9;
}

.btn-color:hover {
  color: #0457a9;
  opacity: 0.5;
}

.el-input__icon {
  cursor: pointer;
}
// :deep(.el-button) {
//   font-weight: bold;
//   color: #fff;
// }
</style>
