<template>
  <div class="send-registration">
    <q-tooltip maxWidth="300px" v-if="tooltip">{{ tooltip }}</q-tooltip>
    <block-loader type="QBtn" :loading="loading">
      <r-btn
        dense
        :label="label"
        icon="pgs-arrow-right"
        :disable="disable"
        @click="open"
        no-wrap
      />
    </block-loader>
    <q-dialog v-model="isModalVisible" no-backdrop-dismiss>
      <q-card>
        <q-card-section class="modal-section">
          <h4 class="modal-header">Подтвердите действие</h4>
          <p class="modal-p">
            После нажатия кнопки "Направить" повестка будет размещена в личном
            кабинете Реестра повесток гражданина
          </p>
          <p class="modal-p">
            В личный кабинет гражданина на ЕПГУ будет направлено уведомление о
            размещении повестки
          </p>
        </q-card-section>
        <q-card-actions class="modal-footer">
          <r-btn label="Отменить" v-close-popup @click="close" />
          <r-btn label="Направить" :action="true" @click="action" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Mixins, Prop } from 'vue-property-decorator';
import TaskButton from '@/mixins/TaskButton';
import { RecruitV4 } from '@/recruits/openapi/person-registry';
import { get, isString } from 'lodash';
import ProcessStarter from '@/mixins/ProcessStarter';
import Dialog from '@/mixins/Dialog';
import LoaderWithText from '@components/common/loader.vue';

interface ButtonOptions {
  fields?: Record<string, string>;
  editableFields?: string[];
  hideFields?: string[];
  hideDialog?: boolean;
}

@Component({ components: { LoaderWithText } })
export default class SendRegistration extends Mixins(
  TaskButton,
  Dialog,
  ProcessStarter
) {
  @Prop({ default: () => false })
  readonly sign: boolean;

  @Prop({ default: () => false })
  readonly tooltip: string;

  @Prop({
    default: () => 'Подтвердите действие',
  })
  readonly title: string;

  @Prop({ default: () => ({}) })
  declare readonly model: (string | RecruitV4)[] | RecruitV4;

  public isModalVisible = false;

  get canFormSubmit(): boolean {
    return this.disable;
  }

  get buttonOptions(): ButtonOptions {
    return get(
      this.userTask,
      ['outData', 'options', this.buttonSettings.id],
      {}
    );
  }

  async action(): Promise<void> {
    try {
      this.$emit('onBeforeAction', 'subpoena_send_done');
      this.$q.loading.show();
      const taskId = this.userTask.taskId;
      const traceId = this.taskProcess.traceId;
      await this.$store.dispatch('wfActions/processes/submitForm', {
        formModel: this.formModel,
        taskId,
        traceId,
      });
      this.registerListener((message, removeListener) => {
        if (traceId !== message.traceId) return;
        if (message.body.type === 'finish') {
          this.$q.loading.hide();
          removeListener();
        }
      });
    } catch (error) {
      this.$q.loading.hide();
      console.error(error);
    }
  }

  get personIds(): string[] {
    if (Array.isArray(this.model)) {
      return (
        this.model?.map((recruitOrId): string => {
          if (isString(recruitOrId)) return recruitOrId;
          return recruitOrId.id;
        }) || []
      );
    }
    return [this.model.id];
  }

  get formModel(): { id: string; personIds: string[] } {
    return {
      id: this.buttonSettings.id,
      personIds: this.personIds,
    };
  }

  finish(): void {
    this.$emit('onBeforeAction', 'subpoena_send_done');
    this.$emit('done');
  }

  open(): void {
    this.$emit('onBeforeAction', 'subpoena_send');
    this.isModalVisible = true;
    if (this.disable) return;
    this.opened = true;
    this.$emit('open');
  }

  close(): void {
    this.$emit('onBeforeAction', 'subpoena_send_cancel');
    this.opened = false;
    this.$emit('close');
  }

  beforeDestroy(): void {
    this.$q.loading.hide();
  }
}
</script>

<style lang="scss" scoped>
.transparent-loader {
  background-color: transparent;
}

.modal-section {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 30px 40px;
}

.modal-header,
.modal-p {
  font-family: 'Golos Text', sans-serif;
  font-style: normal;
  font-weight: 500;
  letter-spacing: -0.015em;
}

.modal-header {
  color: #015e98;
  text-align: center;
  margin-bottom: 24px;
  font-size: 20px;
  margin-top: 0;
}

.modal-p {
  font-size: 14px;
  line-height: 18px;
  margin-bottom: 18px;
  &:last-child {
    margin-bottom: 0;
  }
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  padding: 12px 20px;
}
</style>
