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/queries/query';
import { getInverterStatusByPowerPlantId, getInverterSummaryDailyByPowerPlantId, getInverterSeperateDailyByPowerPlantId, getInverterSummaryMonthlyByPowerPlantId, getInverterRtuBindingListByPowerPlantId } from '../entities/inverter/queries/query';
import '../widgets/power-plant-header';
import '../features/progress-circle';
import { roundNumber, arrayToObject, getDailyChartXAxis } from '../shared/utils/func/common';
import { getCityWeather, getFineDust } from '../shared/api/queries/weather';
import { getTodaySmpAndRec, getThisMonthSmpAndRec } from '../entities/market/queries/query';
import { getToday } from '../shared/utils/func/common';
import { CARBON_EMISSION_FACTORS } from '../shared/const/common';
import { getFirstPowerPlantId, getPowerPlantStatus } from '../shared/utils/func/power-plant';
import '../features/eaas-chart';
import '../widgets/generation-status-page/popup-inverter-detail';
import '../features/dashboard-arrow-animation';
import '../features/chart-type-buttons';
import moment from 'moment-timezone';
import { getRefreshTime } from '../shared/api/queries/common';
import { POWER_PLANT_STATUS_DISPLAY } from '../shared/const/power-plant';
import { isMobileDevice } from '@operato/utils';
let GenerationStatusPage = class GenerationStatusPage extends PageView {
    constructor() {
        super(...arguments);
        this.powerPlantId = '';
        this.powerPlantDetail = {};
        this.powerPlantSummary = {};
        this.inverterStatuses = [];
        this.inverterRtuBindingList = [];
        this.currentPath = '';
        this.todaySmp = {};
        this.todayRec = {};
        this.thisMonthSmp = 0;
        this.thisMonthRec = 0;
        this.weathers = {};
        this.findDust = '';
        this.chartData = [];
        this.seriesNames = [];
        this.chartInverterType = 'summary';
        this.powerPlantHeaderInfo = {};
        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.main-container {
          flex: 1;
          gap: 15px;
          padding-top: 1.5%;
          overflow-y: auto;
        }
        .container-A {
          display: flex;
          justify-content: space-between;
        }
        .container-A-1,
        .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;
          flex-direction: column;
          gap: 15px;
        }

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

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

        .container-B-1 .left,
        .left 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;
        }

        .container-B-1 .right > div:last-child {
          flex: 1;
        }
        .container-B-2 {
          background-color: rgba(0, 0, 0, 0.2);
          display: grid !important;
          grid-template-columns: 1fr 1fr;
        }
        .container-B-2 .revenue-title {
          grid-column: 1 / 3;
          margin-bottom: var(--padding-default);
          padding-bottom: var(--padding-default);
          border-bottom: 1px solid var(--md-sys-color-on-tertiary-container);
          font-size: 0.6em;
          color: #c6f4c9;
          font-weight: bold;
        }
        .container-B-2 .revenue-title label {
          font-size: 1.5em;
          color: var(--md-sys-color-on-secondary);
          font-weight: bold;
        }
        .container-B-2 > div {
          flex: 1;
        }
        .container-B-2 .bigsize {
          margin-bottom: var(--padding-default);
          padding-bottom: var(--padding-default);
          border-bottom: 1px dashed var(--md-sys-color-on-tertiary-container);
          font-size: 1.3em;
        }
        .revenue-today label:last-of-type,
        .revenue-month label:last-of-type {
          margin-top: var(--margin-wide);
        }
        .revenue-month span {
          display: block;
          margin-top: var(--margin-default);
          opacity: 0.7;
          font-size: 0.6em;
          color: var(--md-sys-color-surface-tint);
        }
        .container-B-3 {
          display: flex;
          flex-direction: column;
          gap: 10px;

          div {
            background-color: rgba(0, 0, 0, 0.1);
            border: 1px solid var(--md-sys-color-on-tertiary-container);
            border-radius: 10px;
            padding: var(--padding-narrow) var(--padding-wide);
          }
        }
        .container-C {
          display: flex;
          flex-direction: column;
          gap: 20px;
        }

        .container-C-1 {
          flex: 1;
          display: flex;
          flex-direction: column;

          .container div {
            display: block;

            .apexcharts-tooltip.apexcharts-theme-dark {
              padding: 10px; /* 마우스 오버 툴팁 패딩 조정 */
            }
          }

          .chart-container {
            flex: 1;

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

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

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

          .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;
            }
          }
        }
        .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;
        }
        .container-C-2 strong {
          display: block;
          font-size: 1.3em;
          color: var(--md-sys-color-on-secondary);
        }

        .container-D {
          display: flex;
          flex-direction: column;
          gap: var(--padding-wide);
        }
        .container-D > div {
          padding: var(--padding-default) var(--padding-wide);
        }
        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 chart-type-buttons {
          float: right;
        }
        .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;
        }

        /* Mobile Styles */
        @media (max-width: 768px) {
          div.main-container {
            padding-top: var(--padding-default);
          }
          div.info-cell {
            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);

            .plant-status-text {
              position: absolute;
              top: 4px;
              right: 7px;
              font-size: 1em;
              font-weight: bold;
            }
          }
          div.container-B-3 {
            display: flex !important;
            flex-direction: row;
            gap: var(--padding-default);

            div {
              flex: 1;
              background-color: rgba(0, 0, 0, 0.3);
              border: 1px solid var(--md-sys-color-on-tertiary-container);
              border-radius: 10px;
              padding: var(--padding-default) var(--padding-default) var(--padding-narrow) var(--padding-default);
              line-height: 1.2;
              text-align: center;

              label {
                color: #c6f4c9;
                font-size: 0.8em;

                span {
                  opacity: 1;
                  padding-left: 3px;
                }
              }
              strong {
                display: block;
                font-size: 1.3em;
              }
              & > span {
                opacity: 0.7;
                font-size: 0.8em;

                span.rec-weight {
                  color: #c6f4c9;
                  font-weight: bold;
                }
              }
            }
          }
          .container-C {
            display: flex;
            flex: 1;
            gap: 15px;
          }
          .container-C-1 {
            .chart-container {
              & > eaas-chart {
                min-height: 250px;
              }
            }
          }
          .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 { name, address, ceo, ceoPhone, safetyManager, safetyManagerPhone, alternatingCurrent, capacity, todayGenerated, rec, inverterManufacturer, inverterModel } = this.powerPlantDetail;
        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 weather = this.weathers[this.powerPlantDetail.weatherId]?.weather || {};
        // HH:mm 형식으로 변환
        const formatter = new Intl.DateTimeFormat('ko-KR', {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
            timeZone: 'UTC'
        });
        const now = new Date();
        const sunriseTime = new Date(weather.sunrise || 0);
        const sunsetTime = new Date(weather.sunset || 0);
        const sunrise = formatter?.format(sunriseTime) || '';
        const sunset = formatter?.format(sunsetTime) || '';
        this.isActiveTime = now >= sunsetTime && now <= sunriseTime;
        const todaySmp = roundNumber(this.todaySmp.AVG_PRC * todayGenerated, 0) || 0;
        const todayRec = roundNumber((this.todayRec.AVG_PRC * todayGenerated * rec) / 1000, 0) || 0;
        const mobileStatus = getPowerPlantStatus(Number(this.powerPlantHeaderInfo?.maxInverterCommunicationStatus || 0), Number(this.powerPlantHeaderInfo?.maxInverterOperationStatus || 0), this.powerPlantHeaderInfo.isNoSignal);
        return html `
      <!-- 전체레이아웃 Container begin-->
      <div class="container">
        <!-- 상단 공통 바 Container begin-->
        <power-plant-header .powerPlantId=${this.powerPlantId} .currentPath=${this.currentPath}></power-plant-header>
        <!-- 상단 공통 바 Container end-->

        <!-- 중앙 Container begin-->
        <div class="main-container">
          <!-- 발전소별 요약정보 좌측 Container begin-->
          <div class="container-B">
            <!-- 요약정보 상단 Container begin-->
            <div class="container-B-1">
              <div class="left">
                <div class="info-cell">
                  <label>오늘의 발전량</label>
                  <strong>${roundNumber(todayGenerated, 1) || 0}</strong> kWh
                </div>
                <div class="info-cell">
                  <label>오늘의 발전시간</label>
                  <strong>${roundNumber(todayGenerated / capacity, 1) || 0}</strong> 시간
                </div>
                <div class="info-cell">
                  <label>이번달 발전량</label>
                  <strong>${roundNumber(sumAccValue, 2) || 0}</strong> ${sumSign}
                </div>
                <div class="mhidden info-cell">
                  <label>이번달 평균 발전시간</label>
                  <strong>${roundNumber(avg_generation_time, 1) || 0}</strong> 시간
                </div>
              </div>
              <div class="right">
                <div class="info-cell">
                  <label
                    >이용률
                    <span class="shidden plant-status-text issue-status-${mobileStatus.toLowerCase()}"
                      >${POWER_PLANT_STATUS_DISPLAY[mobileStatus]}</span
                    ></label
                  >
                  <progress-circle
                    .value=${generationRate}
                    suffix="%"
                    fontSize="29px"
                    fontColor="#fff"
                    borderStyle="none"
                    innerCircleSize="28%"
                    circleColor="#00d167"
                    shadow="#00000026 4px 4px 4px"
                    background="rgba(0,0,0,.4)"
                    style="margin-bottom: 18px; margin-top: 5px;"
                  ></progress-circle>
                  <label class="shidden recent-avg-label">※ 최근 30일 평균으로 산출 </label>
                </div>
                <div class="mhidden info-cell">
                  <label>co2절감효과</label>
                  <strong>${roundNumber(sum_acc * CARBON_EMISSION_FACTORS, 2)}</strong> ton/월
                </div>
              </div>
            </div>
            <!-- 요약정보 상단 Container end-->

            <!-- 현재정보 하단 Container begin-->
            <div class="container-B-2 info-cell mhidden">
              <div class="revenue-title">
                <label>발전수익</label>
                REC 가중치 ${this.powerPlantDetail?.rec || 0}
              </div>
              <div class="revenue-today">
                <div class="bigsize">
                  <label>오늘 현재 수익</label>
                  <strong>${(todaySmp + todayRec).toLocaleString()} 원</strong>
                </div>
                <label>오늘 SMP 현재 수익</label>
                <strong>${todaySmp.toLocaleString()} 원</strong>
                <label>오늘 REC 현재 수익</label>
                <strong>${todayRec.toLocaleString()} 원</strong>
              </div>
              <div class="revenue-month">
                <div class="bigsize">
                  <label>이번달 현재 수익</label>
                  <strong>${roundNumber(this.thisMonthSmp + this.thisMonthRec, 0).toLocaleString()} 원</strong>
                </div>
                <label>이번달 SMP 현재 수익</label>
                <strong>${roundNumber(this.thisMonthSmp, 0).toLocaleString()} 원</strong>
                <label>이번달 REC 현재 수익</label>
                <strong>${roundNumber(this.thisMonthRec, 0).toLocaleString()} 원</strong>
                <span>* SMP/REC 최근 30일 평균으로 산출</span>
              </div>
            </div>
            <div class="container-B-3 shidden">
              <div>
                <label>일간 현재 수익</label>
                <strong>${roundNumber(todaySmp + todayRec, 0).toLocaleString()}</strong>
                <span>원 / <span class="rec-weight">가중치 ${this.powerPlantDetail?.rec || 0}</span></span>
              </div>
              <div>
                <label>SMP <span>${moment(this.todaySmp.TRAD_DAY, 'YYYY-MM-DD').format('MM-DD(ddd)')}</span></label>
                <strong>${roundNumber(this.todaySmp.AVG_PRC, 2).toLocaleString()}</strong>
                <span>원 / kWh</span>
              </div>
              <div>
                <label>REC <span>${moment(this.todayRec.TRAD_DAY, 'YYYY-MM-DD').format('MM-DD(ddd)')}</span></label>
                <strong>${roundNumber(this.todayRec.AVG_PRC, 0).toLocaleString()}</strong>
                <span>원 / REC</span>
              </div>
            </div>
            <!-- 현재정보 하단 Container end-->
          </div>
          <!-- 발전소별 요약정보 좌측 Container end-->

          <!-- 시간대 별 발전량,인버터 현황 중앙 Container begin-->
          <div class="container-C">
            <div class="container-C-1">
              <div class="chart-header">
                <div class="title-line">
                  <h3>시간대 별 발전량</h3>
                  <chart-type-buttons
                    .selected=${this.chartInverterType}
                    @chart-type-changed="${(event) => this.setChartInverterType(event.detail)}"
                  ></chart-type-buttons>
                </div>
              </div>
              <div class="chart-container">
                <eaas-chart
                  .data=${this.chartData}
                  chartType=${this.chartInverterType === 'summary' ? 'bar' : 'line'}
                  .seriesNames=${this.seriesNames}
                  .hideLegend=${this.chartInverterType === 'summary'}
                >
                </eaas-chart>
              </div>
            </div>

            <!-- 인버터 현황 Container begin-->
            <div class="container-C-2">
              <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>
              <div class="ac-info">
                <div>
                  AC출력
                  <strong>${roundNumber(this.inverterStatuses.reduce((acc, cur) => acc + cur.ac, 0))} kW</strong>
                </div>
              </div>

              <dashboard-arrow-animation class="mhidden"></dashboard-arrow-animation>

              <div class="shidden inverter">
                ${this.inverterStatuses.map(v => {
            const status = getPowerPlantStatus(v.com, v.run);
            return html `
                    <div class="inverter-cell">
                      <div class="inverter-status issue-status-${status.toLowerCase()}">
                        <md-icon>offline_bolt</md-icon>
                        <span class="issue-status-${status.toLowerCase()}">${POWER_PLANT_STATUS_DISPLAY[status]}</span>
                      </div>
                      <div class="inverter-info">
                        <label>인버터 ${v.ivtId.toString().padStart(2, '0')}</label>
                        <span>입력 <strong>${v.dc}</strong> kW / 출력 <strong>${v.ac}</strong> kW</span>
                      </div>
                      <div class="capacity"><strong>${v.acc}</strong> kWh</div>
                    </div>
                  `;
        })}
              </div>
            </div>
            <!-- 인버터 현황 Container end-->
          </div>
          <!-- 시간대별 발전량,인버터 현황 중앙 Container end-->

          <!-- 날씨,발전소정보,설비정보 우측 Container begin-->
          <div class="container-D mhidden">
            <div class="side-weather">
              <label>일출</label>
              <strong>${sunrise || ''}</strong>
              <label>일몰</label>
              <strong>${sunset || ''}</strong>
              <label>풍속</label>
              <strong>${weather.windSpeed || 0}</strong>
              <label>미세</label>
              <strong>${this.findDust || ''}</strong>
            </div>

            <div class="side-inverter">
              ${this.inverterStatuses.map(v => {
            const status = getPowerPlantStatus(v.com, v.run);
            return html `
                  <div class="inverter-cell">
                    <div class="inverter-status issue-status-${status.toLowerCase()}">
                      <md-icon>offline_bolt</md-icon>
                      <span>${POWER_PLANT_STATUS_DISPLAY[status]}</span>
                    </div>
                    <div class="inverter-info">
                      <label>인버터 ${v.ivtId.toString().padStart(2, '0')}</label>
                      <span class="dc">입력 <strong>${v.dc}</strong> kW</span>
                      <span class="ac">출력 <strong>${v.ac}</strong> kW</span>
                    </div>
                    <div class="capacity"><strong>${v.acc}</strong><span>(kWh)</span></div>
                  </div>
                `;
        })}
            </div>

            <div class="side-plant">
              <label>발전소 정보</label>
              <strong>${name}</strong>

              ${address ? html `주소 <strong>${address}</strong>` : ''}
              ${capacity ? html `총 용량 <strong>${roundNumber(capacity || 0, 2)} kW</strong>` : ''}
              ${ceo || ceoPhone ? html `사업주<strong>${ceo}${ceoPhone ? `(${ceoPhone})` : ''}</strong>` : ''}
              ${safetyManager || safetyManagerPhone
            ? html `안전관리자<strong
                      >${safetyManager}${safetyManagerPhone ? `(${safetyManagerPhone})` : ''}</strong
                    >`
            : ''}
              ${inverterManufacturer ? html `인버터<strong>${inverterManufacturer}</strong>` : ''}
              ${inverterModel ? html `모델<strong>${inverterModel}</strong>` : ''} 수량
              <strong>${this.inverterStatuses.length}대</strong>

              ${this.inverterRtuBindingList?.[0]?.capacity
            ? html `용량 <strong>${roundNumber(this.inverterRtuBindingList?.[0]?.capacity, 0)} kW</strong>`
            : ''}
            </div>
          </div>
          <!-- 날씨,발전소정보,설비정보 우측 Container end-->
        </div>
        <!-- 중앙 Container end-->
      </div>
      <!-- 전체레이아웃 Container end-->

      <popup-inverter-detail .powerPlantId=${this.powerPlantId}></popup-inverter-detail>
    `;
    }
    async pageUpdated(changes, lifecycle) {
        if (this.active) {
            if (!lifecycle.resourceId) {
                navigate(`${lifecycle.page}/${await getFirstPowerPlantId()}`);
                return;
            }
            moment.locale('ko');
            this.initParams();
            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;
            }
        }
    }
    initParams() {
        this.chartInverterType = 'summary';
    }
    async getData() {
        // 헤더 정보 갱신
        if (this.powerPlantHeader) {
            await this.powerPlantHeader.fetchPowerPlantHeaderInfo();
        }
        const { data } = (await getPowerPlantDetailAndSummary(this.powerPlantId)) || {};
        this.powerPlantDetail = data.powerPlantDetail || {};
        this.powerPlantSummary = data.powerPlantSummary || {};
        const { data: inverterStatuses } = (await getInverterStatusByPowerPlantId(this.powerPlantId)) || {};
        this.inverterStatuses = inverterStatuses;
        this.inverterRtuBindingList = (await getInverterRtuBindingListByPowerPlantId(this.powerPlantId)) || {};
        // 모바일에서 인버터 상태 표시용
        const { data: powerPlantHeaderInfo } = (await getPowerPlantHeaderInfo(this.powerPlantId)) || {};
        this.powerPlantHeaderInfo = powerPlantHeaderInfo;
        const { data: todaySmpAndRec } = (await getTodaySmpAndRec()) || {};
        this.todaySmp = {
            AVG_PRC: todaySmpAndRec.todaySmp.AVG_PRC,
            TRAD_DAY: todaySmpAndRec.todaySmp.TRAD_DAY
        };
        this.todayRec = {
            AVG_PRC: todaySmpAndRec.todayRec.AVG_PRC,
            TRAD_DAY: todaySmpAndRec.todayRec.TRAD_DAY
        };
        const { data: thisMonthSmpAndRec } = (await getThisMonthSmpAndRec()) || {};
        const monthlySmpAvg = thisMonthSmpAndRec?.SMP?.AVG_PRC;
        const monthlyRecAvg = thisMonthSmpAndRec?.REC?.AVG_PRC;
        const inverterData = await getInverterSummaryMonthlyByPowerPlantId(this.powerPlantId, moment().format('YYYY-MM'));
        const inverterAccSum = inverterData.reduce((acc, cur) => acc + cur.value, 0);
        this.thisMonthRec = (monthlyRecAvg * inverterAccSum * this.powerPlantDetail?.rec || 0) / 1000;
        this.thisMonthSmp = monthlySmpAvg * inverterAccSum;
        this.getWeatherData();
        this.getChartData();
    }
    setChartInverterType(type) {
        this.chartInverterType = type;
        this.getChartData();
    }
    async getWeatherData() {
        const weather = (await getCityWeather())?.items || [];
        this.weathers = arrayToObject(weather, 'id');
        const { data: findDust } = (await getFineDust()) || {};
        this.findDust = findDust;
    }
    async getChartData() {
        const today = getToday();
        const xDailyAxis = getDailyChartXAxis();
        if (this.chartInverterType === 'summary') {
            const inverterChartData = (await getInverterSummaryDailyByPowerPlantId(this.powerPlantId, today)) || {};
            const result = arrayToObject(inverterChartData, 'date') || {};
            this.chartData = xDailyAxis.map(v => ({ label: v + '시', values: [result[v]?.value || 0] }));
        }
        else {
            const inverterChartData = (await getInverterSeperateDailyByPowerPlantId(this.powerPlantId, today)) || {};
            const result = {};
            // [{values: [10, 10]}] 형태의 데이터 만들기
            for (let icd of inverterChartData) {
                if (!result[icd.date]) {
                    result[icd.date] = { values: [] };
                }
                result[icd.date]['values'][icd.no - 1] = icd.value;
            }
            // 기본 길이로, 인버터가 3개면 [null, null, null] 형태로 만들기
            const defaultLen = new Array(result[Object.keys(result)?.[0]]?.values?.length).fill(null);
            this.chartData = xDailyAxis.map(v => ({ label: v + '시', values: result[v]?.values || defaultLen }));
        }
        const serisePrefix = isMobileDevice() ? '' : '인버터 ';
        this.seriesNames =
            this.chartInverterType === 'summary'
                ? ['발전량']
                : this.chartData[0]?.values?.map((v, idx) => `${serisePrefix}${(idx + 1).toString().padStart(2, '0')}`);
    }
    getInverterLastReceivedTime() {
        return moment(Math.max(...this.inverterStatuses.map(v => new Date(v.collectedAt).getTime())))
            .tz('Asia/Seoul')
            .format('YYYY. MM. DD. HH:mm:ss');
    }
};
__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", Object)
], GenerationStatusPage.prototype, "inverterStatuses", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "inverterRtuBindingList", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], GenerationStatusPage.prototype, "currentPath", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "todaySmp", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "todayRec", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], GenerationStatusPage.prototype, "thisMonthSmp", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], GenerationStatusPage.prototype, "thisMonthRec", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "weathers", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], GenerationStatusPage.prototype, "findDust", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "chartData", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], GenerationStatusPage.prototype, "seriesNames", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], GenerationStatusPage.prototype, "chartInverterType", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], GenerationStatusPage.prototype, "powerPlantHeaderInfo", 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