<template>
  <div>
    <q-btn
      v-if="registry"
      flat
      dense
      :disable="registry.state === 'Аннулирован'"
      icon="highlight_off"
      size="16"
      style="color: rgba(0, 0, 0, 0.54)"
      color="primary"
      @click="annulModal = true"
    >
      <q-tooltip anchor="center left" self="center right">
        {{ $t('registries.objectCard.annulOrder') }}
      </q-tooltip>
    </q-btn>
    <q-dialog @hide="hideAnnulDialog" :value="annulModal">
      <q-card class="full-width no-shadow" style="max-width: 580px">
        <q-card-section>
          <h6 class="q-ma-none">
            {{ $t('registries.objectCard.annulOrder') }}
          </h6>
        </q-card-section>
        <q-card-section>
          <q-input
            filled
            :label="$t('registries.objectCard.annulReason')"
            v-model="reason"
            maxlength="1000"
            type="textarea"
          />
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            :loading="loading"
            color="primary"
            filled
            :disable="!reason"
            @click="annulStart"
            >{{ $t('registries.objectCard.annul') }}</q-btn
          >
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import Component from 'vue-class-component';
import { Vue, Prop } from 'vue-property-decorator';
import { ExportRegistryKompensDetskOtdMIR } from '@openapi/registry-data/api';
import get from 'lodash/get';
import { notifyError } from '@utils/notify';

@Component({})
export default class AnnulUnloading extends Vue {
  @Prop() registry: ExportRegistryKompensDetskOtdMIR;
  @Prop() registryCode: string;
  @Prop() processKey: string;
  @Prop() userId: string;

  private reason = '';
  private annulModal = false;
  private loading = false;

  hideAnnulDialog(): void {
    this.annulModal = false;
    this.reason = '';
  }

  get reasonFormatted(): string {
    return this.reason.replaceAll('\n', ' ');
  }

  async annulStart(): Promise<void> {
    if (!this.registry?.id) {
      notifyError(this.$t('registries.objectCard.annulIdError').toString());
      return;
    }

    this.loading = true;

    const { traceId } = await this.$store.dispatch(
      'wf/processes/dispatchProcess',
      {
        processKey: this.processKey,
        data: {
          id: this.registry.id,
          reason: this.reasonFormatted,
          registryCode: this.registryCode,
          userId: this.userId,
        },
      }
    );
    if (traceId) {
      const handler = (e: any) => {
        const data = JSON.parse(get(e, 'data', '{}'));
        if (data.traceId === traceId) {
          this.loading = false;
          this.$websockets.removeListener(handler);
          this.hideAnnulDialog();
          this.$emit('update');
        }
      };
      this.$websockets.addListener(handler);
    }
  }
}
</script>

<style scoped></style>
