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 { getPowerPlantDetailAndSummary, getPowerPlantHeaderInfo } from '../entities/power-plant/query';
import { QUERY_INVERTER_STATUS_LIST_BY_POWER_PLANT_ID, QUERY_DAILY_INVERTER_SUMMARY_BY_DATE, QUERY_INVERTER_SUMMARY_MONTHLY_BY_POWER_PLANT_ID } from '../entities/inverter/query';
import '../widgets/power-plant-header';
import '../features/progress-circle';
import { roundNumber, arrayToObject, getDailyChartXAxis, getMonthlyChartXAxis, getYearlyChartXAxis, getSolarSavingFeeWithTax } from '../shared/utils/func/common';
import { getCityWeather } from '../shared/api/queries/weather';
import { getToday } from '../shared/utils/func/common';
import { CARBON_EMISSION_FACTORS_KG } from '../shared/const/common';
import { getFirstPowerPlantId } from '../shared/utils/func/power-plant';
import '../features/eaas-chart';
import '../widgets/generation-status-page/popup-inverter-detail';
import '../features/dashboard-arrow-animation';
import moment from 'moment';
import { getRefreshTime } from '../shared/api/queries/common';
import { isMobileDevice } from '@operato/utils';
import { QUERY_POWER_USAGE_BY_DATE } from '../entities/power-usage/query';
import { QUERY_POWER_PLANT_STATE_BY_YEAR_MONTH } from '../entities/power-plant-state/query';
import { getExpectedSolarSavingFeeByDate, QUERY_POWER_BILL_SUMMARY_BY_YEAR } from '../entities/power-bill/query';
import { client } from '@operato/graphql';
import gql from 'graphql-tag';
import { IS_DEV } from '../shared/const/common';
import '../features/small-tooltip';
let GenerationStatusPage = class GenerationStatusPage extends PageView {
    constructor() {
        super(...arguments);
        this.powerPlantId = '';
        this.powerPlantDetail = {};
        this.powerPlantSummary = {};
        this.todayPowerUsageValue = 0;
        this.todayGenerated = 0;
        this.todayPowerUsages = [];
        this.powerGenerations = [];
        this.thisMonthPowerBill = 0;
        this.thisMonthPowerPlantState = {};
        this.inverterStatuses = [];
        this.currentPath = '';
        this.todaySolarSavingFee = 0;
        this.thisMonthSolarSavingFee = 0;
        this.weathers = {};
        this.powerPlantHeaderInfo = {};
        this.powerUsageChartData = [];
        this.powerUsageSeriesNames = [];
        this.peakPowerChartData = [];
        this.peakPowerSeriesNames = [];
        this.peakPowerSeriesTypes = [];
        this.carbonEmissionChartData = [];
        this.carbonEmissionSeriesNames = [];
        this.powerBillChartData = [];
        this.powerBillSeriesNames = [];
        this.isActiveTime = false; // 현재 발전소가 일몰~일출 사이여서 발전하고 있는 상태인지 여부
    }
    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 - 90px); /* Full height of the viewport */
          border-top: 1px solid var(--md-sys-color-on-tertiary-container);
          padding: 20px 25px;
          color: var(--md-sys-color-on-secondary);
          overflow-y: auto;
        }
        h2 {
          margin: 0;
        }
        .container > div {
          display: flex;
          gap: 10px;
          padding: 10px 0;
        }
        div.scroll-container {
          overflow-y: auto;
          padding-top: 1.5%;
        }
        div.main-container {
          display: flex;
          flex: 1;
          gap: 20px;
          height: fit-content;
        }
        .container-A {
          display: flex;
          justify-content: space-between;
        }
        .container-A-1 {
          flex: 3;
        }
        .container-B {
          flex: 4;
        }
        .container-A-2,
        .container-C {
          flex: 5;
        }
        .container-A-3,
        .container-D {
          flex: 2;
        }
        .container-A .content {
          display: flex;
        }

        .container-B {
          display: flex;
          gap: 20px;
          flex-direction: column;
          height: fit-content;
        }

        .container-B-1 {
          display: flex;
          gap: 20px;
          min-width: 400px;
          flex: 1;
        }

        .container-B-1 .left,
        .container-B-1 .right {
          display: flex;
          flex-direction: column;
          gap: 10px;

          .progress-container {
            display: flex;
            margin-block: 15px;
            justify-content: space-between;

            .progress-state {
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              gap: 4px;
              min-width: 75px;

              & > div {
                gap: 4px;

                label.main {
                  font-size: 0.8em;
                  font-weight: 600;
                }
                label.sub {
                  font-size: 0.6em;
                  color: #fff;
                }
              }

              span.current-value {
                font-size: 0.9em;
              }
            }
          }
        }

        .container-B-1 .left {
          flex: 1;
          min-width: 110px;

          div.info-cell {
            flex: 1;
          }
        }

        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;
        }
        label {
          display: block;
          color: var(--md-sys-color-surface-tint);
          font-size: 0.7em;
        }

        .container-B-1 .right {
          flex: 1;
          display: flex;
          flex-direction: column;
        }

        .container-B-1 .right > div:first-child {
          flex: 3;
          position: relative;

          .progress-circle {
            min-width: 140px;

            progress-circle {
              width: 90%;
              justify-self: center;
            }
          }
        }

        .container-B-1 .right > div:last-child {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
        }

        .container-B-2 {
          flex: 1;
          display: flex;
          flex-direction: column;

          .info-cell {
            padding: 13px;
          }

          .title-line {
            label {
              font-size: 0.8em;
              display: inline-block;
              margin-right: 5px;
              font-weight: 600;

              strong {
                font-size: 1.35em;
              }
            }
          }

          .revenue {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
          }

          .revenue label:last-of-type {
            margin-top: var(--margin-wide);
          }
          .revenue span.price {
            font-size: 0.8em;
          }
        }

        .container-C {
          display: flex;
          gap: 20px;
          flex-direction: column;
          min-height: 100%;
        }

        .container-C-1 {
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 10px;
        }

        .container-C-2 {
          background: url(../../assets/images/bg-inverter.png) no-repeat center 30px;
          background-size: 100%;
          position: relative;
          flex: 1;

          .title-line {
            margin-bottom: 10px;
          }

          span {
            margin-left: var(--margin-narrow);
            color: var(--md-sys-color-surface-tint);
            font-size: 0.9em;
          }

          dashboard-arrow-animation {
            position: absolute;
            top: 50px;
            width: 100%;
          }

          .inverter-status-container {
            display: inline;
            float: right;

            button {
              margin-left: 10px;
            }
          }
        }
        .container-C-2 strong {
          font-size: 1.3em;
          color: var(--md-sys-color-on-secondary);
          margin-left: 2px;
        }
        .inverter-status-list {
          display: none;
        }
        .dc-info,
        .ac-info {
          margin: 0 0 100px 0;
          position: relative;
          z-index: 5;
          max-height: 155px;
          overflow: hidden;
        }
        .dc-info div,
        .ac-info div {
          border: 1px solid var(--md-sys-color-on-tertiary-container);
          background-color: rgba(0, 0, 0, 0.3);
          border-radius: 10px;
          margin-top: 20px;
          margin-bottom: var(--padding-default);
          padding: var(--padding-narrow) var(--padding-default);
          text-align: center;
          font-size: 1.1em;
        }
        .dc-info {
          float: left;
          color: #c6f4c9;
        }
        .ac-info {
          float: right;
          color: #aebff0;
        }
        .dc-info span,
        .ac-info span {
          display: block;
          padding: var(--padding-narrow);
          padding-bottom: 0;
          text-align: center;
          font-size: 1em;
        }

        .inverter-status-list {
          background: none !important;
          border: none !important;
          margin-top: 5px !important;
          margin-bottom: 0px !important;
          padding: 0 !important;
          font-size: 1em !important;

          &.inverter-status-list.dc span {
            color: #c6f4c9;
          }

          strong {
            font-size: 1em;
            margin-left: 2px;
          }
        }

        .container-D {
          display: flex;
          flex-direction: column;
          min-height: 100%;
          gap: 20px;
          min-width: 300px;

          & > div {
            flex: 1;
            display: flex;
            flex-direction: column;
          }

          .container-D-2-bottom {
            .value-container {
              font-size: 1.35em;
              text-align: right;
              padding-right: 10px;
            }
          }
        }

        div.side-weather {
          background-color: #2f3e66;
          border-radius: 7px;
          display: grid;
          grid-template-columns: 1fr 2fr 1fr 2fr;
          gap: var(--padding-narrow) var(--padding-default);
        }
        div.side-weather label {
          font-size: 1em;
        }
        div.side-inverter {
          display: flex;
          flex-direction: column;
          gap: var(--padding-default);
          max-height: 300px;
          overflow-y: auto;
          padding: var(--padding-default) 0;
        }
        .inverter-cell {
          gap: var(--padding-default);
          display: flex;
          align-items: center;
          padding-bottom: var(--padding-narrow);
          border-bottom: 1px solid rgba(173, 191, 240, 0.2);

          .issue-status-normal {
            color: var(--status-success-color);
          }
          .issue-status-stop {
            color: var(--status-warning-color);
          }
          .issue-status-fault {
            color: var(--status-danger-color);
          }
          .issue-status-communication_fault {
            color: #9d2adb;
          }
          .inverter-status {
            margin-top: -16px;
            border-radius: 50%;
            width: 34px;
            height: 34px;
            text-align: center;
            font-variation-settings: 'wght' 300;

            md-icon {
              font-size: 28px;
              position: relative;
              top: 5px;
            }
            span {
              width: 100%;
              display: block;
              position: relative;
              font-size: 0.65em;
              letter-spacing: -1px;
              top: 5px;
              white-space: nowrap;
            }
          }
          .inverter-info {
            flex: 1;
            font-size: 0.9em;

            .dc {
              display: block;
              color: #c6f4c9;
              line-height: 1.2;
            }
            .ac {
              display: block;
              color: #aebff0;
              line-height: 1.2;
            }
            label {
              font-size: 1.2em;
              line-height: 1;
              font-weight: bold;
              color: var(--md-sys-color-on-secondary);
            }
          }
          div.capacity {
            padding-right: var(--padding-default);
            text-align: center;
            line-height: 1;
          }
          .capacity strong {
            display: block;
            font-size: 1.15em;
          }
          .capacity span {
            opacity: 0.8;
            font-size: 0.8em;
          }
        }
        div.side-plant {
          max-height: 300px;
          overflow-y: auto;
          background-color: #02134a;
          border-radius: 7px;
          color: var(--md-sys-color-surface-tint);
        }
        .side-plant label {
          font-size: 1.1em;
          font-weight: 600;
        }
        .side-plant strong {
          display: block;
          margin-bottom: var(--padding-narrow);
          color: var(--md-sys-color-on-secondary);
          font-size: 0.8em;
          font-weight: 400;
        }
        .title-line h3 {
          display: inline-block;
          margin: 0;
        }
        .title-line button * {
          vertical-align: middle;
        }
        .title-line button {
          float: right;
          background-color: var(--md-sys-color-tertiary);
          border: 0;
          border-radius: 9px;
          padding: var(--padding-narrow) var(--padding-default);
          color: var(--md-sys-color-on-secondary);
          font-size: 0.9em;
          line-height: 1.2;
          letter-spacing: -1px;
          cursor: pointer;

          md-icon {
            --md-icon-size: 18px;
            position: relative;
            top: -1px;
          }
        }
        .title-line button:hover {
          background-color: var(--status-success-color);
        }
        .shidden {
          display: none !important;
        }

        .chart-container {
          flex: 1;

          & > eaas-chart {
            display: block;
            height: 100%;
            min-height: 220px;

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

        /* Mobile Styles */
        @media (max-width: 768px) {
          div.main-container {
            padding-top: var(--padding-default);
          }
          div.info-cell {
            font-size: 1.2em;
            padding: var(--padding-narrow) var(--padding-wide);
          }
          .shidden {
            display: initial !important;
          }
          .recent-avg-label {
            position: absolute;
            right: 10px;
            bottom: 0px;
            font-size: 0.4em;
            color: var(--md-sys-color-on-secondary);
            opacity: 0.8;
            display: block;
          }
          .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 {
            flex-direction: column;
          }
          .container-B {
            flex: initial;
            gap: var(--padding-default);
          }
          .container-B-1 {
            gap: var(--padding-default);
            display: flex;
            flex-direction: column;
            min-width: unset;

            .left {
              flex-direction: row;
            }

            .right {
              .progress-container {
                justify-content: space-around;
              }
            }
          }
          div.container-B-2 {
            gap: var(--padding-default);
          }
          .container-C {
            display: flex;
            flex: 1;
            gap: 15px;
          }

          .container-C-2 {
            flex: 1;
            background: none;

            .dc-info,
            .ac-info {
              width: 48.5%;
              margin: 0;
              display: inline-block;
              float: initial;
              position: initial;
              max-height: initial;
            }
            .dc-info div,
            .ac-info div {
              margin: 0;
              padding: var(--padding-narrow);
              font-size: 0.8em;
            }
            .dc-info {
              margin-right: 1%;
            }

            span {
              font-size: 0.8em;
            }
          }
          .container-C-2 strong {
            display: initial;
          }

          .inverter {
            display: flex !important;
            flex-direction: column;
            gap: var(--padding-default);
          }
          .inverter-cell {
            gap: var(--padding-default);
            display: flex;
            align-items: center;
            margin-top: var(--margin-default);
            padding-bottom: var(--padding-default);
            border-bottom: 1px solid rgba(173, 191, 240, 0.2);
            position: relative;

            .inverter-status {
              margin-top: -16px;
              border-radius: 50%;
              width: 34px;
              height: 34px;
              text-align: center;
              font-variation-settings: 'wght' 300;

              md-icon {
                font-size: 28px;
                position: relative;
                top: 5px;
              }
              span {
                width: 100%;
                display: block;
                position: relative;
                top: 5px;
                margin-left: 0;
                font-size: 0.65em;
                letter-spacing: -1px;
              }
            }
            .inverter-info {
              flex: 1;
              font-size: 0.9em;

              label {
                font-size: 1.2em;
                line-height: 1;
                font-weight: bold;
              }
            }
            .capacity {
              font-size: 0.9em;
              color: #c6f4c9;

              strong {
                font-size: 1.3em;
                color: #c6f4c9;
              }
            }
          }

          .issue-status-normal {
            color: var(--status-success-color);
          }
          .issue-status-stop {
            color: var(--status-warning-color);
          }
          .issue-status-fault {
            color: var(--status-danger-color);
          }
          .issue-status-communication_fault {
            color: #9d2adb;
          }
        }
      }
    `
    ]; }
    get context() {
        return { title: '전력현황' };
    }
    render() {
        if (!this.powerPlantId)
            return html ``;
        const isMobile = isMobileDevice();
        const { capacity, alternatingCurrent = 0, collectedAt: inverterCollectedAt = '' } = this.powerPlantDetail;
        const { feeApplyPower } = this.thisMonthPowerPlantState;
        const currGenerationCreatedAt = moment(Number(inverterCollectedAt)).tz('Asia/Seoul').format('HH:mm');
        const currMaxDemand = this.todayPowerUsages?.at(-1)?.maxDemand || 0;
        let currMaxDemandCreatedAt = this.todayPowerUsages?.at(-1)?.createdAt;
        currMaxDemandCreatedAt = currMaxDemandCreatedAt
            ? moment(currMaxDemandCreatedAt).tz('Asia/Seoul').format('HH:mm')
            : '';
        const { sum_acc, avg_generation_time } = this.powerPlantSummary;
        const sumSign = sum_acc > 1000 ? 'MWh' : 'kWh';
        const sumAccValue = sum_acc > 1000 ? sum_acc / 1000 : sum_acc;
        // 프로그레시브 데이터
        const generationRate = !alternatingCurrent || !capacity ? 0 : roundNumber((alternatingCurrent / capacity) * 100, 1);
        const peakRate = !feeApplyPower || !currMaxDemand ? 0 : roundNumber((currMaxDemand / feeApplyPower) * 100, 1);
        const weather = this.weathers[this.powerPlantDetail.weatherId]?.weather || {};
        const now = new Date();
        const sunriseTime = new Date(weather.sunrise || 0);
        const sunsetTime = new Date(weather.sunset || 0);
        this.isActiveTime = now >= sunsetTime && now <= sunriseTime;
        // 예상 전기 요금
        const todaySolarSavingFeeWithTax = getSolarSavingFeeWithTax(this.todaySolarSavingFee);
        const thisMonthSolarSavingFeeWithTax = getSolarSavingFeeWithTax(this.thisMonthSolarSavingFee);
        // 탄소배출 저감 효과
        const carbonEmissionEffect = this.carbonEmissionChartData.reduce((acc, cur) => acc + cur.values[0], 0);
        return html `
      <div class="container">
        <power-plant-header .powerPlantId=${this.powerPlantId} .currentPath=${this.currentPath}></power-plant-header>

        <div class="scroll-container">
          <div class="main-container">
            <div class="container-B">
              <div class="container-B-1">
                <div class="left">
                  <div class="info-cell">
                    <label>오늘 전력사용량</label>
                    <strong>${roundNumber(this.todayPowerUsageValue, 1)?.toLocaleString() || 0}</strong> kWh
                  </div>
                  <div class="info-cell">
                    <label>오늘 발전량</label>
                    <strong>${roundNumber(this.todayGenerated, 1)?.toLocaleString() || 0}</strong> kWh
                  </div>
                  <div class="info-cell">
                    <label>이번달 발전량</label>
                    <strong>${roundNumber(sumAccValue, 2)?.toLocaleString() || 0}</strong> ${sumSign}
                  </div>
                  <div class="mhidden info-cell">
                    <label>이번달 평균 발전시간</label>
                    <strong>${roundNumber(avg_generation_time, 1)?.toLocaleString() || 0}</strong> 시간
                  </div>
                </div>
                <div class="right">
                  <div class="info-cell">
                    <div class="progress-container">
                      <div class="progress-state">
                        <div>
                          <label class="main">이용률</label>
                          <label class="sub">${currGenerationCreatedAt}기준</label>
                        </div>
                        <div class="current-value"><strong>${alternatingCurrent.toLocaleString()}</strong>kW</div>
                      </div>
                      <div class="progress-circle">
                        <progress-circle
                          .value=${generationRate}
                          suffix="%"
                          fontSize=${isMobile ? '23px' : '25px'}
                          fontColor="#fff"
                          borderStyle="none"
                          innerCircleSize="35%"
                          circleColor="#00d167"
                          shadow="#00000026 4px 4px 4px"
                          background="rgba(0,0,0,.4)"
                        ></progress-circle>
                      </div>
                    </div>

                    <div class="progress-container">
                      <div class="progress-state">
                        <div>
                          <label class="main">피크 전력</label>
                          <label class="sub"> ${currMaxDemandCreatedAt}기준 </label>
                        </div>
                        <div class="current-value"><strong>${currMaxDemand.toLocaleString()}</strong>kW</div>
                      </div>
                      <div class="progress-circle">
                        <progress-circle
                          .value=${peakRate}
                          suffix="%"
                          fontSize=${isMobile ? '23px' : '25px'}
                          fontColor="#fff"
                          borderStyle="none"
                          innerCircleSize="35%"
                          circleColor="#FF8800"
                          shadow="#00000026 4px 4px 4px"
                          background="rgba(0,0,0,.4)"
                        ></progress-circle>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="container-B-2 mhidden">
                <div class="info-cell">
                  <div class="title-line">
                    <label>이달 예상 전기 요금</label>
                    <strong>${roundNumber(this.thisMonthPowerBill / 1000, 0).toLocaleString()} 천원</strong>
                  </div>

                  <div class="chart-container">
                    <eaas-chart
                      .data=${this.powerBillChartData}
                      chartType="bar"
                      .seriesNames=${this.powerBillSeriesNames}
                      .prefix=${' 천원'}
                      .barColor=${'#03B3BE'}
                      .barWidth=${'50%'}
                      .hideLegend=${true}
                    >
                    </eaas-chart>
                  </div>

                  <div class="revenue">
                    <div>
                      <label>금일 태양광 절감 효과</label>
                      <span class="price">${roundNumber(this.todaySolarSavingFee, 0).toLocaleString()} 원</span>
                    </div>
                    <div>
                      <label>이번 달 태양광 절감 효과</label>
                      <span class="price">${roundNumber(this.thisMonthSolarSavingFee, 0).toLocaleString()} 원</span>
                    </div>
                    <div>
                      <label
                        >전력 산업 기반 기금
                        <small-tooltip
                          content="전력산업 재원 확보를 위해 부과되는 세금 2025.07 기준 2.7%"
                        ></small-tooltip>
                      </label>
                      <span class="price">${roundNumber(todaySolarSavingFeeWithTax, 0).toLocaleString()} 원</span>
                    </div>
                    <div>
                      <label>이번 달 전력 산업 기반 기금</label>
                      <span class="price">${roundNumber(thisMonthSolarSavingFeeWithTax, 0).toLocaleString()} 원</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="container-C">
              <div class="container-C-1">
                <div class="title-line">
                  <h3>전력 현황</h3>
                </div>
                <div class="chart-container">
                  <eaas-chart
                    .data=${this.powerUsageChartData}
                    chartType="bar"
                    .seriesNames=${this.powerUsageSeriesNames}
                    .stacked=${true}
                    .stackedColors=${['#59AFF8', '#FF8800']}
                    .barWidth=${'50%'}
                    .hideLegend=${false}
                  >
                  </eaas-chart>
                </div>
              </div>

              <div class="container-C-2 mhidden">
                <div class="title-line">
                  <h3>인버터 현황</h3>
                  <div class="inverter-status-container">
                    <span class="mhidden">수신 시간:</span><span>${this.getInverterLastReceivedTime()}</span>
                    <button @click=${() => this.popupInverterDetail.open()}>
                      <md-icon>find_in_page</md-icon>운전정보
                    </button>
                  </div>
                </div>
                <div class="dc-info">
                  <div>
                    DC출력
                    <strong>${roundNumber(this.inverterStatuses.reduce((acc, cur) => acc + cur.dc, 0))} kW</strong>
                  </div>

                  <div class="inverter-status-list dc">
                    ${this.inverterStatuses.slice(0, 3).map((v, idx) => {
            return html ` <span>인버터${idx + 1} <strong>${v.dc} kW</strong></span> `;
        })}
                  </div>
                </div>
                <div class="ac-info">
                  <div>
                    AC출력
                    <strong>${roundNumber(this.inverterStatuses.reduce((acc, cur) => acc + cur.ac, 0))} kW</strong>
                  </div>

                  <div class="inverter-status-list ac">
                    ${this.inverterStatuses.slice(0, 3).map((v, idx) => {
            return html ` <span>인버터${idx + 1} <strong>${v.ac} kW</strong></span> `;
        })}
                  </div>
                </div>

                <dashboard-arrow-animation class="mhidden"></dashboard-arrow-animation>
              </div>
              <!-- 인버터 현황 Container end-->
            </div>
            <!-- 시간대별 발전량,인버터 현황 중앙 Container end-->

            <div class="container-D">
              <div class="container-D-1-top">
                <div class="title-line"><h3>당일 피크 전력 관리</h3></div>
                <div class="chart-container">
                  <eaas-chart
                    .data=${this.peakPowerChartData}
                    chartType="mixed"
                    .seriesNames=${this.peakPowerSeriesNames}
                    .seriesTypes=${this.peakPowerSeriesTypes}
                    .mixedColors=${['#FF4444', '#FF8801']}
                    .lineMarkerSize=${0}
                    .barWidth=${'50%'}
                    .hideLegend=${false}
                    .legendPosition=${'top'}
                    .prefix=${' kW'}
                  >
                  </eaas-chart>
                </div>
              </div>

              <div class="container-D-2-bottom">
                <div class="title-line"><h3>이달 탄소배출 저감효과</h3></div>
                <div class="value-container">
                  <strong>${roundNumber(carbonEmissionEffect / 1000, 2)}</strong> ton/월
                </div>
                <div class="chart-container">
                  <eaas-chart
                    .data=${this.carbonEmissionChartData}
                    chartType="bar"
                    .seriesNames=${this.carbonEmissionSeriesNames}
                    .prefix=${' Kg CO₂'}
                    .barWidth=${'50%'}
                    .barColor=${'#00D167'}
                    .hideLegend=${true}
                  >
                  </eaas-chart>
                </div>
              </div>

              <!-- 모바일용 이달 예상 전기 요금-->
              <div class="container-B-2 shidden">
                <div class="info-cell">
                  <div class="title-line">
                    <label>이달 예상 전기 요금</label>
                    <strong>${roundNumber(this.thisMonthPowerBill / 1000, 0).toLocaleString()} 천원</strong>
                  </div>

                  <div class="chart-container">
                    <eaas-chart
                      .data=${this.powerBillChartData}
                      chartType="bar"
                      .seriesNames=${this.powerBillSeriesNames}
                      .prefix=${' 원'}
                      .barColor=${'#03B3BE'}
                      .barWidth=${'50%'}
                      .hideLegend=${true}
                    >
                    </eaas-chart>
                  </div>

                  <div class="revenue">
                    <div>
                      <label>금일 태양광 절감 효과</label>
                      <span class="price">${roundNumber(this.todaySolarSavingFee, 0).toLocaleString()} 원</span>
                    </div>
                    <div>
                      <label>이번 달 태양광 절감 효과</label>
                      <span class="price">${roundNumber(this.thisMonthSolarSavingFee, 0).toLocaleString()} 원</span>
                    </div>
                    <div>
                      <label
                        >전력 산업 기반 기금
                        <small-tooltip
                          content="전력산업 재원 확보를 위해 부과되는 세금 2025.07 기준 2.7%"
                        ></small-tooltip>
                      </label>
                      <span class="price">${roundNumber(todaySolarSavingFeeWithTax, 0).toLocaleString()} 원</span>
                    </div>
                    <div>
                      <label>이번 달 전력 산업 기반 기금</label>
                      <span class="price">${roundNumber(thisMonthSolarSavingFeeWithTax, 0).toLocaleString()} 원</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            </div>
            <!-- 중앙 Container end-->
          </div>
        </div>
        <!-- 전체레이아웃 Container end-->

        <popup-inverter-detail .powerPlantId=${this.powerPlantId}></popup-inverter-detail>
      </div>
    `;
    }
    async pageUpdated(changes, lifecycle) {
        if (this.active) {
            if (!lifecycle.resourceId) {
                navigate(`${lifecycle.page}/${await getFirstPowerPlantId()}`);
                return;
            }
            moment.locale('ko');
            this.powerPlantId = lifecycle.resourceId;
            this.currentPath = lifecycle.page;
            await this.updateComplete;
            this.getData();
            if (isMobileDevice() === false) {
                const refreshTime = await getRefreshTime();
                if (this.refreshInterval)
                    clearInterval(this.refreshInterval);
                this.refreshInterval = window.setInterval(() => {
                    this.getData();
                }, refreshTime);
            }
        }
        else {
            if (this.refreshInterval) {
                clearInterval(this.refreshInterval);
                this.refreshInterval = undefined;
            }
        }
    }
    async getData() {
        // 헤더 정보 갱신
        if (this.powerPlantHeader) {
            await this.powerPlantHeader.fetchPowerPlantHeaderInfo();
        }
        // 발전소 정보
        const { data: powerPlantDetail } = (await getPowerPlantDetailAndSummary(this.powerPlantId)) || {};
        this.powerPlantDetail = powerPlantDetail.powerPlantDetail || {};
        this.powerPlantSummary = powerPlantDetail.powerPlantSummary || {};
        // 발전 데이터
        const { data: powerData } = await this.getPowerData();
        // 시간대 별 오늘 사용량
        this.todayPowerUsages = powerData.powerUsageByDate;
        // 오늘 사용량 합계
        this.todayPowerUsageValue = this.todayPowerUsages.reduce((acc, cur) => acc + cur.usage, 0);
        // 오늘 발전량
        this.todayGenerated = powerData.inverterSummaryDailyByPowerPlantId.reduce((acc, cur) => acc + cur.value, 0);
        // 시간대 별 오늘 발전량
        this.powerGenerations = powerData.inverterSummaryDailyByPowerPlantId;
        // 이번달 발전소 정보
        this.thisMonthPowerPlantState = powerData.powerPlantStateByYearMonth || {};
        // 인버터 상태
        this.inverterStatuses = powerData.inverterStatusListByPowerPlantId || [];
        const thisMonth = IS_DEV ? '2025-07' : moment().format('YYYY-MM');
        const powerBill = powerData.powerBillSummaryByYear?.find(v => v.yearMonth === thisMonth) || {};
        this.thisMonthPowerBill = powerBill.totalFee || 0;
        // 모바일에서 인버터 상태 표시용
        const { data: powerPlantHeaderInfo } = (await getPowerPlantHeaderInfo(this.powerPlantId)) || {};
        this.powerPlantHeaderInfo = powerPlantHeaderInfo;
        // 오늘/이번달 태양광 절감 효과
        this.todaySolarSavingFee = (await getExpectedSolarSavingFeeByDate(this.powerPlantId, getToday(), getToday(), 'YYYY-MM-DD')).reduce((acc, cur) => acc + (cur?.value || 0), 0);
        const fromDate = moment().startOf('month').format('YYYY-MM-DD');
        const toDate = moment().endOf('month').format('YYYY-MM-DD');
        this.thisMonthSolarSavingFee = (await getExpectedSolarSavingFeeByDate(this.powerPlantId, fromDate, toDate, 'YYYY-MM')).reduce((acc, cur) => acc + (cur?.value || 0), 0);
        this.getWeatherData();
        // 전력 사용량 차트
        this.getPowerUsageChartData(this.todayPowerUsages, this.powerGenerations);
        // 피크 차트
        this.getPeakPowerChartData(this.todayPowerUsages, this.thisMonthPowerPlantState.feeApplyPower);
        // 이번달 인버터 발전량으로 탄소 저감 계산
        this.getCarbonEmissionChartData(powerData.inverterSummaryMonthlyByPowerPlantId);
        // 이번달 전력 요금
        this.getPowerBillChartData(powerData.powerBillSummaryByYear);
    }
    async getWeatherData() {
        const weather = (await getCityWeather())?.items || [];
        this.weathers = arrayToObject(weather, 'id');
    }
    async getPowerUsageChartData(todayPowerUsages, powerGenerations) {
        const xDailyAxis = getDailyChartXAxis();
        const powerUsageByHour = arrayToObject(todayPowerUsages, 'hour', v => v.toString().padStart(2, '0')) || {};
        const powerGenerationByHour = arrayToObject(powerGenerations, 'date') || {};
        this.powerUsageChartData = xDailyAxis.map(v => ({
            label: v + '시',
            values: [
                powerUsageByHour[v]?.usage || 0, // 첫 번째 시리즈: 전력 사용량
                powerGenerationByHour[v]?.value || 0 // 두 번째 시리즈: 발전량
            ]
        }));
        this.powerUsageSeriesNames = ['전력 사용량', '태양광 발전량'];
    }
    async getPeakPowerChartData(todayPowerUsages, maxDemand = 0) {
        const xDailyAxis = getDailyChartXAxis();
        const result = arrayToObject(todayPowerUsages, 'hour', v => v.toString().padStart(2, '0')) || {};
        this.peakPowerChartData = xDailyAxis.map(v => ({
            label: v + '시',
            values: [maxDemand, result[v]?.maxDemand || 0]
        }));
        this.peakPowerSeriesNames = ['최대 수요', '피크 전력'];
        this.peakPowerSeriesTypes = ['line', 'bar'];
    }
    async getCarbonEmissionChartData(monthlyPowerGenerations) {
        const yearMonth = IS_DEV ? '2025-07' : moment().format('YYYY-MM');
        const xMonthlyAxis = getMonthlyChartXAxis(yearMonth);
        const result = arrayToObject(monthlyPowerGenerations, 'date') || {};
        this.carbonEmissionChartData = xMonthlyAxis.map(v => ({
            label: moment(v).format('DD') + '일',
            values: [(result[v]?.value || 0) * CARBON_EMISSION_FACTORS_KG]
        }));
        this.carbonEmissionSeriesNames = ['탄소 절감 효과'];
    }
    async getPowerBillChartData(powerBillSummaryByYear) {
        const xYearlyAxis = getYearlyChartXAxis(moment().year());
        const result = arrayToObject(powerBillSummaryByYear, 'yearMonth') || {};
        this.powerBillChartData = xYearlyAxis.map(v => ({
            label: moment(v).format('MM') + '월',
            values: [result[v]?.totalFee / 1000 || 0]
        }));
        this.powerBillSeriesNames = ['전력 요금'];
    }
    getInverterLastReceivedTime() {
        return moment(Math.max(...this.inverterStatuses.map(v => new Date(v.collectedAt).getTime())))
            .tz('Asia/Seoul')
            .format('YYYY. MM. DD. HH:mm:ss');
    }
    async getPowerData() {
        return await client.query({
            query: gql `
        query PowerData($date: String!, $powerPlantId: String!, $yearMonth: String!, $year: Float!) {
          ${QUERY_POWER_USAGE_BY_DATE}
          ${QUERY_DAILY_INVERTER_SUMMARY_BY_DATE}
          ${QUERY_POWER_PLANT_STATE_BY_YEAR_MONTH}
          ${QUERY_INVERTER_STATUS_LIST_BY_POWER_PLANT_ID}
          ${QUERY_INVERTER_SUMMARY_MONTHLY_BY_POWER_PLANT_ID}

          ${QUERY_POWER_BILL_SUMMARY_BY_YEAR}
        }
      `,
            variables: {
                date: getToday(),
                powerPlantId: this.powerPlantId,
                yearMonth: moment().format('YYYY-MM'),
                year: moment().year()
            }
        });
    }
};
__decorate([
    state(),
    __metadata("design:type", String)
], GenerationStatusPage.prototype, "powerPlantId", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "powerPlantDetail", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "powerPlantSummary", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], GenerationStatusPage.prototype, "todayPowerUsageValue", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], GenerationStatusPage.prototype, "todayGenerated", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "todayPowerUsages", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "powerGenerations", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], GenerationStatusPage.prototype, "thisMonthPowerBill", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "thisMonthPowerPlantState", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "inverterStatuses", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], GenerationStatusPage.prototype, "currentPath", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], GenerationStatusPage.prototype, "todaySolarSavingFee", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], GenerationStatusPage.prototype, "thisMonthSolarSavingFee", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "weathers", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "powerPlantHeaderInfo", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "powerUsageChartData", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "powerUsageSeriesNames", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "peakPowerChartData", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "peakPowerSeriesNames", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "peakPowerSeriesTypes", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "carbonEmissionChartData", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "carbonEmissionSeriesNames", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "powerBillChartData", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "powerBillSeriesNames", void 0);
__decorate([
    state(),
    __metadata("design:type", Boolean)
], GenerationStatusPage.prototype, "isActiveTime", void 0);
__decorate([
    query('popup-inverter-detail'),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "popupInverterDetail", void 0);
__decorate([
    query('power-plant-header'),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "powerPlantHeader", void 0);
GenerationStatusPage = __decorate([
    customElement('generation-status-page')
], GenerationStatusPage);
export { GenerationStatusPage };
//# sourceMappingURL=generation-status-page.js.map