<template>
  <operation-dialog
    persistent
    sign
    ref="dialogEditMainInfoAccount"
    :title="accountFIO"
    sub="Редактирование основных данных"
    v-model="opened"
    @hide="close"
  >
    <AccountBaseForm
      v-if="personData"
      :person-data="personData"
      :can-change-ip-address="canChangeIpAddress"
      :submit-function="submitFunction"
      :trigger-submit="triggerSubmit"
      @validateForm="updateStateValidateForm"
    />
    <template #process>
      <result-block
        header="Обновление информации о сотруднике"
        icon="pgs-document"
        type="info"
      />
    </template>
    <template #result>
      <result-block :header="resultMessage" :type="resultType" />
    </template>
    <template #left-actions-panel>
      <r-btn
        outline
        :label="isFinishStep ? 'Закрыть' : 'Отмена'"
        icon="pgs-close"
        color="primary"
        @click="close"
      />
    </template>
    <template #right-actions-panel>
      <r-btn
        v-if="!isFinishStep"
        outline
        label="Сохранить"
        icon="pgs-save"
        positive
        :disable="!validateForm"
        @click="submit"
      />
    </template>
  </operation-dialog>
</template>

<script lang="ts">
import { Component, Prop, Mixins, Watch, Ref } from 'vue-property-decorator';
import get from 'lodash/get';
import ProcessStarter from '@/mixins/ProcessStarter';
import OperationDialog from '@/components/common/operation-dialog/index.vue';
import { Account } from '@interfaces/entities/Account';
import AccountBaseForm from '@/recruits/components/accounts/components/forms/AccountBaseForm.vue';
import { PersonData } from '@/recruits/components/accounts/utils/types';

@Component({
  components: {
    AccountBaseForm,
  },
})
export default class EditMainAccountInfoModal extends Mixins(ProcessStarter) {
  @Prop({ default: null }) account: Account | null;
  @Prop({ default: 'milBaseEditAccountPersonIDMProcess' })
  declare processKey: string;

  @Ref('dialogEditMainInfoAccount') operationDialog: OperationDialog;

  opened = false;
  isFinishStep = false;

  validateForm = false;
  personData: PersonData | null = null;
  triggerSubmit = 0;

  get accountFIO(): string {
    return this.account?.person.fio || 'Сотрудник';
  }

  get canChangeIpAddress(): boolean {
    const localCredentials =
      this.account?.credentials.filter(
        (credential) => credential.schema === 'LocalCredential'
      ) || [];

    return (
      this.$AC.haveScope(this.$AC.scopes.SECURITY_ADMINISTRATOR) &&
      !!localCredentials.length
    );
  }

  private updateStateValidateForm(validateStatus: boolean): void {
    this.validateForm = validateStatus;
  }

  resultType: 'positive' | 'negative' | '' = '';
  resultMessage = '';

  @Watch('account')
  private async accountHandler(): Promise<void> {
    // accountHandler приходит null - значит надо закрыть окно
    this.opened = false;
    this.resultType = '';
    this.personData = null;
    this.isFinishStep = false;
    this.operationDialog.reset();
    if (!this.account?.id) return;
    this.personData = this.account.person;
    this.opened = true;
  }

  async submit(): Promise<void> {
    if (!this.validateForm) {
      return;
    }
    this.triggerSubmit++;
  }

  async submitFunction(personData: PersonData): Promise<void> {
    if (!this.account) {
      return;
    }
    this.operationDialog.toProcess();
    const dataObject: {
      accountId: string;
      organizationId: string;
      personData: PersonData;
    } = {
      accountId: this.account.id,
      organizationId: this.account.userDomain.id,
      personData,
    };

    try {
      const traceId = await this.startProcess(dataObject);

      this.isFinishStep = true;

      this.registerListener((message, removeListener) => {
        if (traceId !== message.traceId) return;
        if (message?.body?.type === 'finish') {
          this.resultType = 'positive';
          this.resultMessage = 'Информация о сотруднике обновлена';
          removeListener();
        }

        if (message?.body?.type === 'error') {
          this.resultType = 'negative';
          // get т.к. message может быть Task | PushMessage, а в Task нет поля msg
          this.resultMessage = get(
            message,
            'body.msg.message',
            'Произошла непредвиденная ошибка'
          );
          removeListener();
        }
      });
    } catch (error: any) {
      this.resultType = 'negative';
      this.$q.notify({
        message: error.message,
        color: 'negative',
      });
    } finally {
      this.operationDialog.toResult();
    }
  }

  close(): void {
    if (this.isFinishStep) {
      this.$emit('refresh');
    } else {
      this.$emit('close');
    }
  }
}
</script>
