import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  ValidatorFn,
  Validators,
} from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { fuseAnimations } from '@fuse/animations';
import { FuseAlertType } from '@fuse/components/alert';
import { BankService } from 'app/modules/polyglot/bank/services/bank.service';
import { IdentityService } from 'app/modules/polyglot/identity/services/identity.service';
import { MemberService } from 'app/modules/polyglot/member/services/member.service';
import { MemberReferrerService } from 'app/modules/polyglot/member_referrer/services/member_referrer.service';
import {
  CreateMemberRequest,
  CreateMemberResponse,
} from 'app/modules/proto/c2se/member_pb';
import { Bank } from 'app/modules/proto/models/bank_pb';

@Component({
  selector: 'sign-up-compose',
  templateUrl: './sign-up-compose.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: fuseAnimations,
})
export class SignUpComposeComponent implements OnInit {
  signupComposeForm!: FormGroup;

  isSendDisable = false;
  banks!: Bank[];

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

  showAlert: boolean = false;

  /**
   * Constructor
   */
  constructor(
    public matDialogRef: MatDialogRef<SignUpComposeComponent>,
    private _formBuilder: FormBuilder,
    private _identityService: IdentityService,
    private _memberService: MemberService,
    private _memberReferrerService: MemberReferrerService,
    private _bankService: BankService
  ) {}

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

  /**
   * On init
   */
  ngOnInit(): void {
    this._bankService
      .listBanks()
      .then((result) => {
        this.banks = result.getBanksList();
      })
      .catch((reson) => console.log(reson));

    // Create the form
    this.signupComposeForm = this._formBuilder.group({
      referalCode: ['maejang0lvl1', [Validators.required]],
      username: ['', [Validators.required]],
      nickname: ['', Validators.required],
      password: ['1234', [Validators.required]],
      passwordConfirm: [
        '1234',
        [Validators.required, this.checkSameForPassword()],
      ],
      exchangePassword: ['1234', [Validators.required]],
      mobilePhoneNumber: ['01012345678', [Validators.required]],
      bankId: ['', [Validators.required]],
      accountNumber: ['123123123', [Validators.required]],
      accountHolder: ['', [Validators.required]],
    });
  }

  // -----------------------------------------------------------------------------------------------------
  // @ 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.signupComposeForm?.valid) {
      return;
    }

    this.isSendDisable = true;

    const {
      referalCode,
      username,
      nickname,
      password,
      passwordConfirm,
      exchangePassword,
      mobilePhoneNumber,
      bankId,
      accountNumber,
      accountHolder,
    } = this.signupComposeForm?.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();

    member.setSiteId('d7cbae26-53b6-4cb1-85a4-66b956cbe1d4');
    member.setUsername(username);
    member.setPassword(password);
    member.setMemberClassId('4598f07a-86d1-42a4-b038-25706683a7cd');
    member.setMemberLevelId('c56231ac-2120-4a81-a30a-5d41fafb6c57');
    member.setReferrerMemberUsername(referalCode);
    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));
  }

  __checkReferrerCode(event: FocusEvent): void {
    const code = this.signupComposeForm.get('referalCode')?.value;
    this._memberReferrerService.getMemberReferrerByCode(code).then((result) => {
      if (!result) {
        this.signupComposeForm
          ?.get('referalCode')
          ?.setErrors({ notExistReferalCode: true });
      }
    });
  }

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

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

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

  close(): void {
    this.matDialogRef.close({
      choice: true,
    });
  }

  private checkSameForPassword(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      if (!control || !control.value || control.value === '') {
        return null;
      }
      const password = this.signupComposeForm?.get('password')?.value as string;
      const passwordConfirm = control.value as string;

      if (password !== passwordConfirm) {
        return { passwordNotMatch: true };
      }
      return null;
    };
  }
}
