import { HttpClient } from '@angular/common/http';
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { differenceInCalendarDays, endOfMonth, endOfWeek, endOfYear, startOfMonth, startOfWeek, startOfYear, subDays, subMonths, subYears } from 'date-fns';

@Component({
  selector: 'cg-pager-filter',
  template: `

  <nz-descriptions *ngIf="filterConfig" [nzColumn]="8">
    <nz-descriptions-item  *ngFor="let config of filterConfig" [nzSpan]="config['span'] || 1" [nzTitle]="config['title']" >
    <!--radio-->
    <nz-radio-group *ngIf="config.filterType == filterType.radio" 
      [(ngModel)]="filters[config['data']]" 
      (ngModelChange)="update()" >
        <label nz-radio-button [nzValue]="undefined" i18n>全部</label>
        <label *ngFor="let option of config.options" nz-radio-button [nzValue]="option['value']">{{option['label']}}</label>
    </nz-radio-group>

    <!--date range picker-->
    <!--
      [nzDisabledDate]="disabledDate" 
    -->
    <nz-range-picker *ngIf="config.filterType == filterType.dateRange" 
      [nzRanges]="ranges" 
      [(ngModel)]="filters[config['data']]" 
      (ngModelChange)="update()"
      [nzAllowClear]="true" >
    </nz-range-picker>

    <!--select-->
    <nz-select *ngIf="config.filterType == filterType.select"  [ngClass]="{'full-width' : config.fullWidth}" 
      [nzMode]="config.mode || 'default'" 
      [(ngModel)]="filters[config['data']]" 
      (ngModelChange)="update()"
      [nzPlaceHolder]="config.title" nzAllowClear>
      <nz-option *ngFor="let option of config.options" [nzValue]="option['value']" [nzLabel]="option['label'] || option['value']"></nz-option>
    </nz-select>


    </nz-descriptions-item>

    <nz-descriptions-item [nzSpan]="1" i18n-nzTitle nzTitle="清空筛选" >
      <button nz-button nzSize="small" (click)="clear()" i18n>清空</button>
    </nz-descriptions-item>
  </nz-descriptions>


  `,
  styles: [
    `
  nz-select{
    min-width:80px;
  }

  .full-width {
    width : 90%;
  }

`
  ]
})
export class PagerFilterComponent implements OnInit {
  @Output() filterChange = new EventEmitter<any>();



  @Input() filters: any = {};
  @Input() set inputFilters(val) {
    if (val) {
      Object.assign(this.filters, val);
      this.update();
    }
  }


  private _filterConfig: FilterItem[];
  public get filterConfig(): FilterItem[] {
    return this._filterConfig;
  }
  @Input()
  public set filterConfig(value: FilterItem[]) {
    this._filterConfig = value;
    if (this._filterConfig) {
      this._filterConfig.forEach(config => {
        if (config.optionsUrl) {
          this.http.get(config.optionsUrl).subscribe(res => {
            config.options = res as FilterOption[];
          })
        }
      })
    }
  }

  public filterType = FilterType;

  constructor(
    private http: HttpClient,
  ) { }

  ngOnInit(): void {
  }


  clear() {
    this.filters = {};
    this.filterChange.emit(this.filters);
  }

  update() {
    this.filterChange.emit(this.filters);
  }



  //////date range
  // Can not select days before today and today
  disabledDate = (current: Date): boolean =>
    differenceInCalendarDays(current, new Date()) > 0;



  ranges = {
    '今天': [new Date(), new Date()],
    '昨天': [subDays(new Date(), 1), subDays(new Date(), 1)],
    '上周': [startOfWeek(subDays(new Date(), 7)), endOfWeek(subDays(new Date(), 7))],
    '本周': [startOfWeek(new Date()), new Date()],
    '上月': [startOfMonth(subMonths(new Date(), 1)), endOfMonth(subMonths(new Date(), 1))],
    '本月': [startOfMonth(new Date()), new Date()],
    '前年': [startOfYear(subYears(new Date(), 2)), endOfYear(subYears(new Date(), 2))],
    '去年': [startOfYear(subYears(new Date(), 1)), endOfYear(subYears(new Date(), 1))],
    '今年': [startOfYear(new Date()), new Date()],
  };


}

export enum FilterType {
  dateRange = 'dateRange', //时间范围
  radio = 'radio',
  select = 'select',
}

export interface FilterOption {
  value: any; //字段值
  label?: string;
}

export interface FilterItem {
  data: string; //字段
  title: string; //名称
  filterType: FilterType, //过滤类型
  mode? : 'default' | 'tags' | 'multiple', //select
  multiple?: boolean, //是否多选
  options?: FilterOption[]; //选项
  span?: number;
  fullWidth?: boolean;
  optionsUrl?: string; //选项url
}