/*
 * @Descripttion: Do not edit
 * @version: 1.0
 * @Author: Eclipse
 * @Date: 2021-05-08 15:57:42
 * @LastEditors: Eclipse
 * @LastEditTime: 2021-05-08 16:05:26
 */
import { ChangeDetectorRef, Component, Injector, OnInit } from '@angular/core';
import { ControlWidget, SFComponent, SFItemComponent } from '@delon/form';
import { format, getISOWeek } from 'date-fns';

@Component({
  selector: 'sl-from-to-search',
  templateUrl: './from-to-search.widget.html',
  preserveWhitespaces: false,
})
export class SLFromToSearchWidget extends ControlWidget implements OnInit {
  static readonly KEY = 'sl-from-to-search';
  /**
   * 组件类型
   */
  type: 'date' | 'number' = 'date';
  /**
   * 控件模式
   */
  mode: 'date' | 'week' | 'month' | 'year' = 'date';
  /**
   * 组件返回值
   */
  data: { start: any; end: any } | null = null;
  /**
   * 组件日期显示格式
   */
  displayFormat = 'yyyy-MM-dd';
  /**
   * 组件日期格式
   */
  format = 'yyyy-MM-dd';
  /**
   * 最小值
   */
  min: any;
  /**
   * 最大值
   */
  max: any;
  /**
   * 日期区间
   */
  date: Array<any> = [];
  /**
   * 开始日期
   */
  startDate: any;
  /**
   * 结束日期
   */
  endDate: any;

  constructor(cd: ChangeDetectorRef, injector: Injector, sfItemComp?: SFItemComponent, sfComp?: SFComponent) {
    super(cd, injector, sfItemComp, sfComp);
  }

  ngOnInit(): void {
    this.type = this.ui?.type || 'date';
    this.mode = this.ui?.mode || 'date';
    this.displayFormat = this.ui?.displayFormat;
    this.format = this.ui?.format || 'yyyy-MM-dd';
  }
  onChange(result: any): void {
    if (this.startDate && this.endDate) {
      const date1 = new Date(this.startDate);
      const date2 = new Date(this.endDate);
      if (date1.getTime() > date2.getTime()) {
        const date3 = this.endDate;
        this.endDate = this.startDate;
        this.startDate = date3;
      }
    }
    if (this.startDate) {
      this.date[0] = format(this.startDate, this.format);
    } else {
      this.date[0] = '';
    }
    if (this.endDate) {
      this.date[1] = format(this.endDate, this.format);
    } else {
      this.date[1] = '';
    }

    if (this.type === 'date') {
      this.setValue(this.date);
    } else if (this.type === 'number') {
    } else {
      this.setValue(null);
    }
  }

  reset(value: string) {
    this.startDate = null;
    this.endDate = null;
  }
}
