<style scoped>
.btn-toggle {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.4rem;
  font-size: 1rem;
  font-weight: 900;
  color: #fff;
  background-color: transparent;
  border: 0;
}
.btn-toggle:hover {
  color: #fff;
  background-color: #ffbf53;
}
.btn-toggle.hasSub.hide-after::after {
  content: none !important;
}
.btn-toggle.hasSub::after {
  width: 1.25em;
  line-height: 0;
  content: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M5 14l6-6-6-6'/%3e%3c/svg%3e");
  transition: transform 0.35s ease;
  transform-origin: 0.5em 50%;
}
.btn-toggle[aria-expanded="true"] {
  color: #fff;
}
.btn-toggle[aria-expanded="true"].hasSub::after {
  transform: rotate(90deg);
}
.btn-toggle-nav a {
  width: 80%;
  display: inline-flex;
  padding: 0.4rem 0.4rem 0.4rem 0.8rem;
  margin-top: 0.125rem;
  margin-left: 2rem;
  text-decoration: none;
  font-size: 1rem;
  font-weight: bold;
  color: #fff;
}
.btn-toggle-nav a:hover,
.btn-toggle-nav a:focus {
  background-color: #ffbf53;
}
.border-top {
  color: #fff;
}
.sub-item {
  position: relative;
}
.sub-item::before {
  content: "";
  background-color: #fff;
  width: 0.2rem;
  height: 1.1rem;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 1rem;
}
/**--------------------------- */
.collapse-icon {
  position: absolute;
  bottom: 0;
  margin-bottom: 1.5em;
  transition: 0.2s linear;
}
.rotate-180 {
  transform: rotate(180deg);
  transition: 0.2s linear;
}
.user-bg-color {
  /* background-color: #0fa1b8; */
  background-image: url("@images/sidebar/sidebar_bg.png");
  background-size: cover;
  z-index: 5;
  overflow-y: auto;
}
.admin-bg-color {
  /* background-color: #676767; */
  background-image: url("@images/sidebar/sidebar_bg.png");
  background-size: cover;
  z-index: 5;
  overflow-y: auto;
}
.icon-size {
  width: 35px;
  height: 35px;
}
.text-hide {
  display: none;
  margin: 0;
}
.icon-hover {
  display: block;
  position: fixed;
  left: 55px;
  background-color: azure;
  padding: 10px;
  border-radius: 10px;
  color: #000 !important;
}
.icon-hover .btn-toggle-nav a {
  color: #000;
  margin-left: 1.5rem;
}
.icon-hover .sub-item::before {
  background-color: #000;
}
.icon-hover .collapse-text {
  display: block;
  font-size: 1rem;
  font-weight: bold;
  color: #000;
}
.collapse-text {
  display: none;
}
.side-nav {
  height: 90%;
  overflow: auto;
}
.side-nav .nav-item {
  padding: 0 10px;
}
.nav-item-sub {
  position: relative;
  display: flex;
}
.router-link-active {
  background-color: #ffbf53;
}
</style>
<template>
  <aside
    class="d-flex flex-column align-items-sm-start pt-2 text-white"
    :class="{ 'admin-bg-color': isAdmin, 'user-bg-color': !isAdmin }"
    :style="{ width: sidebarWidth }"
  >
    <div class="side-nav w-100 py-2">
      <ul id="sideAccordion" class="list-unstyled ps-0">
        <li class="mb-3 nav-item">
          <router-link :to="isAdmin ? '/home/adminHome' : '/home/parentHome'" 
            class="btn btn-toggle align-items-center rounded collapsed">
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/home.png" class="icon-size" alt="" />
              <div class="side-text ml-4">
                <span>{{ $t('global.homepage') }}</span>
              </div>
            </div>
          </router-link>
        </li>
        <li class="mb-3 nav-item" v-if="systemRole[1]">
          <button @click="gotoSubSystem(1)" class="btn btn-toggle align-items-center rounded collapsed w-100 text-start">
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/pb_icon.png" class="icon-size" alt="" />
              <div class="side-text ml-4 text-start">
                <span>安全智慧巡檢功能</span>
              </div>
            </div>
          </button>
        </li>

        <li class="mb-3 nav-item" v-if="systemRole[2]">
          <button @click="gotoSubSystem(2)" class="btn btn-toggle align-items-center rounded collapsed w-100 text-start">
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/hb_icon.png" class="icon-size" alt="" />
              <div class="side-text ml-4 text-start">
                <span>電氣火災預警功能</span>
              </div>
            </div>
          </button>
        </li>

        <li class="mb-3 nav-item" v-if="systemRole[3]">
          <button @click="gotoSubSystem(3)" class="btn btn-toggle align-items-center rounded collapsed w-100 text-start">
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/cb_icon.png" class="icon-size" alt="" />
              <div class="side-text ml-4 text-start">
                <span>化學品智慧安全管理功能</span>
              </div>
            </div>
          </button>
        </li>
        <li class="mb-3 nav-item" v-if="isParent || isSub">
          <router-link
            :to="`/user/subUserIndex/${id}`"
            class="btn btn-toggle align-items-center rounded collapsed"
          >
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/usercenter.png" class="icon-size" alt="" />
              <div class="side-text ml-4">
                <span>{{ $t('backend.user.sub_user_management') }}</span>
              </div>
            </div>
          </router-link>
        </li>
        <li class="mb-3 nav-item" v-if="isSuperAdmin || (isAdmin && productGroupBooleans[0])">
          <router-link
            to="/plan/index"
            class="btn btn-toggle align-items-center rounded collapsed"
          >
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/plan_management.png" class="icon-size" alt="" />
              <div class="side-text ml-4">
                <span>{{ $t('sidebar.plan_management') }}</span>
              </div>
            </div>
          </router-link>
        </li>
        <li class="mb-3 nav-item" v-if="isSuperAdmin || (isAdmin && productGroupBooleans[1])">
          <router-link
            to="/statistics/index"
            class="btn btn-toggle align-items-center rounded collapsed"
          >
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/activation_statistics.png" class="icon-size" alt="" />
              <div class="side-text ml-4">
                <span>{{ $t('sidebar.activation_statistics') }}</span>
              </div>
            </div>
          </router-link>
        </li>
        <li class="mb-3 nav-item" v-if="isAdmin && (productGroupBooleans[6] || productGroupBooleans[7])">
          <button
            class="btn btn-toggle align-items-center rounded collapsed hasSub"
            data-bs-toggle="collapse"
            data-bs-target="#member-collapse"
          >
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/usermanage.png" class="icon-size" alt="" />
              <div class="side-text ml-4">
                <span>{{ $t('sidebar.member_management') }}</span>
              </div>
            </div>
          </button>

          <div class="collapse" id="member-collapse" data-bs-parent="#sideAccordion">
            <div class="collapse-text ml-4">
              <span>{{ $t('sidebar.member_management') }}</span>
            </div>
            <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
              <li v-if="productGroupBooleans[6]">
                <router-link to="/user/parentIndex" class="sub-item rounded">
                  {{ $t('sidebar.account_data_management') }}
                </router-link>
              </li>
              <li v-if="productGroupBooleans[7]">
                <router-link to="/activate/index" class="sub-item rounded">
                  {{ $t('sidebar.member_service_activation') }}
                </router-link>
              </li>
            </ul>
          </div>
        </li>
        <li class="mb-3 nav-item" v-if="isAdmin && productGroupBooleans[4]">
          <router-link
            to="/news/index"
            class="btn btn-toggle align-items-center rounded collapsed"
          >
            <div class="inline-flex align-items-center">
              <img src="@images/sidebar/news.png" class="icon-size" alt="" />
              <div class="side-text ml-4">
                <span>{{ $t('sidebar.announcement_settings') }}</span>
              </div>
            </div>
          </router-link>
        </li>
      </ul>
    </div>
    <span
      class="collapse-icon px-3"
      :class="{ 'rotate-180': collapsed }"
      @click="toggleSidebar"
    >
      <svg
        class="icon-size"
        aria-hidden="true"
        fill="none"
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="2"
        viewBox="0 0 24 24"
        stroke="currentColor"
      >
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          d="M18.75 19.5l-7.5-7.5 7.5-7.5m-6 15L5.25 12l7.5-7.5"
        />
      </svg>
    </span>
  </aside>
</template>
<script>
import { api } from "@/global/axios";
import { isSuperAdmin, isAdmin, isParent, isSub, isUser, systemRole } from "@/global/request";
import { useSidebarState } from "./state";
export default {
  data() {
    const sidebar = useSidebarState();
    return {
      ...sidebar,
      baseUrl: import.meta.env.VITE_ASSET_URL || '',
      hotbeeUrl: import.meta.env.VITE_HOTBEE_API_URL || '',
      polibeeUrl: import.meta.env.VITE_POLIBEE_API_URL || '',
      chembeeUrl: import.meta.env.VITE_CHEMBEE_API_URL || '',
      hotbeeSystemCode: import.meta.env.VITE_HOTBEE_SYSTEM_CODE || '',
      polibeeSystemCode: import.meta.env.VITE_POLIBEE_SYSTEM_CODE || '',
      chembeeSystemCode: import.meta.env.VITE_CHEMBEE_SYSTEM_CODE || '',
      jwtToken: "",
      isSuperAdmin: isSuperAdmin(),
      isAdmin: isAdmin(),
      isParent: isParent(),
      isSub: isSub(),
      isUser: isUser(),
      systemRole: systemRole(),
      id: this.$store.state.auth.user.id,
      systemToken: [],
    };
  },
  async created() {
    await api.get(`/api/getJwtToken`).then((res) => {
      this.systemToken = res.data.data;
    });
  },
  computed: {
    productGroupBooleans() {
      if (this.isSuperAdmin) {
        return [true, true, true, true, true, true, true, true, true, true];
      }
      if (this.isAdmin) {
        const productGroup = this.$store.state.auth.user.group.product_group;
        return productGroup.split('').map(char => char === '1');
      }
    },
  },
  methods: {
    hasPermission() {
      return this.$route.meta.permission;
    },
    rememberClick(id) {
      this.$store.commit("SET_SIDEBAR", id);
    },
    gotoSubSystem: async function (subSystemId) {
      const vm = this;

      const systemCodehMap = {
        1: vm.polibeeSystemCode,
        2: vm.hotbeeSystemCode,
        3: vm.chembeeSystemCode,
      };

      const systemUrlMap = {
        1: vm.polibeeUrl,
        2: vm.hotbeeUrl,
        3: vm.chembeeUrl,
      };

      const loginPathMap = {
        1: '/login/',
        2: '/thermal-web/login/',
        3: '/login/',
      };

      const isInternalRoute = vm.isAdmin || vm.isParent || vm.isSub;

      // 若為內部身分，走 Vue router 導向
      if (isInternalRoute) {
        const path = vm.isAdmin
          ? `${vm.baseUrl}/userSubSystem/parentSubSystemIndex/${subSystemId}`
          : `${vm.baseUrl}/userSubSystem/subUserSubSystemIndex/${subSystemId}/${vm.id}`;
        window.location.href = path;
        return;
      }

      try {
        const payload = {
          userId: vm.id,
          system: systemCodehMap[subSystemId],
        };
        await api.post('/api/sso/ida/addLoginLog', payload);

        const res = await api.get(`/api/getJwtTokenByUserId/${vm.id}`);
        const token = res.data.data?.[subSystemId];

        if (!token) {
          sendFailedSwal('找不到子系統 Token');
          return;
        }

        const redirectUrl = `${systemUrlMap[subSystemId]}${loginPathMap[subSystemId]}${token}`;
        window.location.href = redirectUrl;

      } catch (err) {
        console.error('登入導向錯誤', err);
        sendFailedSwal('導向失敗，請稍後再試');
      }
    },
    async logout() {
      await api.post(`/auth/logout`);
      localStorage.removeItem("access_token");
      localStorage.removeItem("APP_USER_TOKEN");
      this.$store.commit("auth/SET_USER", {});
      this.$store.commit("auth/SET_AUTHENTICATED", false);
      window.location.href = "/login";
    },
  },
};
</script>
