<template>
  <div :class="prefixCls" class="flx-center w-screen h-screen relative">
    <!-- <div :class="`${prefixCls}__unlock`" class="flx-center pt-32 flx-col" v-show="showDate" @click="handleShowForm(false)">
      <i class="iconfont iconUnlock"></i>
      <span>{{ $t("sys.lock.unlock") }}</span>
    </div>

    <div class="flx-center w-screen h-screen" @click="handleShowForm(false)">
      <div :class="`${prefixCls}__hour`" class="relative">
        <span>{{ hour }}</span>
        <span class="meridiem absolute left-32 top-32 text-h4-m" v-show="showDate">
          {{ meridiem }}
        </span>
      </div>
      <div :class="`${prefixCls}__minute`">
        <span> {{ minute }}</span>
      </div>
    </div> -->
    <!-- <transition name="fade-slide"> -->
    <div :class="`${prefixCls}-entry`">
      <div :class="`${prefixCls}-entry-content enter-x`">
        <template v-if="!ifChangAccount">
          <div :class="`${prefixCls}-entry__header flx-col enter-x `">
            <div :class="`${prefixCls}-entry__header-icon flx-center`">
              <i class="iconfont iconuser-circle" :class="`${prefixCls}-entry__header-iconfont`"></i>
            </div>
            <div :class="`${prefixCls}-entry__header-name mb-12 flx-col`">
              <span class="relative">
                {{ userinfo.username }}
              </span>
              <!-- <span class="text-disable text-f-c sle flx-1"> 当前账套: {{ userStore.currentAccount }} </span> -->
            </div>
          </div>
          <el-form
            ref="lockFormRef"
            :model="lockForm"
            status-icon
            :rules="rules"
            class="demo-ruleForm"
            :size="assemblySize"
            @submit.prevent
          >
            <el-form-item prop="password">
              <el-input
                ref="passwordRef"
                v-model="lockForm.psw"
                type="password"
                show-password
                class="enter-x"
                :placeholder="$t('sys.lock.placeholder')"
                @keydown.enter="unLock(lockFormRef)"
              >
                <template #prefix>
                  <i class="iconfont iconPassword"></i>
                </template>
              </el-input>
            </el-form-item>
            <div :class="`flx-col enter-x`">
              <el-button class="flx-1" type="primary" size="default" @click.stop="unLock(lockFormRef)" :loading="loading">
                {{ $t("sys.login.loginButton") }}
              </el-button>
              <div class="flx-center mt-12">
                <el-button type="primary" plain size="default" class="flx-1 enter-x" @click="ifChangAccount = true">
                  {{ $t("sys.lock.swtichAccount") }}
                </el-button>
                <el-button type="default" size="default" class="flx-1 enter-x" :disabled="loading" @click.stop="goLogin">
                  {{ $t("sys.lock.backToLogin") }}
                </el-button>
              </div>
            </div>
          </el-form>
        </template>
        <template v-else>
          <div :class="`${prefixCls}-entry__header flx-col flx-center enter-x`">
            <div :class="`${prefixCls}-entry__header-icon flx-center`" @click="ifChangAccount = false">
              <img src="@/assets/images/logo.png" alt="" style="width: 70px; height: 70px" />
            </div>
            <div :class="`${prefixCls}-entry__header-name  mb-12`">
              {{ AppName }}
            </div>
          </div>
          <LoginForm @login-success="autoLoginSuccess" />
        </template>
      </div>
    </div>
    <!-- </transition> -->

    <div class="absolute bottom-24 w-full color-gray-9 text-h2-m text-center enter-y">
      <div class="text-2xl" :class="{ 'color-gray-12': !showDate }">{{ year }}/{{ month }}/{{ day }} {{ week }}</div>
    </div>
  </div>
</template>

<script lang="ts" setup name="LoginPage">
import { ref, reactive, computed, nextTick, onMounted } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { useLockStore } from "@/stores/modules/lock";
import { useNow } from "./useNow";
import { useDesign } from "@/hooks/useDesign";
// import headerImg from "/@/assets/images/header.jpg";
// import md5 from "js-md5";
import type { FormInstance, FormRules } from "element-plus";
import { ElNotification, ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { getTimeState } from "@/utils";
import LoginForm from "@/views/login/components/LoginForm.vue";
import { Switch } from "@element-plus/icons-vue";
import { useGlobalStore } from "@/stores/modules/global";

const AppName = import.meta.env.VITE_GLOB_APP_COMPANY + import.meta.env.VITE_GLOB_APP_TITLE;
const loading = ref(false);
const errMsg = ref(false);
const showDate = ref(true);
const { t } = useI18n();
const ifChangAccount = ref(false);

const { prefixCls } = useDesign("login-page");
const lockStore = useLockStore();
const userStore = useUserStore();
const { assemblySize } = useGlobalStore();
const emit = defineEmits(["loginSuccess"]);

const { hour, month, minute, meridiem, year, day, week } = useNow(true);

const userinfo = computed(() => {
  return userStore.userInfo || {};
});

/**
 * @description 验证规则
 */
const lockForm = reactive({
  psw: ""
});
const lockFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  // password: [{ required: true, message: t("sys.login.passwordPlaceholder"), trigger: "blur" }]
});

/**
 * @description: 解锁，进入系统
 */
function unLock(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      await lockStore.unLock(lockForm.psw, false).then(
        () => {
          ElNotification({
            title: getTimeState(t),
            message: t("sys.login.welcome") + " " + AppName,
            type: "success",
            duration: 3000
          });

          lockStore.setLockInfo({
            isLogin: false
          });

          emit("loginSuccess");
        },
        () => {
          ElMessage.error(t("sys.errorLog.login"));
        }
      );
    } finally {
      loading.value = false;
    }
  });
}

async function goLogin() {
  // userStore.logout(true);
  await userStore.logout(true, () => {
    lockStore.resetLockInfo();
  });
}

const passwordRef = ref<any>();
function handleShowForm(show = false) {
  if (!show) {
    nextTick(() => {
      passwordRef.value.focus();
      passwordRef.value.select();
    });
  }
  showDate.value = show;
}

const autoLoginSuccess = () => {
  lockStore.setLockInfo({
    isLogin: false
  });
};

onMounted(() => {
  passwordRef.value.focus();
});
</script>
<style lang="scss" scoped>
@import "./LoginPage.scss";
</style>
