<template>
  <operation-dialog
    persistent
    sign
    ref="dialogEditOrganizationAccount"
    :title="accountFIO"
    sub="Редактирование учетной записи"
    v-model="opened"
    @hide="close"
  >
    <AccountOrganizationsForm
      v-if="accountData"
      :account-data="accountData"
      :is-my-account="isMyAccount"
      :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 ProcessStarter from '@/mixins/ProcessStarter';
import OperationDialog from '@/components/common/operation-dialog/index.vue';
import { Account } from '@interfaces/entities/Account';
import get from 'lodash/get';
import AccountOrganizationsForm from '@/recruits/components/accounts/components/forms/AccountOrganizationsForm.vue';
import { AccountOrganizationsData } from '@/recruits/components/accounts/utils/types';

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

  @Ref('dialogEditOrganizationAccount') operationDialog: OperationDialog;

  opened = false;
  isFinishStep = false;
  validateForm = false;
  triggerSubmit = 0;

  accountData: Account | null = null;

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

  get isMyAccount(): boolean {
    return (
      this.accountData?.id === this.$store.getters['oidcClient/currentUser'].sub
    );
  }

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

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

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

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

  async submitFunction(accountData: AccountOrganizationsData): Promise<void> {
    if (!this.account?.id) {
      return;
    }
    this.operationDialog.toProcess();

    try {
      const traceId = await this.startProcess({
        account: {
          ...accountData,
          id: this.account.id,
        },
      });

      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>
