import { AXPanViewDirective } from '@acorex/cdk/pan-view';
import { AXBadgeModule } from '@acorex/components/badge';
import { AXBreadcrumbsModule } from '@acorex/components/breadcrumbs';
import * as i2 from '@acorex/components/button';
import { AXButtonModule } from '@acorex/components/button';
import * as i4 from '@acorex/components/decorators';
import { AXDecoratorModule } from '@acorex/components/decorators';
import { AXDropdownButtonModule } from '@acorex/components/dropdown-button';
import { AXLoadingModule } from '@acorex/components/loading';
import { AXContextMenuComponent, AXMenuModule } from '@acorex/components/menu';
import * as i3 from '@acorex/core/translation';
import { AXTranslationService, AXTranslationModule } from '@acorex/core/translation';
import { AXPPageLayoutBaseComponent, AXPPageLayoutComponent, AXPPageLayoutBase } from '@acorex/platform/layout/views';
import { AXPThemeLayoutBlockComponent } from '@acorex/platform/layout/components';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { inject, signal, Injectable, viewChild, NgZone, ViewContainerRef, afterNextRender, ViewEncapsulation, ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterModule } from '@angular/router';
import set from 'lodash-es/set';
import { AXMOrganizationManagementChartEntityService, RootConfig, AXMOrgChartNodeType, AXMOrgChartCategory } from './acorex-modules-organization-management.mjs';
import { AXLoadingDialogService } from '@acorex/components/loading-dialog';
import { AXPExportService } from '@acorex/platform/common';
import { AXPCommandService } from '@acorex/platform/runtime';
import { AXPLayoutBuilderService } from '@acorex/platform/layout/builder';
import { AXPDataGenerator, getActionButton } from '@acorex/platform/core';

class AXMOrgChartService {
    constructor() {
        // Employee moved to HCM; resolve via runtime query mapping instead of direct service
        this.chartService = inject(AXMOrganizationManagementChartEntityService);
        this.loadingDialog = inject(AXLoadingDialogService);
        this.exportService = inject(AXPExportService);
        this.translationService = inject(AXTranslationService);
        this.commandService = inject(AXPCommandService);
        this.layoutBuilder = inject(AXPLayoutBuilderService);
        this._rootNode = signal({ id: AXPDataGenerator.uuid(), title: 'Company' }, ...(ngDevMode ? [{ debugName: "_rootNode" }] : []));
        this.rootNode = this._rootNode.asReadonly();
    }
    async load() {
        const first = (await this.chartService.query({
            skip: 0,
            take: 1,
            sort: [{ field: 'version', dir: 'desc' }],
        })).items[0];
        //
        if (first && first.data) {
            const data = first.data;
            this._rootNode.set(data);
        }
        else {
            await this.generate();
            await this.load();
        }
    }
    async generate() {
        const dialogResult = await this.showGenerateDialog();
        if (dialogResult.cancelled) {
            return;
        }
        const input = dialogResult.input || {
            includeEmployees: true,
            preferPrimary: true,
            mode: 'structure',
        };
        // Prefer generating a fresh chart via mock command when available
        await this.commandService.execute('OrganizationManagement.OrgChart:Generate', input);
    }
    /**
     * Show dialog to get OrgChart generation parameters from user
     */
    async showGenerateDialog() {
        const dialogRef = await this.layoutBuilder
            .create()
            .dialog(dialog => {
            dialog
                .setTitle('@organization-management:chart.generate-dialog.title')
                .setContext({
                mode: 'structure',
                includeEmployees: true,
                preferPrimary: false
            })
                .content(flex => {
                flex.formField('Mode', (field) => {
                    field.path('mode');
                    field.selectionList({
                        valueField: 'value',
                        textField: 'text',
                        dataSource: [
                            { value: 'structure', text: '@organization-management:chart.mode.structure' },
                            { value: 'location', text: '@organization-management:chart.mode.location' },
                            { value: 'reporting', text: '@organization-management:chart.mode.reporting' }
                        ]
                    });
                })
                    .formField('Include Employees', (field) => {
                    field.path('includeEmployees');
                    field.toggleSwitch();
                })
                    .formField('Prefer Primary', (field) => {
                    field.path('preferPrimary');
                    field.toggleSwitch();
                });
            })
                .setActions(actions => {
                actions
                    .cancel()
                    .submit('@general:generate');
            });
        })
            .show();
        // Check if dialog was cancelled (result is null/undefined or has cancelled property)
        const formData = dialogRef.context();
        const action = dialogRef.action();
        dialogRef.close();
        if (!formData || action === 'cancel') {
            return { cancelled: true };
        }
        return {
            cancelled: false,
            input: formData
        };
    }
    //#region ----   Printing   ----
    async printChart(element) {
        const d = this.loadingDialog.show({
            title: 'Printing Organization Chart...',
            mode: 'determinate',
            progressColor: 'primary',
            progressValue: 0,
            status: '0/10',
            text: 'Initializing print process...',
            buttons: [
                { text: 'Cancel', color: 'danger', onClick: () => d.close() }
            ],
        });
        try {
            await this.updateStep(d, await this.translate('preparing-document'), 10, '1/10');
            const chartElement = element;
            const { originalStyles, modifiedStyles } = this.expandChart(chartElement);
            await this.updateStep(d, await this.translate('rendering-chart-image'), 25, '2.5/10');
            const blob = await this.exportService.generateBlobFromElement(chartElement, {
                popup: true,
                filter: (node) => !(node instanceof Element && node.classList.contains('--toggle')),
                bgcolor: 'transparent',
                scale: 2,
                quality: 1,
                height: Number.parseInt(modifiedStyles.modifiedHeight),
                width: Number.parseInt(modifiedStyles.modifiedWidth),
            });
            await this.updateStep(d, await this.translate('finalizing-image-processing'), 50, '5/10');
            this.restoreChartStyles(chartElement, originalStyles);
            await this.updateStep(d, await this.translate('downloading-image'), 75, '7.5/10');
            this.exportService.download(blob, 'org-chart.png');
            await this.updateStep(d, await this.translate('process-complete'), 100, '10/10');
            setTimeout(() => d.close(), 1500);
        }
        catch (err) {
            console.error('Error capturing chart:', err);
            await this.updateStep(d, await this.translate('failed-to-generate-chart-image'), 100, 'Error', 'danger');
            d.close();
        }
    }
    expandChart(chartElement) {
        const originalStyles = {
            originalOverflow: chartElement.style.overflow,
            originalWidth: chartElement.style.width,
            originalHeight: chartElement.style.height,
        };
        const modifiedStyles = {
            modifiedOverflow: 'visible',
            modifiedWidth: `${chartElement.scrollWidth}px`,
            modifiedHeight: `${chartElement.scrollHeight}px`,
        };
        chartElement.style.overflow = modifiedStyles.modifiedOverflow;
        chartElement.style.width = modifiedStyles.modifiedWidth;
        chartElement.style.height = modifiedStyles.modifiedHeight;
        return { originalStyles, modifiedStyles };
    }
    restoreChartStyles(chartElement, originalStyles) {
        chartElement.style.overflow = originalStyles.originalOverflow;
        chartElement.style.width = originalStyles.originalWidth;
        chartElement.style.height = originalStyles.originalHeight;
    }
    async updateStep(dialog, text, progress, status, color = 'primary') {
        return new Promise((resolve) => {
            dialog.setProgressColor(color);
            dialog.setProgressText(text);
            dialog.setProgressValue(progress);
            dialog.setProgressStatus(status);
            resolve();
        });
    }
    async translate(key) {
        return (await this.translationService.translateAsync(key, { scope: 'organization-management' })) + '...';
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMOrgChartService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMOrgChartService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMOrgChartService, decorators: [{
            type: Injectable
        }] });

/**
 * Component for displaying and interacting with an organizational chart.
 */
class AXMOrgChartPage extends AXPPageLayoutBaseComponent {
    constructor() {
        super(...arguments);
        this.rootConfig = RootConfig;
        this.nodeTemplate = viewChild.required('nodeTemplate');
        this.treeContainer = viewChild.required('chart');
        this.parent = viewChild.required('parent');
        this.contextMenu = viewChild(AXContextMenuComponent, ...(ngDevMode ? [{ debugName: "contextMenu" }] : []));
        this.panView = viewChild(AXPanViewDirective, ...(ngDevMode ? [{ debugName: "panView" }] : []));
        this.ngzone = inject(NgZone);
        this.viewContainerRef = inject(ViewContainerRef);
        // printing is handled by service itself
        this.chartService = inject(AXMOrgChartService);
        this.NODE_STROKE_COLOR = 'rgba(var(--ax-sys-color-primary-400))';
        this.LINK_STROKE_WIDTH = 1;
        this.NodeTypes = AXMOrgChartNodeType;
        this.isFullscreen = signal(false, ...(ngDevMode ? [{ debugName: "isFullscreen" }] : []));
        this.panX = signal(0, ...(ngDevMode ? [{ debugName: "panX" }] : []));
        this.panY = signal(0, ...(ngDevMode ? [{ debugName: "panY" }] : []));
        this.panZoomLevel = signal(100, ...(ngDevMode ? [{ debugName: "panZoomLevel" }] : []));
        this.isChartRendered = false;
        this.nodeTypes = [
            { title: 'Company', color: 'primary', icon: 'fal fa-building', category: AXMOrgChartCategory.Company },
            { title: 'Location', color: 'accent1', icon: 'fal fa-globe', category: AXMOrgChartCategory.Location },
            { title: 'Business Unit', color: 'accent2', icon: 'fal fa-sitemap', category: AXMOrgChartCategory.BusinessUnit },
            { title: 'Position', color: 'accent3', icon: 'fal fa-user-tie', category: AXMOrgChartCategory.Position },
            { title: 'Employee', color: 'surface', icon: 'fal fa-address-card', category: AXMOrgChartCategory.Employee },
        ];
        this.#initialize = afterNextRender(async () => {
            this.d3 = await import('d3');
            await this.refresh();
        });
    }
    #initialize;
    /**
     * Zooms in the chart.
     */
    zoomIn() {
        this.panView()?.zoomIn();
    }
    /**
     * Zooms out the chart.
     */
    zoomOut() {
        this.panView()?.zoomOut();
    }
    /**
     * Resets the zoom level and pan position of the chart.
     */
    zoomReset() {
        this.panView()?.resetPosition();
    }
    /**
     * Toggles fullscreen mode for the chart.
     */
    toggleFullscreen() {
        if (this.isFullscreen()) {
            document.exitFullscreen();
            this.isFullscreen.set(false);
        }
        else {
            this.parent().nativeElement.requestFullscreen();
            this.isFullscreen.set(true);
        }
        document.querySelector(`foreignObject[node="node-${this.chartService.rootNode().id}"]`)?.scrollIntoView({
            behavior: 'smooth',
            block: 'start',
            inline: 'center',
        });
    }
    /**
     * Calculates the maximum depth of the organizational chart.
     * @param node - The root node of the chart.
     * @returns The maximum depth of the chart.
     */
    calculateMaxDepth(node) {
        if (!node.children || node.children.length === 0 || node.isExpanded === false) {
            return 1;
        }
        return 1 + Math.max(...node.children.map((child) => this.calculateMaxDepth(child)));
    }
    /**
     * Calculates the maximum breadth of the organizational chart.
     * @param node - The root node of the chart.
     * @returns The maximum breadth of the chart.
     */
    calculateMaxBreadth(node) {
        if (!node.children || node.children.length === 0 || node.isExpanded === false) {
            return 1;
        }
        return node.children.reduce((acc, child) => acc + this.calculateMaxBreadth(child), 0);
    }
    /**
     * Creates and renders the organizational chart.
     * @param el - The container element for the chart.
     * @param data - The root node of the organizational chart.
     */
    createChart(el, data) {
        if (!this.d3) {
            return;
        }
        this.ngzone.runOutsideAngular(() => {
            const NODE_WIDTH_BASE = 260;
            const NODE_HEIGHT_BASE = 180;
            const HORIZONTAL_SPACING = 20;
            const VERTICAL_SPACING = 40;
            this.clearChart(el);
            const newSvg = this.d3.select(el).append('svg');
            const root = this.d3.hierarchy(data);
            root.descendants().forEach((node) => {
                if (node.data.isExpanded === false) {
                    node.children = undefined;
                }
            });
            const treeLayout = this.d3
                .tree()
                .nodeSize([NODE_WIDTH_BASE + HORIZONTAL_SPACING, NODE_HEIGHT_BASE + VERTICAL_SPACING]);
            treeLayout(root);
            let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
            root.descendants().forEach((d) => {
                if (d.x < minX)
                    minX = d.x;
                if (d.x > maxX)
                    maxX = d.x;
                if (d.y < minY)
                    minY = d.y;
                if (d.y > maxY)
                    maxY = d.y;
            });
            const CONTAINER_WIDTH = maxX - minX + NODE_WIDTH_BASE + 2 * HORIZONTAL_SPACING;
            const CONTAINER_HEIGHT = maxY - minY + NODE_HEIGHT_BASE + 2 * VERTICAL_SPACING;
            newSvg.attr('width', CONTAINER_WIDTH).attr('height', CONTAINER_HEIGHT);
            const g = newSvg
                .append('g')
                .attr('transform', `translate(${-minX + NODE_WIDTH_BASE / 2 + HORIZONTAL_SPACING / 2}, ${-minY + NODE_HEIGHT_BASE / 2 + VERTICAL_SPACING / 2})`);
            const link = g
                .selectAll('.link')
                .data(root.links())
                .enter()
                .append('path')
                .attr('class', 'link')
                .attr('d', (d) => {
                const source = d.source;
                const target = d.target;
                return `M${source.x},${source.y}V${(source.y + target.y) / 2}H${target.x}V${target.y - 10}`;
            })
                .attr('fill', 'none')
                .attr('stroke', this.NODE_STROKE_COLOR)
                .attr('stroke-width', this.LINK_STROKE_WIDTH)
                .attr('from', (d) => `node-${d.source.data.id}`)
                .attr('to', (d) => `node-${d.target.data.id}`);
            const node = g
                .selectAll('.axp-chart-node')
                .data(root.descendants())
                .enter()
                .append('foreignObject')
                .attr('class', 'axp-chart-node')
                .attr('node', (d) => `node-${d.data.id}`)
                .attr('x', (d) => d.x - NODE_WIDTH_BASE / 2)
                .attr('y', (d) => d.y - NODE_HEIGHT_BASE / 2 + 10)
                .attr('width', NODE_WIDTH_BASE)
                .attr('height', NODE_HEIGHT_BASE)
                .each((d) => this.renderNodeTemplate(d.data, d.x, d.y));
            this.contextMenu()?.refresh();
        });
        if (!this.isChartRendered) {
            // document.querySelector(`foreignObject[node="node-${data.id}"] .--heading-container`)?.scrollIntoView({
            //   behavior: 'smooth',
            //   block: 'center',
            //   inline: 'center',
            // });
            this.isChartRendered = true;
            this.panView()?.resetPosition();
        }
    }
    /**
     * Renders the node template for a given organizational node.
     * @param data - The node data.
     * @param x - The x-coordinate of the node.
     * @param y - The y-coordinate of the node.
     */
    renderNodeTemplate(data, x, y) {
        // Find the key that matches the node type
        // category is the same as type in simplified structure
        set(data, 'category', data.type);
        const viewRef = this.viewContainerRef.createEmbeddedView(this.nodeTemplate(), {
            $implicit: data,
        });
        const nodeElement = this.d3.select(this.treeContainer().nativeElement).select(`[node="node-${data.id}"]`);
        const element = nodeElement.node();
        if (element) {
            element.appendChild(viewRef.rootNodes[0]);
        }
    }
    /**
     * Toggles the expansion state of a node.
     * @param data - The node data.
     * @param el - The HTML element representing the node.
     */
    toggleNode(data, el) {
        data.isExpanded = data.isExpanded === undefined ? false : !data.isExpanded;
        this.createChart(this.treeContainer().nativeElement, this.chartService.rootNode());
        // el.scrollIntoView({
        //   behavior: 'smooth',
        // });
    }
    /**
     * Clears the chart from the container element.
     * @param el - The container element.
     */
    clearChart(el) {
        if (this.d3) {
            this.d3.select(el).select('svg').remove();
            this.viewContainerRef.clear();
        }
    }
    async refresh() {
        if (this.d3) {
            await this.chartService.load();
            this.createChart(this.treeContainer().nativeElement, this.chartService.rootNode());
        }
    }
    //#region Context Menu
    // protected async handleContextMenuOnOpening(e: AXContextMenuOpeningEvent) {
    //   const node = get(e.targetElement, '__data__.data') as any as AXMOrganizationNode;
    //   const allowedAddItems = await this.chartService.getAllowedAddMenuItems(node);
    //   const allowDelete = node.type != AXMOrganizationNodeType.Company;
    //   const isPasteAvailable = await this.chartService.isPasteAvailable();
    //   const allowPaste = await this.chartService.allowPaste(node);
    //   //
    //   if (allowedAddItems.length) {
    //     e.items.push({
    //       text: 'Add New',
    //       icon: 'fa-light fa-plus',
    //       items: allowedAddItems,
    //       break: allowDelete,
    //     });
    //   }
    //   //
    //   if (allowDelete) {
    //     e.items.push({
    //       name: 'cut',
    //       text: 'Cut',
    //       icon: 'fa-light fa-cut',
    //       data: node,
    //     });
    //     e.items.push({
    //       name: 'copy',
    //       text: 'Copy',
    //       icon: 'fa-light fa-copy',
    //       data: node,
    //       break: !isPasteAvailable,
    //     });
    //   }
    //   if (isPasteAvailable) {
    //     e.items.push({
    //       name: 'paste',
    //       text: 'Paste',
    //       icon: 'fa-light fa-paste',
    //       data: node,
    //       break: true,
    //       disabled: !allowPaste,
    //     });
    //   }
    //   //
    //   if (allowDelete) {
    //     e.items.push({
    //       name: 'remove',
    //       text: 'Remove',
    //       color: 'danger',
    //       icon: 'fa-light fa-trash-can',
    //       data: node,
    //     });
    //   }
    //   //
    //   if (e.items.length == 0) {
    //     e.canceled = true;
    //   }
    // }
    async handleContextMenuItemClick(e) {
    }
    //#endregion
    /**
     * Prints the organizational chart.
     */
    async printChart() {
        let [panX, panY, panZoomLevel] = [this.panX(), this.panY(), this.panZoomLevel()];
        this.panX.set(0), this.panY.set(0), this.panZoomLevel.set(100);
        await this.chartService.printChart(this.treeContainer().nativeElement);
        this.panX.set(panX), this.panY.set(panY), this.panZoomLevel.set(panZoomLevel);
    }
    /**
     * Gets the node colors based on the provided color.
     * @param color - The color to use for the node.
     * @returns An object containing the node's background, text, and border colors.
     */
    getNodeColors(color) {
        if (color.includes('surface')) {
            return {
                '--node-bg-color': `var(--ax-sys-color-${color})`,
                '--node-text-color': `var(--ax-sys-color-on-${color})`,
                '--node-border-color': `var(--ax-sys-color-border-${color})`,
            };
        }
        return {
            '--node-bg-color': `var(--ax-sys-color-${color}-surface)`,
            '--node-text-color': `var(--ax-sys-color-on-${color}-surface)`,
            '--node-border-color': `var(--ax-sys-color-border-${color}-surface)`,
        };
    }
    updateVar(oldValue, newValue) {
        oldValue.cat = newValue;
    }
    async getPageTitle() {
        return await this.translateService.translateAsync('@organization-management:chart.page-title');
    }
    async getPageDescription() {
        return await this.translateService.translateAsync('@organization-management:chart.page-description');
    }
    async getSecondaryMenuItems() {
        return [
            {
                ...getActionButton('print'),
                command: {
                    name: 'print',
                },
            },
            {
                ...getActionButton('refresh'),
                command: {
                    name: 'refresh',
                },
            }
        ];
    }
    async getPageBreadcrumbs() {
        return [
            {
                title: await this.translateService.translateAsync('@organization-management:root-menu')
            },
        ];
    }
    async execute(command) {
        if (command.name == 'print') {
            await this.printChart();
        }
        if (command.name == 'refresh') {
            await this.chartService.generate();
            await this.refresh();
        }
    }
    ngOnDestroy() {
        this.clearChart(this.treeContainer().nativeElement);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMOrgChartPage, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.4", type: AXMOrgChartPage, isStandalone: true, selector: "ng-component", providers: [
            AXMOrgChartService,
            {
                provide: AXPPageLayoutBase,
                useExisting: AXMOrgChartPage
            }
        ], viewQueries: [{ propertyName: "nodeTemplate", first: true, predicate: ["nodeTemplate"], descendants: true, isSignal: true }, { propertyName: "treeContainer", first: true, predicate: ["chart"], descendants: true, isSignal: true }, { propertyName: "parent", first: true, predicate: ["parent"], descendants: true, isSignal: true }, { propertyName: "contextMenu", first: true, predicate: AXContextMenuComponent, descendants: true, isSignal: true }, { propertyName: "panView", first: true, predicate: AXPanViewDirective, descendants: true, isSignal: true }], usesInheritance: true, ngImport: i0, template: "<axp-page-layout *translate=\"let t\">\n  <axp-page-content class=\"ax-overflow-hidden\">\n    <div class=\"ax-h-[calc(100vh-290px)]\" #parent id=\"parent\">\n      <div\n        #chart\n        axPanView\n        [(panX)]=\"panX\"\n        [(panY)]=\"panY\"\n        [freeMode]=\"true\"\n        [(zoom)]=\"panZoomLevel\"\n        [fitContent]=\"true\"\n        wrapperClasses=\"h\"\n        class=\"ax-light\"\n      ></div>\n      <!-- <ax-context-menu\n        [target]=\"'.axp-chart-node'\"\n        [orientation]=\"'vertical'\"\n        [closeOn]=\"'leave'\"\n        (onItemClick)=\"handleContextMenuItemClick($event)\"\n        (onOpening)=\"handleContextMenuOnOpening($event)\"\n      >\n      </ax-context-menu> -->\n    </div>\n  </axp-page-content>\n  <axp-page-footer>\n    <axp-layout-prefix>\n      <div class=\"ax-flex ax-gap-1 ax-light ax-flex-wrap ax-justify-center\">\n        @let v = {cat:'Company'}; @for (item of nodeTypes; track $index) {\n        <div class=\"axp-node-hint\" [style]=\"getNodeColors(item.color)\" [class.ax-ms-4]=\"v.cat!=item.category\">\n          <div class=\"--badge\"></div>\n          {{item.title}}\n        </div>\n        {{updateVar(v, item.category)}} }\n      </div>\n    </axp-layout-prefix>\n    <axp-layout-suffix>\n      <div class=\"ax-flex ax-gap-2\">\n        <ax-button (onClick)=\"zoomOut()\">\n          <ax-icon class=\"fa-solid fa-minus\"> </ax-icon>\n        </ax-button>\n        <ax-button [text]=\"panZoomLevel()\" (onClick)=\"zoomReset()\"></ax-button>\n        <ax-button (onClick)=\"zoomIn()\">\n          <ax-icon class=\"fa-solid fa-add\"> </ax-icon>\n        </ax-button>\n        <ax-button (onClick)=\"toggleFullscreen()\">\n          <ax-icon>\n            <i class=\"fa-solid\" [class]=\"isFullscreen()? 'fa-compress' : 'fa-expand'\"></i>\n          </ax-icon>\n        </ax-button>\n      </div>\n    </axp-layout-suffix>\n  </axp-page-footer>\n</axp-page-layout>\n\n<ng-template #nodeTemplate let-data>\n  <div>\n    @switch (data.category) {\n    <!-- Company -->\n    @case (NodeTypes.Company) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'primary' }\"></ng-container>\n    }\n    <!-- Location -->\n    @case (NodeTypes.Country) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent1' }\"></ng-container>\n    } @case (NodeTypes.State) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent1' }\"></ng-container>\n    } @case (NodeTypes.City) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent1' }\"></ng-container>\n    }\n    <!-- BusinessUnit -->\n    @case (NodeTypes.Division) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent2' }\"></ng-container>\n    } @case (NodeTypes.Department) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent2' }\"></ng-container>\n    } @case (NodeTypes.Branch) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent2' }\"></ng-container>\n    }\n    <!-- Role -->\n    @case (NodeTypes.Position) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent3' }\"></ng-container>\n    }\n    <!-- Employee -->\n    @case (NodeTypes.Employee) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'surface' }\"></ng-container>\n    } }\n  </div>\n</ng-template>\n\n<!----------------------------------- General Node Template ----------------------------------->\n<ng-template #generalTemplate let-data=\"data\" let-color=\"color\">\n  <div #node class=\"--node-container\" [style]=\"getNodeColors(color)\">\n    <div class=\"--container\">\n      <div class=\"--heading-container\">\n        <div class=\"--content\">\n          <div class=\"--icon\">\n            <i class=\"fa-light fa-xl fa-fw\" [class]=\"data.icon\"></i>\n          </div>\n          <div class=\"--titles\">\n            <span class=\"--title\" [title]=\"data.title\">{{data.title}}</span>\n            @if(data.subtitle) {\n            <span class=\"--sub-title\" [title]=\"data.subtitle\">{{data.subtitle}}</span>\n            }\n          </div>\n          @if(data?.children?.length){\n          <div class=\"--badge\">\n            <span>{{data?.children?.length ?? 0}}</span>\n          </div>\n          }\n        </div>\n      </div>\n      @if(data.description) {\n      <div class=\"--body-container\">\n        <div class=\"--description\" [class.ax-pb-3]=\"data.children && data.children.length > 0\">\n          <span>{{data.description}}</span>\n        </div>\n      </div>\n      } @if(data.children && data.children.length > 0){\n      <div class=\"--toggle\">\n        <ax-button class=\"ax-xs ax-rounded-sm\" (onClick)=\"toggleNode(data,node)\">\n          <ax-icon icon=\"fa-solid\" [class]=\"data.isExpanded === false ? 'fa-chevron-down' : 'fa-chevron-up'\"></ax-icon>\n        </ax-button>\n      </div>\n      }\n    </div>\n  </div>\n</ng-template>\n", styles: [".axp-node-hint{display:flex;align-items:center;justify-content:center;gap:.25rem;font-size:.75rem;line-height:1rem}.axp-node-hint>div.--badge{background-color:rgba(var(--node-bg-color));color:rgba(var(--node-text-color));display:flex;width:.75rem;height:.75rem;align-items:center;justify-content:center;border-radius:.125rem}.axp-chart-node{display:flex;align-items:center;justify-content:center}.axp-chart-node .--node-container{position:relative;cursor:pointer;--node-bg-color: var(--ax-sys-color-primary-surface);--node-text-color: var(--ax-sys-color-on-primary-surface);--node-border-color: var(--ax-sys-color-border-primary-surface)}.axp-chart-node .--node-container .--container{display:flex;max-height:100%;width:100%;flex-direction:column;overflow:hidden;border-radius:.375rem;border-width:1px;--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow);border-color:rgba(var(--node-border-color))}.axp-chart-node .--node-container .--container .--heading-container{background-color:rgba(var(--node-bg-color));color:rgba(var(--node-text-color));width:100%;padding:.5rem .75rem}.axp-chart-node .--node-container .--container .--heading-container .--content{display:flex;width:100%;align-items:center;justify-content:center;gap:.5rem;overflow:hidden}.axp-chart-node .--node-container .--container .--heading-container .--content .--icon{background-color:color-mix(in srgb,rgba(var(--node-bg-color),1) 85%,black);display:flex;width:2.75rem;height:2.75rem;flex:none;align-items:center;justify-content:center;border-radius:.5rem}.axp-chart-node .--node-container .--container .--heading-container .--content .--badge{background-color:color-mix(in srgb,rgba(var(--node-bg-color),1) 85%,black);display:flex;width:1.5rem;height:1.5rem;flex:none;align-items:center;justify-content:center;border-radius:.375rem;line-height:1}.axp-chart-node .--node-container .--container .--heading-container .--content .--badge>span{font-size:.75rem;line-height:1rem}.axp-chart-node .--node-container .--container .--heading-container .--content .--titles{display:flex;width:100%;flex:1 1 0%;flex-direction:column;overflow:hidden}.axp-chart-node .--node-container .--container .--heading-container .--content .--titles .--title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:1.125rem;line-height:1.75rem;font-weight:600}.axp-chart-node .--node-container .--container .--heading-container .--content .--titles .--sub-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:.75rem;line-height:1rem;opacity:.85}.axp-chart-node .--node-container .--container .--body-container{width:100%;--tw-bg-opacity: 1;background-color:rgba(var(--ax-sys-color-lightest-surface),var(--tw-bg-opacity, 1));padding:.5rem .75rem;--tw-text-opacity: 1;color:rgba(var(--ax-sys-color-on-lightest-surface),var(--tw-text-opacity, 1))}.axp-chart-node .--node-container .--container .--body-container .--description{text-align:center;font-size:.875rem;line-height:1rem;opacity:.85}.axp-chart-node .--node-container .--container .--toggle{position:absolute;left:0;right:0;bottom:-.75rem;display:flex;width:100%;-webkit-user-select:none;-moz-user-select:-moz-none;user-select:none;align-items:center;justify-content:center}#parent:fullscreen{background-color:rgba(var(--ax-sys-color-primary-lightest-surface))}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "ngmodule", type: RouterModule }, { kind: "ngmodule", type: 
                //
                AXMenuModule }, { kind: "ngmodule", type: AXButtonModule }, { kind: "component", type: i2.AXButtonComponent, selector: "ax-button", inputs: ["disabled", "size", "tabIndex", "color", "look", "text", "toggleable", "selected", "iconOnly", "type", "loadingText"], outputs: ["onBlur", "onFocus", "onClick", "selectedChange", "toggleableChange", "lookChange", "colorChange", "disabledChange", "loadingTextChange"] }, { kind: "ngmodule", type: AXDropdownButtonModule }, { kind: "ngmodule", type: AXTranslationModule }, { kind: "directive", type: i3.AXTranslatorDirective, selector: "[translate]" }, { kind: "ngmodule", type: AXDecoratorModule }, { kind: "component", type: i4.AXDecoratorIconComponent, selector: "ax-icon", inputs: ["icon"] }, { kind: "directive", type: AXPanViewDirective, selector: "[axPanView]", inputs: ["zoomStep", "minZoom", "maxZoom", "freeMode", "fitContent", "disablePan", "disableZoom", "wrapperClasses", "panX", "panY", "zoom"], outputs: ["panXChange", "panYChange", "zoomChange", "positionChange"], exportAs: ["axPanView"] }, { kind: "ngmodule", type: AXLoadingModule }, { kind: "ngmodule", type: AXBreadcrumbsModule }, { kind: "ngmodule", type: AXBadgeModule }, { kind: "component", type: 
                //
                AXPThemeLayoutBlockComponent, selector: "    axp-page-content,     axp-page-footer-container,    axp-page-footer,    axp-page-header,    axp-page-header-container,    axp-page-toolbar,    axp-layout-content,     axp-layout-page-content,     axp-layout-sections,    axp-layout-body,    axp-layout-page-body,    axp-layout-prefix,    axp-layout-suffix,    axp-layout-title-bar,    axp-layout-title,     axp-layout-title-actions,     axp-layout-nav-button,     axp-layout-description,     axp-layout-breadcrumbs,    axp-layout-list-action,    " }, { kind: "component", type: AXPPageLayoutComponent, selector: "axp-page-layout" }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMOrgChartPage, decorators: [{
            type: Component,
            args: [{ imports: [
                        CommonModule,
                        RouterModule,
                        //
                        AXMenuModule,
                        AXButtonModule,
                        AXDropdownButtonModule,
                        AXTranslationModule,
                        AXDecoratorModule,
                        AXPanViewDirective,
                        AXLoadingModule,
                        AXBreadcrumbsModule,
                        AXBadgeModule,
                        //
                        AXPThemeLayoutBlockComponent,
                        AXPPageLayoutComponent,
                    ], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [
                        AXMOrgChartService,
                        {
                            provide: AXPPageLayoutBase,
                            useExisting: AXMOrgChartPage
                        }
                    ], template: "<axp-page-layout *translate=\"let t\">\n  <axp-page-content class=\"ax-overflow-hidden\">\n    <div class=\"ax-h-[calc(100vh-290px)]\" #parent id=\"parent\">\n      <div\n        #chart\n        axPanView\n        [(panX)]=\"panX\"\n        [(panY)]=\"panY\"\n        [freeMode]=\"true\"\n        [(zoom)]=\"panZoomLevel\"\n        [fitContent]=\"true\"\n        wrapperClasses=\"h\"\n        class=\"ax-light\"\n      ></div>\n      <!-- <ax-context-menu\n        [target]=\"'.axp-chart-node'\"\n        [orientation]=\"'vertical'\"\n        [closeOn]=\"'leave'\"\n        (onItemClick)=\"handleContextMenuItemClick($event)\"\n        (onOpening)=\"handleContextMenuOnOpening($event)\"\n      >\n      </ax-context-menu> -->\n    </div>\n  </axp-page-content>\n  <axp-page-footer>\n    <axp-layout-prefix>\n      <div class=\"ax-flex ax-gap-1 ax-light ax-flex-wrap ax-justify-center\">\n        @let v = {cat:'Company'}; @for (item of nodeTypes; track $index) {\n        <div class=\"axp-node-hint\" [style]=\"getNodeColors(item.color)\" [class.ax-ms-4]=\"v.cat!=item.category\">\n          <div class=\"--badge\"></div>\n          {{item.title}}\n        </div>\n        {{updateVar(v, item.category)}} }\n      </div>\n    </axp-layout-prefix>\n    <axp-layout-suffix>\n      <div class=\"ax-flex ax-gap-2\">\n        <ax-button (onClick)=\"zoomOut()\">\n          <ax-icon class=\"fa-solid fa-minus\"> </ax-icon>\n        </ax-button>\n        <ax-button [text]=\"panZoomLevel()\" (onClick)=\"zoomReset()\"></ax-button>\n        <ax-button (onClick)=\"zoomIn()\">\n          <ax-icon class=\"fa-solid fa-add\"> </ax-icon>\n        </ax-button>\n        <ax-button (onClick)=\"toggleFullscreen()\">\n          <ax-icon>\n            <i class=\"fa-solid\" [class]=\"isFullscreen()? 'fa-compress' : 'fa-expand'\"></i>\n          </ax-icon>\n        </ax-button>\n      </div>\n    </axp-layout-suffix>\n  </axp-page-footer>\n</axp-page-layout>\n\n<ng-template #nodeTemplate let-data>\n  <div>\n    @switch (data.category) {\n    <!-- Company -->\n    @case (NodeTypes.Company) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'primary' }\"></ng-container>\n    }\n    <!-- Location -->\n    @case (NodeTypes.Country) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent1' }\"></ng-container>\n    } @case (NodeTypes.State) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent1' }\"></ng-container>\n    } @case (NodeTypes.City) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent1' }\"></ng-container>\n    }\n    <!-- BusinessUnit -->\n    @case (NodeTypes.Division) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent2' }\"></ng-container>\n    } @case (NodeTypes.Department) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent2' }\"></ng-container>\n    } @case (NodeTypes.Branch) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent2' }\"></ng-container>\n    }\n    <!-- Role -->\n    @case (NodeTypes.Position) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'accent3' }\"></ng-container>\n    }\n    <!-- Employee -->\n    @case (NodeTypes.Employee) {\n    <ng-container *ngTemplateOutlet=\"generalTemplate; context: {  data,color:'surface' }\"></ng-container>\n    } }\n  </div>\n</ng-template>\n\n<!----------------------------------- General Node Template ----------------------------------->\n<ng-template #generalTemplate let-data=\"data\" let-color=\"color\">\n  <div #node class=\"--node-container\" [style]=\"getNodeColors(color)\">\n    <div class=\"--container\">\n      <div class=\"--heading-container\">\n        <div class=\"--content\">\n          <div class=\"--icon\">\n            <i class=\"fa-light fa-xl fa-fw\" [class]=\"data.icon\"></i>\n          </div>\n          <div class=\"--titles\">\n            <span class=\"--title\" [title]=\"data.title\">{{data.title}}</span>\n            @if(data.subtitle) {\n            <span class=\"--sub-title\" [title]=\"data.subtitle\">{{data.subtitle}}</span>\n            }\n          </div>\n          @if(data?.children?.length){\n          <div class=\"--badge\">\n            <span>{{data?.children?.length ?? 0}}</span>\n          </div>\n          }\n        </div>\n      </div>\n      @if(data.description) {\n      <div class=\"--body-container\">\n        <div class=\"--description\" [class.ax-pb-3]=\"data.children && data.children.length > 0\">\n          <span>{{data.description}}</span>\n        </div>\n      </div>\n      } @if(data.children && data.children.length > 0){\n      <div class=\"--toggle\">\n        <ax-button class=\"ax-xs ax-rounded-sm\" (onClick)=\"toggleNode(data,node)\">\n          <ax-icon icon=\"fa-solid\" [class]=\"data.isExpanded === false ? 'fa-chevron-down' : 'fa-chevron-up'\"></ax-icon>\n        </ax-button>\n      </div>\n      }\n    </div>\n  </div>\n</ng-template>\n", styles: [".axp-node-hint{display:flex;align-items:center;justify-content:center;gap:.25rem;font-size:.75rem;line-height:1rem}.axp-node-hint>div.--badge{background-color:rgba(var(--node-bg-color));color:rgba(var(--node-text-color));display:flex;width:.75rem;height:.75rem;align-items:center;justify-content:center;border-radius:.125rem}.axp-chart-node{display:flex;align-items:center;justify-content:center}.axp-chart-node .--node-container{position:relative;cursor:pointer;--node-bg-color: var(--ax-sys-color-primary-surface);--node-text-color: var(--ax-sys-color-on-primary-surface);--node-border-color: var(--ax-sys-color-border-primary-surface)}.axp-chart-node .--node-container .--container{display:flex;max-height:100%;width:100%;flex-direction:column;overflow:hidden;border-radius:.375rem;border-width:1px;--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow);border-color:rgba(var(--node-border-color))}.axp-chart-node .--node-container .--container .--heading-container{background-color:rgba(var(--node-bg-color));color:rgba(var(--node-text-color));width:100%;padding:.5rem .75rem}.axp-chart-node .--node-container .--container .--heading-container .--content{display:flex;width:100%;align-items:center;justify-content:center;gap:.5rem;overflow:hidden}.axp-chart-node .--node-container .--container .--heading-container .--content .--icon{background-color:color-mix(in srgb,rgba(var(--node-bg-color),1) 85%,black);display:flex;width:2.75rem;height:2.75rem;flex:none;align-items:center;justify-content:center;border-radius:.5rem}.axp-chart-node .--node-container .--container .--heading-container .--content .--badge{background-color:color-mix(in srgb,rgba(var(--node-bg-color),1) 85%,black);display:flex;width:1.5rem;height:1.5rem;flex:none;align-items:center;justify-content:center;border-radius:.375rem;line-height:1}.axp-chart-node .--node-container .--container .--heading-container .--content .--badge>span{font-size:.75rem;line-height:1rem}.axp-chart-node .--node-container .--container .--heading-container .--content .--titles{display:flex;width:100%;flex:1 1 0%;flex-direction:column;overflow:hidden}.axp-chart-node .--node-container .--container .--heading-container .--content .--titles .--title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:1.125rem;line-height:1.75rem;font-weight:600}.axp-chart-node .--node-container .--container .--heading-container .--content .--titles .--sub-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:.75rem;line-height:1rem;opacity:.85}.axp-chart-node .--node-container .--container .--body-container{width:100%;--tw-bg-opacity: 1;background-color:rgba(var(--ax-sys-color-lightest-surface),var(--tw-bg-opacity, 1));padding:.5rem .75rem;--tw-text-opacity: 1;color:rgba(var(--ax-sys-color-on-lightest-surface),var(--tw-text-opacity, 1))}.axp-chart-node .--node-container .--container .--body-container .--description{text-align:center;font-size:.875rem;line-height:1rem;opacity:.85}.axp-chart-node .--node-container .--container .--toggle{position:absolute;left:0;right:0;bottom:-.75rem;display:flex;width:100%;-webkit-user-select:none;-moz-user-select:-moz-none;user-select:none;align-items:center;justify-content:center}#parent:fullscreen{background-color:rgba(var(--ax-sys-color-primary-lightest-surface))}\n"] }]
        }] });

export { AXMOrgChartPage };
//# sourceMappingURL=acorex-modules-organization-management-org-chart.page-CD9kyK0Z.mjs.map
