<template>
  <operation-dialog
    persistent
    sign
    ref="dialogEditRolesAccount"
    :title="accountFIO"
    sub="Редактирование ролей учетной записи"
    v-model="opened"
    @hide="close"
    width="800px"
  >
    <AccountRolesForm
      v-if="opened"
      :user-roles-ids="userRolesIds"
      :submit-function="submitFunction"
      :trigger-submit="triggerSubmit"
    />
    <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
        @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 AccountRolesForm from '@/recruits/components/accounts/components/forms/AccountRolesForm.vue';
import { AccountRolesData } from '@/recruits/components/accounts/utils/types';

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

  @Ref('dialogEditRolesAccount') operationDialog: OperationDialog;

  opened = false;
  isFinishStep = false;
  triggerSubmit = 0;
  userRolesIds: string[] = [];

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

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

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

    this.userRolesIds = this.account.roles
      .filter((role) => role.ervuRole)
      .map((role) => role.id);
  }

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

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

    try {
      const traceId = await this.startProcess({
        account: {
          ...accountRolesData,
          accountId: 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>
