import { Subject } from 'rxjs';
import { takeUntil, take } from 'rxjs/operators';

import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Input,
  Output,
  EventEmitter
} from '@angular/core';

import { Store, select } from '@ngrx/store';

import { VersionInfo2Response } from '@ucap/api-public';
import { LoginResponse } from '@ucap/protocol-authentication';
import {
  UserInfoSS,
  DeptSearchType,
  DeptUserRequest
} from '@ucap/protocol-query';

import { LogService } from '@ucap/ng-logger';
import {
  LoginSelector,
  ConfigurationSelector
} from '@ucap/ng-store-authentication';
import { QueryProtocolService } from '@ucap/ng-protocol-query';
import {
  DepartmentActions,
  DepartmentSelector,
  PresenceActions
} from '@ucap/ng-store-organization';
import {
  FixedSizeVirtualScrollStrategy,
  VIRTUAL_SCROLL_STRATEGY
} from '@angular/cdk/scrolling';

import { SearchData } from '../models/search-data';
import { SortOrder } from '@ucap/core';

export class ProfileListVirtualScrollStrategy extends FixedSizeVirtualScrollStrategy {
  constructor() {
    super(70, 250, 500); // (itemSize, minBufferPx, maxBufferPx)
  }
}

interface CheckedInfo {
  checked: boolean;
  userInfo: UserInfoSS;
}

@Component({
  selector: 'app-organization-profile-list',
  templateUrl: './profile-list.component.html',
  styleUrls: ['./profile-list.component.scss'],
  providers: [
    {
      provide: VIRTUAL_SCROLL_STRATEGY,
      useClass: ProfileListVirtualScrollStrategy
    }
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProfileListComponent implements OnInit, OnDestroy {
  @Input()
  set searchData(data: SearchData) {
    if (!this.loginRes) {
      this._searchData = data;
      return;
    }
    this.searchMember(data);
  }
  // tslint:disable-next-line: variable-name
  private _searchData: SearchData;

  @Input()
  selectedUser: UserInfoSS[];

  @Input()
  set sortOrder(value: SortOrder) {
    this._sortOrder = value;
    this.userInfos = this.sort(this.userInfos);
  }
  get sortOrder() {
    return this._sortOrder;
  }
  // tslint:disable-next-line: variable-name
  _sortOrder: SortOrder = {
    property: 'name',
    ascending: true
  };

  @Output()
  searched: EventEmitter<UserInfoSS[]> = new EventEmitter();

  @Output()
  changedCheck: EventEmitter<CheckedInfo[]> = new EventEmitter();

  set userInfos(userInfos: UserInfoSS[]) {
    this._userInfos = userInfos;
    this.searched.emit(userInfos);
  }
  get userInfos() {
    return this._userInfos;
  }
  // tslint:disable-next-line: variable-name
  _userInfos: UserInfoSS[] = [];

  loginRes: LoginResponse;
  versionInfo2Res: VersionInfo2Response;

  processing = false;

  private ngOnDestroySubject: Subject<void>;
  private myDeptDestroySubject: Subject<void>;

  constructor(
    private queryProtocolService: QueryProtocolService,
    private store: Store<any>,
    private changeDetectorRef: ChangeDetectorRef,
    private logService: LogService
  ) {}

  ngOnInit(): void {
    this.ngOnDestroySubject = new Subject();

    this.store
      .pipe(
        takeUntil(this.ngOnDestroySubject),
        select(ConfigurationSelector.versionInfo2Response)
      )
      .subscribe((versionInfo2Res) => {
        this.versionInfo2Res = versionInfo2Res;
      });

    this.store
      .pipe(takeUntil(this.ngOnDestroySubject), select(LoginSelector.loginRes))
      .subscribe((loginRes) => {
        this.loginRes = loginRes;
        if (!!this._searchData) {
          this.searchMember(this._searchData);
          this._searchData = undefined;
        }
      });
  }

  ngOnDestroy(): void {
    if (!!this.ngOnDestroySubject) {
      this.ngOnDestroySubject.complete();
    }
  }

  checkAll() {
    if (!this.userInfos || 0 === this.userInfos.length) {
      return;
    }

    const checked: CheckedInfo[] = [];
    this.userInfos.forEach((u) => {
      checked.push({
        checked: true,
        userInfo: u
      });
    });
    this.changedCheck.emit(checked);
  }

  /** 개별 체크여부 */
  getCheckedUser(userInfo: UserInfoSS) {
    if (!!this.selectedUser && this.selectedUser.length > 0) {
      return (
        this.selectedUser.filter((item) => item.seq === userInfo.seq).length > 0
      );
    }
    return false;
  }

  /** 개별선택(토글) 이벤트 */
  onChangeCheckUser(param: { checked: boolean; userInfo: UserInfoSS }) {
    this.changedCheck.emit([param]);
  }

  onOpenProfile(userInfo: UserInfoSS): void {
    alert('Open Profile');
  }

  private getMyDeptMember() {
    this.myDeptDestroySubject = new Subject();

    const req: DeptUserRequest = {
      divCd: 'ORG',
      companyCode: this.loginRes.companyCode,
      seq: this.loginRes.departmentCode,
      search: '',
      searchRange: DeptSearchType.All,
      senderCompanyCode: this.loginRes.companyCode,
      senderEmployeeType: this.loginRes.userInfo.employeeType
    };

    this.store
      .pipe(
        takeUntil(this.ngOnDestroySubject),
        select(DepartmentSelector.myDepartmentUserInfoList)
      )
      .subscribe(
        (myDepartmentUserInfoList) => {
          if (!myDepartmentUserInfoList) {
            this.store.dispatch(DepartmentActions.myDeptUser({ req }));
            return;
          }
          this.userInfos = this.sort(myDepartmentUserInfoList);

          this.myDeptDestroySubject.next();
          this.myDeptDestroySubject.complete();
          this.myDeptDestroySubject = undefined;
        },
        (error) => {},
        () => {}
      );
  }

  private sort(userInfos: UserInfoSS[]): UserInfoSS[] {
    if (!userInfos || 0 === userInfos.length) {
      return userInfos;
    }

    const property = this.sortOrder.property;
    const ascending = this.sortOrder.ascending;

    return userInfos.slice().sort((a, b) => {
      let c: any;
      let d: any;
      try {
        c = ascending ? a[property] : b[property];
        d = ascending ? b[property] : a[property];
      } catch (error) {
        console.log(error);
      }
      return c < d ? -1 : c > d ? 1 : 0;
    });
  }

  private searchMember(searchData: SearchData) {
    if (!searchData || (!searchData.companyCode && !searchData.deptSeq)) {
      this.getMyDeptMember();
      return;
    }

    if (!!this.myDeptDestroySubject) {
      this.myDeptDestroySubject.next();
      this.myDeptDestroySubject.complete();
      this.myDeptDestroySubject = undefined;
    }

    let req: DeptUserRequest;
    if (searchData.bySearch) {
      req = {
        divCd: 'ORGS',
        companyCode: searchData.companyCode,
        searchRange: DeptSearchType.All,
        search: searchData.searchWord,
        senderCompanyCode: this.loginRes.userInfo.companyCode,
        senderEmployeeType: this.loginRes.userInfo.employeeType
      };
    } else {
      req = {
        divCd: 'ORG',
        companyCode: this.loginRes.companyCode,
        seq: Number(searchData.deptSeq),
        search: '',
        searchRange: DeptSearchType.All,
        senderCompanyCode: this.loginRes.companyCode,
        senderEmployeeType: this.loginRes.userInfo.employeeType
      };
    }

    this.processing = true;
    this.queryProtocolService
      .deptUser(req)
      .pipe(take(1))
      .subscribe(
        (data) => {
          this.userInfos = this.sort(data.userInfos);
          this.changeDetectorRef.detectChanges();

          // 검색 결과에 따른 프레즌스 조회.
          const userSeqList: string[] = [];
          this.userInfos.map((user) => userSeqList.push(user.seq));

          if (userSeqList.length > 0) {
            this.store.dispatch(
              PresenceActions.bulkInfo({
                divCd: 'orgSrch',
                userSeqs: userSeqList
              })
            );
          }
        },
        (error) => {},
        () => {
          this.processing = false;
        }
      );
  }
}
