<style scoped>
.user-bg-color {
  background-color: #e9e9e9;
  height: 100%;
  overflow: auto;
}
.admin-bg-color {
  background-color: #fffbdd;
  height: 100%;
  overflow: auto;
}
table {
  min-width: 600px;
}
table tbody tr {
  border: 2px #bbbbbb solid;
}
table th,
td {
  border: 0;
  vertical-align: middle;
}
table th {
  background-color: transparent;
}
.inside-border-color {
  border-color: #0c4e82 !important;
  background-color: #fff;
  font-size: 0.8rem;
}
</style>
<template>
  <div class="main-view px-4 pt-2">
    <div class="d-flex align-items-center mb-3">
      <button class="btn-goback me-2" @click="$router.back()">
        <i class="bi bi-chevron-left me-1"></i>{{ $t('global.go_back') }}
      </button>
      <nav style="--bs-breadcrumb-divider: '>'" aria-label="breadcrumb">
        <ol class="breadcrumb m-0">
          <li class="breadcrumb-item"><a href="#">{{ $t('global.homepage') }}</a></li>
          <li class="breadcrumb-item" v-if="isAdmin">
            <router-link to="/userSubSystem/parentSubSystemIndex/1"> {{ parentName }} </router-link>
          </li>
          <li class="breadcrumb-item" v-if="(isAdmin || isParent) && parentName != subName">
            <a href="javascript:;" @click="$router.back()">{{ subName }}</a>
          </li>
          <li class="breadcrumb-item active" aria-current="page">【{{ subSystem[subSystemId] }}】{{ $t('backend.userSubSystem.sub_user_list') }}</li>
        </ol>
      </nav>
    </div>
    <h1 class="mb-5">【{{ subSystem[subSystemId] }}】{{ $t('backend.userSubSystem.sub_user_list') }}</h1>
    <div class="text-end" v-if="isSub || isParent">
      <button class="btn btn-primary mb-2" @click="gotoSubSystem(id)">
        {{ $t('global.navigate_to') }}
      </button>
    </div>
  </div>
  <div class="p-4" :class="{ 'admin-bg-color': isAdmin, 'user-bg-color': !isAdmin }">
    <div class="input-group w-50 mb-3">
      <input
        type="search"
        class="form-control border border-2 border-end-0 inside-border-color"
        placeholder="Search..."
      />
      <button
        class="btn btn-light border border-2 border-start-0 inside-border-color"
        type="button"
      >
        <i class="bi bi-search"></i>
      </button>
    </div>
    <table class="table table-hover" id="table">
      <thead>
        <tr>
          <th class="text-center">{{ $t('global.serial_number') }}</th>
          <th>{{ $t('global.name') }}</th>
          <th>{{ $t('global.email') }}</th>
          <th class="text-center">{{ $t('global.operation') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(user, index) in users" :key="user.id">
          <td class="col-1 text-center">{{ index + 1 }}</td>
          <td class="col-2">{{ user.name }}</td>
          <td class="col-3">{{ user.email }}</td>
          <td class="col-2 text-center">
            <button class="btn btn-success mx-1" @click="gotoSubSystem(user.id)">
              {{ $t('global.navigate_to') }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
import { api } from "@/global/axios";
import { sendFailedSwal } from "@/global/swal";
import { isAdmin, isParent, isSub } from "@/global/request";
export default {
  data() {
    return {
      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 || '',
      id: this.$route.params.id ?? null,
      subSystemId: this.$route.params.subSystemId ?? null,
      subSystem: ["", "安全智慧巡檢功能", "電氣火災預警功能", "化學品智慧安全管理功能"],
      isAdmin: isAdmin(),
      isParent: isParent(),
      isSub: isSub(),
      users: [],
      parentName: "",
      subName: "",
      dataTable: null,
      systemToken: [],
    };
  },
  mounted() {
    const vm = this;
    vm.fetchData();

    $("input[type='search']").on("keyup input", function () {
      vm.dataTable.search(this.value).draw();
    });
  },
  methods: {
    fetchData: async function () {
      const vm = this;
      await api
        .get(`/api/getUserSubHasSystemRole/${this.subSystemId}/u/${this.id}`)
        .then((res) => {
          vm.users = res.data.data;
          vm.subName = res.data.subName;
          vm.parentName = res.data.parentName;
        })
        .catch(sendFailedSwal);

      vm.dataTable = $("#table").DataTable();
    },
    gotoSubSystem: async function (id) {
      const vm = this;

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

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

      const loginUrlMap = {
        1: (token) => `${vm.polibeeUrl}/login/${token}`,
        2: (token) => `${vm.hotbeeUrl}/thermal-web/login/${token}`,
        3: (token) => `${vm.chembeeUrl}/login/${token}`,
      };

      const systemPath = systemPathMap[vm.subSystemId];

      if (!systemPath) {
        sendFailedSwal('找不到對應的子系統 URL');
        return;
      }

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

        // Step 2: 取得 JWT Token
        const res = await api.get(`/api/getJwtTokenByUserId/${id}`);
        vm.systemToken = res.data.data;

        const token = vm.systemToken[vm.subSystemId];
        if (!token) {
          sendFailedSwal('找不到子系統 Token');
          return;
        }

        // Step 3: 導向子系統
        const targetUrl = loginUrlMap[vm.subSystemId](token);
        window.location.href = targetUrl;

      } catch (error) {
        console.error('gotoSubSystem error:', error);
        sendFailedSwal('登入子系統失敗，請稍後再試');
      }
    }
  },
};
</script>
