<script setup lang="ts">
import UserPassword from '@/components/UserPassword.vue';
import UserPreview from '@/components/UserPreview.vue';
import type { UserModel } from '@/model/system.model';
import { accountMethod } from '@/request/api/account.api';
import { useAccountStore } from '@/stores';
import { LogoutOutlined } from '@ant-design/icons-vue';
import { useElementSize } from '@vueuse/core';
import { useRequest } from 'alova/client';
import { notification } from 'ant-design-vue';
import type { MenuProps } from 'ant-design-vue';

import { storeToRefs } from 'pinia';
import { VxeButton, VxeUI } from 'vxe-pc-ui';

defineOptions({ name: 'IndexPage' });

const title = import.meta.env.SIX_TITLE;
const Account = useAccountStore();
const { local, menus, token } = storeToRefs(Account);

const titleRef = ref();
const { width } = useElementSize(titleRef, void 0, { box: 'border-box' });

const router = useRouter();
function findMenuKeyDeep(items: any[] | undefined, targetKey: string): string | undefined {
  if (!items?.length) return void 0;
  for (const item of items) {
    if (item?.key === targetKey) return item.key;
    const hit = findMenuKeyDeep(item?.children as any[], targetKey);
    if (hit) return hit;
  }
  return void 0;
}

const selectedKeys = computed(() => {
  const currentPath = router.currentRoute.value.path;
  if (currentPath && currentPath !== '/') return [currentPath];

  const patientKey = findMenuKeyDeep(menus.value as any[], '/patient/history');
  if (patientKey) return [patientKey];

  return [menus.value?.[0]?.key ?? '/'];
});

const selectMenuItem: MenuProps['onClick'] = (info) => {
  router.push({ path: String(info.key) }).then();
};

function handleLogout() {
  Account.$reset();
  router.replace({ path: '/login' });
}

const { loading: userLoading, send: loadUser } = useRequest(
  () => accountMethod(token.value!),

  { immediate: false }
);

async function openUserPreview() {
  if (userLoading.value) return;
  const { user: model } = await loadUser();
  if (!model) return;
  VxeUI.drawer.open({
    title: `用户信息`,
    maskClosable: true,
    escClosable: true,
    slots: {
      default() {
        return h(UserPreview, { data: model, request: false } as any);
      },
      corner() {
        return h(VxeButton, {
          content: '修改登录密码',
          size: 'mini',
          onClick() {
            updateUserPassword(model);
          },
        });
      },
    },
  });
}

function updateUserPassword(model: UserModel) {
  const { userName } = model;
  VxeUI.modal.open({
    title: `重置 ${userName} 登录密码`,
    escClosable: true,
    destroyOnClose: true,
    id: `user-edit-password-modal`,
    remember: true,
    storage: true,
    mask: false,
    slots: {
      default() {
        return h(UserPassword, {
          update: true,
          data: model,
          onSubmit() {
            notification.success({
              message: `重置用户: ${userName} 的登录密码`,
              description: '操作成功',
            });
            VxeUI.modal.close(`user-edit-password-modal`);
            VxeUI.drawer.close();
            router.push({ path: '/login' });
          },
        } as any);
      },
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col h-vh w-vw">
    <header class="flex-none flex items-center h-60px">
      <div ref="titleRef" class="title flex-none">{{ title }}</div>
      <div class="app-header-menus-wrapper flex-auto">
        <a-menu mode="horizontal" :items="menus" :selectedKeys="selectedKeys" @click="selectMenuItem" />
      </div>
      <div class="mr-5">{{ local?.dept?.deptName }}</div>
      <div class="account">
        <a-avatar size="large" :src="local?.avatar">{{ local?.name?.slice(0, 1) }}</a-avatar>
        <span class="m-x-2 cursor-pointer" @click="openUserPreview()">{{ local?.name }}</span>
        <LogoutOutlined class="cursor-pointer" @click="handleLogout" />
      </div>
    </header>
    <main class="flex-auto flex flex-row">
      <RouterView name="aside" class="flex-none" :style="{ width: `${width}px` }" />
      <RouterView class="flex-auto" />
    </main>
  </div>
</template>
<style scoped lang="scss">
.page-container {
  > header {
    background-image: linear-gradient(to right, #154665, #1a82ca);
    padding-right: 12px;
    color: #fff;

    > .title {
      min-width: 256px;
      color: #fff;
      font-size: 24px;
      font-weight: 700;
      letter-spacing: 0.2em;
      text-align: center;
    }
  }

  > main {
    --page-main-container: calc(100vh - 60px);
  }
}

.app-header-menus-wrapper {
  margin-left: 12px;
  height: 100%;

  :deep(.ant-menu) {
    height: 100%;
    color: #fff;
    background-color: transparent;

    &.ant-menu-horizontal {
      line-height: normal;

      .ant-menu-item,
      .ant-menu-submenu .ant-menu-submenu-title {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100%;
      }

      .ant-menu-submenu {
        padding: 0;

        .ant-menu-submenu-title {
          padding: 0 16px;
        }
      }
    }

    > .ant-menu-item-selected,
    > .ant-menu-submenu-selected {
      background-color: #1a82ca;
      color: #fff;
    }

    .ant-menu-item:hover:not(.ant-menu-item-selected):not(.ant-menu-submenu-selected),
    .ant-menu-submenu-title:hover:not(.ant-menu-item-selected):not(.ant-menu-submenu-selected) {
      color: rgba(255, 255, 255, 0.75);
    }

    .ant-menu-item-selected::after {
      display: none;
    }

    .ant-menu-submenu-selected > .ant-menu-submenu-title {
      color: inherit;
    }
  }
}
</style>
