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 '../widgets/power-plant-header';
import '../features/eaas-calendar';
import '../features/eaas-pagenation';
import '../features/eaas-chart';
import { getTodaySmpAndRec, getSmps, getRecs } from '../entities/market/queries/query';
import moment from 'moment';
import { MARKET_PAGE_LIMIT } from '../shared/const/power-plant';
import { arrayToObject } from '../shared/utils/func/common';
import { getRefreshTime } from '../shared/api/queries/common';
import { isMobileDevice } from '@operato/utils';
import { getFirstPowerPlantId } from '../shared/utils/func/power-plant';
let MarketInfoPage = class MarketInfoPage extends PageView {
    constructor() {
        super(...arguments);
        this.powerPlantId = '';
        this.currentPath = '';
        this.fromDate = moment().subtract(1, 'month').format('YYYY-MM-DD'); // 1달전
        this.toDate = moment().format('YYYY-MM-DD');
        this.todaySmp = {};
        this.todayRec = {};
        this.smpPage = 1;
        this.recPage = 1;
        this.smpItems = [];
        this.smpTotal = 0;
        this.recItems = [];
        this.recTotal = 0;
        this.smpChartData = [];
        this.recChartData = [];
    }
    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 {
          flex: 1;
          margin: 0;
          padding: 0;
          font-size: 1.17em;
        }
        .container div {
          display: flex;
          gap: 10px;

          .chart > * {
            display: block;
            height: 100%;
            width: 100%;
            min-height: 200px;
          }

          .calendar-select-container {
            display: flex;
            gap: 6px;
            align-items: center;

            eaas-calendar {
              width: 210px;
            }
          }
        }
        div.title-container {
          margin: var(--margin-wide) 0 var(--margin-narrow) 0;
          padding: 0;
          position: relative;
        }
        .title-container div {
          gap: 0;
          padding: 0;
        }
        div.main-container {
          flex: 1;
          gap: 15px;
          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,
        .container-C {
          flex: 1;
          flex-direction: column;
        }

        .container-B-2,
        .container-C-2 {
          flex: 1;
        }
        .container-B-3,
        .container-C-3 {
          flex: 2;
        }
        div.average {
          border: 1px solid var(--md-sys-color-on-tertiary-container);
          border-radius: 10px;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          align-items: center;
          padding: var(--padding-default) var(--padding-wide);
          font-size: 1.2em;
        }
        .average .title {
          background: url(../../assets/images/market-arrow-smp.png) center no-repeat;
          background-size: cover;
          padding: 0 var(--padding-wide);
          padding-bottom: 15px;
          font-weight: bold;
          font-size: 0.9em;
        }
        .average label {
          color: var(--md-sys-color-surface-tint);
          font-size: 0.9em;
        }
        .rec.average label {
          color: #88e6eb;
        }
        .smp.average {
          border-color: #5079ff;
        }
        .rec.average {
          border-color: #03b3be;
        }
        .smp.date {
          color: var(--md-sys-color-surface-tint);
          font-size: 0.8em;
          flex: 1;
        }
        .rec.date {
          color: #88e6eb;
          font-size: 0.8em;
          flex: 1;
        }
        .rec.average .title {
          background: url(../../assets/images/market-arrow-rec.png) center no-repeat;
        }
        div.detail {
          flex: 2;
          flex-direction: column;
          overflow-y: auto;
        }
        div.chart {
          flex: 1;

          .apexcharts-tooltip.apexcharts-theme-dark {
            padding: 10px; /* 마우스 오버 툴팁 패딩 조정 */
          }
        }
        div.chart div {
          display: block;
        }
        .detail 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;
          }
          td {
            border-bottom: 1px solid rgba(173, 191, 240, 0.2);
            padding: 7px 4px;
            font-size: 0.9em;
            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;
            }
          }
        }
        .max {
          color: #f85864;
        }
        .min {
          color: #59aff8;
        }
        .avg {
          font-weight: bold;
        }
        div.pagenation {
          display: block;
          font-size: 0.9em;
        }
        .pagenation md-icon {
          font-size: 24px;
          color: var(--md-sys-color-surface-tint);
        }
        .pagenation .total {
          float: right;
          gap: 0 5px;
          color: var(--md-sys-color-surface-tint);
        }
        .total strong {
          color: var(--md-sys-color-on-secondary);
        }
        div.number {
          float: left;
          display: block;
          color: var(--md-sys-color-surface-tint);
        }
        .number * {
          vertical-align: middle;
          text-decoration: none;
        }
        .number a {
          padding: var(--padding-narrow) var(--padding-default);
          color: var(--md-sys-color-surface-tint);
        }
        .number a.active {
          color: var(--md-sys-color-on-secondary);
          font-weight: bold;
          text-decoration: underline;
        }
        .number a:hover {
          color: var(--md-sys-color-on-secondary);
          font-weight: bold;
          text-decoration: underline;
        }

        .shidden {
          display: none;
        }

        /* Mobile Styles */
        @media (max-width: 768px) {
          .container {
            height: calc(100vh - 130px); /* Full height of the viewport */
            padding: var(--padding-default);
            max-height: 100%;

            .calendar-select-container {
              eaas-calendar {
                width: 107px !important;
              }
              @supports (-webkit-touch-callout: none) {
                eaas-calendar {
                  width: 115px !important;
                }
              }
            }
          }
          .shidden {
            display: initial;
          }
          .mhidden {
            display: none !important; /* mobile mode content hidden */
          }
          .container-A,
          .main-container {
            flex-direction: column;
          }
          div.average {
            font-size: 1em;
          }
        }
      }
    `
    ]; }
    get context() {
        return { title: '시장정보' };
    }
    render() {
        if (!this.powerPlantId)
            return html ``;
        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 class="calendar-select-container">
            <eaas-calendar
              type="daily"
              .selectedDate=${this.fromDate}
              @change=${e => this.handleDateChange(e, 'fromDate')}
              hostStyle=${isMobileDevice() ? 'position: static;' : ''}
              displayFormat=${isMobileDevice() ? 'YY-MM-DD' : 'YYYY-MM-DD'}
              id="from-calendar"
            ></eaas-calendar>
            ~
            <eaas-calendar
              type="daily"
              .selectedDate=${this.toDate}
              @change=${e => this.handleDateChange(e, 'toDate')}
              hostStyle=${isMobileDevice() ? 'position: static;' : ''}
              displayFormat=${isMobileDevice() ? 'YY-MM-DD' : 'YYYY-MM-DD'}
              id="to-calendar"
            ></eaas-calendar>
          </div>
        </div>
        <!-- title container end-->

        <!-- 중앙 Container begin-->
        <div class="main-container">
          <!-- SMP 좌측 Container begin-->
          <div class="container-B">
            <div class="smp average">
              <div class="title">SMP</div>
              <span class="smp date"
                >${this.todaySmp?.TRAD_DAY ? moment(this.todaySmp.TRAD_DAY).format('MM-DD(ddd)') : ''}</span
              >
              <label>평균 SMP</label>
              <div class="value"><strong>${this.todaySmp?.AVG_PRC?.toLocaleString() || 0}</strong> 원/kWh</div>
            </div>
            <div class="chart">
              <eaas-chart
                .data=${this.smpChartData}
                chartType="line"
                barColor=${'#59AFF8'}
                .lineColors=${['#59AFF8']}
                .seriesNames=${['SMP']}
                .hideLegend=${true}
                .yTickAmount=${5}
                .xLabelRotate=${isMobileDevice() ? -30 : 0}
                .prefix=${' 원'}
              >
              </eaas-chart>
            </div>
            <div class="detail">
              <table class="issue-table">
                <tr>
                  <th>거래일</th>
                  <th>최대</th>
                  <th>최소</th>
                  <th>평균</th>
                </tr>
                ${this.smpItems.map(item => html `
                    <tr>
                      <td>${item.date || ''}</td>
                      <td class="max">${item.HIGH_PRC?.toLocaleString() || 0}</td>
                      <td class="min">${item.LOW_PRC?.toLocaleString() || 0}</td>
                      <td class="avg">${item.AVG_PRC?.toLocaleString() || 0}</td>
                    </tr>
                  `)}
              </table>

              <eaas-pagenation
                totalRecords=${this.smpTotal}
                pageSize=${MARKET_PAGE_LIMIT}
                @page-changed=${this.handleSmpPageChange}
                .currentPage=${this.smpPage}
                maxPages=${5}
              ></eaas-pagenation>
            </div>
          </div>
          <!-- SMP 좌측 Container end-->

          <!-- REC 우측 Container begin-->
          <div class="container-C">
            <div class="rec average">
              <div class="title">REC</div>
              <span class="rec date"
                >${this.todayRec?.TRAD_DAY ? moment(this.todayRec.TRAD_DAY).format('MM-DD(ddd)') : ''}</span
              >
              <label>평균 REC</label>

              <div class="value"><strong>${this.todayRec?.AVG_PRC?.toLocaleString() || 0}</strong> 원/REC</div>
            </div>
            <div class="chart">
              <eaas-chart
                .data=${this.recChartData}
                chartType="line"
                .barColor=${'#03b3be'}
                .lineColors=${['#03b3be']}
                .seriesNames=${['REC']}
                .hideLegend=${true}
                .prefix=${' 원'}
                .yTickAmount=${5}
                .xLabelRotate=${isMobileDevice() ? -30 : 0}
              >
              </eaas-chart>
            </div>
            <div class="detail">
              <table class="issue-table">
                <tr>
                  <th>거래일</th>
                  <th>최대</th>
                  <th>최소</th>
                  <th>평균</th>
                </tr>
                ${this.recItems.map(item => html `
                    <tr>
                      <td>${item.date || ''}</td>
                      <td class="max">${item.HIGH_PRC?.toLocaleString() || 0}</td>
                      <td class="min">${item.LOW_PRC?.toLocaleString() || 0}</td>
                      <td class="avg">${item.AVG_PRC?.toLocaleString() || 0}</td>
                    </tr>
                  `)}
              </table>
              <eaas-pagenation
                totalRecords=${this.recTotal}
                pageSize=${MARKET_PAGE_LIMIT}
                @page-changed=${this.handleRecPageChange}
                .currentPage=${this.recPage}
                maxPages=${5}
              ></eaas-pagenation>
            </div>
          </div>
          <!-- REC 우측 Container end-->
        </div>
        <!-- 중앙 Container end-->
      </div>
      <!-- 전체레이아웃 Container end-->
    `;
    }
    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;
            // 오늘 데이터
            const { data: todaySmpAndRec } = (await getTodaySmpAndRec()) || {};
            this.todaySmp = todaySmpAndRec.todaySmp;
            this.todayRec = todaySmpAndRec.todayRec;
            await this.updateComplete;
            this.getMonthlyData();
            if (isMobileDevice() === false) {
                const refreshTime = await getRefreshTime();
                if (this.refreshInterval)
                    clearInterval(this.refreshInterval);
                this.refreshInterval = window.setInterval(() => {
                    this.getMonthlyData();
                }, refreshTime);
            }
        }
        else {
            if (this.refreshInterval) {
                clearInterval(this.refreshInterval);
                this.refreshInterval = undefined;
            }
        }
    }
    initParams() {
        this.smpPage = 1;
        this.recPage = 1;
        this.fromDate = moment().subtract(1, 'month').format('YYYY-MM-DD'); // 1달전
        this.toDate = moment().format('YYYY-MM-DD');
    }
    async handleDateChange(e, name) {
        const value = e.detail.value;
        if (!value)
            return;
        // fromDate, toDate 계산
        let newFromDate = this.fromDate;
        let newToDate = this.toDate;
        if (name === 'fromDate') {
            newFromDate = value;
        }
        else if (name === 'toDate') {
            newToDate = value;
        }
        // 3개월(93일) 이상 차이 체크
        const diffDays = Math.abs(moment(newToDate).diff(moment(newFromDate), 'days'));
        if (diffDays > 92) {
            this.fromCalendar.renderCalendarInput(this.fromDate);
            this.toCalendar.renderCalendarInput(this.toDate);
            alert('조회 기간은 최대 3개월까지만 선택할 수 있습니다.');
            return;
        }
        if (name === 'fromDate') {
            this.fromDate = value;
        }
        else if (name === 'toDate') {
            this.toDate = value;
        }
        this.getMonthlyData();
    }
    async getSmpList() {
        const { data: smpData } = await getSmps(this.fromDate, this.toDate, this.smpPage, MARKET_PAGE_LIMIT);
        this.smpItems = smpData?.items || [];
        this.smpTotal = smpData?.total || 0;
    }
    async getRecList() {
        const { data: recData } = await getRecs(this.fromDate, this.toDate, this.recPage, MARKET_PAGE_LIMIT);
        this.recItems = recData?.items || [];
        this.recTotal = recData?.total || 0;
    }
    async getMonthlyData() {
        // 헤더 정보 갱신
        if (this.powerPlantHeader) {
            await this.powerPlantHeader.fetchPowerPlantHeaderInfo();
        }
        // 월별 차트 데이터
        const { data: smpChartData } = await getSmps(this.fromDate, this.toDate, this.smpPage, 0);
        const smpResult = arrayToObject(smpChartData?.items, 'date');
        this.smpChartData =
            smpChartData?.items
                ?.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
                ?.map(v => ({
                label: v.date.slice(2),
                values: [smpResult[v.date]?.AVG_PRC || null]
            })) || [];
        const { data: recChartData } = await getRecs(this.fromDate, this.toDate, this.recPage, 0);
        this.recChartData =
            recChartData?.items
                ?.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
                ?.map(item => ({
                label: moment(item.date, 'YYYY-MM-DD').format('YY-MM-DD'),
                values: [item.AVG_PRC || 0]
            })) || [];
        this.getSmpList();
        this.getRecList();
    }
    handleSmpPageChange(e) {
        this.smpPage = e.detail.page;
        this.getSmpList();
    }
    handleRecPageChange(e) {
        this.recPage = e.detail.page;
        this.getRecList();
    }
};
__decorate([
    state(),
    __metadata("design:type", String)
], MarketInfoPage.prototype, "powerPlantId", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], MarketInfoPage.prototype, "currentPath", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], MarketInfoPage.prototype, "fromDate", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], MarketInfoPage.prototype, "toDate", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], MarketInfoPage.prototype, "todaySmp", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], MarketInfoPage.prototype, "todayRec", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], MarketInfoPage.prototype, "smpPage", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], MarketInfoPage.prototype, "recPage", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], MarketInfoPage.prototype, "smpItems", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], MarketInfoPage.prototype, "smpTotal", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], MarketInfoPage.prototype, "recItems", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], MarketInfoPage.prototype, "recTotal", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], MarketInfoPage.prototype, "smpChartData", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], MarketInfoPage.prototype, "recChartData", void 0);
__decorate([
    query('eaas-calendar#from-calendar'),
    __metadata("design:type", Object)
], MarketInfoPage.prototype, "fromCalendar", void 0);
__decorate([
    query('eaas-calendar#to-calendar'),
    __metadata("design:type", Object)
], MarketInfoPage.prototype, "toCalendar", void 0);
__decorate([
    query('power-plant-header'),
    __metadata("design:type", Object)
], MarketInfoPage.prototype, "powerPlantHeader", void 0);
MarketInfoPage = __decorate([
    customElement('market-info-page')
], MarketInfoPage);
export { MarketInfoPage };
//# sourceMappingURL=market-info-page.js.map