<script setup lang="ts">
import { useNav } from "@/layout/hooks/useNav";
import LaySearch from "../lay-search/index.vue";
import LayNotice from "../lay-notice/index.vue";
import LayNavMix from "../lay-sidebar/NavMix.vue";
import LaySidebarFullScreen from "../lay-sidebar/components/SidebarFullScreen.vue";
import LaySidebarBreadCrumb from "../lay-sidebar/components/SidebarBreadCrumb.vue";
import LaySidebarTopCollapse from "../lay-sidebar/components/SidebarTopCollapse.vue";
import LogoutCircleRLine from "@iconify-icons/ri/logout-circle-r-line";
import Setting from "@iconify-icons/ri/settings-3-line";
import { h, ref } from "vue";
import { addDialog } from "@/components/ReDialog/index";
import {
  changePassword,
  editUser as editUserApi,
  getUser,
  userList
} from "@/api/user";
import { storageLocal } from "@pureadmin/utils";
import { setUser, userKey } from "@/utils/auth";
import forms, { type FormProps } from "./component/user.vue";
import changePwdForms, {
  type ChangePwdFormProps
} from "./component/change-password.vue";
import { useRouter } from "vue-router";
import useGetGlobalProperties from "@/hooks/useGetGlobalProperties";
import { Refresh } from "@element-plus/icons-vue";
import { getServerRestartRule, restartServer } from "@/api/server";
import { message } from "@/utils/message";

const {
  layout,
  device,
  logout,
  onPanel,
  pureApp,
  username,
  userAvatar,
  avatarsStyle,
  toggleSideBar
} = useNav();

const { $bus } = useGetGlobalProperties();

const router = useRouter();
const userEditFormRef = ref();
const changePwdFormRef = ref();
// eslint-disable-next-line vue/valid-define-emits
const emit = defineEmits();

// 打开用户信息编辑窗口
const openUserInfoDialog = () => {
  const loginUser = storageLocal().getItem(userKey);
  addDialog({
    width: "20%",
    title: loginUser.name,
    contentRenderer: () => h(forms, { ref: userEditFormRef }),
    props: {
      formInline: {
        id: loginUser.id,
        avatar: loginUser.avatar,
        name: loginUser.name,
        account: loginUser.account,
        email: loginUser.email,
        isAdmin: loginUser.isAdmin,
        status: loginUser.status
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = userEditFormRef.value.getUserEditFormRef();
      FormRef.validate(valid => {
        if (!valid) return;
        editUserApi(options.props.formInline).then(res => {
          if (res.code === 200) {
            // 重新拉一下当前登陆用户信息
            getUser().then(res => {
              if (res.code === 200) {
                setUser(res.data);
                // 指定路由，刷新页面数据
                if (router.options.history.location === "/user/index") {
                  userList({
                    current: 1,
                    size: 10
                  }).then(res => {
                    if (res.code === 200) {
                      $bus.emit("userListData", res);
                    }
                  });
                }
              }
            });
            done();
          }
        });
      });
    }
  });
};

const openChangePasswordDialog = () => {
  const loginUser = storageLocal().getItem(userKey);
  addDialog({
    width: "20%",
    title: loginUser.name,
    contentRenderer: () => h(changePwdForms, { ref: changePwdFormRef }),
    props: {
      formInline: {
        id: loginUser.id,
        originPassword: "",
        newPassword: "",
        confirmPassword: ""
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = changePwdFormRef.value.getUserChangePwdFormRef();
      FormRef.validate(valid => {
        if (!valid) return;
        changePassword(options.props.formInline).then(res => {
          if (res.code === 200) {
            done();
          }
        });
      });
    }
  });
};
let rule = ref(false);
// 判断是否展示重载配置按钮
const getRule = () => {
  getServerRestartRule().then(res => {
    if (res.code === 200) {
      rule.value = res.data.rule === "hand";
    }
  });
  storageLocal().setItem("restart-rule", rule.value);
  return rule;
};

// 重启服务端
const restartServerCommand = () => {
  restartServer({
    status: "RESTART"
  }).then(res => {
    if (res.code === 200) {
      message("应用配置成功", { type: "success" });
    }
  });
};

getRule();
</script>

<template>
  <div class="navbar bg-[#fff] shadow-sm shadow-[rgba(0,21,41,0.08)]">
    <LaySidebarTopCollapse
      v-if="device === 'mobile'"
      class="hamburger-container"
      :is-active="pureApp.sidebar.opened"
      @toggleClick="toggleSideBar"
    />

    <LaySidebarBreadCrumb
      v-if="layout !== 'mix' && device !== 'mobile'"
      class="breadcrumb-container"
    />

    <LayNavMix v-if="layout === 'mix'" />

    <div v-if="layout === 'vertical'" class="vertical-header-right">
      <el-button
        v-if="rule"
        type="danger"
        :icon="Refresh"
        style="margin-right: 150px"
        @click="restartServerCommand()"
        >重载配置</el-button
      >
      <!--       菜单搜索-->
      <!--            <LaySearch id="header-search" />-->
      <!--       全屏-->
      <!--            <LaySidebarFullScreen id="full-screen" />-->
      <!--       消息通知-->
      <!--            <LayNotice id="header-notice" />-->
      <!--       退出登录-->
      <el-dropdown trigger="click">
        <span class="el-dropdown-link navbar-bg-hover select-none">
          <img :src="userAvatar" :style="avatarsStyle" />
          <p v-if="username" class="dark:text-white">{{ username }}</p>
        </span>
        <template #dropdown>
          <el-dropdown-menu class="logout">
            <el-dropdown-item @click="openUserInfoDialog">
              <IconifyIconOnline
                icon="eva:person-outline"
                style="margin: 5px"
              />
              个人信息
            </el-dropdown-item>
          </el-dropdown-menu>
          <el-dropdown-menu class="logout">
            <el-dropdown-item @click="openChangePasswordDialog">
              <IconifyIconOnline
                icon="ic:baseline-lock-person"
                style="margin: 5px"
              />
              修改密码
            </el-dropdown-item>
          </el-dropdown-menu>
          <el-dropdown-menu class="logout">
            <el-dropdown-item @click="logout">
              <IconifyIconOffline
                :icon="LogoutCircleRLine"
                style="margin: 5px"
              />
              退出系统
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <span
        class="set-icon navbar-bg-hover"
        title="打开系统配置"
        @click="onPanel"
      >
        <IconifyIconOffline :icon="Setting" />
      </span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.navbar {
  width: 100%;
  height: 48px;
  overflow: hidden;

  .hamburger-container {
    float: left;
    height: 100%;
    line-height: 48px;
    cursor: pointer;
  }

  .vertical-header-right {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    min-width: 280px;
    height: 48px;
    color: #000000d9;

    .el-dropdown-link {
      display: flex;
      align-items: center;
      justify-content: space-around;
      height: 48px;
      padding: 10px;
      color: #000000d9;
      cursor: pointer;

      p {
        font-size: 14px;
      }

      img {
        width: 52px;
        height: 52px;
        border-radius: 50%;
      }
    }
  }

  .breadcrumb-container {
    float: left;
    margin-left: 16px;
  }
}

.logout {
  width: 120px;

  ::v-deep(.el-dropdown-menu__item) {
    display: inline-flex;
    flex-wrap: wrap;
    min-width: 100%;
  }
}
</style>
