import { __decorate, __metadata } from "tslib";
import '@material/web/icon/icon.js';
import '@operato/data-grist';
import { CommonButtonStyles, CommonGristStyles, ScrollbarStyles } from '@operato/styles';
import { PageView } from '@operato/shell';
import { css, html } from 'lit';
import { customElement, query, state } 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 gql from 'graphql-tag';
import { openPopup } from '@operato/popup';
import './popup/popup-domain-list';
let OnmList = class OnmList extends localize(i18next)(ScopedElementsMixin(PageView)) {
    constructor() {
        super(...arguments);
        this.onmDomainId = '';
    }
    static { this.styles = [
        ScrollbarStyles,
        CommonGristStyles,
        css `
      :host {
        display: flex;
        flex-direction: row;

        width: 100%;

        --grid-record-emphasized-background-color: red;
        --grid-record-emphasized-color: yellow;
      }

      .onm-list {
        flex: 3;
      }

      .power-plant-list {
        flex: 7;
        overflow-y: auto;
      }
    `
    ]; }
    get context() {
        return {
            title: i18next.t('title.onm-power-plant-management'),
            actions: [
                {
                    title: '다중 생성',
                    action: this.createOnmDomainBindings.bind(this),
                    ...CommonButtonStyles.add
                },
                {
                    title: i18next.t('button.save'),
                    action: this.updateOnmDomainBindings.bind(this),
                    ...CommonButtonStyles.save
                },
                {
                    title: i18next.t('button.delete'),
                    action: this.deleteOnmDomainBindings.bind(this),
                    ...CommonButtonStyles.delete
                }
            ]
        };
    }
    render() {
        return html `
      <div class="onm-list">
        <ox-grist
          class="parent-grist"
          .mode=${'GRID'}
          .config=${this.parentGristConfig}
          .fetchHandler=${this.onmFetchHandler.bind(this)}
        >
        </ox-grist>
      </div>

      <div class="power-plant-list">
        <ox-grist
          class="child-grist"
          .mode=${'GRID'}
          .config=${this.childGristConfig}
          .fetchHandler=${this.powerPlantFetchHandler.bind(this)}
        >
          <div slot="headroom">
            <div id="filters">
              <ox-filters-form autofocus></ox-filters-form>
            </div>
          </div>
        </ox-grist>
      </div>
    `;
    }
    async pageInitialized(lifecycle) {
        this.parentGristConfig = {
            columns: [
                { type: 'gutter', gutterName: 'sequence' },
                { type: 'gutter', gutterName: 'row-selector', multiple: false },
                {
                    type: 'string',
                    name: 'id',
                    hidden: true
                },
                {
                    type: 'string',
                    name: 'name',
                    header: i18next.t('field.domain_name'),
                    filter: 'search',
                    sortable: true,
                    width: 150
                },
                {
                    type: 'string',
                    name: 'description',
                    header: i18next.t('field.description'),
                    filter: 'search',
                    sortable: true,
                    width: 150
                },
                {
                    type: 'string',
                    name: 'ceo',
                    header: i18next.t('field.ceo'),
                    width: 120
                }
            ],
            sorters: [
                {
                    name: 'name'
                }
            ],
            rows: {
                appendable: false,
                selectable: { multiple: false },
                handlers: {
                    click: (columns, data, column, record, rowIndex, field) => {
                        console.log('record', record);
                        this.onmDomainId = record.id;
                        this.childGrist.fetch();
                    },
                    focus: 'select-row-toggle'
                }
            }
        };
        this.childGristConfig = {
            columns: [
                { type: 'gutter', gutterName: 'sequence' },
                { type: 'gutter', gutterName: 'row-selector', multiple: true },
                {
                    type: 'string',
                    name: 'id',
                    hidden: true
                },
                {
                    type: 'resource-object',
                    name: 'name',
                    header: i18next.t('field.domain_name'),
                    filter: 'search',
                    sortable: true,
                    width: 150,
                    record: {
                        editable: true,
                        options: {
                            queryName: 'domains',
                            basicArgs: {
                                filters: [{ name: 'extType', value: 'power-plant', operator: 'eq' }]
                            },
                            columns: [
                                { name: 'id', hidden: true },
                                { name: 'name', header: i18next.t('field.domain_name'), filter: 'search' },
                                { name: 'description', header: i18next.t('field.description'), filter: 'search' },
                                {
                                    name: 'attributes',
                                    header: i18next.t('field.ceo'),
                                    record: { renderer: (value) => value?.ceo || '' }
                                }
                            ]
                        },
                        renderer: (value, _, record) => {
                            record.description = value?.description;
                            record.ceo = value?.attributes?.ceo;
                            return value?.name || '';
                        }
                    }
                },
                {
                    type: 'string',
                    name: 'description',
                    header: i18next.t('field.description'),
                    filter: 'search',
                    sortable: true,
                    width: 150,
                    record: {
                        renderer: (value, _, record) => record?.name?.description || ''
                    }
                },
                {
                    type: 'string',
                    name: 'ceo',
                    header: i18next.t('field.ceo'),
                    width: 120,
                    record: {
                        renderer: (value, _, record) => record?.name?.attributes?.ceo || ''
                    }
                }
            ],
            rows: {
                appendable: true,
                selectable: { multiple: true },
                handlers: { click: 'select-row-toggle' }
            },
            pagination: {
                infinite: true
            },
            sorters: [
                {
                    name: 'name'
                }
            ]
        };
    }
    async pageUpdated(changes, lifecycle) {
        if (this.active) {
            // do something here when this page just became as active
        }
    }
    async onmFetchHandler({ page = 1, limit = 100, sortings = [], filters = [] }) {
        const response = await client.query({
            query: gql `
        query Domains($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          responses: domains(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              description
              attributes
              updatedAt
            }
            total
          }
        }
      `,
            variables: {
                filters: [{ name: 'extType', value: 'onm', operator: 'eq' }],
                pagination: { page, limit },
                sortings
            }
        });
        const records = response.data.responses.items.map(v => ({ ...v, ...v.attributes }));
        return {
            total: response.data.responses.total || 0,
            records
        };
    }
    async powerPlantFetchHandler({ page = 1, limit = 100, sortings = [], filters = [] }) {
        if (!this.onmDomainId) {
            return { total: 0, records: [] };
        }
        const response = await client.query({
            query: gql `
        query domainsByOnmDomainId(
          $onmDomainId: String!
          $filters: [Filter!]
          $pagination: Pagination
          $sortings: [Sorting!]
        ) {
          responses: domainsByOnmDomainId(
            onmDomainId: $onmDomainId
            filters: $filters
            pagination: $pagination
            sortings: $sortings
          ) {
            items {
              id
              updatedAt
              onmDomain {
                id
              }
              powerPlantDomain {
                id
                name
                description
                attributes
              }
            }
            total
          }
        }
      `,
            variables: {
                onmDomainId: this.onmDomainId,
                filters,
                pagination: { page: 0, limit: 0 },
                sortings
            }
        });
        const records = response.data.responses.items.map(v => ({ id: v.id, name: v.powerPlantDomain }));
        return {
            total: response.data.responses.total || 0,
            records
        };
    }
    async updateOnmDomainBindings() {
        let patches = this.childGrist.dirtyRecords;
        const onmDomainId = this.onmDomainId;
        if (patches && patches.length) {
            patches = patches.map(patch => {
                let patchField = patch.id ? { id: patch.id } : {};
                const dirtyFields = patch.__dirtyfields__ || {};
                patchField['onmDomainId'] = onmDomainId;
                patchField['powerPlantDomainId'] = dirtyFields['name'].after.id;
                patchField.cuFlag = patch.__dirty__;
                return patchField;
            });
            const oldIds = this.childGrist.data.records.map((v) => v.name.id);
            patches = patches.filter(v => !oldIds.includes(v.powerPlantDomainId));
            const response = await client.mutate({
                mutation: gql `
          mutation UpdateMultipleOnmDomainBinding($patches: [OnmDomainBindingPatch!]!) {
            updateMultipleOnmDomainBinding(patches: $patches) {
              id
            }
          }
        `,
                variables: {
                    patches
                }
            });
            if (!response.errors) {
                document.dispatchEvent(new CustomEvent('notify', { detail: { message: '저장되었습니다.' } }));
                this.childGrist.fetch();
            }
        }
    }
    async deleteOnmDomainBindings() {
        if (confirm(i18next.t('text.sure_to_x', { x: i18next.t('text.delete') }))) {
            const ids = this.childGrist.selected.map(record => record.id);
            if (ids && ids.length > 0) {
                const response = await client.mutate({
                    mutation: gql `
            mutation DeleteOnmDomainBindings($ids: [String!]!) {
              deleteOnmDomainBindings(ids: $ids)
            }
          `,
                    variables: {
                        ids
                    }
                });
                if (!response.errors) {
                    this.childGrist.fetch();
                    document.dispatchEvent(new CustomEvent('notify', { detail: { message: '삭제되었습니다.' } }));
                }
            }
        }
    }
    createOnmDomainBindings() {
        if (this.parentGrist.selected.length == 0) {
            alert('O&M 도메인을 선택해주세요.');
            return;
        }
        openPopup(html `<popup-domain-list
        @selected=${e => {
            const selected = e.detail;
            if (selected.length > 0) {
                this.childGrist.dirtyData.records = [
                    ...this.childGrist.dirtyData.records,
                    ...selected.map(v => {
                        return {
                            name: { id: v.id, name: v.name, description: v.description },
                            ceo: v.ceo,
                            __dirty__: '+'
                        };
                    })
                ];
                this.childGrist.checkDirties();
            }
        }}
      ></popup-domain-list>`, { size: 'large', title: '도메인 멀티 선택' });
    }
};
__decorate([
    state(),
    __metadata("design:type", Object)
], OnmList.prototype, "parentGristConfig", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], OnmList.prototype, "childGristConfig", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], OnmList.prototype, "onmDomainId", void 0);
__decorate([
    query('ox-grist.parent-grist'),
    __metadata("design:type", DataGrist)
], OnmList.prototype, "parentGrist", void 0);
__decorate([
    query('ox-grist.child-grist'),
    __metadata("design:type", DataGrist)
], OnmList.prototype, "childGrist", void 0);
OnmList = __decorate([
    customElement('onm-list')
], OnmList);
export { OnmList };
//# sourceMappingURL=onm-list.js.map