import { __decorate, __metadata } from "tslib";
import '@operato/data-grist';
import '@operato/context/ox-context-page-toolbar.js';
import './attribute-set-item-list.js';
import gql from 'graphql-tag';
import { css, html } from 'lit';
import { customElement, query, state } from 'lit/decorators.js';
import { connect } from 'pwa-helpers/connect-mixin';
import { DataGrist } from '@operato/data-grist';
import { client } from '@operato/graphql';
import { i18next, localize } from '@operato/i18n';
import { notify, openPopup } from '@operato/layout';
import { PageView, store } from '@operato/shell';
import { CommonHeaderStyles, ScrollbarStyles } from '@operato/styles';
import { isMobileDevice } from '@operato/utils';
let AttributeSetManagementPage = class AttributeSetManagementPage extends connect(store)(localize(i18next)(PageView)) {
    constructor() {
        super(...arguments);
        this.mode = isMobileDevice() ? 'CARD' : 'GRID';
    }
    get context() {
        var _a;
        return {
            title: i18next.t('title.attributes'),
            search: {
                handler: (search) => {
                    this.grist.searchText = search;
                },
                value: ((_a = this.grist) === null || _a === void 0 ? void 0 : _a.searchText) || ''
            },
            filter: {
                handler: () => {
                    this.grist.toggleHeadroom();
                }
            },
            // help: 'system/attribute',
            actions: [
                {
                    title: i18next.t('button.save'),
                    action: this.updateAttributeSet.bind(this),
                    icon: 'save'
                },
                {
                    title: i18next.t('button.delete'),
                    action: this.deleteAttributeSet.bind(this),
                    icon: 'delete'
                }
            ],
            toolbar: false
        };
    }
    render() {
        const mode = this.mode || (isMobileDevice() ? 'CARD' : 'GRID');
        return html `
      <ox-grist
        .mode=${mode}
        .config=${this.gristConfig}
        .fetchHandler=${this.fetchHandler.bind(this)}
        ?url-params-sensitive=${this.active}
      >
        <div slot="headroom" class="header">
          <div class="title">
            <mwc-icon>summarize</mwc-icon>
            ${i18next.t('title.attributes')}
          </div>

          <ox-context-page-toolbar class="actions" .context=${this.context}> </ox-context-page-toolbar>
        </div>
      </ox-grist>
    `;
    }
    async pageInitialized(lifecycle) {
        this.gristConfig = {
            list: {
                fields: ['entity', 'description']
            },
            columns: [
                { type: 'gutter', gutterName: 'sequence' },
                { type: 'gutter', gutterName: 'row-selector', multiple: true },
                {
                    type: 'gutter',
                    gutterName: 'button',
                    title: i18next.t('title.attribute model'),
                    icon: 'reorder',
                    handlers: {
                        click: (columns, data, column, record, rowIndex) => {
                            if (!record.id)
                                return;
                            const popup = openPopup(html ` <attribute-set-item-list .attribute=${record}></attribute-set-item-list> `, {
                                backdrop: true,
                                help: 'attribute/ui/attribute-set-item-list',
                                size: 'large',
                                title: i18next.t('title.attribute-item list')
                            });
                            popup.onclosed = () => {
                                this.grist.fetch();
                            };
                        }
                    }
                },
                {
                    type: 'string',
                    name: 'entity',
                    header: i18next.t('field.entity'),
                    record: {
                        editable: true
                    },
                    filter: 'search',
                    sortable: true,
                    width: 150
                },
                {
                    type: 'string',
                    name: 'description',
                    header: i18next.t('field.description'),
                    record: {
                        editable: true
                    },
                    filter: 'search',
                    width: 200
                },
                {
                    type: 'datetime',
                    name: 'updatedAt',
                    header: i18next.t('field.updated_at'),
                    record: {
                        editable: false
                    },
                    sortable: true,
                    width: 180
                }
            ],
            rows: {
                selectable: {
                    multiple: true
                }
            },
            sorters: [
                {
                    name: 'name'
                }
            ]
        };
    }
    async fetchHandler({ page, limit, sortings = [], filters = [] }) {
        const response = await client.query({
            query: gql `
        query ($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          responses: attributeSets(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              entity
              description
              updatedAt
              items {
                name
                description
                tag
                active
                hidden
                type
                options
              }
            }
            total
          }
        }
      `,
            variables: {
                filters,
                pagination: { page, limit },
                sortings
            }
        });
        return {
            total: response.data.responses.total || 0,
            records: response.data.responses.items || []
        };
    }
    async deleteAttributeSet() {
        if (confirm(i18next.t('text.sure_to_x', { x: i18next.t('text.delete') }))) {
            const ids = this.grist.selected.map(record => record.id);
            if (ids && ids.length > 0) {
                const response = await client.mutate({
                    mutation: gql `
            mutation ($ids: [String!]!) {
              deleteAttributeSets(ids: $ids)
            }
          `,
                    variables: {
                        ids
                    }
                });
                if (!response.errors) {
                    this.grist.fetch();
                    notify({
                        message: i18next.t('text.info_x_successfully', { x: i18next.t('text.delete') })
                    });
                }
            }
        }
    }
    async updateAttributeSet() {
        let patches = this.grist.dirtyRecords;
        if (patches && patches.length) {
            patches = patches.map(patch => {
                let patchField = patch.id ? { id: patch.id } : {};
                const dirtyFields = patch.__dirtyfields__;
                for (let key in dirtyFields) {
                    patchField[key] = dirtyFields[key].after;
                }
                if (patchField['reportTemplate'] instanceof FileList) {
                    patchField['reportTemplate'] = patchField['reportTemplate'][0];
                }
                patchField.cuFlag = patch.__dirty__;
                return patchField;
            });
            const response = await client.mutate({
                mutation: gql `
          mutation ($patches: [AttributeSetPatch!]!) {
            updateMultipleAttributeSet(patches: $patches) {
              entity
            }
          }
        `,
                variables: {
                    patches
                },
                context: {
                    hasUpload: true
                }
            });
            if (!response.errors) {
                this.grist.fetch();
            }
        }
    }
};
AttributeSetManagementPage.styles = [
    ScrollbarStyles,
    CommonHeaderStyles,
    css `
      :host {
        display: flex;

        width: 100%;

        --grid-record-emphasized-background-color: #8b0000;
        --grid-record-emphasized-color: #ff6b6b;
      }

      ox-grist {
        overflow-y: auto;
        flex: 1;
      }
    `
];
__decorate([
    state(),
    __metadata("design:type", Object)
], AttributeSetManagementPage.prototype, "gristConfig", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], AttributeSetManagementPage.prototype, "mode", void 0);
__decorate([
    query('ox-grist'),
    __metadata("design:type", DataGrist)
], AttributeSetManagementPage.prototype, "grist", void 0);
AttributeSetManagementPage = __decorate([
    customElement('attribute-set-management')
], AttributeSetManagementPage);
export { AttributeSetManagementPage };
//# sourceMappingURL=attribute-set-management.js.map