<template>
  <div id="main" class="header-bar">
    <header>
      <ul class="nav">
        <!-- <div class="logo">ByteSailing</div> -->
        <div class="logo" style="display: flex; align-items: center; justify-content: center">
          <img v-if="!logoUrl" :src="'/img/logo2.png'" />
          <el-image v-else style="width: 120px; height: 30px" :src="logoUrl" fit="scale-down" />
        </div>
        <li class="header-bar-hover-warp nav-li" :class="isChildMenu ? 'active' : ''">
          <div @click="isChildMenu = !isChildMenu" class="menu-modal">
            <i class="iconfont icon-icomx_gongndh" style="margin: 0 5px 0 0"></i>
            {{$t('header.functionGuide')}}
            <i class="iconfont icon-iconm_xialan1" style="margin: 0 0 0 3px"></i>
          </div>
        </li>
        <div class="auto-list">
          <li class="nav-li" @click="commonsBannerToRouter(i)" v-for="(i, index) in commonsRouterList" v-show="index < autoListChidrenNum - 1" :key="i.id">
            <span>{{ i.menuName }}</span>
          </li>
          <li class="nav-li more-box" v-show="commonsRouterList.length > autoListChidrenNum - 1">
            {{$t('header.more')}}
            <i class="iconfont icon-iconm_xialan1"></i>
            <ul class="more-list">
              <li v-for="(i, index) in commonsRouterList" v-show="index >= autoListChidrenNum - 1" :key="i.id">
                <span @click="commonsBannerToRouter(i)">{{ i.menuName }}</span>
              </li>
            </ul>
          </li>
        </div>
        <div class="header-bar-warp" v-if="isChildMenu" @click.stop="isChildMenu = false">
          <div class="header-bar-hover" @click.stop>
            <div class="header-bar-hover-content">
              <div class="left-banner">
                <div class="first-order" @click="leftBanerType = 2">
                  <el-icon size="16" color="#0084FF">
                    <edit />
                  </el-icon>
                  {{$t('header.commonFunctions')}}
                </div>
                <div class="first-order">
                  <el-icon size="16" color="#0084FF">
                    <edit />
                  </el-icon>
                  {{$t('header.functionMenu')}}
                </div>
                <ul>
                  <li @click="openLeftBaner(i, index)" v-for="(i, index) in sidebarRoutersCopy" :key="i.name" v-show="i.type == 1 && i.status == '0'">
                    {{ i.menuName }}
                  </li>
                </ul>
                <!-- <div class="first-order">
									<el-icon size="16" color="#0084FF">
										<edit /> 
									</el-icon>
									推荐服务
								</div> -->
              </div>
              <div class="menu-warp" v-show="leftBanerType == 1">
                <div class="first-order-title">{{ activeLeftData.menuName }}</div>
                <!-- <ul class="second-level" v-for="i in activeLeftData.children" :key="i.menuId">
									<li class="menu-title">
											
											{{ i.menuName }}
										</li>
									<div v-for="(j, index) in i.children" :key="index">
										<li v-if="i.isNone" class="menu-ul" style="cursor: auto"></li>
										
										<li class="menu-ul" @click="routerPush(i,j)" style="cursor: pointer">
											{{ j.menuName }}
										</li>
									</div>
								</ul> -->
                <ul class="second-level">
                  <div v-for="(i, index) in activeLeftData" :key="index">
                    <li v-if="i.isNone" class="menu-ul" style="cursor: auto"></li>
                    <li class="menu-title" v-else-if="i.isTitle">
                      <a v-if="i.icon && i.icon !== '#'" :class="'iconfont icon-' + i.icon" style="margin-right: 4px"></a><span>{{ i.menuName }}</span>
                    </li>
                    <li v-else class="menu-ul" @click="commonsBannerToRouter(i)" style="cursor: pointer">
                      <span>{{ i.menuName }}</span>
                    </li>
                  </div>
                </ul>
              </div>
              <div class="menu-warp" v-show="leftBanerType == 2">
                <div class="first-order-title">{{$t('header.commonFunctions')}}</div>
                <div class="commons-warp">
                  <div>
                    <div class="header-button-box cp" v-for="(i, index) in commonsRouterList" :key="i.name" @click="commonsBannerToRouter(i)">
                      <span>{{ i.menuName }}</span>
                      <div class="right-icon" @click.stop="deleteCommonsRouter(i, index)">
                        <!-- <el-icon color="#46A6FF"><CirclePlus /></el-icon> -->
                        <el-icon color="#BBBBBB" v-show="isEidtType">
                          <Close />
                        </el-icon>
                      </div>
                    </div>
                    <div class="header-add-button-box" v-if="!isEidtType" @click="isEidtType = true">
                      <el-icon color="#46A6FF">
                        <CirclePlus />
                      </el-icon>
                      {{$t('header.edit')}}
                    </div>
                  </div>
                </div>
                <div class="first-order-title" v-if="isEidtType">{{$t('header.toAdd')}}</div>
                <div class="all-menu-warp" v-if="isEidtType">
                  <div v-for="(i, index) in sidebarRoutersCopy" :key="i.name" v-show="i.type === 1">
                    <div class="all-menu-title" v-for="(j, jindex) in i.children" :key="j.name">
                      <div class="title">
                        {{ j.menuName }}
                      </div>
                      <div class="all-menu-lists">
                        <div class="header-button-box" v-for="(n, nindex) in j.children" v-show="n.visible == '0'" :key="n.name">
                          <span>{{ n.menuName }}</span>

                          <div class="right-icon" @click="addCommonsRouter(index, jindex, nindex, n)">
                            <el-icon color="#46A6FF">
                              <CirclePlus />
                            </el-icon>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="btn-warp" v-if="isEidtType">
                  <el-button type="" @click="isEidtType = false">取消</el-button>
                  <el-button type="primary" @click="userMenuEdit">保存</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </ul>
      <div class="fr">
        <el-badge :value="12" class="badge">
          <el-icon :size="20">
            <BellFilled />
          </el-icon>
        </el-badge>
        <el-dropdown @command="handleCommand" class="right-menu-item hover-effect" trigger="click">
          <div class="dropdown-box">
            {{ userData }}
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <router-link to="/user/profile">
                <el-dropdown-item>{{$t('header.personalCenter')}}</el-dropdown-item>
              </router-link>
              <el-dropdown-item command="setLayout">
                <span>{{$t('header.layoutSettings')}}</span>
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <span>{{$t('header.logout')}}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>
  </div>
</template>

<script setup>
import Cookies from "js-cookie";
import { ElMessageBox, ElNotification, ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
import "@/components/headerBar/header.scss";
const router = useRouter();
const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const sidebarRouters = ref([]);
const sidebarRoutersCopy = ref([]);
const isChildMenu = ref(false);
const autoListChidrenNum = ref(0);
const isEidtType = ref(false);
const leftBanerType = ref(2);

const userData = ref(Cookies.get("nickName") || "");
const commonsRouterList = ref([]);
const activeLeftData = ref({});
const openLeftBaner = (i, index) => {
  leftBanerType.value = 1;
  activeLeftData.value = i;
  routerInit(i);
};
const logoUrl = ref();
const getLogo = () => {
  proxy.post("/tenantInfo/getLogo", {}).then((res) => {
    if (res && res.length > 0 && res[0].fileUrl) {
      logoUrl.value = res[0].fileUrl;
    }
  });
};
getLogo();
const userMenuEdit = () => {
  proxy
    .post("/sysUserMenu/edit", {
      type: 1,
      menuIdList: commonsRouterList.value.map((item) => item.menuId),
    })
    .then((res) => {
      ElMessage({
        message: "保存成功",
        type: "success",
      });
      isEidtType.value = false;
    });
};

const deleteCommonsRouter = (i, index) => {
  commonsRouterList.value.splice(index, 1);
};

const addCommonsRouter = (index, jindex, nindex, n) => {
  for (let i = 0; i < commonsRouterList.value.length; i++) {
    const element = commonsRouterList.value[i];
    if (element.menuId === n.menuId) {
      ElMessage({
        message: proxy.t('header.thisDirectoryHasBeenAdded'),
        type: "error",
      });
      return;
    }
  }
  if (n.hidden) {
    ElMessage({
      message: proxy.t('header.thisDirectoryRequiresAdditionalParameters'),
      type: "error",
    });
    return;
  }
  commonsRouterList.value.push(n);
  sidebarRoutersCopy.value[index].children[jindex].children[nindex].isCommonsBanner = true;
};

const routerInit = (item) => {
  //二维转一维
  const arr = [];
  for (let i = 0; i < item.children.length; i++) {
    const element = item.children[i];
    if (element.type === 1) {
      element.isTitle = true;

      arr.push(element);
    }

    if (element.children && element.children.length > 0) {
      for (let j = 0; j < element.children.length; j++) {
        const jelement = element.children[j];
        jelement.isTitle = false;
        if (jelement.type === 1) {
          arr.push({ ...jelement, fatherPath: element.path });
        }
      }
    }
  }
  //添加剩余子元素，补齐一列
  for (let i = 0; i < arr.length; i++) {
    const element = arr[i];
    if (element.isTitle) {
      //判断余数加上子项列会不会爆掉
      if (element.children && element.children.length > 0 && (i % 11) + element.children.length + 1 > 11 && element.children.length < 11) {
        let num = 11 - (i % 11);
        for (let j = 0; j < num; j++) {
          arr.splice(i, 0, { ...element, isNone: true });
          i++;
        }
      }
    }
  }
  activeLeftData.value = arr;
};
function handleCommand(command) {
  switch (command) {
    case "setLayout":
      setLayout();
      break;
    case "logout":
      logout();
      break;
    default:
      break;
  }
}

function logout() {
  ElMessageBox.confirm(proxy.t('header.areYouSureYouWantToLogOutAndExitTheSystem'), proxy.t('common.prompt'), {
    confirmButtonText:  proxy.t('common.confirm'),
    cancelButtonText: proxy.t('common.cancel'),
    type: "warning",
  })
    .then(() => {
      userStore.logOut().then(() => {
        location.href = "/index";
      });
    })
    .catch(() => {});
}

//使用id计算拼接url
const commonsBannerToRouter = (i) => {
  sidebarRoutersCopy.value.map((item) => {
    if (item.children) {
      item.children.map((j) => {
        if (j.children) {
          j.children.map((n) => {
            if (n.menuId === i.menuId) {
              router.push("/" + item.path + "/" + j.path + "/" + n.path);
              isChildMenu.value = false;
            }
          });
        }
      });
    }
  });
};

//获取浏览器宽度
function getBrowserWidth() {
  return document.documentElement.clientWidth;
}

//计算auto-list 能放下几个
function calcAutoListChidren() {
  autoListChidrenNum.value = Math.floor((getBrowserWidth() - 616) / 120);
}

//一维数组转tree

onMounted(() => {
  calcAutoListChidren();
  window.addEventListener("resize", calcAutoListChidren);
  proxy.get("/getInfo").then((res) => {
    userData.value = res.user.nickName;
  });
  proxy.get("/system/menu/list").then((res) => {
    res.data = res.data.map((item) => {
      return {
        ...item,
        isCommonsBanner: false,
      };
    });
    sidebarRoutersCopy.value = proxy.handleTree(res.data, "menuId");
    //循环删除 i.status != 0 || i.visible != 0 的元素
    sidebarRoutersCopy.value.map((item) => {
      if (item.children) {
        item.children.map((j) => {
          if (j.children) {
            j.children.map((n) => {
              if (n.status != 0 || n.visible != 0 || n.type != 1) {
                j.children.splice(j.children.indexOf(n), 1);
              }
            });
          }
        });
      }
    });
  });
  proxy.post("/sysUserMenu/list", { type: 1 }).then((res) => {
    commonsRouterList.value = res;
  });
});
</script>

<style lang="scss"></style>
