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';
let PowerPlantList = class PowerPlantList extends localize(i18next)(ScopedElementsMixin(PageView)) {
    static { this.styles = [
        ScrollbarStyles,
        CommonGristStyles,
        css `
      :host {
        display: flex;

        width: 100%;

        --grid-record-emphasized-background-color: red;
        --grid-record-emphasized-color: yellow;
      }
    `
    ]; }
    get context() {
        return {
            title: i18next.t('title.power-plant-list'),
            actions: [
                {
                    title: i18next.t('button.save'),
                    action: this.updatePowerPlans.bind(this),
                    ...CommonButtonStyles.save
                }
            ]
        };
    }
    render() {
        return html `
      <ox-grist .mode=${'GRID'} .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) {
        const weatherAddressList = await this.getWeatherAddressList();
        this.gristConfig = {
            columns: [
                { type: 'gutter', gutterName: 'sequence' },
                { type: 'gutter', gutterName: 'row-selector', multiple: true },
                {
                    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'),
                    record: {
                        editable: true
                    },
                    filter: 'search',
                    sortable: true,
                    width: 150
                },
                {
                    type: 'string',
                    name: 'ceo',
                    header: i18next.t('field.ceo'),
                    record: {
                        editable: true
                    },
                    width: 120
                },
                {
                    type: 'string',
                    name: 'phone',
                    header: i18next.t('field.phone'),
                    record: {
                        editable: true
                    },
                    width: 120
                },
                {
                    type: 'string',
                    name: 'safetyManager',
                    header: i18next.t('field.safety_manager_name'),
                    record: {
                        editable: true
                    },
                    width: 120
                },
                {
                    type: 'string',
                    name: 'phone2',
                    header: i18next.t('field.phone2'),
                    record: {
                        editable: true
                    },
                    width: 120
                },
                {
                    type: 'string',
                    name: 'phone3',
                    header: i18next.t('field.phone3'),
                    record: {
                        editable: true
                    },
                    width: 120
                },
                {
                    type: 'string',
                    name: 'email',
                    header: i18next.t('field.email'),
                    record: {
                        editable: true
                    },
                    width: 150
                },
                {
                    type: 'string',
                    name: 'ppname',
                    header: i18next.t('field.ppname'),
                    record: {
                        editable: true
                    },
                    width: 150
                },
                {
                    type: 'string',
                    name: 'brn',
                    header: i18next.t('field.brn'),
                    record: {
                        editable: true
                    },
                    width: 150
                },
                {
                    type: 'date',
                    name: 'startDate',
                    header: i18next.t('field.start_date'),
                    record: {
                        editable: true
                    },
                    width: 150
                },
                {
                    type: 'string',
                    name: 'postalCode',
                    header: i18next.t('field.postal_code'),
                    record: {
                        editable: true
                    },
                    width: 100
                },
                {
                    type: 'float',
                    name: 'capacity',
                    header: i18next.t('field.capacity'),
                    record: {
                        editable: true
                    },
                    width: 100
                },
                {
                    type: 'select',
                    name: 'biztype',
                    header: i18next.t('field.biztype'),
                    record: {
                        editable: true,
                        options: [
                            { value: 'Individual', display: '개인' },
                            { value: 'Corporation', display: '법인' }
                        ]
                    },
                    width: 150
                },
                {
                    type: 'string',
                    name: 'address',
                    header: i18next.t('field.address'),
                    record: {
                        editable: true
                    },
                    width: 200
                },
                {
                    type: 'select',
                    name: 'weatherId',
                    header: i18next.t('field.weather'),
                    record: {
                        editable: true,
                        options: [{ value: '', display: '' }, ...weatherAddressList]
                    },
                    width: 150
                },
                {
                    type: 'float',
                    name: 'rec',
                    header: i18next.t('field.rec'),
                    record: {
                        editable: true
                    },
                    width: 100
                },
                {
                    type: 'select',
                    name: 'inverterManufacturer',
                    header: i18next.t('field.inverter_manufacturer'),
                    record: {
                        editable: true,
                        options: [
                            { value: '', display: '' },
                            { value: '솔리스', display: '솔리스' },
                            { value: 'HD현대', display: 'HD현대' },
                            { value: '한화', display: '한화' },
                            { value: 'DASSTECH', display: 'DASSTECH' },
                            { value: 'Kstar', display: 'Kstar' },
                            { value: 'ABB', display: 'ABB' },
                            { value: 'OCI', display: 'OCI' },
                            { value: '효성', display: '효성' },
                            { value: '금비전자', display: '금비전자' },
                            { value: '동양', display: '동양' },
                            { value: 'REFU', display: 'REFU' }
                        ]
                    },
                    width: 150
                },
                {
                    type: 'string',
                    name: 'inverterModel',
                    header: i18next.t('field.inverter_model'),
                    record: {
                        editable: true
                    },
                    width: 150
                },
                {
                    type: 'float',
                    name: 'refreshTime',
                    header: i18next.t('field.refresh_time'),
                    record: {
                        editable: true
                    },
                    width: 180
                },
                {
                    type: 'datetime',
                    name: 'updatedAt',
                    header: i18next.t('field.updated_at'),
                    width: 180
                },
                {
                    type: 'string',
                    name: 'other',
                    header: i18next.t('field.other'),
                    width: 180,
                    record: {
                        editable: true
                    }
                }
            ],
            rows: {
                selectable: {
                    multiple: true
                },
                appendable: false
            },
            sorters: [
                {
                    name: 'name'
                }
            ]
        };
    }
    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 = [] }) {
        console.log('filters :', filters);
        filters.push({
            name: 'extType',
            operator: 'in',
            value: ['power-plant', 'all-power-plant']
        });
        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
              createdAt
              updatedAt
            }
            total
          }
        }
      `,
            variables: {
                filters,
                pagination: { page, limit },
                sortings
            }
        });
        const records = response.data.responses.items.map(v => ({ ...v.attributes, ...v }));
        return {
            total: response.data.responses.total || 0,
            records
        };
    }
    async getWeatherAddressList() {
        const response = await client.query({
            query: gql `
        query OpenWeatherCities {
          openWeatherCities {
            items {
              id
              cityName
            }
          }
        }
      `
        });
        return response.data.openWeatherCities.items.map(v => ({ value: v.id, display: v.cityName }));
    }
    async updatePowerPlans() {
        let patches = this.grist.dirtyRecords;
        if (patches && patches.length) {
            patches = patches.map(patch => {
                let patchField = { id: patch.id, attributes: patch.attributes };
                const dirtyFields = patch.__dirtyfields__;
                for (let key in dirtyFields) {
                    // id, description 필드는 도메인 정보, 나머지는 도메인의 attributes 정보
                    if (key == 'id' || key == 'description') {
                        patchField[key] = dirtyFields[key].after;
                    }
                    else {
                        patchField['attributes'] = {
                            ...patchField['attributes'],
                            [key]: dirtyFields[key].after
                        };
                    }
                }
                return patchField;
            });
            const response = await client.mutate({
                mutation: gql `
          mutation updateDomains($patches: [DomainPatch!]!) {
            updateDomains(patches: $patches)
          }
        `,
                variables: {
                    patches
                }
            });
            if (!response.errors) {
                document.dispatchEvent(new CustomEvent('notify', { detail: { message: '저장되었습니다.' } }));
                this.grist.fetch();
            }
        }
    }
};
__decorate([
    state(),
    __metadata("design:type", Object)
], PowerPlantList.prototype, "gristConfig", void 0);
__decorate([
    query('ox-grist'),
    __metadata("design:type", DataGrist)
], PowerPlantList.prototype, "grist", void 0);
PowerPlantList = __decorate([
    customElement('power-plant-list')
], PowerPlantList);
export { PowerPlantList };
//# sourceMappingURL=power-plant-list.js.map