<template>
  <div class="send-registration">
    <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="opened" 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, Watch } from 'vue-property-decorator';
import TaskButton from '@/mixins/TaskButton';
import {SubpoenaByRecruitV2, SubpoenaRegistryApi} from '@/recruits/openapi/subpoena-service';
import { get, isString } from 'lodash';
import ProcessStarter from '@/mixins/ProcessStarter';
import Dialog from '@/mixins/Dialog';
import LoaderWithText from '@components/common/loader.vue';
import { UserTaskListItem, WorkflowServiceApi } from '@/openapi/wf';
import { notifyError } from '@/utils/notify';
import {PersonRegistryApi, RecruitV4} from "@/recruits/openapi/person-registry";

interface Task {
  traceId: string;
  taskId: string;
}

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

@Component({ components: { LoaderWithText } })
export default class MultiSendRegistration extends Mixins(Dialog, ProcessStarter) {
  @Prop({ default: () => '' })
  label: string;

  @Prop({ default: () => false })
  disable: boolean;

  @Prop({ default: () => null }) data: any;

  @Prop({ default: () => false })
  loading: boolean;

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

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

  recruits: RecruitV4[] = [];
  // summonsByRecruit: Record<string, SubpoenaByRecruitV2[]> = {};
  taskByRecruit: Record<string, UserTaskListItem | null> = {};

  async action(): Promise<void> {
    if (!this.recruits.length) {
      notifyError('Нет повесток для отправки');
      return;
    }
    this.$q.loading.show();
    try {
      this.$emit('onBeforeAction', 'summons_send', 'send');
      const { traceId } = await this.$store.dispatch(
        'wfActions/processes/dispatchProcess',
        {
          processKey: 'milBaseMassSendProcess',
          data: {
            personIds: this.personIds,
            listId: this.data?.listInfo?.id || null,
          },
        }
      );

      this.registerListener((message, removeListener) => {
        if (traceId !== message.traceId) return;
        if (message.body.type === 'success' || message.body.type === 'finish') {
          removeListener();
          this.$q.loading.hide();
          this.finish();
        }
      });

    } catch (error) {
      this.$q.loading.hide();
      console.error(error);
    }
  }

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

  @Watch('personIds', { immediate: true })
  async fetchRecruits(ids: string[]): Promise<void> {
    const recruits: RecruitV4[] = [];
    for (const id of ids) {
      const recruitInfo = await this.getRecruit(id);
      if (recruitInfo.status === '3.14') {
        recruits.push(recruitInfo);
        try {
          // this.summonsByRecruit[id] = await this.getSummon(id);
          const businessKey = recruitInfo.recruitSystemInfo?.processIdMain;
          this.taskByRecruit[id] = await this.fetchUserData(businessKey);
        } catch {}
      }
    }
    this.recruits = recruits;
  }

  async fetchUserData(businessKey?: string): Promise<UserTaskListItem | null> {
    if (!businessKey) return null;
    const assignee = this.$store.getters['oidcClient/currentUser'].sub;
    const {
      data: { tasks = [] },
    } = await new WorkflowServiceApi().findUserTasks(
      businessKey,
      undefined,
      assignee
    );
    return tasks[0] || null;
  }

  async getRecruit(id: string): Promise<RecruitV4> {
    const { data } = await new PersonRegistryApi().getOneRecruitV4(id);
    return data;
  }

  async getSummon(id: string): Promise<SubpoenaByRecruitV2[]> {
    const { data } = await new SubpoenaRegistryApi().getSubpoenaByRecruitV2(id);
    return data.subpoenas || [];
  }

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

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

  close(): void {
    this.$emit('onBeforeAction', 'summons_cancel', 'send');
    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>
