import {
  ChangeDetectorRef,
  Component,
  Inject,
  OnInit,
  ViewEncapsulation,
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FuseAlertType } from '@fuse/components/alert';
import { SiteService } from 'app/modules/polyglot/site/services/site.service';
import { IdentityService } from 'app/modules/polyglot/identity/services/identity.service';
import { MemberService } from 'app/modules/polyglot/member/services/member.service';
import {
  CreateMemberRequest,
  CreateMemberResponse,
} from 'app/modules/proto/c2se/member_pb';
import { Bank } from 'app/modules/proto/models/bank_pb';
import { Site } from 'app/modules/proto/models/site_pb';
import { MemberModel } from 'app/modules/proto/models/member_pb';
import { fuseAnimations } from '@fuse/animations';
import { BankService } from 'app/modules/polyglot/bank/services/bank.service';

export interface RegistComposeData {
  title: string;
  parent: MemberModel;
  classId: string;
}
export interface RegistComposeResult {
  choice: boolean;
}

@Component({
  selector: 'app-regist-compose',
  templateUrl: './regist-compose.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: fuseAnimations,
})
export class RegistComposeComponent implements OnInit {
  composeForm!: FormGroup;
  sites!: Site[];
  banks!: Bank[];

  alert: { type: FuseAlertType; message: string } = {
    type: 'success',
    message: '등록이 성공하였습니다.',
  };

  showAlert: boolean = false;
  isSendDisable = false;
  /**
   * Constructor
   */
  constructor(
    private _changeDetectorRef: ChangeDetectorRef,
    public matDialogRef: MatDialogRef<RegistComposeComponent>,
    @Inject(MAT_DIALOG_DATA) public data: RegistComposeData,
    private _formBuilder: FormBuilder,
    private _identityService: IdentityService,
    private _memberService: MemberService,
    private _siteService: SiteService,
    private _bankService: BankService
  ) {}

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

  /**
   * On init
   */
  ngOnInit(): void {
    // Create the form
    this.composeForm = this._formBuilder.group({
      partnerId: [{ value: this.data.parent.getUsername(), disabled: true }],
      siteId: ['', [Validators.required]],
      username: ['', [Validators.required]],
      password: ['beteran', [Validators.required]],
      exchangePassword: ['beteran', [Validators.required]],
      nickname: ['', [Validators.required]],
      calculateType: ['', [Validators.required]],
      mobilePhoneNumber: ['', [Validators.required]],
      bankId: ['', [Validators.required]],
      accountNumber: ['', [Validators.required]],
      accountHolder: ['', [Validators.required]],
    });

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

    this._bankService
      .listBanks()
      .then((result) => {
        this.banks = result.getBanksList();
      })
      .catch((reson) => console.log(reson));
  }

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

  /**
   * Save and close
   */
  saveAndClose(): void {
    // Save the message as a draft
    this.saveAsDraft();

    // Close the dialog
    this.matDialogRef.close();
  }

  /**
   * Discard the message
   */
  discard(): void {}

  /**
   * Save the message as a draft
   */
  saveAsDraft(): void {}

  /**
   * Send the message
   * 
  }
   */
  send(): void {
    if (!this.composeForm.valid) {
      return;
    }

    this.isSendDisable = true;

    const {
      partnerId,
      siteId,
      username,
      password,
      exchangePassword,
      nickname,
      calculateType,
      mobilePhoneNumber,
      bankId,
      accountNumber,
      accountHolder,
    } = this.composeForm.value;

    let bank_account = new CreateMemberRequest.BankAccount();
    bank_account.setBankId(bankId);
    bank_account.setName(accountHolder);
    bank_account.setAccountNumber(accountNumber);
    bank_account.setExchangePassword(exchangePassword);

    const member = new CreateMemberRequest();
    const site = new Site();
    site.setId(siteId);

    member.setSiteId(siteId);
    member.setUsername(username);
    member.setPassword(password);
    member.setMemberClassId(this.data.classId);
    member.setMemberLevelId('c56231ac-2120-4a81-a30a-5d41fafb6c57');
    member.setReferrerMemberUsername(this.data.parent.getUsername());
    member.setNickname(nickname);
    member.setMobilePhoneNumber(mobilePhoneNumber);
    member.setBankAccount(bank_account);

    this._memberService
      .createMember(member)
      .then((res: CreateMemberResponse.Result) => {
        console.log(res.getMember());
        this.showAlert = true;
      })
      .catch((e) => {
        this.showAlert = true;
        this.alert = { type: 'error', message: '등록에 실패하였습니다.' };
      })
      .finally(() => setTimeout(() => this.close(), 5000));
  }

  close(): void {
    this.matDialogRef.close({
      choice: true,
    });
  }
  __checkUsernameDuplicate(event: FocusEvent): void {
    const username = this.composeForm.get('username')?.value;
    // console.log(event, '::', username);
    this._identityService
      .checkUsernameForDuplication(username)
      .then((isUse: boolean) => {
        if (!!isUse) {
          this.composeForm
            .get('username')
            ?.setErrors({ usernameDuplicate: true });
        }
        // this._changeDetectorRef.markForCheck();
      });
  }

  __checkNickname(event: FocusEvent): void {
    const nickname = this.composeForm.get('nickname')?.value;

    this._identityService
      .checkNicknameForDuplication(nickname)
      .then((isUse: boolean) => {
        if (!!isUse) {
          this.composeForm
            .get('nickname')
            ?.setErrors({ nicknameDuplicate: true });
        }
        // this._changeDetectorRef.markForCheck();
      });
  }
}
