<script setup lang="ts">
import { computed, ref, nextTick } from "vue";
import { useNav } from "../hooks/nav";
import mixNav from "./sidebar/mixNav.vue";
import avatars from "/@/assets/avatars.jpg";
import Hamburger from "./sidebar/hamBurger.vue";
import Breadcrumb from "./sidebar/breadCrumb.vue";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { useRouter, useRoute } from "vue-router";
import Company from "../components/company/index.vue";
import Super from "../components/company/super.vue";
import { useUserInfo } from "/@/hooks/core/useUser";
import { getToken } from "/@/utils/auth";
import SystemNotify from "./system-notify.vue";
import HelpModal from "./help-modal.vue";
import { initRouter } from "/@/router/utils";
import { useCompany } from "/@/hooks/core/useCompany";
import CryptoJS from "crypto-js";
import { usePermissionStore, usePermissionStoreHook } from "/@/store/modules/permission";
import { loadEnv } from "@build/index";
import { ElMessageBox } from "element-plus";
import router from "/@/router";

let timerID: NodeJS.Timeout | null = null;
const route = useRoute();
const { push } = useRouter();
const showBackButton = computed(() => route.path.indexOf("Detail") >= 0);
const helpModalRef = ref<InstanceType<typeof HelpModal> | null>(null);
const systemNotifyRef = ref<InstanceType<typeof SystemNotify>>(null);
const { logout, toggleSideBar, pureApp, avatarsStyle } = useNav();
const { VITE_PURCHASE_URL, VITE_GD_URL, VITE_SECRET_KEY, VITE_DASHBOARD_URL } = loadEnv();

const SuperCompanyRef = ref<InstanceType<typeof Super> | null>(null);

const { isSuperUser, userInfo, userLevel, setUserLevel } = useUserInfo();

const menuData = computed(() => usePermissionStore().wholeMenus);

const store = usePermissionStoreHook();

const { setCurrentCompany } = useCompany();

const switchAccountModeText = computed(() =>
  userLevel.value === "3" ? "切换至业务公司" : "切换至供应商"
);

function routeToList() {
  const { path, query } = route;

  const purchaseDetails = ((store.collections as any).purchase || []).map(({ menu_route }) => {
    const chunks = menu_route.split('_');
    return `${chunks[0]}Detail`
  })


  const postSupplierOrderDetails = ((store.collections as any).postSupplierOrder || []).map(({ menu_route }) => {
    const chunks = menu_route.split('_');
    return `${chunks[0]}Detail`
  })


  const supplierOrderDetails = ((store.collections as any).supplierOrder || []).map(({ menu_route }) => {
    const chunks = menu_route.split('_');
    return `${chunks[0]}Detail`
  })

  const pathName = (path.split('/'))[2];
  console.log(pathName)

  if (purchaseDetails.includes(pathName)) {
    const prefix = (pathName.split('Detail'))[0]
    push(`/purchase/purchaseCollection?tab=${prefix}_collection`)
    return;
  }


  if (postSupplierOrderDetails.includes(pathName)) {
    const prefix = (pathName.split('Detail'))[0]
    push(`/postSupplierOrder/postSupplierOrderCollection?tab=${prefix}_collection`)
    return;
  }

  if (supplierOrderDetails.includes(pathName)) {
    const prefix = (pathName.split('Detail'))[0]
    push(`/supplierOrder/supplierOrderCollection?tab=${prefix}_collection`)
    return;
  }

  if(pathName === 'supplyInvoiceRelationDetail' || pathName === 'unSupplyInvoiceRelationDetail'){
    const prefix = (pathName.split('Detail'))[0]
    push(`/supply/supplyCollection?tab=${prefix}_collection`)
    return;
  }

  push((query?.back as string) ? (query.back as string) : path.split("Detail")[0]);
}

function openPurchaseSystem(type) {
  const encJson = CryptoJS.AES.encrypt(
    JSON.stringify({ token: getToken() }),
    VITE_SECRET_KEY
  );
  const encData = CryptoJS.enc.Base64.stringify(
    CryptoJS.enc.Utf8.parse(encJson)
  );

  let url = "";
  switch (type) {
    case 1:
      url = VITE_PURCHASE_URL + "#/accept?t=";
      break;
    case 2:
      // this.url =;
      url = VITE_GD_URL + "#/accept?t=";
      break;
    default:
      url = VITE_DASHBOARD_URL + "#/accept?t=";
      break;
  }

  window.open(url + encData);
}

function openAlert() {
  ElMessageBox.alert("正在开发中，敬请期待", "提示", {
    type: "warning"
  });
}

//超管切换供应商、业务公司视角
async function onSwitchAccountMode() {
  if (timerID) {
    window.clearTimeout(timerID);
    timerID = null;
  }

  const isSupplier = userLevel.value === "3";
  setUserLevel(isSupplier ? "1" : "3");

  await initRouter({ level: isSupplier ? "1" : "3" });

  await nextTick(() => {
    setCurrentCompany("");
    SuperCompanyRef.value && SuperCompanyRef.value.selectAll();

    timerID = setTimeout(() => {
      router.push(menuData.value[1].children[0].path + "?reload=" + userLevel.value);
    }, 500);
  });
}
</script>

<template>
  <div class="navbar">
    <Hamburger
      v-if="pureApp.layout !== 'mix'"
      :is-active="pureApp.sidebar.opened"
      class="hamburger-container"
      @toggleClick="toggleSideBar"
    />

    <Breadcrumb
      v-if="pureApp.layout !== 'mix'"
      class="breadcrumb-container"
      :ml="showBackButton ? '20px' : '0px'"
    />

    <ElButton
      v-if="showBackButton"
      link
      absolute
      top="15px"
      left="45px"
      :icon="useRenderIcon('d-arrow-left')"
      @click="() => routeToList()"
    />

    <mixNav v-if="pureApp.layout === 'mix'" />
    <div v-if="pureApp.layout === 'vertical'" class="vertical-header-right">
      <!-- 公司名称筛选 -->
      <Super v-if="isSuperUser" ref="SuperCompanyRef" />
      <Company v-else />
      <!--  超管切换至供应商和业务公司    -->
      <el-tooltip placement="bottom" :content="switchAccountModeText">
        <p
          class="bell-icon shake"
          v-if="isSuperUser"
          @click="onSwitchAccountMode"
        >
          <IconifyIconOffline icon="sort" />
        </p>
      </el-tooltip>
      
      <!-- 采销系统入口 -->
      <el-tooltip placement="bottom" content="登录采销平台">
        <p class="bell-icon shake" @click="openPurchaseSystem(1)">
          <IconifyIconOnline icon="ep:shopping-cart-full" />
        </p>
      </el-tooltip>
      
      <!-- 采销数据统计 -->
      <el-tooltip placement="bottom" content="登录采销数据统计" v-if="Number(userLevel) !== 3">
        <p class="bell-icon shake" @click="openPurchaseSystem(3)">
          <IconifyIconOnline icon="ep:data-line" />
        </p>
      </el-tooltip>

      <!-- 工单管理系统 -->
      <el-tooltip placement="bottom" content="登录工单管理系统">
        <p class="bell-icon shake" @click="openPurchaseSystem(2)">工单</p>
      </el-tooltip>

      <p class="bell-icon shake" @click="() => systemNotifyRef.onDisplay()">
        <IconifyIconOffline icon="bell-filled" />
      </p>

      <!-- 全屏 -->
      <!-- <screenfull id="header-screenfull" v-show="!deviceDetection()" /> -->

      <!-- 退出登录 -->
      <el-dropdown trigger="click">
        <span class="el-dropdown-link">
          <img v-if="avatars" :src="avatars" :style="avatarsStyle" text-key="91110113MA028K5Y7Y" />
          &nbsp; &nbsp;
          <template v-if="userInfo">
            <p>{{ userInfo.nickname }}</p>
          </template>
        </span>
        <template #dropdown>
          <el-dropdown-menu class="logout">
            <el-dropdown-item>
              <IconifyIconOffline icon="user" style="margin: 5px" />
              <template v-if="userInfo">
                <span>{{ userInfo.mobile }}</span>
              </template>
            </el-dropdown-item>

            <el-dropdown-item @click="() => helpModalRef.onDisplay()">
              <IconifyIconOffline icon="dict" style="margin: 5px" />
              使用说明
            </el-dropdown-item>

            <el-dropdown-item @click="logout">
              <IconifyIconOffline
                icon="logout-circle-r-line"
                style="margin: 5px"
              />
              退出系统
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <HelpModal ref="helpModalRef" />
    <SystemNotify ref="systemNotifyRef" />
  </div>
</template>

<style lang="scss" scoped>
@keyframes shake {
  /* 水平抖动，核心代码 */
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%,
  80% {
    transform: translate3d(+2px, 0, 0);
  }

  30%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%,
  60% {
    transform: translate3d(+4px, 0, 0);
  }

  50% {
    transform: translate3d(-4px, 0, 0);
  }
}

.shake {
  animation: shake 800ms ease-in-out;
}

.navbar {
  width: 100%;
  height: 48px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .hamburger-container {
    line-height: 48px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;
  }

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

    :deep(.dropdown-badge) {
      &:hover {
        background: #f6f6f6;
      }
    }

    .screen-full {
      cursor: pointer;

      &:hover {
        background: #f6f6f6;
      }
    }

    .globalization {
      height: 48px;
      width: 40px;
      padding: 11px;
      cursor: pointer;

      &:hover {
        background: #f6f6f6;
      }
    }

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

      &:hover {
        background: #f6f6f6;
      }

      p {
        font-size: 14px;
      }

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

    .el-icon-setting {
      height: 48px;
      width: 38px;
      padding: 12px;
      display: flex;
      cursor: pointer;
      align-items: center;

      &:hover {
        background: #f6f6f6;
      }
    }
  }

  .breadcrumb-container {
    float: left;
  }
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}

.logout {
  max-width: 165px;

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

.bell-icon {
  margin: 0px 10px;
  cursor: pointer;
}
</style>
./nav../components/sidebar/mixNav.vue../components/sidebar/hamBurger.vue../components/sidebar/breadCrumb.vue../components/system-notify.vue../components/help-modal.vue
