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

import { Subject, of } from 'rxjs';
import { Store, select } from '@ngrx/store';
import { takeUntil, take, map, catchError } from 'rxjs/operators';
import {
  LoginSelector,
  AuthorizationSelector
} from '@ucap/ng-store-authentication';
import { LoginResponse } from '@ucap/protocol-authentication';
import { QueryProtocolService } from '@ucap/ng-protocol-query';
import {
  UserInfoSS,
  AuthResponse,
  DeptSearchType,
  UserInfoF,
  UserInfoDN
} from '@ucap/protocol-query';
import { GroupSelector } from '@ucap/ng-store-group';
import { GroupDetailData, UserInfo } from '@ucap/protocol-sync';
import { PresenceActions } from '@ucap/ng-store-organization';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { UserInfo as RoomUserInfo } from '@ucap/protocol-room';
import { MatDialog } from '@angular/material/dialog';
import {
  AlertDialogComponent,
  AlertDialogData,
  AlertDialogResult
} from '@ucap/ng-ui';
import { MatCheckbox } from '@angular/material/checkbox';
import { SearchData } from '@app/ucap/organization/models/search-data';

export type UserInfoTypes =
  | UserInfo
  | UserInfoSS
  | UserInfoF
  | UserInfoDN
  | RoomUserInfo;

@Component({
  selector: 'app-sections-select-group',
  templateUrl: './select-group.section.component.html',
  styleUrls: ['./select-group.section.component.scss'],

  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SelectGroupSectionComponent implements OnInit, OnDestroy {
  @Input()
  isMemberMove: boolean;

  @Input()
  isDialog = false;

  @Input()
  checkable = false;

  @Input()
  curGroup: GroupDetailData;

  @Output()
  changeUserList: EventEmitter<{
    checked: boolean;
    userInfo: UserInfoSS;
  }> = new EventEmitter();

  @Output()
  changeGroupList: EventEmitter<GroupDetailData[]> = new EventEmitter();

  @Output()
  changeGroupName: EventEmitter<string> = new EventEmitter();

  set companySearchData(searchData: SearchData) {
    this._companySearchData = searchData;
    this.onChangedCompanySearch();
  }
  get companySearchData() {
    return this._companySearchData;
  }
  // tslint:disable-next-line: variable-name
  _companySearchData: SearchData;

  private ngOnDestroySubject = new Subject<boolean>();

  constructor(
    private store: Store<any>,
    private queryProtocolService: QueryProtocolService,
    private changeDetectorRef: ChangeDetectorRef,
    private formBuilder: FormBuilder,
    public dialog: MatDialog
  ) {}

  loginRes: LoginResponse;
  isSearch = false;
  searchWord: string;
  searchUserInfos: UserInfoSS[] = [];
  groupList: GroupDetailData[];
  selectedUserList: UserInfoTypes[] = [];
  selectedGroupList: GroupDetailData[] = [];
  inputForm: FormGroup;
  groupChecked = false;

  groupName: string;

  ngOnInit(): void {
    this.store
      .pipe(takeUntil(this.ngOnDestroySubject), select(LoginSelector.loginRes))
      .subscribe((loginRes) => {
        this.loginRes = loginRes;
      });

    this.store
      .pipe(takeUntil(this.ngOnDestroySubject), select(GroupSelector.groups))
      .subscribe((groups) => {
        this.groupList = groups;
      });

    this.inputForm = this.formBuilder.group({
      groupName: [
        this.groupName,
        [
          // Validators.required
          // StringUtil.includes(, CharactorType.Special),
          // this.checkBanWords(),
          // this.checkSameName()
        ]
      ]
    });
  }

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

  onKeyupGroupName() {
    this.inputForm.get('groupName').markAsTouched();
    this.changeGroupName.emit(this.inputForm.get('groupName').value);
  }

  onCheckForGroup(checbox: MatCheckbox, group: GroupDetailData) {
    if (
      this.isMemberMove &&
      !!this.selectedGroupList &&
      this.selectedGroupList.length > 0 &&
      this.selectedGroupList[0].seq !== group.seq
    ) {
      this.dialog.open<
        AlertDialogComponent,
        AlertDialogData,
        AlertDialogResult
      >(AlertDialogComponent, {
        data: {
          title: '멤버이동',
          html: '멤버이동은 그룹 여러개를 선택할 수 없습니다.'
        }
      });

      checbox.checked = false;
      return;
    }
    if (
      this.selectedGroupList.filter((g) => g.seq === group.seq).length === 0
    ) {
      this.selectedGroupList = [...this.selectedGroupList, group];
    } else {
      this.selectedGroupList = this.selectedGroupList.filter(
        (g) => g.seq !== group.seq
      );
    }

    this.changeGroupList.emit(this.selectedGroupList);
  }

  // onCheckForUser(params: { isChecked: boolean; userInfo: UserInfoTypes }) {
  //   if (
  //     this.selectedUserList.filter((user) => user.seq === params.userInfo.seq)
  //       .length === 0
  //   ) {
  //     this.selectedUserList = [...this.selectedUserList, params.userInfo];
  //   } else {
  //     this.selectedUserList = this.selectedUserList.filter(
  //       (item) => item.seq !== params.userInfo.seq
  //     );
  //   }

  //   this.changeUserList.emit(this.selectedUserList);
  // }

  onToggleCheck(data: { checked: boolean; userInfo: UserInfoSS }) {
    this.changeUserList.emit(data);
  }

  onChangedCompanySearch() {
    this.isSearch = true;
  }

  onCanceled() {
    this.isSearch = false;
  }

  getCheckedUser(userInfo: UserInfoTypes) {
    if (!!this.selectedUserList && this.selectedUserList.length > 0) {
      return (
        this.selectedUserList.filter((item) => item.seq === userInfo.seq)
          .length > 0
      );
    }
    return false;
  }
  checkVisible(group: GroupDetailData): boolean {
    if (!!this.curGroup && this.curGroup.seq === group.seq) {
      return false;
    }
    return true;
  }
}
