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 { notify } from '@operato/layout';
let SunflowPowerPlantList = class SunflowPowerPlantList extends localize(i18next)(ScopedElementsMixin(PageView)) {
    constructor() {
        super(...arguments);
        this.POWER_PLANNER_CONNECTION_NAME = 'powerplanner';
        this.EMISSION_MARKET_CONNECTION_NAME = 'ets.krx.co.kr';
    }
    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: 'Sunflow 발전소 관리',
            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: 'powerPlannerConnectionId', hidden: true },
                { type: 'string', name: 'emissionMarketConnectionId', hidden: true },
                {
                    type: 'gutter',
                    gutterName: 'button',
                    header: '파워 플래너 연결',
                    name: 'powerPlannerConnectionState',
                    icon: record => record?.powerPlannerConnectionId && record?.powerPlannerConnectionState == 'CONNECTED'
                        ? 'link_off'
                        : 'link',
                    iconOnly: false,
                    title: record => record?.powerPlannerConnectionId && record?.powerPlannerConnectionState == 'CONNECTED'
                        ? '연결끊기'
                        : '연결',
                    width: 120,
                    handlers: {
                        click: (columns, data, column, record, rowIndex) => {
                            if (!record || !record.name || record.__dirty__ == '+') {
                                return;
                            }
                            if (record.powerPlannerConnectionState == 'CONNECTED') {
                                this.disconnect(record, this.POWER_PLANNER_CONNECTION_NAME);
                            }
                            else {
                                this.connect(record, this.POWER_PLANNER_CONNECTION_NAME);
                            }
                        }
                    }
                },
                {
                    type: 'gutter',
                    gutterName: 'button',
                    header: '배출권시장 연결',
                    name: 'emissionMarketConnectionState',
                    icon: record => record?.emissionMarketConnectionId && record?.emissionMarketConnectionState == 'CONNECTED'
                        ? 'link_off'
                        : 'link',
                    iconOnly: false,
                    title: record => record?.emissionMarketConnectionId && record?.emissionMarketConnectionState == 'CONNECTED'
                        ? '연결끊기'
                        : '연결',
                    width: 120,
                    handlers: {
                        click: (columns, data, column, record, rowIndex) => {
                            if (!record || !record.name || record.__dirty__ == '+') {
                                return;
                            }
                            if (record.emissionMarketConnectionState == 'CONNECTED') {
                                this.disconnect(record, this.EMISSION_MARKET_CONNECTION_NAME);
                            }
                            else {
                                this.connect(record, this.EMISSION_MARKET_CONNECTION_NAME);
                            }
                        }
                    }
                },
                {
                    type: 'string',
                    name: 'kepcoId',
                    header: '파워 플래너 ID',
                    record: {
                        editable: true
                    },
                    width: 120
                },
                {
                    type: 'password',
                    name: 'kepcoPassword',
                    header: '파워 플래너 비밀번호',
                    record: {
                        editable: true
                    },
                    width: 120
                },
                {
                    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 = [] }) {
        filters.push({
            name: 'extType',
            operator: 'in',
            value: ['sunflow-power-plant', 'all-power-plant']
        });
        const response = await client.query({
            query: gql `
        query SunflowPowerPlants($filters: [Filter!], $pagination: Pagination, $sortings: [Sorting!]) {
          responses: sunflowPowerPlants(filters: $filters, pagination: $pagination, sortings: $sortings) {
            items {
              id
              name
              description
              attributes
              createdAt
              updatedAt

              kepcoId
              kepcoPassword
              powerPlannerConnectionId
              emissionMarketConnectionId
              powerPlannerConnectionState
              emissionMarketConnectionState
            }
            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];
        let connectionPatches = [...this.grist.dirtyRecords];
        if (patches?.length || connectionPatches?.length) {
            // 1. 도메인 업데이트 파라미터
            patches = patches.map(patch => {
                let patchField = { id: patch.id, attributes: patch.attributes };
                const dirtyFields = patch.__dirtyfields__;
                for (let key in dirtyFields) {
                    // 커넥션 정보 필드는 제외
                    if (key == 'kepcoId' ||
                        key == 'kepcoPassword' ||
                        key == 'powerPlannerConnectionId' ||
                        key == 'emissionMarketConnectionId' ||
                        key == 'powerPlannerConnectionState' ||
                        key == 'emissionMarketConnectionState') {
                        continue;
                    }
                    // id, description 필드는 도메인 정보, 나머지는 도메인의 attributes 정보
                    if (key == 'id' || key == 'description') {
                        patchField[key] = dirtyFields[key].after;
                    }
                    else {
                        patchField['attributes'] = {
                            ...patchField['attributes'],
                            [key]: dirtyFields[key].after
                        };
                    }
                }
                return patchField;
            });
            // 2. 커넥션 업데이트 파라미터
            connectionPatches = connectionPatches.map(patch => {
                let patchField = {
                    id: patch.id,
                    powerPlannerConnectionId: patch.powerPlannerConnectionId,
                    emissionMarketConnectionId: patch.emissionMarketConnectionId
                };
                const dirtyFields = patch.__dirtyfields__;
                for (let key in dirtyFields) {
                    // 커넥션 정보 필드만 업데이트
                    if (['kepcoId', 'kepcoPassword'].includes(key)) {
                        patchField[key] = dirtyFields[key].after.toString();
                    }
                }
                return patchField;
            });
            // 3. 도메인 업데이트 & 커넥션 업데이트
            const response = await client.mutate({
                mutation: gql `
          mutation updateDomains($patches: [DomainPatch!]!, $connectionPatches: [SunflowConnectionPatch!]!) {
            updateDomains(patches: $patches)

            updateSunflowConnections(patches: $connectionPatches)
          }
        `,
                variables: {
                    patches,
                    connectionPatches
                }
            });
            if (!response.errors) {
                document.dispatchEvent(new CustomEvent('notify', { detail: { message: '저장되었습니다.' } }));
                this.grist.fetch();
            }
        }
    }
    async connect(record, name) {
        if (!record.powerPlannerConnectionId) {
            notify({ level: 'error', message: '파워 플래너 연결 정보가 없습니다. 연결 정보를 먼저 저장해주세요.' });
            return;
        }
        const response = await client.mutate({
            mutation: gql `
        mutation ($name: String!, $domainId: String!) {
          connectPowerPlantConnection(name: $name, domainId: $domainId)
        }
      `,
            variables: { name, domainId: record.id }
        });
        if (response.data.connectPowerPlantConnection) {
            this.grist.fetch();
            notify({ level: 'info', message: `success to connect : ${name}` });
        }
    }
    async disconnect(record, name) {
        if (!record.powerPlannerConnectionId) {
            notify({ level: 'error', message: '파워 플래너 연결 정보가 없습니다. 연결 정보를 먼저 저장해주세요.' });
            return;
        }
        const response = await client.mutate({
            mutation: gql `
        mutation ($name: String!, $domainId: String!) {
          disconnectPowerPlantConnection(name: $name, domainId: $domainId)
        }
      `,
            variables: { name, domainId: record.id }
        });
        if (response.data.disconnectPowerPlantConnection) {
            this.grist.fetch();
            notify({ level: 'info', message: `success to disconnect : ${name}` });
        }
    }
};
__decorate([
    state(),
    __metadata("design:type", Object)
], SunflowPowerPlantList.prototype, "gristConfig", void 0);
__decorate([
    query('ox-grist'),
    __metadata("design:type", DataGrist)
], SunflowPowerPlantList.prototype, "grist", void 0);
SunflowPowerPlantList = __decorate([
    customElement('sunflow-power-plant-list')
], SunflowPowerPlantList);
export { SunflowPowerPlantList };
//# sourceMappingURL=sunflow-power-plant-list.js.map