import { __decorate, __metadata } from "tslib";
import { css, html } from 'lit';
import { customElement, query, state } from 'lit/decorators.js';
import { navigate, PageView } from '@operato/shell';
import { getExpectedSolarSavingFeeByDate, getPowerBillSummaryByDate } from '../entities/power-bill/query';
import { getInverterSummaryDailyByPowerPlantId, getInverterSummaryMonthlyByPowerPlantId, getInverterSummaryYearlyByPowerPlantId, getInverterSeperateDailyByPowerPlantId, getInverterSeperateMonthlyByPowerPlantId, getInverterSeperateYearlyByPowerPlantId, getAllInverterHistoriesByDate, getInverterHistoriesByDate, getInverterStatusByPowerPlantId, getInverterSummaryBetweenDate } from '../entities/inverter/query';
import '../widgets/power-plant-header';
import '../features/eaas-chart';
import '../features/eaas-chart-donut';
import '../features/eaas-calendar';
import '../features/chart-type-buttons';
import '../features/eaas-pagenation';
import { getDailyChartXAxis, getMonthlyChartXAxis, getYearlyChartXAxis, getToday, roundNumber, arrayToObject } from '../shared/utils/func/common';
import moment from 'moment-timezone';
import { getPowerPlantDetail } from '../entities/power-plant/query';
import '../features/eaas-select';
import { DataAlign, ExcelEaasExport, downloadExcel } from '../shared/utils/modules/excel';
import { getRefreshTime } from '../shared/api/queries/common';
import { isMobileDevice } from '@operato/utils';
import { getFirstPowerPlantId } from '../shared/utils/func/power-plant';
import { getPowerUsageByDate, getPowerUsageSummaryByYear, getPowerUsageSummaryByYearMonth } from '../entities/power-usage/query';
let PowerGenerationHistoryPage = class PowerGenerationHistoryPage extends PageView {
    constructor() {
        super(...arguments);
        this.powerPlantId = '';
        this.currentPath = '';
        this.powerPlantDetail = {};
        this.usageAmount = 0;
        this.maxPeakPower = 0;
        this.generationAmount = 0;
        this.generationTime = 0;
        this.solarSavingFeeAmount = 0;
        this.usageFee = 0;
        this.seriesNames = [];
        this.monthYearlyTableData = [];
        this.monthYearlyTableSummary = {};
        this.chartData = [];
        this.chartType = 'daily';
        this.chartInverterType = 'summary';
        this.date = getToday();
        this.seriesTypes = [];
        this.donutData = [];
        this.inverterList = [];
        this.selectedInverter = {};
        this.inverterHistoryList = [];
        this.inverterHistoryCount = 0;
        this.page = 1;
        this.PAGE_LIMIT = 15;
    }
    static { this.styles = [
        css `
      :host {
        * ::-webkit-scrollbar {
          width: 5px;
        }
        *::-webkit-scrollbar-thumb {
          background-color: rgba(57, 78, 100, 0.5);
        }

        background-color: var(--primary-color);

        .container {
          display: flex;
          flex-direction: column;
          height: calc(100vh - 50px); /* Full height of the viewport */
          border-top: 1px solid var(--md-sys-color-on-tertiary-container);
          padding: 20px 25px;
          overflow-y: auto;
        }
        .container * {
          color: var(--md-sys-color-on-secondary);
        }
        .container div {
          display: flex;
          gap: 10px;
        }
        div.title-container {
          margin-top: var(--margin-wide);
          padding: 0;
          padding-bottom: 5px;
          border-bottom: 2px solid #2681eb;
        }
        .title-container div {
          gap: 0;
          padding: 0;
          margin-bottom: -5px;
          margin-top: 5px;
        }
        .title-container div a {
          background-color: var(--md-sys-color-outline);
          text-decoration: none;
          padding: var(--padding-narrow) var(--padding-wide);
          padding-bottom: 0px;
          color: #aebff0;
        }
        .title-container div a:hover {
          color: var(--md-sys-color-on-secondary);
        }
        .title-container div a.active {
          background-color: var(--md-sys-color-tertiary);
          color: var(--md-sys-color-on-secondary);
          font-weight: bold;
        }
        .title-container div a.active:before {
          content: '';
          position: relative;
          display: inline-block;
          margin-right: 7px;
          width: 0;
          height: 0;
          border-left: 4px solid transparent;
          border-right: 4px solid transparent;
          border-top: 5px solid var(--md-sys-color-on-secondary);
        }
        h2 {
          flex: 1;
          margin: 0;
          padding: 0;
          font-size: 1.17em;
        }
        div.main-container {
          flex: 1;
          padding: var(--padding-default) 0;
          overflow-y: auto;
        }
        .container-A {
          display: flex;
          justify-content: space-between;
        }
        .container-A-1,
        .container-B {
          flex: 4;

          .chart-header {
            display: flex;
            padding: 0;

            h3 {
              margin: 0;
              flex: 1;
              color: var(--md-sys-color-surface-tint);
            }
          }
          table {
            width: 100%;
            border-spacing: 0;

            th {
              border-top: 2px solid rgba(173, 191, 240, 0.4);
              border-bottom: 1px solid rgba(173, 191, 240, 0.2);
              background-color: rgba(0, 0, 0, 0.3);
              padding: 5px;
              color: var(--md-sys-color-surface-tint);
              font-weight: normal;
            }
            th.level2nd {
              min-width: 30px;
              padding-inline: 2px;
              border-top: 1px solid rgba(173, 191, 240, 0.4);
              border-left: 1px solid rgba(173, 191, 240, 0.3);
              font-size: 0.9em;
              line-height: 1;
            }
            tr:nth-child(n + 3):nth-child(even) {
              background-color: rgba(255, 255, 255, 0.05);
            }
            td {
              border-bottom: 1px solid rgba(173, 191, 240, 0.2);
              padding: 7px 4px;
              font-size: 0.8em;
              text-align: center;

              &.issue-status-normal {
                color: var(--status-success-color);
                font-weight: bold;
              }
              &.issue-status-stop {
                color: var(--status-danger-color);
                font-weight: bold;
              }
              &.issue-status-fault {
                color: var(--status-warning-color);
                font-weight: bold;
              }
            }
            td:first-child {
              border-left: none;
            }
            td.dc {
              color: #c6f4c9;
            }
            td.ac {
              color: #aebff0;
              line-break: anywhere;
            }
          }
        }
        .container-A-2,
        .container-C {
          flex: 5;
        }
        .container-A-3,
        .container-D {
          flex: 2;
        }
        .container-A .content {
          display: flex;
        }

        .container-B {
          flex: 9;
          flex-direction: column;
        }

        div.container-C {
          flex: 2;
          flex-direction: column;
          padding: 0;
          position: relative;
        }
        div.chart-container {
          flex-direction: column;
          flex: 1;
          padding-bottom: 20px;

          & > * {
            display: block;
            height: 100%;
            width: 100%;
          }

          eaas-chart {
            min-height: 330px;
            height: 100%;

            .apexcharts-legend-series {
              gap: 3px;
            }
          }

          eaas-chart-donut {
            min-height: 330px;
            .apexcharts-legend-series {
              gap: 3px;
            }
          }
        }
        div.chart-container div {
          padding: 0;

          div.apexcharts-canvas {
            display: initial;
          }
          .apexcharts-tooltip.apexcharts-theme-dark {
            padding: 10px; /* 마우스 오버 툴팁 패딩 조정 */
          }
        }
        div.info-cell {
          border: 1px solid var(--md-sys-color-on-tertiary-container);
          border-radius: 10px;
          display: block;
          padding: var(--padding-default) var(--padding-wide);
          font-size: 1.3em;
          line-height: 1.3;
        }
        .info-cell label {
          display: block;
          color: var(--md-sys-color-surface-tint);
          font-size: 0.7em;
        }
        .info-cell span {
          font-size: 0.7em;
        }
        button {
          background-color: var(--md-sys-color-tertiary);
          border: 0;
          border-radius: 5px;
          padding: var(--padding-default);
          font-size: 1em;
          line-height: 1.2;
        }
        button * {
          vertical-align: middle;
        }
        button md-icon {
          --md-icon-size: 23px;
          margin-top: -4px;
        }
        .focus-button {
          background-color: var(--status-success-color);
          cursor: pointer;
        }
        div.shidden {
          display: none;
        }

        /* 차트 레이아웃 스타일 */
        .chart-layout-container {
          display: flex !important;
          gap: 20px;
          height: 100%;
        }

        .main-chart-container {
          flex: 3;
          flex-flow: column;
        }

        .donut-chart-container {
          flex: 1;
          flex-flow: column;
          flex-direction: column;
        }

        .donut-chart-title {
          margin: 0 0 10px 0;
          color: var(--md-sys-color-surface-tint);
        }

        .donut-chart-content {
          justify-content: center;
          margin-top: 25px;
          height: 100%;
        }

        /* Mobile Styles */
        @media (max-width: 768px) {
          div.shidden {
            display: initial;
          }
          .mhidden {
            display: none !important; /* mobile mode content hidden */
          }
          .container {
            height: calc(100vh - 130px); /* Full height of the viewport */
            padding: var(--padding-default);
            max-height: 100%;
          }
          .container-A,
          .main-container {
            display: flex;
            flex-direction: column;
          }
          .main-container > .container-B {
            order: 2;
          }
          .main-container > .container-C {
            order: 1;
          }

          .container-B {
            flex: 1;

            div.chart-container {
              & > eaas-chart {
                min-height: 250px;
              }
            }
          }

          .chart-layout-container {
            flex-direction: column;
            gap: 10px;
          }

          .main-chart-container,
          .donut-chart-container {
            flex: 1;
            min-width: auto;
          }
          td {
            padding: var(--padding-narrow) !important;
            border-left: 1px solid rgba(173, 191, 240, 0.3);
          }
          div.container-C {
            display: block;
            flex: initial;
            padding: 0;

            eaas-calendar {
              display: block;
              margin: var(--margin-default) 0;
            }
          }
          div.info-cell {
            display: inline-block;
            width: 24%;
            font-size: 1.1em;
            margin-bottom: 5px;

            label {
              font-size: 0.68em;
            }
          }

          .donut-chart-content {
            margin-top: 0;
          }
        }
      }
    `
    ]; }
    get context() {
        return { title: '전력이력' };
    }
    render() {
        if (!this.powerPlantId)
            return html ``;
        let dateTitle = '일간';
        let usageAmount = roundNumber(this.usageAmount, 0);
        let usageAmountSign = 'kW';
        let maxPeakPower = roundNumber(this.maxPeakPower, 0);
        let maxPeakPowerSign = 'kW';
        let generationAmount = roundNumber(this.generationAmount, 1);
        let generationAmountSign = 'kWh';
        let generationTime = roundNumber(this.generationTime, 1);
        let solarSavingFeeAmount = roundNumber(this.solarSavingFeeAmount, 0);
        let solarSavingFeeAmountSign = '원';
        if (this.chartType === 'monthly' || this.chartType === 'yearly') {
            dateTitle = this.chartType === 'monthly' ? '월간' : '연간';
            usageAmountSign = 'MW';
            generationAmount = roundNumber(this.generationAmount / 1000, 2);
            generationAmountSign = 'MWh';
            solarSavingFeeAmount = roundNumber(this.solarSavingFeeAmount / 1000, 0);
            solarSavingFeeAmountSign = '천원';
        }
        return html `
      <!-- 전체레이아웃 Container begin-->
      <div class="container">
        <!-- 상단 공통 바 Container begin-->
        <power-plant-header .powerPlantId=${this.powerPlantId} .currentPath=${this.currentPath}></power-plant-header>
        <!-- 상단 공통 바 Container end-->

        <!-- title container begin-->
        <div class="title-container">
          <h2>전력이력</h2>
          <div>
            <a class=${this.chartType === 'daily' ? 'active' : ''} @click=${() => this.setChartType('daily')}>일간</a>
            <a class=${this.chartType === 'monthly' ? 'active' : ''} @click=${() => this.setChartType('monthly')}
              >월간</a
            >
            <a class=${this.chartType === 'yearly' ? 'active' : ''} @click=${() => this.setChartType('yearly')}>연간</a>
          </div>
        </div>
        <!-- title container end-->

        <!-- 중앙 Container begin-->
        <div class="main-container">
          <!-- 시간대별 챠트 요약정보 좌측 Container begin-->
          <div class="container-B">
            <div class="chart-header">
              <h3>
                ${this.chartType === 'daily' ? '시간대' : this.chartType === 'monthly' ? '일' : '월'}별 전력 현황 (kWh)
              </h3>
              <chart-type-buttons
                .selected=${this.chartInverterType}
                @chart-type-changed="${(event) => this.setChartInverterType(event.detail)}"
              ></chart-type-buttons>
            </div>
            <div class="chart-container">
              <div class="chart-layout-container">
                <div class="main-chart-container">
                  <eaas-chart
                    .data=${this.chartData}
                    chartType=${this.chartInverterType === 'summary' ? 'mixed' : 'line'}
                    .seriesNames=${this.seriesNames}
                    .seriesTypes=${this.seriesTypes}
                    .mixedColors=${['#59AFF8', '#FF8800']}
                    .hideLegend=${false}
                    .lineMarkerSize=${this.chartInverterType === 'summary' ? 4.5 : 3}
                    .lineMarkerCircleColor=${this.chartInverterType === 'summary' ? '#ffffff' : undefined}
                    .lineStrokeWidth=${3}
                  >
                  </eaas-chart>
                </div>
                ${this.chartType !== 'daily' && this.chartInverterType === 'summary' && this.donutData.length > 0
            ? html `
                      <div class="donut-chart-container">
                        <h3 class="donut-chart-title">전력 사용량 비중</h3>
                        <div class="donut-chart-content">
                          <eaas-chart-donut
                            .data=${this.donutData}
                            .colors=${['#59AFF8', '#FFB84D', '#FF6B7D']}
                            suffix=" kWh"
                            .showLabels=${true}
                            .showLegend=${true}
                            legendPosition="top"
                          ></eaas-chart-donut>
                        </div>
                      </div>
                    `
            : ''}
              </div>
              ${this.chartType === 'daily'
            ? html `
                    <div class="content mhidden">
                      <div class="chart-header">
                        <h3>인버터 운전 현황</h3>
                        <eaas-select
                          .items=${this.inverterList}
                          .selectedItem=${this.selectedInverter}
                          @selection-changed=${this.handleInverterSelection}
                          .isShowAll=${false}
                        ></eaas-select>
                      </div>

                      <table class="pp-table">
                        <thead>
                          <tr>
                            <th>시간</th>
                            <th>역률</th>
                            <th>DC전압</th>
                            <th>DC전류</th>
                            <th>DC전력</th>
                            <th>AC전압 R</th>
                            <th>AC전압 S</th>
                            <th>AC전압 T</th>
                            <th>AC전류 R</th>
                            <th>AC전류 S</th>
                            <th>AC전류 T</th>
                            <th>AC전력</th>
                            <th>일일누적 발전량</th>
                            <th>총 누적 발전량</th>
                          </tr>
                        </thead>
                        <tbody>
                          ${this.inverterHistoryList?.map(item => {
                return html `
                              <tr>
                                <td>${moment(item.DATE_INFO, 'YYYY-MM-DD HH:mm:ss').format('HH:mm')}</td>
                                <td>${roundNumber(item.PF, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.DC_V, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.DC_I, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.DC_P, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.IV_R, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.IV_S, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.IV_T, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.IC_R, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.IC_S, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.IC_T, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.AC_P, 0).toLocaleString()}</td>
                                <td>${roundNumber(item.dailyGeneration, 0).toLocaleString()}kWh</td>
                                <td>${roundNumber(item.totalGeneration, 0).toLocaleString()}MWh</td>
                              </tr>
                            `;
            })}
                        </tbody>
                      </table>

                      <eaas-pagenation
                        totalRecords=${this.inverterHistoryCount}
                        pageSize=${this.PAGE_LIMIT}
                        @page-changed=${this.handlePageChange}
                        .currentPage=${this.page}
                        maxPages=${5}
                      ></eaas-pagenation>
                    </div>

                    <div class="content shidden">
                      <div class="chart-header">
                        <h3>인버터 운전 현황</h3>
                        <eaas-select
                          .items=${this.inverterList}
                          .selectedItem=${this.selectedInverter}
                          @selection-changed=${this.handleInverterSelection}
                          .isShowAll=${false}
                        ></eaas-select>
                      </div>

                      <table class="pp-table">
                        <thead>
                          <tr>
                            <th rowspan="2">시간</th>
                            <th colspan="3">입력(DC)</th>
                            <th colspan="3">출력(AC)</th>
                          </tr>
                          <tr>
                            <th class="level2nd">전압(V)</th>
                            <th class="level2nd">전류(A)</th>
                            <th class="level2nd">전력(kW)</th>
                            <th class="level2nd">전압(V)</th>
                            <th class="level2nd">전류(A)</th>
                            <th class="level2nd">전력(kW)</th>
                          </tr>
                        </thead>
                        <tbody>
                          ${this.inverterHistoryList?.map(item => {
                const IV_R = roundNumber(item.IV_R, 0).toLocaleString();
                const IV_S = roundNumber(item.IV_S, 0).toLocaleString();
                const IV_T = roundNumber(item.IV_T, 0).toLocaleString();
                const IC_R = roundNumber(item.IC_R, 0).toLocaleString();
                const IC_S = roundNumber(item.IC_S, 0).toLocaleString();
                const IC_T = roundNumber(item.IC_T, 0).toLocaleString();
                return html `
                              <tr>
                                <td>${moment(item.DATE_INFO, 'YYYY-MM-DD HH:mm:ss').format('HH:mm')}</td>
                                <td class="dc">${roundNumber(item.DC_V, 0).toLocaleString()}</td>
                                <td class="dc">${roundNumber(item.DC_I, 0).toLocaleString()}</td>
                                <td class="dc">${roundNumber(item.DC_P, 0).toLocaleString()}</td>
                                <td class="ac">${IV_R}/${IV_S}/${IV_T}</td>
                                <td class="ac">${IC_R}/${IC_S}/${IC_T}</td>
                                <td class="ac">${roundNumber(item.AC_P, 0).toLocaleString()}</td>
                              </tr>
                            `;
            })}
                        </tbody>
                      </table>

                      <eaas-pagenation
                        totalRecords=${this.inverterHistoryCount}
                        pageSize=${this.PAGE_LIMIT}
                        @page-changed=${this.handlePageChange}
                        .currentPage=${this.page}
                        maxPages=${5}
                      ></eaas-pagenation>
                    </div>
                  `
            : html ` <div class="content shidden">
                    <div class="chart-header">
                      <h3>절감 현황</h3>
                    </div>

                    <table class="pp-table">
                      <thead>
                        <tr>
                          <th>날짜</th>
                          <th>사용량(kWh)</th>
                          <th>발전량(kWh)</th>
                          <th>절감요금(원)</th>
                        </tr>
                      </thead>
                      <tbody>
                        ${this.monthYearlyTableData?.map(item => {
                const usage = roundNumber(item.usage, 0);
                const generation = roundNumber(item.generation, 0);
                const savingFee = roundNumber(item.savingFee, 0);
                return html `
                            <tr>
                              <td>${item.date}</td>
                              <td>${usage.toLocaleString()}</td>
                              <td>${generation.toLocaleString()}</td>
                              <td>${savingFee.toLocaleString()}</td>
                            </tr>
                          `;
            })}
                        <tr>
                          <td>합계</td>
                          <td>${roundNumber(this.monthYearlyTableSummary.usage, 0).toLocaleString()}</td>
                          <td>${roundNumber(this.monthYearlyTableSummary.generation, 0).toLocaleString()}</td>
                          <td>${roundNumber(this.monthYearlyTableSummary.savingFee, 0).toLocaleString()}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>`}
            </div>
          </div>
          <!-- 시간대별 챠트 요약정보 좌측 Container end-->

          <!-- 사이드 정보 우측 Container begin-->
          <div class="container-C">
            <eaas-calendar
              type=${this.chartType}
              .selectedDate=${this.date}
              @change=${this.handleDateChange}
              title=${this.chartType === 'daily' ? '조회일자' : this.chartType === 'monthly' ? '조회월' : '조회연도'}
            ></eaas-calendar>
            <div class="info-cell">
              <label>${dateTitle} 전력 사용량</label>
              <strong>${usageAmount.toLocaleString()}</strong><span>${usageAmountSign}h</span>
            </div>
            <div class="info-cell">
              <label>${dateTitle} 피크 전력</label>
              <strong>${maxPeakPower.toLocaleString()}</strong><span>${maxPeakPowerSign}</span>
            </div>
            <div class="info-cell">
              <label>${dateTitle} 발전량</label>
              <strong>${generationAmount.toLocaleString()}</strong><span>${generationAmountSign}</span>
            </div>
            <div class="info-cell">
              <label>${dateTitle} 발전 시간</label>
              <strong>${generationTime.toLocaleString()}</strong><span>시간</span>
            </div>
            <div class="info-cell">
              <label>${dateTitle} 요금 절감액</label>
              <strong>${solarSavingFeeAmount.toLocaleString()}</strong><span>${solarSavingFeeAmountSign}</span>
            </div>
            <button class="focus-button mhidden" @click=${this.downloadExcel}>
              <md-icon>sim_card_download</md-icon> 엑셀 다운로드
            </button>
          </div>
          <!-- 사이드 정보 우측 Container end-->
        </div>
        <!-- 중앙 Container end-->
      </div>
      <!-- 전체레이아웃 Container end-->
    `;
    }
    async pageUpdated(changes, lifecycle) {
        if (this.active) {
            if (!lifecycle.resourceId) {
                navigate(`${lifecycle.page}/${await getFirstPowerPlantId()}`);
                return;
            }
            this.initParams();
            this.powerPlantId = lifecycle.resourceId;
            this.currentPath = lifecycle.page;
            const { data: powerPlantDetail } = await getPowerPlantDetail(this.powerPlantId);
            this.powerPlantDetail = powerPlantDetail;
            const inverterList = await getInverterStatusByPowerPlantId(this.powerPlantId);
            this.inverterList = inverterList?.map(v => ({
                id: v.ivtId,
                name: `인버터 ${v.ivtId.toString().padStart(2, '0')}`
            }));
            this.selectedInverter = this.inverterList[0];
            await this.updateComplete;
            this.getInverterHistoriesByDate();
            this.getChartData();
            if (isMobileDevice() === false) {
                const refreshTime = await getRefreshTime();
                if (this.refreshInterval)
                    clearInterval(this.refreshInterval);
                this.refreshInterval = window.setInterval(() => {
                    this.getChartData();
                    this.getInverterHistoriesByDate();
                }, refreshTime);
            }
        }
        else {
            if (this.refreshInterval) {
                clearInterval(this.refreshInterval);
                this.refreshInterval = undefined;
            }
        }
    }
    initParams() {
        this.page = 1;
        this.date = getToday();
        this.chartType = 'daily';
        this.chartInverterType = 'summary';
    }
    async getChartData() {
        // 헤더 정보 갱신
        if (this.powerPlantHeader) {
            await this.powerPlantHeader.fetchPowerPlantHeaderInfo();
        }
        let inverterChartData = [];
        let usageChartData = [];
        let startDate = '';
        let endDate = '';
        if (this.chartType === 'daily') {
            // daily 모드에서는 도넛 차트를 표시하지 않음
            this.donutData = [];
            startDate = this.date;
            endDate = this.date;
            if (this.chartInverterType === 'summary') {
                inverterChartData = await getInverterSummaryDailyByPowerPlantId(this.powerPlantId, this.date);
                usageChartData = await getPowerUsageByDate(this.powerPlantId, this.date);
            }
            else {
                inverterChartData = await getInverterSeperateDailyByPowerPlantId(this.powerPlantId, this.date);
                usageChartData = await getPowerUsageByDate(this.powerPlantId, this.date);
            }
        }
        else if (this.chartType === 'monthly') {
            startDate = moment(this.date, 'YYYY-MM').startOf('month').format('YYYY-MM-DD');
            endDate = moment(this.date, 'YYYY-MM').endOf('month').format('YYYY-MM-DD');
            if (this.chartInverterType === 'summary') {
                inverterChartData = await getInverterSummaryMonthlyByPowerPlantId(this.powerPlantId, this.date);
                usageChartData = await getPowerUsageSummaryByYearMonth(this.powerPlantId, this.date);
                // 도넛 차트 데이터 가져오기
                const powerUsageSummary = await getPowerBillSummaryByDate(this.powerPlantId, startDate, endDate);
                this.donutData = [
                    { label: '경부하', value: powerUsageSummary.usageLight || 0 },
                    { label: '중부하', value: powerUsageSummary.usageMid || 0 },
                    { label: '최대부하', value: powerUsageSummary.usageMax || 0 }
                ];
            }
            else {
                inverterChartData = await getInverterSeperateMonthlyByPowerPlantId(this.powerPlantId, this.date);
                usageChartData = await getPowerUsageSummaryByYearMonth(this.powerPlantId, this.date);
                this.donutData = [];
            }
        }
        else if (this.chartType === 'yearly') {
            startDate = moment(this.date, 'YYYY').startOf('year').format('YYYY-MM-DD');
            endDate = moment(this.date, 'YYYY').endOf('year').format('YYYY-MM-DD');
            if (this.chartInverterType === 'summary') {
                inverterChartData = await getInverterSummaryYearlyByPowerPlantId(this.powerPlantId, this.date);
                usageChartData = await getPowerUsageSummaryByYear(this.powerPlantId, this.date);
                // 도넛 차트 데이터 가져오기
                const powerUsageSummary = await getPowerBillSummaryByDate(this.powerPlantId, startDate, endDate);
                this.donutData = [
                    { label: '경부하', value: powerUsageSummary.usageLight || 0 },
                    { label: '중부하', value: powerUsageSummary.usageMid || 0 },
                    { label: '최대부하', value: powerUsageSummary.usageMax || 0 }
                ];
            }
            else {
                inverterChartData = await getInverterSeperateYearlyByPowerPlantId(this.powerPlantId, this.date);
                usageChartData = await getPowerUsageSummaryByYear(this.powerPlantId, this.date);
                this.donutData = [];
            }
        }
        const prefix = this.chartType === 'daily' ? '시' : this.chartType === 'monthly' ? '일' : '월';
        const xAxis = this.chartType === 'daily'
            ? getDailyChartXAxis()
            : this.chartType === 'monthly'
                ? getMonthlyChartXAxis(this.date)
                : getYearlyChartXAxis(this.date);
        let chartData = [];
        let seriesNames = [];
        const serisePrefix = isMobileDevice() ? '' : '인버터 ';
        if (this.chartInverterType === 'summary') {
            const inverterResult = arrayToObject(inverterChartData, 'date');
            const usageResult = arrayToObject(usageChartData, 'criteriaTime', v => v.toString().padStart(2, '0'));
            chartData =
                xAxis?.map(v => ({
                    label: v.slice(-2) + prefix,
                    values: [
                        usageResult[v]?.usage || null, // 첫 번째 시리즈: 전력 사용량 (막대차트)
                        inverterResult[v]?.value || null // 두 번째 시리즈: 발전량 (라인차트)
                    ]
                })) || [];
            seriesNames = ['전력 사용량', '발전량'];
            this.seriesTypes = ['bar', 'line'];
        }
        else {
            const result = {};
            for (let icd of inverterChartData) {
                if (!result[icd.date]) {
                    result[icd.date] = { values: [] };
                }
                result[icd.date]['values'][icd.no - 1] = icd.value;
            }
            chartData = xAxis.map(v => ({
                label: v.slice(-2) + prefix,
                values: result[v]?.values || new Array(this.inverterList.length).fill(null)
            }));
            // seriesNames를 inverterList 기반으로 생성
            seriesNames = this.inverterList.map(inverter => `${serisePrefix}${inverter.id.toString().padStart(2, '0')}`);
            this.seriesTypes = [];
        }
        this.usageAmount = usageChartData?.reduce((acc, curr) => acc + curr.usage, 0) || 0;
        this.maxPeakPower = usageChartData?.reduce((acc, curr) => Math.max(acc, curr.maxDemand), 0) || 0;
        this.generationAmount = inverterChartData?.reduce((acc, curr) => acc + curr.value, 0) || 0;
        this.usageFee = usageChartData?.reduce((acc, curr) => acc + curr.fee, 0) || 0;
        this.seriesNames = seriesNames;
        this.chartData = chartData;
        // 요금 절감액
        const dateFormat = this.chartType === 'monthly' ? 'YYYY-MM-DD' : 'YYYY-MM';
        const solarSavingFeeData = await getExpectedSolarSavingFeeByDate(this.powerPlantId, startDate, endDate, dateFormat);
        this.solarSavingFeeAmount = solarSavingFeeData?.reduce((acc, cur) => acc + (cur?.value || 0), 0) || 0;
        // 발전 시간 계산 월/연도는 일수로 나눠서
        if (this.chartType === 'daily') {
            this.generationTime = inverterChartData?.reduce((acc, curr) => acc + curr.generationTime, 0) || 0;
        }
        else {
            const inverterSummaryBetweenDate = await getInverterSummaryBetweenDate(this.powerPlantId, startDate, endDate);
            this.generationTime = inverterSummaryBetweenDate?.dailyAverageGenerationTime || 0;
            // 월/연도 차트일때만 테이블 데이터 셋팅
            // 테이블 날짜 셋팅
            const monthYearlyTableData = xAxis.reduce((acc, curr) => {
                acc[curr] = { date: curr, generation: 0, usage: 0, savingFee: 0 };
                return acc;
            }, {});
            // 리스트 + 서머리 데이터 셋팅
            const monthYearlyTableSummary = { usage: 0, generation: 0, savingFee: 0 };
            inverterChartData.forEach(v => {
                monthYearlyTableData[v.date].generation += v.value;
                monthYearlyTableSummary.generation += v.value;
            });
            usageChartData.forEach(v => {
                monthYearlyTableData[v.date].usage += v.usage;
                monthYearlyTableSummary.usage += v.usage;
            });
            solarSavingFeeData.forEach(v => {
                monthYearlyTableData[v.date].savingFee += v.value;
                monthYearlyTableSummary.savingFee += v.value;
            });
            this.monthYearlyTableSummary = monthYearlyTableSummary;
            this.monthYearlyTableData = Object.values(monthYearlyTableData);
        }
    }
    // 날짜 변경시 차트 데이터 갱신
    handleDateChange(e) {
        this.date = e.detail.value;
        this.getChartData();
        this.getInverterHistoriesByDate();
    }
    // 차트 타입 변경시 날짜 셋팅 (일간/월간/연간)
    setChartType(type) {
        this.chartType = type;
        this.page = 1;
        if (type === 'daily') {
            this.date = getToday();
        }
        else if (type === 'monthly') {
            this.date = moment().format('YYYY-MM');
        }
        else if (type === 'yearly') {
            this.date = moment().format('YYYY');
        }
        this.getChartData();
    }
    setChartInverterType(type) {
        this.chartInverterType = type;
        this.getChartData();
    }
    handleInverterSelection(e) {
        this.selectedInverter = e.detail;
        this.page = 1;
        this.getInverterHistoriesByDate();
    }
    handlePageChange(e) {
        this.page = e.detail.page;
        this.getInverterHistoriesByDate();
    }
    async getInverterHistoriesByDate() {
        if (this.chartType !== 'daily' || !this.selectedInverter?.id)
            return;
        const { data } = await getInverterHistoriesByDate(this.powerPlantId, this.selectedInverter?.id?.toString(), this.chartType, this.date, this.page, this.PAGE_LIMIT);
        this.inverterHistoryList = data.items;
        this.inverterHistoryCount = data.total;
    }
    async downloadExcel() {
        if (this.chartType === 'daily') {
            this.downloadExcelDaily();
        }
        else if (this.chartType === 'monthly' || this.chartType === 'yearly') {
            this.downloadExcelMonthlyOrYearly();
        }
    }
    async downloadExcelDaily() {
        const excel = new ExcelEaasExport();
        const dateString = '일간이력';
        const fileName = `${this.powerPlantDetail.name}_${dateString}_${this.date}`;
        const sheetName = '시간별 발전량';
        const headerSetting = [
            { header: '시간', key: 'date', width: 20, dataAlign: DataAlign.CENTER },
            { header: '사용전력량', key: 'usage', width: 20, dataAlign: DataAlign.RIGHT },
            { header: '발전량(kWh)', key: 'sum', width: 20, dataAlign: DataAlign.RIGHT },
            { header: '전기요금', key: 'electricityFee', width: 20, dataAlign: DataAlign.RIGHT },
            { header: '절감요금', key: 'savingFee', width: 20, dataAlign: DataAlign.RIGHT }
        ];
        const inverterSeperateData = await getInverterSeperateDailyByPowerPlantId(this.powerPlantId, this.date);
        const usageChartData = await getPowerUsageByDate(this.powerPlantId, this.date);
        const usageChartDataMap = arrayToObject(usageChartData, 'hour', v => v.toString().padStart(2, '0'));
        let excelData = {};
        for (let inverter of inverterSeperateData) {
            if (!excelData[inverter.date]) {
                excelData[inverter.date] = new Array(this.inverterList.length).fill(0);
            }
            excelData[inverter.date][inverter.no - 1] = inverter.value;
        }
        // 1. 첫번째 시간별 발전량 시트
        excel.addWorksheet(sheetName);
        // 헤더는 4행에 위치
        excel.setHeader(headerSetting, 4);
        // 2행 헤더데이터 셋팅
        const summaryLabels = ['발전소 명', '사용전력량', '발전량(kWh)', '전기요금', '절감요금'];
        const summaryValues = [
            this.powerPlantDetail?.name || '',
            roundNumber(this.usageAmount, 0) || 0,
            roundNumber(this.generationAmount, 0) || 0,
            roundNumber(this.usageFee, 0) || 0,
            roundNumber(this.solarSavingFeeAmount, 0) || 0
        ];
        // 기존 API를 재활용해 요약을 생성 (확장된 다중 컬럼 지원)
        excel.setSummaryData(summaryLabels, summaryValues);
        // 본문 시간 별 데이터 셋팅
        const hours = getDailyChartXAxis();
        for (let hour of hours) {
            const powerUsage = usageChartDataMap[hour] || {};
            const time = `${this.date} ${hour}:00`;
            const hourUsage = powerUsage?.usage || 0;
            const hourGeneration = excelData[hour]?.reduce((acc, curr) => acc + curr, 0) || 0;
            const hourFee = powerUsage?.fee || 0;
            const hourSavingFee = hourGeneration * powerUsage?.hourlyApplyPricing || 0;
            excel.addRow([time, hourUsage, hourGeneration, hourFee, hourSavingFee]);
        }
        // 2. 두번째 부터는 인버터 시트
        const inverterHeader = [
            { header: '시간', key: 'date', width: 20, dataAlign: DataAlign.CENTER },
            { header: '역률', key: 'PF', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'DC전압', key: 'DC_V', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'DC전류', key: 'DC_I', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'DC전력', key: 'DC_P', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'AC전압 R', key: 'IV_R', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'AC전압 S', key: 'IV_S', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'AC전압 T', key: 'IV_T', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'AC전류 R', key: 'IC_R', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'AC전류 S', key: 'IC_S', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'AC전류 T', key: 'IC_T', width: 20, dataAlign: DataAlign.CENTER },
            { header: 'AC전력', key: 'AC_P', width: 20, dataAlign: DataAlign.CENTER },
            { header: '일일누적 발전량', key: 'dailyGeneration', width: 20, dataAlign: DataAlign.CENTER },
            { header: '총 누적발젼량', key: 'totalGeneration', width: 20, dataAlign: DataAlign.CENTER }
        ];
        // 인버터 데이터 파싱
        const allInverterHistories = await getAllInverterHistoriesByDate(this.powerPlantId, this.date);
        let inverterExcelData = {};
        for (let inverter of allInverterHistories) {
            if (!inverterExcelData[`inverter_${inverter.no - 1}`]) {
                inverterExcelData[`inverter_${inverter.no - 1}`] = [];
            }
            inverterExcelData[`inverter_${inverter.no - 1}`].push(inverter);
        }
        for (let i = 0; i < Object.keys(inverterExcelData).length; i++) {
            const inverters = inverterExcelData[`inverter_${i}`].sort((a, b) => parseInt(a.collectedAt) - parseInt(b.collectedAt));
            excel.addWorksheet(`인버터 ${inverters[0].no.toString().padStart(2, '0')}`);
            excel.setHeader(inverterHeader, 1);
            for (let inverter of inverters) {
                excel.addRow([
                    moment(inverter.DATE_INFO, 'YYYY-MM-DD HH:mm:ss').tz('Asia/Seoul').format('HH:mm'),
                    inverter.PF,
                    inverter.DC_V,
                    inverter.DC_I,
                    inverter.DC_P,
                    inverter.IV_R,
                    inverter.IV_S,
                    inverter.IV_T,
                    inverter.IC_R,
                    inverter.IC_S,
                    inverter.IC_T,
                    inverter.AC_P,
                    inverter.dailyGeneration,
                    inverter.totalGeneration
                ]);
            }
        }
        downloadExcel(excel, fileName);
    }
    async downloadExcelMonthlyOrYearly() {
        const excel = new ExcelEaasExport();
        const dateString = this.chartType === 'monthly' ? '월간이력' : '연간이력';
        const fileName = `${this.powerPlantDetail.name}_${dateString}_${this.date}`;
        const sheetName = `${dateString} 발전량`;
        const headerSetting = [
            { header: '시간', key: 'date', width: 20, dataAlign: DataAlign.CENTER },
            { header: '사용전력량', key: 'usage', width: 20, dataAlign: DataAlign.RIGHT },
            { header: '발전량(kWh)', key: 'sum', width: 20, dataAlign: DataAlign.RIGHT },
            { header: '전기요금', key: 'electricityFee', width: 20, dataAlign: DataAlign.RIGHT },
            { header: '절감요금', key: 'savingFee', width: 20, dataAlign: DataAlign.RIGHT }
        ];
        let inverterSeperateData = [];
        let powerUsageData = [];
        let solarSavingFeeData = [];
        if (this.chartType === 'monthly') {
            inverterSeperateData = await getInverterSeperateMonthlyByPowerPlantId(this.powerPlantId, this.date);
            const usageResponse = await getPowerUsageSummaryByYearMonth(this.powerPlantId, this.date);
            powerUsageData = arrayToObject(usageResponse, 'date');
            const startDate = moment(this.date, 'YYYY-MM').startOf('month').format('YYYY-MM-DD');
            const endDate = moment(this.date, 'YYYY-MM').endOf('month').format('YYYY-MM-DD');
            const savingResponse = await getExpectedSolarSavingFeeByDate(this.powerPlantId, startDate, endDate, 'YYYY-MM-DD');
            solarSavingFeeData = arrayToObject(savingResponse, 'date');
        }
        else {
            inverterSeperateData = await getInverterSeperateYearlyByPowerPlantId(this.powerPlantId, this.date);
            const response = await getPowerUsageSummaryByYear(this.powerPlantId, this.date);
            powerUsageData = arrayToObject(response, 'date');
            const startDate = moment(this.date, 'YYYY').startOf('year').format('YYYY-MM-DD');
            const endDate = moment(this.date, 'YYYY').endOf('year').format('YYYY-MM-DD');
            const savingResponse = await getExpectedSolarSavingFeeByDate(this.powerPlantId, startDate, endDate, 'YYYY-MM');
            solarSavingFeeData = arrayToObject(savingResponse, 'date');
        }
        let excelData = {};
        for (let inverter of inverterSeperateData) {
            if (!excelData[inverter.date]) {
                excelData[inverter.date] = new Array(this.inverterList.length).fill(0);
            }
            excelData[inverter.date][inverter.no - 1] = inverter.value;
        }
        // 1. 첫번째 시간별 발전량 시트
        excel.addWorksheet(sheetName);
        // 헤더는 4행에 위치
        excel.setHeader(headerSetting, 4);
        // 2행 헤더데이터 셋팅
        const summaryLabels = ['발전소 명', '사용전력량', '발전량(kWh)', '전기요금', '절감요금'];
        const summaryValues = [
            this.powerPlantDetail?.name || '',
            roundNumber(this.usageAmount, 0) || 0,
            roundNumber(this.generationAmount, 0) || 0,
            roundNumber(this.usageFee, 0) || 0,
            roundNumber(this.solarSavingFeeAmount, 0) || 0
        ];
        // 기존 API를 재활용해 요약을 생성 (확장된 다중 컬럼 지원)
        excel.setSummaryData(summaryLabels, summaryValues);
        // 본문 시간 별 데이터 셋팅
        const times = this.chartType === 'monthly' ? getMonthlyChartXAxis(this.date) : getYearlyChartXAxis(this.date);
        for (let time of times) {
            const powerUsage = powerUsageData[time] || {};
            const hourUsage = powerUsage?.usage || 0;
            const hourGeneration = excelData[time]?.reduce((acc, curr) => acc + curr, 0) || 0;
            const hourFee = powerUsage?.fee || 0;
            const hourSavingFee = solarSavingFeeData[time]?.value || 0;
            excel.addRow([time, hourUsage, hourGeneration, hourFee, hourSavingFee]);
        }
        downloadExcel(excel, fileName);
    }
};
__decorate([
    state(),
    __metadata("design:type", String)
], PowerGenerationHistoryPage.prototype, "powerPlantId", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], PowerGenerationHistoryPage.prototype, "currentPath", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], PowerGenerationHistoryPage.prototype, "powerPlantDetail", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], PowerGenerationHistoryPage.prototype, "usageAmount", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], PowerGenerationHistoryPage.prototype, "maxPeakPower", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], PowerGenerationHistoryPage.prototype, "generationAmount", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], PowerGenerationHistoryPage.prototype, "generationTime", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], PowerGenerationHistoryPage.prototype, "solarSavingFeeAmount", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], PowerGenerationHistoryPage.prototype, "usageFee", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], PowerGenerationHistoryPage.prototype, "seriesNames", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], PowerGenerationHistoryPage.prototype, "monthYearlyTableData", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], PowerGenerationHistoryPage.prototype, "monthYearlyTableSummary", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], PowerGenerationHistoryPage.prototype, "chartData", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], PowerGenerationHistoryPage.prototype, "chartType", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], PowerGenerationHistoryPage.prototype, "chartInverterType", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], PowerGenerationHistoryPage.prototype, "date", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], PowerGenerationHistoryPage.prototype, "seriesTypes", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], PowerGenerationHistoryPage.prototype, "donutData", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], PowerGenerationHistoryPage.prototype, "inverterList", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], PowerGenerationHistoryPage.prototype, "selectedInverter", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], PowerGenerationHistoryPage.prototype, "inverterHistoryList", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], PowerGenerationHistoryPage.prototype, "inverterHistoryCount", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], PowerGenerationHistoryPage.prototype, "page", void 0);
__decorate([
    query('power-plant-header'),
    __metadata("design:type", Object)
], PowerGenerationHistoryPage.prototype, "powerPlantHeader", void 0);
PowerGenerationHistoryPage = __decorate([
    customElement('power-generation-history-page')
], PowerGenerationHistoryPage);
export { PowerGenerationHistoryPage };
//# sourceMappingURL=power-generation-history-page.js.map