import { Component, OnInit } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute, Router } from '@angular/router';
import { addDays, differenceInDays, endOfDay, endOfMonth, format, isAfter, isBefore, isEqual, startOfDay, startOfMonth, subDays } from 'date-fns';
import { DailyService } from './daily.service';
import { firstValueFrom } from 'rxjs';

@Component({
  selector: 'app-daily',
  template: `
  <nz-page-header i18n-nzTitle nzTitle="每日一图">
    <nz-page-header-subtitle>
      <ng-container *ngIf="epgOptions && epgOptions.length > 0">
        <nz-select [(ngModel)]="epgId" (ngModelChange)="onEpgChange($event)">
          <nz-option *ngFor="let item of epgOptions; let i=index" [nzValue]="item.value" [nzLabel]="item.label"></nz-option>
        </nz-select>
      </ng-container>
    </nz-page-header-subtitle>
    <nz-page-header-extra>

    </nz-page-header-extra>
    <nz-page-header-content>
    </nz-page-header-content>
  </nz-page-header>

  <nz-calendar
    [nzDateFullCell]="dateCellTpl"
    [nzFullscreen]="true"
    [(ngModel)]="date"
    [(nzMode)]="model"
    [nzDisabledDate]="disabledDate"	
    (nzPanelChange)="panelChange($event)"
    (nzSelectChange)="dateChange($event)">
  </nz-calendar>

  <!-- 传入 TemplateRef 的方式 -->
  <ng-template #dateCellTpl let-date>
    <app-daily-cell [productId]="epgId" [date]="date" [data]="getByDate(date)"></app-daily-cell>
  </ng-template>
  `,
  styles: [
  ]
})
export class DailyComponent implements OnInit {

  epgOptions: any[] = [];
  epgId: string;


  model: 'month' | 'year' = 'month';
  date: Date;
  month: string;

  constructor(
    private modal: NzModalService,
    private dailayService: DailyService,
    private message: NzMessageService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
  ) {

    firstValueFrom(this.dailayService.epgOption())
    .then((resp: any) => {
      this.epgOptions = resp;
      this.epgId = this.epgOptions[0].value;

      this.activatedRoute.queryParams.subscribe(params => {
        this.date = new Date();
        if (params['date']) {
          let date = new Date(params['date']);
          if (date.toString() != 'Invalid Date') {
            this.date = date;
          }
        }
        this.loadCalendarData();
      })

    }) 

  }

  ngOnInit(): void {
  }

  disabledDate(date) {
    return false;
    // return differenceInDays(date, new Date()) < 0;
  }

  
  panelChange(event) {
    console.log('panelChange:', event);
  }


  dateChange(date: Date) {
    this.date = date;
    this.updateParams('date', this.date.toISOString());
  }

  updateParams(key: string, value: string) {
    let oldParams = this.activatedRoute.snapshot.queryParams;
    let params = Object.assign({}, oldParams);
    params[key] = value;
    this.router.navigate([], { queryParams: params });
  }


  monthlyData: any;

  getMonth(date: Date) {
    return format(date, 'yyyyMM');
  }
  
  loadCalendarData() {
    let start = subDays(startOfMonth(this.date), 14);
    let end = addDays(endOfMonth(this.date), 14);
    let filters = {
      dailyDate: [start, end],
    }
    let params = {
      filters: JSON.stringify(filters),
      length: 128,
    }
    firstValueFrom(this.dailayService.list(this.epgId, params))
      .then((resp: any) => {
      this.monthlyData = resp.data;
      this.month = this.getMonth(this.date);
    }).catch(err => this.message.error(err.error?.message || err.message));

  }


  getByDate(date: Date) {
    if (!this.monthlyData) return null;
    let data = this.monthlyData.find(item => {
      let dailyDate = new Date(item.dailyDate);
      return isEqual(date, dailyDate);
    })
    return data;
  }


  onEpgChange(value: string) {
    this.loadCalendarData();
  }

}
