import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { FuseAlertType } from '@fuse/components/alert';
import { BankService } from 'app/modules/polyglot/bank/services/bank.service';
import { MemberBankWithdrawService } from 'app/modules/polyglot/member_bank_withdraw/services/member_bank_withdraw.service';
import { CreateMemberBankWithdrawRequest } from 'app/modules/proto/c2se/member_bank_withdraw_pb';
import { Bank } from 'app/modules/proto/models/bank_pb';

@Component({
  selector: 'withdraw-compose',
  templateUrl: './withdraw-compose.component.html',
  encapsulation: ViewEncapsulation.None,
})
export class WithdrawComposeComponent implements OnInit {
  withdrawComposeForm!: FormGroup;
  alert: { type: FuseAlertType; message: string } = {
    type: 'success',
    message: '출금신청이 완료 되었습니다.',
  };
  showAlert: boolean = false;
  banks!: Bank[];
  hide: boolean = true;
  /**
   * Constructor
   */
  constructor(
    public matDialogRef: MatDialogRef<WithdrawComposeComponent>,
    private _formBuilder: FormBuilder,
    private _memberBankWithdrawService: MemberBankWithdrawService,
    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.withdrawComposeForm = this._formBuilder.group({
      bankId: ['', [Validators.required]],
      accountNumber: ['123123123', [Validators.required]],
      accountHolder: ['', [Validators.required]],
      exchangePassword: ['1234', [Validators.required]],
      amount: ['', [Validators.required]],
      holdingMoney: ['', [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.withdrawComposeForm.valid) {
      return;
    }

    this.withdrawComposeForm?.disable();

    const req = new CreateMemberBankWithdrawRequest();
    const amount = this.withdrawComposeForm.get('amount')?.value as number;
    const holder = this.withdrawComposeForm.get('accountHolder')
      ?.value as string;
    req.setAmount(amount);
    req.setName(holder);
    req.setMemo('test');

    this._memberBankWithdrawService
      .createMemberBankWithdraw
      // req    - 에러나서 지워둠. 이담
      ()
      .then(() => {
        console.log();
        this.showAlert = true;
      })
      .catch((e) => {
        this.showAlert = true;
        this.alert = { type: 'error', message: '출금신청이 실패 하였습니다.' };
        // Re-enable the form
        this.withdrawComposeForm?.enable();

        // Reset the form
      })
      .finally(() =>
        setTimeout(() => {
          this.matDialogRef.close();
        }, 2000)
      );
    // req.set
  }

  __changeAmount(amount: string): void {
    const amountInput = this.withdrawComposeForm.get('amount');

    if (amount === '0') {
      amountInput?.setValue('');
      return;
    }
    amountInput?.setValue(amount);
  }
}
