<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <div class="breadcrumb-title"> 应急架构体系 </div>
    </div>
    <div class="safety-platform-container__main">
      <OrgChart :treeData="treeData" @node-click="handleNodeClick" />
    </div>
    <div class="safety-platform-container__footer" v-if="showOperationBar">
      <el-button @click="router.push('team-management')"> 编辑 </el-button>
    </div>
  </div>
  <TeamDetailDrawer ref="teamDetailDrawerRef" :selected-team-id="selectedTeamId" />
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import OrgChart from '../components/OrgChart.vue';
  import TeamDetailDrawer from './components/TeamDetailDrawer.vue';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import useTeamStore from './team-management/store/userTeam';
  import { EMERGENCY_PERMISSIONS } from '@/views/emergency/constant';

  type OrganizationTreeType = {
    id: string;
    data: { name: string };
    children?: OrganizationTreeType[];
  };

  const treeData = ref<OrganizationTreeType>({
    id: 'root',
    data: { name: '应急领导小组' },
    children: [
      {
        id: 'group1',
        data: { name: '应急指挥小组' },
      },
      {
        id: 'group2',
        data: { name: '应急响应小组' },
      },
      {
        id: 'group3',
        data: { name: '应急支援小组' },
      },
    ],
  });

  const router = useRouter();

  const showOperationBar = ref(false);

  const { permissions } = useUserInfoHook();
  const { getLeaderTeams } = useTeamStore();

  const teamDetailDrawerRef = ref<InstanceType<typeof TeamDetailDrawer>>();

  const selectedTeamId = ref<number | null>(null);

  const handleNodeClick = (nodeData: any) => {
    selectedTeamId.value = Number(nodeData.id);

    teamDetailDrawerRef.value?.drawerShow();
  };

  function convertData(leaderTeams): OrganizationTreeType {
    return {
      id: leaderTeams.teamId.toString(),
      data: {
        name: leaderTeams.teamName,
      },
      children: leaderTeams.children?.map((child) => convertData(child)),
    };
  }

  onMounted(async () => {
    showOperationBar.value = Boolean(
      permissions.find((item: { code: string }) => item.code === EMERGENCY_PERMISSIONS.ORGANIZATION_MANAGEMENT),
    );

    const res = await getLeaderTeams();

    treeData.value = convertData(res);
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/page-details-layout.scss' as *;
</style>
