import { AXMCalendarManagementModule } from '@acorex/modules/calendar-management';
import { AXPEntityCommandScope, createAllQueryView, AXPEntityQueryType, AXP_MENU_PROVIDER } from '@acorex/platform/common';
import * as i0 from '@angular/core';
import { inject, Injector, runInInjectionContext, Injectable, NgModule } from '@angular/core';
import { AXP_PERMISSION_DEFINITION_PROVIDER } from '@acorex/platform/auth';
import { ensureListActions, actionExists, AXMEntityCrudServiceImpl, AXP_ENTITY_ACTION_PLUGIN, AXPEntityDefinitionRegistryService, entityMasterDeleteAction, AXP_ENTITY_DEFINITION_LOADER } from '@acorex/platform/layout/entity';
import * as i2 from '@acorex/platform/layout/widget-core';
import { AXPWidgetGroupEnum, AXP_WIDGETS_LAYOUT_CATEGORY, AXPWidgetCoreModule, AXPWidgetsCatalog } from '@acorex/platform/layout/widget-core';
import * as i1 from '@acorex/platform/workflow';
import { AXPWorkflowAction, AXPWorkflowModule } from '@acorex/platform/workflow';
import { AXTranslationService } from '@acorex/core/translation';
import { AXPLayoutBuilderService } from '@acorex/platform/layout/builder';
import { AXP_NAME_PROPERTY, AXP_DATA_PATH_PROPERTY } from '@acorex/platform/layout/widgets';
import { AXPWorkflowTaskProvider, AXP_WORKFLOW_TASK_PROVIDER } from '@acorex/modules/task-management';
import { AXPCommandExecutor, provideCommandSetups } from '@acorex/platform/runtime';

class AXMMenuProvider {
    async provide(context) { }
}

const signPlugin = {
    name: 'sign',
    order: 47,
    apply: (ctx, options) => {
        const opts = options ?? {};
        const field = opts.field && opts.field.trim().length > 0 ? opts.field : 'signatures';
        const displayTitle = opts.title && opts.title.trim().length > 0 ? opts.title : 'Digital Signatures';
        const moduleName = ctx.entity.module;
        const baseEntityName = ctx.entity.name;
        const distributionEntityName = `${baseEntityName}Distribution`;
        if (typeof options?.command === 'string') {
            options.command = {
                name: options.command,
                options: {
                    entity: `${ctx.entity.module}.${ctx.entity.name}`,
                    schemaEntity: ctx,
                },
            };
        }
        else {
            if (options?.command) {
                options.command = {
                    name: options.command.name,
                    options: {
                        entity: `${ctx.entity.module}.${ctx.entity.name}`,
                        schemaEntity: ctx,
                        ...options.command.options,
                    },
                    metadata: options.command.metadata,
                };
            }
        }
        const action = {
            title: '@general:actions.sign.title',
            name: 'sign-entity',
            command: {
                name: 'sign',
                options: {
                    refId: '{{ context.eval("id") }}',
                    refType: `${ctx.entity.module}.${ctx.entity.name}`,
                    viewType: options?.viewType ?? 'none',
                    checkBoxLabel: options?.checkBoxLabel,
                    command: options?.command,
                },
            },
            priority: 'secondary',
            type: 'sign',
            scope: AXPEntityCommandScope.Individual,
            disabled: "{{ (context.eval('signatures') ?? []).filter((x) => x.auditInfo.created.by.id === session.currentUser().id).length > 0 }}",
        };
        // Ensure group and section ids (unique per field)
        const sectionId = `signatures-${field}`;
        const groupIdForProperty = `signatures-${field}`;
        const existingGroups = ctx.groups.list() ?? [];
        if (!existingGroups.some((g) => g.id === groupIdForProperty)) {
            ctx.groups.add({ id: groupIdForProperty, title: displayTitle });
        }
        // Ensure property exists for displaying signatures
        const props = ctx.properties.list();
        if (!props.some((p) => p.name === field)) {
            ctx.properties.add({
                name: field,
                title: displayTitle,
                groupId: groupIdForProperty,
                schema: {
                    dataType: 'string',
                    interface: {
                        type: 'signature-list',
                    },
                },
            });
        }
        // Ensure single view section and property layout exists
        const sectionOrder = 9;
        const colSpan = 12;
        ctx.interfaces.master.single.update((single) => {
            const next = single ?? { title: ctx.entity.title, sections: [], properties: [] };
            next.sections = next.sections ?? [];
            if (!next.sections.some((s) => s.id === sectionId)) {
                next.sections.push({ id: sectionId, title: displayTitle, order: 200 });
            }
            next.properties = next.properties ?? [];
            if (!next.properties.some((p) => p.name === field)) {
                next.properties.push({
                    name: field,
                    layout: {
                        label: { visible: false },
                        positions: { lg: { colSpan, order: sectionOrder } },
                    },
                });
            }
            return next;
        });
        ensureListActions(ctx);
        ctx.interfaces.update((i) => {
            const actions = i.master.list.actions;
            if (!actionExists(actions, action.name ?? '')) {
                actions.push(action);
            }
            const singleActions = i.master.single.actions;
            if (!actionExists(singleActions, action.name ?? '')) {
                singleActions.push(action);
            }
            return i;
        });
        // Stamp normalized config for middleware
        ctx.entity.extensions ??= {};
        ctx.entity.extensions.signatures ??= {};
        ctx.entity.extensions.signatures[field] = { title: displayTitle };
    },
};

/**
 * Action to show document distribution popup
 */
class AXMSignPopupAction extends AXPWorkflowAction {
    constructor() {
        super(...arguments);
        this.translationService = inject(AXTranslationService);
        this.layoutBuilder = inject(AXPLayoutBuilderService);
        this.injector = inject(Injector);
    }
    async execute(context) {
        const refId = context.getVariable('options')['refId'];
        const refType = context.getVariable('options')['refType'];
        const viewType = context.getVariable('options')['viewType'];
        const checkBoxLabel = context.getVariable('options')['checkBoxLabel'] ?? await this.translationService.translateAsync('@general:actions.sign.checkBox.label');
        const signatureLabel = context.getVariable('options')['signatureLabel'] ?? await this.translationService.translateAsync('@general:actions.sign.signature.label');
        const command = context.getVariable('options')['command'];
        const dialogTitle = await this.translationService.translateAsync('@general:actions.sign.title');
        const entityService = runInInjectionContext(this.injector, () => new AXMEntityCrudServiceImpl(`${refType}Signature`));
        const dialogRef = await this.layoutBuilder
            .create()
            .dialog(dialog => {
            dialog
                .setTitle(dialogTitle)
                .setSize('md')
                .setContext({})
                .content(flex => {
                flex
                    .setDirection('column')
                    .formField('@general:actions.sign.title', field => {
                    field.path('signed');
                    // Determine widget type based on viewType
                    if (viewType === 'checkBox') {
                        field.toggleSwitch({
                            label: checkBoxLabel,
                        });
                    }
                    else if (viewType === 'none') {
                        field.customWidget('text-block-layout', {
                            content: signatureLabel,
                        });
                    }
                    else {
                        field.customWidget('signature', {
                            label: checkBoxLabel,
                        });
                    }
                });
            })
                .setActions(actions => {
                actions.cancel('@general:actions.cancel.title');
                const submitAction = {
                    title: '@general:actions.sign.title',
                    color: 'primary',
                    command: typeof command === 'string' ? {
                        name: command,
                    } : command,
                };
                actions.custom(submitAction);
            });
        })
            .show();
        const action = dialogRef.action();
        if (action === 'cancel') {
            context.setOutput('confirmed', 'cancelled');
            dialogRef.close();
            return;
        }
        const ctx = dialogRef.context();
        dialogRef.setLoading(true);
        dialogRef.close();
        const signId = await entityService.insertOne({
            [refType]: refId,
            signed: ctx.signed,
            //  user : session.currentUser(),
            meta: {
                type: viewType,
            },
        });
        if (signId) {
            context.setOutput('confirmed', 'success');
        }
        else {
            context.setOutput('confirmed', 'failed');
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMSignPopupAction, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMSignPopupAction }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMSignPopupAction, decorators: [{
            type: Injectable
        }] });
/**
 * Workflow for distributing documents to users
 */
const AXMSignWorkflow = {
    startStepId: 'show-sign-popup',
    steps: {
        'show-sign-popup': {
            id: 'show-sign-popup',
            action: 'AXMSignPopupAction',
            nextSteps: [
                {
                    conditions: [{ type: 'SINGLE', expression: 'context.getOutput("confirmed") == "success"' }],
                    nextStepId: 'show-success',
                },
                {
                    conditions: [{ type: 'SINGLE', expression: 'context.getOutput("confirmed") == "failed"' }],
                    nextStepId: 'show-error',
                },
            ],
        },
        'show-success': {
            id: 'show-success',
            action: 'AXPToastAction',
            input: {
                color: 'success',
                title: 'general:actions.sign.success.title',
                content: 'general:actions.sign.success.message',
            },
            nextSteps: [
                {
                    conditions: [],
                    nextStepId: 'reload-entity',
                },
            ],
        },
        'show-error': {
            id: 'show-error',
            action: 'AXPToastAction',
            input: {
                color: 'danger',
                title: 'general:actions.sign.error.title',
                content: 'general:actions.sign.error.message',
            },
        },
        'reload-entity': {
            id: 'reload-entity',
            action: 'reload',
        },
    },
};

const AXPSignatureListWidget = {
    name: 'signature-list',
    title: 'Signature List',
    description: 'Displays signature list',
    icon: 'fa-light fa-text',
    categories: AXP_WIDGETS_LAYOUT_CATEGORY,
    groups: [AXPWidgetGroupEnum.EntityWidget],
    type: 'view',
    properties: [AXP_NAME_PROPERTY, AXP_DATA_PATH_PROPERTY],
    components: {
        view: {
            component: () => import('./acorex-modules-workflow-management-signature-list-widget-view.component-B9rKQvol.mjs').then((c) => c.AXPSignatureListWidgetViewComponent),
        },
        edit: {
            component: () => import('./acorex-modules-workflow-management-signature-list-widget-view.component-B9rKQvol.mjs').then((c) => c.AXPSignatureListWidgetViewComponent),
        },
        designer: {
            component: () => import('./acorex-modules-workflow-management-signature-list-widget-designer.component-BLPdpGGv.mjs').then((c) => c.AXPSignatureListWidgetDesignerComponent),
        },
    },
};

class AXMSignPluginModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMSignPluginModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.4", ngImport: i0, type: AXMSignPluginModule, imports: [i1.AXPWorkflowModule, i2.AXPWidgetCoreModule] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMSignPluginModule, providers: [
            { provide: AXP_ENTITY_ACTION_PLUGIN, multi: true, useValue: signPlugin },
            {
                provide: AXP_PERMISSION_DEFINITION_PROVIDER,
                multi: true,
                useFactory: () => {
                    const provider = {
                        define: async (context) => {
                            // Generate permissions for any entity that declared category extension
                            // We can’t scan registry here reliably at bootstrap; rely on generic pattern per module via wildcard
                            // Consumers can still override with module-level providers.
                            // No-op here; permissions will be added when category entity is resolved via provideEntity elsewhere if needed.
                        },
                    };
                    return provider;
                },
            },
        ], imports: [AXPWorkflowModule.forChild({
                actions: {
                    AXMSignPopupAction,
                },
                workflows: {
                    sign: AXMSignWorkflow,
                },
            }),
            AXPWidgetCoreModule.forChild({
                widgets: [AXPSignatureListWidget],
            })] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMSignPluginModule, decorators: [{
            type: NgModule,
            args: [{
                    providers: [
                        { provide: AXP_ENTITY_ACTION_PLUGIN, multi: true, useValue: signPlugin },
                        {
                            provide: AXP_PERMISSION_DEFINITION_PROVIDER,
                            multi: true,
                            useFactory: () => {
                                const provider = {
                                    define: async (context) => {
                                        // Generate permissions for any entity that declared category extension
                                        // We can’t scan registry here reliably at bootstrap; rely on generic pattern per module via wildcard
                                        // Consumers can still override with module-level providers.
                                        // No-op here; permissions will be added when category entity is resolved via provideEntity elsewhere if needed.
                                    },
                                };
                                return provider;
                            },
                        },
                    ],
                    imports: [
                        AXPWorkflowModule.forChild({
                            actions: {
                                AXMSignPopupAction,
                            },
                            workflows: {
                                sign: AXMSignWorkflow,
                            },
                        }),
                        AXPWidgetCoreModule.forChild({
                            widgets: [AXPSignatureListWidget],
                        }),
                    ],
                }]
        }] });

class AXMEntityDistributionProvider {
    constructor() {
        this.injector = inject(Injector);
    }
    preload() {
        return [];
    }
    async get(moduleName, entityName) {
        // Generic per-entity Category provider (works for any module)
        if (entityName.endsWith('Distribution')) {
            const fullKey = `${moduleName}.${entityName}`;
            const dataService = runInInjectionContext(this.injector, () => new AXMEntityCrudServiceImpl(fullKey));
            // Check if base entity has appearance enabled using lazy injection
            const baseEntityName = entityName.replace('Distribution', '');
            let enableAppearance = false;
            let enableMetaDataSelector = false;
            try {
                // Use lazy injection to avoid circular dependency
                const entityRegistry = runInInjectionContext(this.injector, () => {
                    try {
                        return inject(AXPEntityDefinitionRegistryService);
                    }
                    catch {
                        return null;
                    }
                });
                if (entityRegistry) {
                    try {
                        const baseEntity = await entityRegistry.resolve(moduleName, baseEntityName);
                        if (baseEntity?.extensions?.distribution?.enableAppearance) {
                            enableAppearance = true;
                        }
                        if (baseEntity?.extensions?.distribution?.enableMetaDataSelector) {
                            enableMetaDataSelector = true;
                        }
                    }
                    catch (error) {
                        // Base entity not found or error loading, continue with default behavior
                        console.warn(`Could not load base entity ${moduleName}.${baseEntityName} to check category plugin configuration:`, error);
                    }
                }
            }
            catch (error) {
                // Registry not available, continue with default behavior
                console.warn(`Entity registry not available, using default category configuration:`, error);
            }
            const entityDef = {
                module: moduleName,
                name: entityName,
                plugins: [],
                title: '@general:terms.classification.distribution',
                formats: {
                    individual: '@general:terms.classification.distribution',
                    plural: '@general:terms.classification.distributions',
                    searchResult: {
                        title: '{{ title }}',
                        description: '{{ module }}',
                    },
                },
                relatedEntities: [],
                groups: [
                    { id: 'basic-info', title: '@general:terms.interface.basic-info' },
                    ...(enableAppearance ? [{ id: 'appearance', title: '@general:terms.interface.appearance' }] : []),
                ],
                properties: [
                    {
                        name: 'assignedId',
                        title: '@workflow-management:terms.distribution.assignedTo',
                        groupId: 'basic-info',
                        schema: {
                            dataType: 'string', interface: {
                                type: AXPWidgetsCatalog.lookup, options: {
                                    multiple: false,
                                    entity: 'SecurityManagement.User',
                                    textField: 'displayName',
                                    valueField: 'id',
                                    conditions: [],
                                    expose: [
                                        { source: 'id', target: 'assigned.id' },
                                        { source: 'username', target: 'assigned.username' },
                                        { source: 'displayName', target: 'assigned.displayName' },
                                    ],
                                }
                            }
                        },
                        validations: [{ rule: 'required' }],
                    },
                    {
                        name: 'auditInfo.created.at',
                        title: '@workflow-management:terms.distribution.distributionAt',
                        groupId: 'basic-info',
                        schema: {
                            dataType: 'string',
                            interface: {
                                type: AXPWidgetsCatalog.dateTime,
                                options: {},
                            },
                        },
                    },
                    {
                        name: 'viewAt',
                        title: '@workflow-management:terms.distribution.viewAt',
                        groupId: 'basic-info',
                        schema: {
                            dataType: 'string',
                            interface: {
                                type: AXPWidgetsCatalog.dateTime,
                                options: {},
                            },
                        },
                    },
                    {
                        name: 'signedAt',
                        title: '@workflow-management:terms.distribution.signedAt',
                        groupId: 'basic-info',
                        schema: { dataType: 'string', interface: { type: AXPWidgetsCatalog.dateTime } },
                    },
                ],
                columns: [{ name: 'assignedTo', options: { dataPath: 'assigned.displayName' } }, { name: 'viewAt' }, { name: 'signedAt' }],
                commands: {
                    create: { execute: async (data) => ({ id: await dataService.insertOne(data) }) },
                    delete: { execute: async (id) => dataService.deleteOne(id) },
                    update: { execute: async (data) => dataService.updateOne(data.id, data) },
                },
                queries: {
                    byKey: { execute: async (id) => dataService.getOne(id), type: AXPEntityQueryType.Single },
                    list: {
                        execute: async (e) => {
                            const res = await dataService.query(e);
                            console.log(res);
                            return res;
                        },
                        type: AXPEntityQueryType.List,
                    },
                },
                interfaces: {
                    master: {
                        update: {
                            sections: [{ id: 'basic-info' }, ...(enableAppearance ? [{ id: 'appearance' }] : [])],
                            properties: [
                                { name: 'assignedTo', layout: { positions: { lg: { colSpan: 12, order: 2 } } } },
                                { name: 'viewAt', layout: { positions: { lg: { colSpan: 12, order: 3 } } } },
                                { name: 'signedAt', layout: { positions: { lg: { colSpan: 12, order: 4 } } } },
                            ],
                        },
                        single: {
                            title: '{{assignedTo}}',
                            sections: [
                                { id: 'basic-info', layout: { positions: { lg: { colSpan: 12 } } } },
                                ...(enableAppearance ? [{ id: 'appearance', layout: { positions: { lg: { colSpan: 12 } } } }] : []),
                            ],
                            properties: [
                                { name: 'assignedTo', layout: { positions: { lg: { colSpan: 12, order: 2 } } } },
                                { name: 'viewAt', layout: { positions: { lg: { colSpan: 12, order: 3 } } } },
                                { name: 'signedAt', layout: { positions: { lg: { colSpan: 12, order: 4 } } } },
                            ],
                            actions: [entityMasterDeleteAction()],
                        },
                        list: {
                            views: [createAllQueryView({ sorts: [{ name: 'assignedTo', dir: 'asc' }] })],
                        },
                    },
                },
            };
            return entityDef;
        }
        return null;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMEntityDistributionProvider, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMEntityDistributionProvider }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMEntityDistributionProvider, decorators: [{
            type: Injectable
        }] });

const distributionPlugin = {
    name: 'distribution',
    order: 46,
    apply: (ctx, options) => {
        const moduleName = ctx.entity.module;
        const baseEntityName = ctx.entity.name;
        const distributionEntityName = `${moduleName}.${baseEntityName}Distribution`;
        const action = {
            title: '@workflow-management:actions.distribution.title',
            name: 'distribution-entity',
            command: {
                name: 'distribution',
                options: {
                    refId: '{{ context.eval("id") }}',
                    refType: `${ctx.entity.module}.${ctx.entity.name}`,
                },
            },
            priority: 'secondary',
            type: 'distribution',
            scope: AXPEntityCommandScope.Individual,
            // disabled: '{{ context.eval("stateInfo.isDistributed") }}'
        };
        ensureListActions(ctx);
        ctx.interfaces.update((i) => {
            const actions = i.master.list.actions;
            if (!actionExists(actions, action.name ?? '')) {
                actions.push(action);
            }
            const singleActions = i.master.single.actions;
            if (!actionExists(singleActions, action.name ?? '')) {
                singleActions.push(action);
            }
            return i;
        });
        ctx.relatedEntities.add({
            entity: distributionEntityName,
            title: '@workflow-management:terms.classification.distribution',
            columns: ['assignedTo', 'auditInfo.created.at', 'viewAt', 'signedAt'],
            conditions: [
                {
                    name: 'distributionRefId',
                    operator: { type: 'equal' },
                    value: '{{context.eval("id")}}',
                },
            ],
        });
    },
};

/**
 * Action to show document distribution popup
 */
class AXMCommonDistributionPopupAction extends AXPWorkflowAction {
    constructor() {
        super(...arguments);
        this.translationService = inject(AXTranslationService);
        this.layoutBuilder = inject(AXPLayoutBuilderService);
    }
    async execute(context) {
        const dialogTitle = await this.translationService.translateAsync('@general:actions.distribution.title');
        const dialogRef = await this.layoutBuilder
            .create()
            .dialog(dialog => {
            dialog
                .setTitle(dialogTitle)
                .setSize('md')
                .setContext({ assignedTo: [] })
                .content(flex => {
                flex
                    .setDirection('column')
                    .formField('@workflow-management:actions.distribution.title', field => {
                    field.path('assignedTo');
                    field.lookupBox({
                        entity: 'SecurityManagement.User',
                        multiple: true,
                        look: 'lookup',
                        columns: ['username', 'displayName'],
                        validations: [{ rule: 'required' }],
                    });
                });
            })
                .setActions(actions => {
                actions.cancel('@general:actions.cancel.title');
                const submitAction = {
                    title: '@workflow-management:actions.distribution.title',
                    color: 'primary',
                    command: { name: 'submit', options: { validate: true } },
                };
                actions.custom(submitAction);
            });
        })
            .show();
        const action = dialogRef.action();
        if (action === 'cancel') {
            context.setOutput('confirmed', false);
            dialogRef.close();
            return;
        }
        const ctx = dialogRef.context();
        dialogRef.close();
        const confirmed = Array.isArray(ctx?.assignedTo) && ctx.assignedTo.length > 0;
        context.setOutput('confirmed', confirmed);
        if (confirmed) {
            context.setOutput('assignedTo', ctx.assignedTo);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMCommonDistributionPopupAction, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMCommonDistributionPopupAction }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMCommonDistributionPopupAction, decorators: [{
            type: Injectable
        }] });
/**
 * Action to create distribution records and update document status
 */
class AXMCommonCreateDistributionRecordsAction extends AXPWorkflowAction {
    constructor() {
        super(...arguments);
        this.commandExecutor = inject(AXPCommandExecutor);
    }
    async execute(context) {
        const refId = context.getVariable('options.refId');
        const refType = context.getVariable('options.refType');
        const assignedTo = context.getOutput('assignedTo');
        const res = await this.commandExecutor.execute('Distribution:Record', {
            refId,
            refType,
            assignedTo,
        });
        context.setOutput('success', res?.success);
        context.setOutput('message', res?.message);
        context.setOutput('distributionCount', assignedTo.length);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMCommonCreateDistributionRecordsAction, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMCommonCreateDistributionRecordsAction }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMCommonCreateDistributionRecordsAction, decorators: [{
            type: Injectable
        }] });
/**
 * Workflow for distributing documents to users
 */
const AXMCommonDistributionWorkflow = {
    startStepId: 'show-distribution-popup',
    steps: {
        'show-distribution-popup': {
            id: 'show-distribution-popup',
            action: 'AXMCommonDistributionPopupAction',
            nextSteps: [
                {
                    conditions: [{ type: 'SINGLE', expression: 'context.getOutput("confirmed") == true' }],
                    nextStepId: 'create-distributions',
                },
            ],
        },
        'create-distributions': {
            id: 'create-distributions',
            action: 'AXMCommonCreateDistributionRecordsAction',
            nextSteps: [
                {
                    conditions: [{ type: 'SINGLE', expression: 'context.getOutput("success") == true' }],
                    nextStepId: 'show-success',
                },
                {
                    conditions: [{ type: 'SINGLE', expression: 'context.getOutput("success") == false' }],
                    nextStepId: 'show-error',
                },
            ],
        },
        'show-success': {
            id: 'show-success',
            action: 'AXPToastAction',
            input: {
                color: 'success',
                title: '@general:actions.distribution.success.title',
                content: '@general:actions.distribution.success.message',
            },
            nextSteps: [
                {
                    conditions: [],
                    nextStepId: 'reload-entity',
                },
            ],
        },
        'show-error': {
            id: 'show-error',
            action: 'AXPToastAction',
            input: {
                color: 'danger',
                title: 'general:actions.distribution.error.title',
                content: 'general:actions.distribution.error.message',
            },
        },
        'reload-entity': {
            id: 'reload-entity',
            action: 'reload',
        },
    },
};

class AXMPromotionDistributionTaskProvider extends AXPWorkflowTaskProvider {
    constructor() {
        super();
        this.injector = inject(Injector);
        this.commandExecutor = inject(AXPCommandExecutor);
        this.entityKey = 'ContentManagement.Promotion';
    }
    get name() {
        return `${this.entityKey}-distribution`;
    }
    get title() {
        return `${this.entityKey} Distribution`;
    }
    get icon() {
        return 'fa-light fa-file-pen';
    }
    /**
     * Retrieves a list of tasks, optionally filtered by a date range.
     * If a date range is provided in the options, only tasks that overlap with that range will be returned.
     * @param options Filtering options, primarily containing a date range.
     * @returns An array of filtered tasks.
     */
    async getTasks(options) {
        const dataService = runInInjectionContext(this.injector, () => new AXMEntityCrudServiceImpl(this.entityKey));
        const dataServiceDistribution = runInInjectionContext(this.injector, () => new AXMEntityCrudServiceImpl(`${this.entityKey}Distribution`));
        const baseFilter = {
            logic: 'and',
            filters: [],
        };
        baseFilter.filters?.push({
            field: 'stateInfo.isDistributed',
            operator: { type: 'equal' },
            value: true,
        });
        // if (options?.range?.from) {
        //   baseFilter.filters?.push({
        //     field: 'distributionDate',
        //     operator: { type: 'gte' },
        //     value: options!.range!.from,
        //   });
        // }
        // if (options?.range?.end) {
        //   baseFilter.filters?.push({
        //     field: 'distributionDate',
        //     operator: { type: 'lte' },
        //     value: options!.range!.end,
        //   });
        // }
        const filteredList = await dataService.query({
            skip: options?.skip ?? 0,
            take: options?.take ?? 10,
            filter: baseFilter,
        });
        const itemsDistribution = (await dataServiceDistribution.query({
            skip: options?.skip ?? 0,
            take: 1,
            filter: {
                logic: 'and',
                filters: [
                    {
                        field: 'distributionRefId',
                        operator: { type: 'equal' },
                        value: filteredList.items[0].id,
                    },
                ],
            },
        })).items[0];
        return {
            items: filteredList.items.map((item) => ({
                id: item.id,
                title: `${item.title}`,
                startDate: itemsDistribution.auditInfo?.created?.at ?? new Date(),
                endDate: itemsDistribution.dueDate ?? new Date(),
                index: 0,
                status: {
                    id: 0,
                    title: 'Pending',
                },
                priority: 'high',
                reporter: {
                    id: item.auditInfo?.created?.by?.id ?? '',
                    type: 'user',
                    fullName: item.auditInfo?.created?.by?.fullName ?? '',
                },
                data: item,
            })),
            total: filteredList.total,
        };
    }
    /**
     * Updates one or more tasks in the provider's list.
     * This method finds each task by its ID and applies the new properties from the input.
     * It also automatically recalculates the `allDay` flag based on the task's duration.
     * @param tasksToUpdate An array of task objects to update. Each object must have an `id`.
     * @returns An array of the tasks that were successfully updated.
     */
    async updateTasks(tasksToUpdate) {
        console.log(tasksToUpdate);
        return tasksToUpdate;
    }
    async executeCommand(command) {
        if (command.name === 'Distribution:Overview') {
            this.commandExecutor.execute(command.name, command.options);
        }
        return { success: true };
    }
    async getActions(task) {
        const edit = {
            title: '@workflow-management:actions.distribution.sign',
            command: {
                name: 'Distribution:Overview',
                options: {
                    id: task?.id,
                    title: task?.title,
                    refId: task?.data?.id,
                    refType: this.entityKey,
                },
            },
        };
        return [edit];
    }
    async getExtraFields() {
        return [];
    }
    async getStatuses() {
        return [
            { index: 0, key: 'pending', title: 'Pending' },
            { index: 1, key: 'in-progress', title: 'In Progress' },
            { index: 2, key: 'done', title: 'Done' },
            { index: 3, key: 'canceled', title: 'Canceled' },
        ];
    }
}

class AXPDistributionPluginModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXPDistributionPluginModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.4", ngImport: i0, type: AXPDistributionPluginModule, imports: [i1.AXPWorkflowModule] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXPDistributionPluginModule, providers: [
            { provide: AXP_ENTITY_ACTION_PLUGIN, multi: true, useValue: distributionPlugin },
            {
                provide: AXP_PERMISSION_DEFINITION_PROVIDER,
                multi: true,
                useFactory: () => {
                    const provider = {
                        define: async (context) => {
                            // Generate permissions for any entity that declared category extension
                            // We can’t scan registry here reliably at bootstrap; rely on generic pattern per module via wildcard
                            // Consumers can still override with module-level providers.
                            // No-op here; permissions will be added when category entity is resolved via provideEntity elsewhere if needed.
                        },
                    };
                    return provider;
                },
            },
            {
                provide: AXP_ENTITY_DEFINITION_LOADER,
                useClass: AXMEntityDistributionProvider,
                multi: true,
            },
            {
                provide: AXP_WORKFLOW_TASK_PROVIDER,
                useClass: AXMPromotionDistributionTaskProvider,
                multi: true,
            },
            provideCommandSetups([
                {
                    key: 'Distribution:Overview',
                    command: () => import('./acorex-modules-workflow-management-overview.command-C0NWREXN.mjs').then((c) => c.AXMOverviewCommand),
                },
            ])
        ], imports: [AXPWorkflowModule.forChild({
                actions: {
                    AXMCommonDistributionPopupAction,
                    AXMCommonCreateDistributionRecordsAction,
                },
                workflows: {
                    'distribution': AXMCommonDistributionWorkflow,
                },
            })] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXPDistributionPluginModule, decorators: [{
            type: NgModule,
            args: [{
                    providers: [
                        { provide: AXP_ENTITY_ACTION_PLUGIN, multi: true, useValue: distributionPlugin },
                        {
                            provide: AXP_PERMISSION_DEFINITION_PROVIDER,
                            multi: true,
                            useFactory: () => {
                                const provider = {
                                    define: async (context) => {
                                        // Generate permissions for any entity that declared category extension
                                        // We can’t scan registry here reliably at bootstrap; rely on generic pattern per module via wildcard
                                        // Consumers can still override with module-level providers.
                                        // No-op here; permissions will be added when category entity is resolved via provideEntity elsewhere if needed.
                                    },
                                };
                                return provider;
                            },
                        },
                        {
                            provide: AXP_ENTITY_DEFINITION_LOADER,
                            useClass: AXMEntityDistributionProvider,
                            multi: true,
                        },
                        {
                            provide: AXP_WORKFLOW_TASK_PROVIDER,
                            useClass: AXMPromotionDistributionTaskProvider,
                            multi: true,
                        },
                        provideCommandSetups([
                            {
                                key: 'Distribution:Overview',
                                command: () => import('./acorex-modules-workflow-management-overview.command-C0NWREXN.mjs').then((c) => c.AXMOverviewCommand),
                            },
                        ])
                    ],
                    imports: [
                        AXPWorkflowModule.forChild({
                            actions: {
                                AXMCommonDistributionPopupAction,
                                AXMCommonCreateDistributionRecordsAction,
                            },
                            workflows: {
                                'distribution': AXMCommonDistributionWorkflow,
                            },
                        }),
                    ]
                }]
        }] });

class AXMWorkflowManagementModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMWorkflowManagementModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.4", ngImport: i0, type: AXMWorkflowManagementModule, imports: [AXMCalendarManagementModule, AXMSignPluginModule, AXPDistributionPluginModule] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMWorkflowManagementModule, providers: [
            {
                provide: AXP_MENU_PROVIDER,
                useClass: AXMMenuProvider,
                multi: true,
            },
        ], imports: [AXMCalendarManagementModule, AXMSignPluginModule, AXPDistributionPluginModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.4", ngImport: i0, type: AXMWorkflowManagementModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [AXMCalendarManagementModule, AXMSignPluginModule, AXPDistributionPluginModule],
                    providers: [
                        {
                            provide: AXP_MENU_PROVIDER,
                            useClass: AXMMenuProvider,
                            multi: true,
                        },
                    ],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { AXMCommonCreateDistributionRecordsAction, AXMCommonDistributionPopupAction, AXMCommonDistributionWorkflow, AXMMenuProvider, AXMSignPluginModule, AXMSignPopupAction, AXMSignWorkflow, AXMWorkflowManagementModule, AXPDistributionPluginModule, distributionPlugin, signPlugin };
//# sourceMappingURL=acorex-modules-workflow-management.mjs.map
