import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';

import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import {
  debounceTime,
  delay,
  map,
  merge,
  Observable,
  of,
  startWith,
  Subject,
  switchMap,
  takeUntil,
  timer,
} from 'rxjs';
import { fuseAnimations } from '@fuse/animations';
import { FuseConfirmationService } from '@fuse/services/confirmation';

import { Partner } from '../models/partner';
import { PartnerPagination } from '../models/partner-pagination';
import { PartnerService } from '../services/partner.service';
import { ActivatedRoute, Router } from '@angular/router';
import { RegistComposeComponent } from '../compose/regist-compose.component';
import { CashComposeComponent } from '../compose/cash-compose.component';
import { CommissionComposeComponent } from '../compose/commission-compose.component';
import { CompComposeComponent } from '../compose/comp-compose.component';

import { MatDialog } from '@angular/material/dialog';
import { SiteService } from 'app/modules/polyglot/domain/services/site.service';
import { Site } from 'app/modules/protobuf/models/domain/site_pb';
import { MemberService } from 'app/modules/polyglot/member/services/member.service';
import { MemberModel } from 'app/modules/protobuf/models/member/member_pb';
import {
  ListMembersRequest,
  ListMembersResponse,
} from 'app/modules/protobuf/c2se/backend/member_pb';
import { Pagination } from 'app/modules/protobuf/protobuf/pagination/pagination_pb';
@Component({
  selector: 'partner-list',
  templateUrl: './list.component.html',
  styles: [
    /* language=SCSS */
    `
      .partner-grid {
        /*                     관리   요율  매장  아이디  등급 */
        grid-template-columns: 40px 40px 100px auto 40px;

        @screen sm {
          /*                     관리   요율  매장  아이디  등급 예금주 */
          grid-template-columns: 40px 40px 100px auto 40px 140px;
        }

        @screen md {
          /*                     관리   요율  매장  아이디  등급  예금주 정산 보유금 */
          grid-template-columns: 80px auto 80px 40px 40px 120px 120px 120px 120px 120px 100px;
        }

        @screen lg {
          /*                     관리  아이디 등급  예금주 정산  보유금   충전  환전금 수익금 가입   비고 */
          grid-template-columns: 60px auto 60px 40px 40px 100px 100px 100px 100px 120px 100px;
        }
      }
      .mat-tooltip {
        white-space: pre-line;
      }
    `,
  ],
  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;

  /* partners$!: Observable<Partner[] | undefined>; */

  listPartner$!: Observable<MemberModel[] | undefined>;

  isLoading = false;
  searchInputControl = new FormControl();
  selectedPartner?: Partner;
  pagination?: PartnerPagination;
  sites!: Site[];
  __members: MemberModel[] = [];

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

  /**
   * Constructor
   */
  constructor(
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseConfirmationService: FuseConfirmationService,
    private _formBuilder: FormBuilder,
    private _activatedRoute: ActivatedRoute,
    private _partnerService: PartnerService,
    private __memberService: MemberService,
    private _siteService: SiteService,
    private router: Router,
    private _matDialog: MatDialog
  ) {}

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

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

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

    this._siteService
      .listSites()
      .then((result) => {
        this.sites = result.getSitesList();
      })
      .catch((reson) => console.log(reson));
    // Get the products

    this._activatedRoute.data.subscribe((data) => {
      let listMemberResult: ListMembersResponse.Result = data['listPartner'];
      this.listPartner$ = of(listMemberResult.getMembersList());

      /* console.log('dddd', listMemberResult.getMembersList()); */

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

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

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

      // If the partner 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;

            let req = new ListMembersRequest();
            let paging = new Pagination();
            paging.setPage(this._paginator.pageIndex);
            paging.setPageSize(this._paginator.pageSize);

            req.setPagination(paging);
            req.setMemberClassId('4b014ef5-3bab-4413-aaf9-b0040a70ec77');
            return of(this.__memberService.listMembers(req));
          }),
          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 {}

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

  __onClickRegist(event: MouseEvent, partner: MemberModel): void {
    const dialogRef = this._matDialog.open(RegistComposeComponent, {
      data: { title: '대본 등록하기', parent: partner, sites: this.sites },
    });

    dialogRef.afterClosed().subscribe((result) => {
      console.log('Compose dialog was closed!');
    });
  }
  __onClickCash(event: MouseEvent): void {
    const dialogRef = this._matDialog.open(CashComposeComponent, {
      data: { price: '', memo: '' },
    });

    dialogRef.afterClosed().subscribe((result) => {
      console.log('Compose dialog was closed!');
    });
  }
  __onClickCommission(event: MouseEvent): void {
    const dialogRef = this._matDialog.open(CommissionComposeComponent, {
      data: { price: '', memo: '' },
    });

    dialogRef.afterClosed().subscribe((result) => {
      console.log('Compose dialog was closed!');
    });
  }
  __onClickComp(event: MouseEvent): void {
    const dialogRef = this._matDialog.open(CompComposeComponent, {
      data: { price: '', memo: '' },
    });

    dialogRef.afterClosed().subscribe((result) => {
      console.log('Compose dialog was closed!');
    });
  }

  __getRateTooltop(): string {
    const tempRate = 0;
    const resultTooltip = `
    요율확인 \n 카지노-바카라: ${tempRate}% \n 카지노-룰렛: ${tempRate}% \n 카지노-드레곤타이거: ${tempRate}% \n 카지노-그외:${tempRate}% \n 슬롯:${tempRate}% \n 카지노루징: ${tempRate}% \n 슬롯루징: ${tempRate}%
    `;
    return resultTooltip;
  }
}
