import { __decorate, __metadata } from "tslib";
import '@operato/data-grist';
import { CommonButtonStyles, CommonHeaderStyles, CommonGristStyles, ScrollbarStyles } from '@operato/styles';
import { PageView, store } from '@operato/shell';
import { css, html } from 'lit';
import { customElement, property, query } from 'lit/decorators.js';
import { ScopedElementsMixin } from '@open-wc/scoped-elements';
import { DataGrist } from '@operato/data-grist';
import { client } from '@operato/graphql';
import { i18next, localize } from '@operato/i18n';
import { notify } from '@operato/layout';
import { isMobileDevice } from '@operato/utils';
import { connect } from 'pwa-helpers/connect-mixin';
import gql from 'graphql-tag';
let NotificationListPage = class NotificationListPage extends connect(store)(localize(i18next)(ScopedElementsMixin(PageView))) {
    constructor() {
        super(...arguments);
        this.mode = isMobileDevice() ? 'CARD' : 'GRID';
    }
    get context() {
        var _a;
        return {
            title: i18next.t('title.notification list'),
            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: 'notification/notification',
            actions: [
                Object.assign({ title: i18next.t('button.save'), action: this._updateNotification.bind(this) }, CommonButtonStyles.save),
                Object.assign({ title: i18next.t('button.delete'), action: this._deleteNotification.bind(this) }, CommonButtonStyles.delete)
            ]
        };
    }
    render() {
        const mode = this.mode || (isMobileDevice() ? 'CARD' : 'GRID');
        return html `
      <ox-grist .mode=${mode} .config=${this.gristConfig} .fetchHandler=${this.fetchHandler.bind(this)}>
        <div slot="headroom" class="header">
          <div class="filters">
            <ox-filters-form autofocus></ox-filters-form>

            <div id="modes">
              <md-icon @click=${() => (this.mode = 'GRID')} ?active=${mode == 'GRID'}>grid_on</md-icon>
              <md-icon @click=${() => (this.mode = 'LIST')} ?active=${mode == 'LIST'}>format_list_bulleted</md-icon>
              <md-icon @click=${() => (this.mode = 'CARD')} ?active=${mode == 'CARD'}>apps</md-icon>
            </div>
          </div>
        </div>
      </ox-grist>
    `;
    }
    async pageInitialized(lifecycle) {
        this.gristConfig = {
            list: {
                fields: ['title', 'body'],
                details: ['state', 'updatedAt']
            },
            columns: [
                { type: 'gutter', gutterName: 'sequence' },
                { type: 'gutter', gutterName: 'row-selector', multiple: true },
                {
                    type: 'string',
                    name: 'title',
                    header: i18next.t('field.title'),
                    record: {
                        editable: false
                    },
                    filter: 'search',
                    sortable: true,
                    width: 150
                },
                {
                    type: 'string',
                    name: 'body',
                    header: i18next.t('field.body'),
                    record: {
                        editable: false
                    },
                    filter: 'search',
                    width: 200
                },
                {
                    type: 'checkbox',
                    name: 'state',
                    label: true,
                    header: i18next.t('field.state'),
                    record: {
                        editable: true
                    },
                    filter: true,
                    sortable: true,
                    width: 60
                },
                {
                    type: 'datetime',
                    name: 'createdAt',
                    header: i18next.t('field.created_at'),
                    record: {
                        editable: false
                    },
                    sortable: true,
                    width: 180
                }
            ],
            rows: {
                selectable: {
                    multiple: true
                }
            },
            sorters: [
                {
                    name: 'createdAt',
                    desc: true
                }
            ]
        };
    }
    async pageUpdated(changes, lifecycle) {
        if (this.active) {
            // do something here when this page just became as active
        }
    }
    async fetchHandler({ page = 1, limit = 100, sortings = [], filters = [] }) {
        const response = await client.query({
            query: gql `
        query ($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          responses: notiBoxes(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              title
              body
              state
              createdAt
            }
            total
          }
        }
      `,
            variables: {
                filters,
                pagination: { page, limit },
                sortings
            }
        });
        return {
            total: response.data.responses.total || 0,
            records: response.data.responses.items || []
        };
    }
    async _deleteNotification() {
        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!]!) {
              deleteNotificationes(ids: $ids)
            }
          `,
                    variables: {
                        ids
                    }
                });
                if (!response.errors) {
                    this.grist.fetch();
                    notify({
                        message: i18next.t('text.info_x_successfully', { x: i18next.t('text.delete') })
                    });
                }
            }
        }
    }
    async _updateNotification() {
        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;
                }
                patchField.cuFlag = patch.__dirty__;
                return patchField;
            });
            const response = await client.mutate({
                mutation: gql `
          mutation ($patches: [NotificationPatch!]!) {
            updateMultipleNotification(patches: $patches) {
              name
            }
          }
        `,
                variables: {
                    patches
                }
            });
            if (!response.errors) {
                this.grist.fetch();
            }
        }
    }
};
NotificationListPage.styles = [
    ScrollbarStyles,
    CommonGristStyles,
    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;
      }

      ox-filters-form {
        flex: 1;
      }
    `
];
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], NotificationListPage.prototype, "gristConfig", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], NotificationListPage.prototype, "mode", void 0);
__decorate([
    query('ox-grist'),
    __metadata("design:type", DataGrist)
], NotificationListPage.prototype, "grist", void 0);
NotificationListPage = __decorate([
    customElement('notification-list-page')
], NotificationListPage);
export { NotificationListPage };
//# sourceMappingURL=notification-list-page.js.map