import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import {
  debounceTime,
  map,
  merge,
  Observable,
  Subject,
  switchMap,
  takeUntil,
} from 'rxjs';
import { fuseAnimations } from '@fuse/animations';
import { FuseConfirmationService } from '@fuse/services/confirmation';

import { User } from '../../../member/user/models/user';
import { DailyPartner } from '../models/daily-partner';
import { DailyPartnerPagination } from '../models/daily-partner-pagination';
import { DailyPartnerService } from '../services/daily-partner.service';
import { Router } from '@angular/router';

@Component({
  selector: 'daily-partner-list',
  templateUrl: './list.component.html',
  styles: [
    /* language=SCSS */
    `
      .daily-partner-grid {
        /*                     아이디 등급  회원 */
        grid-template-columns: 40px auto 30px;

        @screen sm {
          /*                     아이디 등급  회원 파트너 손익  머니  콤프  카배팅 */
          grid-template-columns: 40px auto 30px 30px 30px 30px 30px 30px;
        }

        @screen md {
          /*                     아이디 등급  회원 파트너 손익  머니  콤프  카배팅 카당첨 */
          grid-template-columns: 40px auto 30px 30px 30px 30px 30px 30px 30px;
        }

        @screen lg {
          /*                     아이디 등급  회원 파트너 손익  머니  콤프 카배팅 카당첨 카윈로스 카수수료 카정산 슬배팅 슬당첨 슬윈로스 슬수수료 슬정산 파배팅 파당첨 파윈로스 파수수료 파정산 총정산 */
          grid-template-columns: 40px auto 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px 30px;
        }
      }
    `,
  ],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: fuseAnimations,
})
export class ListComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild(MatPaginator) private _paginator!: MatPaginator;
  @ViewChild(MatSort) private _sort!: MatSort;

  dailyPartners$!: Observable<any | undefined>;
  users$!: Observable<User[] | undefined>;

  __isSearchOpened = false;
  isLoading = false;
  searchInputControl = new FormControl();
  selectedDailyPartner?: DailyPartner;
  pagination?: DailyPartnerPagination;

  private _unsubscribeAll: Subject<any> = new Subject<any>();

  /**
   * Constructor
   */
  constructor(
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseConfirmationService: FuseConfirmationService,
    private _formBuilder: FormBuilder,
    private _dailyPartnerService: DailyPartnerService,
    private router: Router
  ) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Lifecycle hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On init
   */
  ngOnInit(): void {
    // Get the pagination
    this._dailyPartnerService.pagination$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((pagination: DailyPartnerPagination | undefined) => {
        // Update the pagination
        this.pagination = pagination;

        // Mark for check
        this._changeDetectorRef.markForCheck();
      });

    // Get the products
    this.dailyPartners$ = this._dailyPartnerService.dailyPartners$;
  }

  /**
   * After view init
   */
  ngAfterViewInit(): void {
    if (this._sort && this._paginator) {
      // Set the initial sort
      this._sort.sort({
        id: 'lastDayHoldingMoney',
        start: 'asc',
        disableClear: true,
      });

      // Mark for check
      this._changeDetectorRef.markForCheck();

      // If the daily changes the sort order...
      this._sort.sortChange
        .pipe(takeUntil(this._unsubscribeAll))
        .subscribe(() => {
          // Reset back to the first page
          this._paginator.pageIndex = 0;
        });

      // Get products if sort or page changes
      merge(this._sort.sortChange, this._paginator.page)
        .pipe(
          switchMap(() => {
            this.isLoading = true;
            return this._dailyPartnerService.getDailyPartners(
              this._paginator.pageIndex,
              this._paginator.pageSize,
              this._sort.active,
              this._sort.direction
            );
          }),
          map(() => {
            this.isLoading = false;
          })
        )
        .subscribe();
    }
  }

  /**
   * On destroy
   */
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this._unsubscribeAll.next(null);
    this._unsubscribeAll.complete();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  viewUserDetail(id: string): void {
    let url: string = 'member/user/' + id;
    this.router.navigateByUrl(url);
  }
  // -----------------------------------------------------------------------------------------------------
  // @ Private methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Create product
   */
  __createProduct(): void {}

  /**
   * Toggle product details
   *
   * @param productId
   */
  __toggleDetails(productId: string): void {}

  /**
   * toggle the search
   * Used in 'bar'
   */
  __onClickSearch(): void {
    this.__isSearchOpened = !this.__isSearchOpened;
  }

  /**
   * Track by function for ngFor loops
   *
   * @param index
   * @param item
   */
  __trackByFn(index: number, item: any): any {
    return item.id || index;
  }
}
