import { __decorate, __metadata } from "tslib";
import '@operato/data-grist';
import { CommonButtonStyles, CommonGristStyles, ScrollbarStyles } from '@operato/styles';
import { PageView } 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 gql from 'graphql-tag';
let OpenWeatherCityList = class OpenWeatherCityList extends localize(i18next)(ScopedElementsMixin(PageView)) {
    constructor() {
        super(...arguments);
        this.mode = isMobileDevice() ? 'CARD' : 'GRID';
    }
    static { this.styles = [
        ScrollbarStyles,
        CommonGristStyles,
        css `
      :host {
        display: flex;
        flex-direction: column;

        width: 100%;

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

      .title {
        margin: 10px;
      }
    `
    ]; }
    get context() {
        return {
            title: i18next.t('title.open-weather-city-list'),
            search: {
                handler: (search) => {
                    this.grist.searchText = search;
                },
                value: this.grist.searchText
            },
            filter: {
                handler: () => {
                    this.grist.toggleHeadroom();
                }
            },
            help: 'ppms/open-weather-city',
            actions: [
                {
                    title: i18next.t('button.save'),
                    action: this._updateOpenWeatherCity.bind(this),
                    ...CommonButtonStyles.save
                },
                {
                    title: i18next.t('button.delete'),
                    action: this._deleteOpenWeatherCity.bind(this),
                    ...CommonButtonStyles.delete
                }
            ]
        };
    }
    render() {
        const mode = this.mode || (isMobileDevice() ? 'CARD' : 'GRID');
        return html `
      <div class="title">1시간 마다 업데이트할 OPEN WEATHER API 도시 목록</div>

      <ox-grist .mode=${mode} .config=${this.gristConfig} .fetchHandler=${this.fetchHandler.bind(this)}>
        <div slot="headroom">
          <div id="filters">
            <ox-filters-form autofocus></ox-filters-form>
          </div>
        </div>
      </ox-grist>
    `;
    }
    async pageInitialized(lifecycle) {
        this.gristConfig = {
            list: {
                fields: ['cityName', 'cityId'],
                details: ['updatedAt']
            },
            columns: [
                { type: 'gutter', gutterName: 'sequence' },
                { type: 'gutter', gutterName: 'row-selector', multiple: true },
                {
                    type: 'string',
                    name: 'cityName',
                    header: i18next.t('field.cityName'),
                    record: { editable: true },
                    filter: 'search',
                    width: 150
                },
                {
                    type: 'string',
                    name: 'cityId',
                    header: i18next.t('field.cityId'),
                    record: { editable: true },
                    filter: 'search',
                    width: 200
                },
                {
                    type: 'resource-object',
                    name: 'updater',
                    header: i18next.t('field.updater'),
                    record: { editable: false },
                    width: 120
                },
                {
                    type: 'datetime',
                    name: 'updatedAt',
                    header: i18next.t('field.updated_at'),
                    record: { editable: false },
                    width: 180
                }
            ],
            rows: {
                selectable: {
                    multiple: true
                }
            },
            sorters: [{ name: 'cityName' }]
        };
    }
    async pageUpdated(changes, lifecycle) {
        if (this.active) {
            this.grist.fetch();
        }
    }
    async fetchHandler({ page = 1, limit = 100, sortings = [], filters = [] }) {
        const response = await client.query({
            query: gql `
        query ($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          responses: openWeatherCities(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              cityName
              cityId
              updater {
                id
                name
              }
              updatedAt
            }
            total
          }
        }
      `,
            variables: {
                filters,
                pagination: { page, limit },
                sortings: [{ name: 'cityName' }]
            }
        });
        return {
            total: response.data.responses.total || 0,
            records: response.data.responses.items || []
        };
    }
    async _deleteOpenWeatherCity() {
        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!]!) {
              deleteOpenWeatherCities(ids: $ids)
            }
          `,
                    variables: { ids }
                });
                if (!response.errors) {
                    this.grist.fetch();
                    notify({
                        message: i18next.t('text.info_x_successfully', { x: i18next.t('text.delete') })
                    });
                }
            }
        }
    }
    async _updateOpenWeatherCity() {
        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.toString();
                }
                patchField.cuFlag = patch.__dirty__;
                return patchField;
            });
            const response = await client.mutate({
                mutation: gql `
          mutation ($patches: [OpenWeatherCityPatch!]!) {
            updateMultipleOpenWeatherCity(patches: $patches) {
              id
            }
          }
        `,
                variables: { patches }
            });
            if (!response.errors) {
                this.grist.fetch();
            }
        }
    }
};
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], OpenWeatherCityList.prototype, "gristConfig", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], OpenWeatherCityList.prototype, "mode", void 0);
__decorate([
    query('ox-grist'),
    __metadata("design:type", DataGrist)
], OpenWeatherCityList.prototype, "grist", void 0);
OpenWeatherCityList = __decorate([
    customElement('open-weather-city-list')
], OpenWeatherCityList);
export { OpenWeatherCityList };
//# sourceMappingURL=open-weather-city-list.js.map