<template>
  <div class="AccountBaseForm">
    <r-input
      class="AccountBaseForm__Field"
      label="Логин*"
      v-model="userName"
      validate-on-blur
      :rules="loginRules"
    >
      <template #append v-if="isCheckingDuplicateLogin">
        <q-inner-loading
          :showing="isCheckingDuplicateLogin"
          size="24px"
          class="AccountBaseForm__Loading"
        ></q-inner-loading>
      </template>
      <template #error v-if="errorMessage">
        <span>{{ errorMessage }}</span>
      </template>
    </r-input>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RInput from '@/recruits/components/common/r-input/index.vue';
import { AccountLogin } from '@/recruits/components/accounts/utils/types';
import isString from 'lodash/isString';
import { CredentialsApi } from '@/openapi/idm';
const credentialsApi = new CredentialsApi();

@Component({
  components: {
    RInput,
  },
})
export default class AccountBaseForm extends Vue {
  @Prop({}) submitFunction: (accountLogin: AccountLogin) => void;
  @Prop({ default: 0 }) triggerSubmit: number;
  @Prop({ default: null }) accountLogin: AccountLogin | null;

  userName = '';
  haveDuplicateLogin = false;
  isCheckingDuplicateLogin = false;
  debounceTimer: ReturnType<typeof setTimeout> | null = null;

  isCurrentLogin(val: string | null): boolean {
    return isString(val) ? !!val.trim().length && !val.includes(' ') : false;
  }

  loginRules = [
    (val: string): boolean | string =>
      this.isCurrentLogin(val) || 'Обязательное поле',
  ];

  get errorMessage(): string {
    return this.haveDuplicateLogin
      ? 'Сотрудник с таким логином уже есть в системе'
      : '';
  }

  get validateForm(): boolean {
    return (
      this.isCurrentLogin(this.userName) &&
      !this.isCheckingDuplicateLogin &&
      !this.haveDuplicateLogin
    );
  }

  @Watch('userName')
  private userNameHandler(): void {
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
      this.isCheckingDuplicateLogin = false;
      this.haveDuplicateLogin = false;
    }
    if (this.isCurrentLogin(this.userName)) {
      this.isCheckingDuplicateLogin = true;
      this.debounceTimer = setTimeout(async () => {
        const credentials = await credentialsApi
          .getProps(this.userName)
          .then(({ data }) => data);
        this.haveDuplicateLogin = !!credentials.length;
        this.isCheckingDuplicateLogin = false;
      }, 800);
    }
  }

  @Watch('accountLogin', { immediate: true, deep: true })
  private accountLoginHandler(): void {
    this.userName = this.accountLogin?.userName || '';
  }

  @Watch('validateForm', { immediate: true })
  private validateFormHandler(val: boolean): void {
    this.$emit('validateForm', val);
  }

  @Watch('triggerSubmit')
  private triggerSubmitHandler(): void {
    this.submitFunction({
      userName: this.userName.trim(),
    });
  }
}
</script>

<style lang="scss" scoped>
.AccountBaseForm {
  &__Field {
    margin-bottom: 15px;
  }

  &__Loading {
    color: #107abc;
    display: flex;
    background: none;
  }
}
</style>
