<template>
  <operation-dialog
    persistent
    sign
    ref="dialogOrganizationDelete"
    :title="organizationName"
    sub="Подтверждение действия"
    v-model="opened"
    @hide="close"
  >
    <div>Вы действительно хотите архивировать организацию?</div>
    <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 ? 'Закрыть' : 'Отмена'"
        positive
        @click="close"
      />
    </template>
    <template #right-actions-panel>
      <r-btn
        v-if="!isFinishStep"
        outline
        label="Подтверждение"
        negative
        @click="deleteOrganization"
      />
    </template>
  </operation-dialog>
</template>

<script lang="ts">
import { Component, Prop, Mixins, Watch, Ref } from 'vue-property-decorator';
import { Organization } from '@openapi/idm';
import get from 'lodash/get';
import ProcessStarter from '@/mixins/ProcessStarter';
import OperationDialog from '@/components/common/operation-dialog/index.vue';

@Component({})
export default class DeleteModal extends Mixins(ProcessStarter) {
  @Prop({ default: null }) organization: Organization | null;
  @Prop({ default: 'milBaseDeleteOrganizationIDMProcess' })
  declare processKey: string;

  @Ref('dialogOrganizationDelete') operationDialog: OperationDialog;

  opened = false;
  isFinishStep = false;

  get organizationName(): string {
    return (
      this.organization?.fullname ||
      this.organization?.shortname ||
      this.organization?.name ||
      'Организация'
    );
  }

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

  @Watch('organization')
  private async organizationHandler(): Promise<void> {
    // organizationHandler приходит null - значит надо закрыть окно
    this.opened = false;
    this.isFinishStep = false;
    this.resultType = '';

    this.operationDialog.reset();
    if (!this.organization?.id) return;
    this.opened = true;
  }

  close(): void {
    if (this.isFinishStep) {
      this.$emit('finish');
    } else {
      this.$emit('close');
    }
  }

  async deleteOrganization(): Promise<void> {
    try {
      const traceId = await this.startProcess({
        organizationId: this.$route.params.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();
        }
        this.operationDialog.toResult();
      });
    } catch (error: any) {
      this.resultType = 'negative';
      this.$q.notify({
        message: error.message,
        color: 'negative',
      });
    } finally {
      this.operationDialog.toResult();
    }
  }
}
</script>

<style lang="scss" scoped>
.EditModalForm {
  &__FieldLabel {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    display: inline-block;
    cursor: pointer;
    font-size: 12px;
    line-height: 16px;
    margin-bottom: 4px;
    font-weight: 600;
    color: rgba(2, 12, 18, 0.58);
    transition: 0.3s;
  }

  &__Field {
    margin-bottom: 15px;
    &::v-deep {
      .q-field--with-bottom {
        padding-bottom: 0;
      }

      .q-field--auto-height .q-field__control {
        background: #e5edf5;
        border-bottom: 1px solid rgba(1, 72, 116, 0.18);
      }

      .q-field--filled.q-field--highlighted .q-field__control:before {
        opacity: 0;
      }

      .q-field--filled .q-field__control:after {
        height: 0;
      }

      .q-field--focused {
        &.q-field--filled .q-field__control {
          background: white;
          border: 1px solid #0148742e;
        }
      }

      .q-field--filled .q-field__control {
        background: #e5edf5;
        // border-bottom: 1px solid rgba(1, 72, 116, 0.18);
      }
    }
  }

  &__FieldIcon {
    cursor: pointer;
  }

  &__TogglesBlock {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
  }
}
</style>
