<template>
  <div class="register-new-recruit">
    <r-btn
      dense
      positive
      :disable="disable"
      :label="label"
      :icon="sign ? 'pgs-sign' : 'pgs-user-check'"
      :disabled-background-color="disabledBackgroundColor"
      @click="open"
      no-wrap
    >
      <q-tooltip max-width="200px" v-if="tooltipInformer">
        {{ tooltipInformer }}
      </q-tooltip>
    </r-btn>
    <operation-dialog
      persistent
      ref="dialog"
      :title="title"
      :sub="sub"
      :process-key="processKey"
      v-model="opened"
      @hide="close"
    >
      <div class="row q-col-gutter-md">
        <div class="col-12" v-if="listType">
          <data-block
            :form-data="{
              label: 'Причина вызова',
              value: options[listType] || '-',
              icon: 'pgs-document',
            }"
            bolder
          />
        </div>
        <div class="col-12 col-sm-4">
          <data-block
            :form-data="{
              label: 'Дата и время вызова',
              value: resolutionDate,
              icon: 'pgs-calendar',
            }"
          />
        </div>
        <div class="col-12 col-sm-4" v-if="getDeliveryType">
          <data-block
            :form-data="{
              label: 'Способ направления',
              value: getDeliveryMethod[getDeliveryType] || '-',
              icon: 'pgs-document',
            }"
          />
        </div>
        <div class="col-12">
          <span class="MultiInit-UserInfo__Header"> ФИО / ДАТА РОЖДЕНИЯ </span>
          <div
            class="col-12 MultiInit-UserInfo"
            v-for="recruit in usersInfo"
            :key="recruit.id"
          >
            <span class="col-12 MultiInit-UserInfo__FullName">
              {{ recruit.fullName }}
            </span>
            <span class="col-12 MultiInit-UserInfo__BirthDate">
              <q-icon
                class="MultiInit-UserInfo__Calendar"
                name="pgs-calendar"
              />
              <span class="MultiInit-UserInfo__Date">
                {{ formatDate(recruit.birthDate) }}
              </span>
            </span>
          </div>
        </div>
      </div>
      <template #process>
        <result-block
          type="info"
          :icon="sign ? 'pgs-sign' : 'pgs-document'"
          :header="processMessage"
        >
          <TransitionGroup name="results" tag="div">
            <div v-for="res in resultList" :key="res.id">
              <q-icon name="pgs-sign-2" color="info" size="sm" />
              <span>{{ get(res, 'fullName') }}</span>
            </div>
          </TransitionGroup>
        </result-block>
      </template>
      <template #result>
        <result-block :header="resultMessage">
          <div class="results">
            <div v-for="res in resultList" :key="res.id">
              <q-icon name="pgs-check" color="positive" size="sm" />
              <span>{{ get(res, 'fullName') }}</span>
            </div>
          </div>
        </result-block>
      </template>
      <template #right-actions>
        <r-btn action label="Сформировать" @click="action" />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          label="Продолжить"
          icon-right="pgs-shevron-right-off"
          @click="finish"
        />
      </template>
    </operation-dialog>
  </div>
</template>

<i18n>
{
  "ru": {
    "MultiSign": {
      "selected": "не выбрано | одного гражданина | {n} гражданина | {n} граждан",
      "signing": " | Повестка формируется | Повестки формируются | Повестки формируются",
      "signed": " | Повестка сформирована | Повестки сформированы | Повестки сформированы"
    }
  }
}
</i18n>

<style lang="scss" scoped>
.results-enter-active,
.results-leave-active {
  transition: all 0.5s ease;
}
.results-enter-from,
.results-leave-to {
  opacity: 0;
  transform: translateY(-30px);
}

.MultiInit {
  &-UserInfo {
    display: flex;
    flex-direction: column;
    padding: 6px;
    background-color: rgba(53, 126, 172, 0.05);
    border-radius: 4px;
    font-family: 'Golos Text', sans-serif;
    &__FullName {
      color: rgba(2, 12, 18, 0.58);
      font-size: 14px;
      font-weight: 500;
    }
    &__BirthDate {
      color: rgba(2, 12, 18, 0.9);
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    &__Calendar {
      font-size: 20px;
      margin-right: 5px;
    }
    &__Date {
      line-height: 1px;
    }
    &__Id {
      font-size: 14px;
      font-weight: 600;
    }
    &__Header {
      font-size: 12px;
      font-family: 'Golos Text', sans-serif;
      color: rgba(2, 12, 18, 0.58);
      font-weight: 600;
      text-transform: uppercase;
    }
    &:not(:last-child) {
      margin-bottom: 4px;
    }
  }
}
</style>

<script lang="ts">
import { Component, Mixins, Prop, Ref } from 'vue-property-decorator';
import dataBlock from '@components/cards/statements/components/dataBlock.vue';
import TaskButton from '@/mixins/TaskButton';
import OperationDialog from '@/components/common/operation-dialog/index.vue';
import { RecruitV3 } from '@/recruits/openapi/person-registry';
import {
  ListElementV2,
  ListRecordV2,
} from '@/recruits/openapi/summon-list-service';
import get from 'lodash/get';
import ProcessStarter from '@/mixins/ProcessStarter';
import { DateFormat, convertDateFormat } from '@/utils/format-date';
import { isArray } from 'lodash';
import RInput from '@/recruits/components/common/r-input.vue';
import { formatDate } from '@/recruits/utils';

type PersonInfo = {
  id: string;
  fullName: string;
};

type UserInfo = {
  id: string;
  fullName: string;
  birthDate: string;
};

@Component({
  components: {
    RInput,
    dataBlock,
  },
  methods: {
    get,
    formatDate,
  },
})
export default class MultiShape extends Mixins(TaskButton, ProcessStarter) {
  get: typeof get;

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

  @Prop({ default: () => true })
  readonly sign: boolean;

  @Prop({ default: () => '' })
  readonly title: string;

  @Prop({ default: () => null }) data: {
    data: Array<ListElementV2>;
    listInfo: ListRecordV2;
  };

  @Prop() disabledBackgroundColor: string | null;

  @Prop()
  readonly activityOptions: any;

  @Prop({ default: () => 'initPersonAdult' })
  actionType: 'initPersonYoung' | 'initPersonAdult';

  @Prop() activityRecorderOptions: any;

  @Prop() disabledShapeEmpty: boolean;

  @Ref('dialog') operationDialog: OperationDialog;

  opened = false;

  modalCounter = 0;

  get options(): string {
    return (
      this.$store.getters[
        'ervuDictionaries/militaryRegistrationUpdatingGoalsDictionary'
      ] || []
    );
  }

  get getDeliveryMethod(): string {
    return this.$store.getters['ervuDictionaries/getDeliveryDirections'] || [];
  }

  get getDeliveryType(): string {
    return this.data?.listInfo?.deliveryMethod || '';
  }

  get listType() {
    return this.data?.listInfo?.summonObjective || '';
  }

  resultList: PersonInfo[] = [];

  get processMessage(): string {
    return this.$tc('MultiSign.signing', this.length);
  }

  get resultMessage(): string {
    return this.$tc('MultiSign.signed', this.length);
  }

  get length(): number {
    return this.sendInfo?.length;
  }

  get sub(): string {
    if (isArray(this.model))
      return `${this.$tc('MultiSign.selected', this.model.length)}`;
    return this.model.fullName || '';
  }

  get fio(): string {
    if (isArray(this.model)) return '';
    return this.model?.mainInfo?.fullName || '';
  }

  get shortName(): string {
    if (isArray(this.model)) return '';
    return `${this.model?.mainInfo?.firstName || ''} ${
      this.model?.mainInfo?.middleName || ''
    }`;
  }

  get tooltipInformer() {
    return this.disabledShapeEmpty ? 'Выберите способ отправки по всем адресам направления повестки или удалите ненужный адрес' : '';
  }

  get usersInfo(): UserInfo[] {
    if (Array.isArray(this.model)) {
      return this.model?.map((recruit) => {
        return {
          // @ts-ignore
          fullName: recruit.fullName || '',
          // @ts-ignore
          birthDate: recruit.birthDate || '',
          // @ts-ignore
          id: recruit.id || '',
        };
      });
    }
    return [
      {
        fullName: this.model.mainInfo.fullName,
        birthDate: this.model.mainInfo.birthDate,
        id: this.model.id,
      },
    ];
  }

  get resolutionDate(): string {
    return convertDateFormat(
      new Date(this.data?.listInfo?.turnoutDate as string),
      DateFormat.date
    );
  }

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

  get sendInfo(): any {
    return this.model?.map((recruit: any) => {
      return {
        personId: recruit.id,
        sendData: recruit.sendInfo.map((send: any) => {
          return {
            sendCode: send.sendCode,
            addressType: send.addressType,
          };
        }),
      };
    });
  }

  async action(): Promise<void> {
    this.modalCounter = 0;
    this.operationDialog.toProcess();
    try {
      this.$emit('onBeforeAction', 'summons_form', 'shape');
      const summonObjective = this.data.listInfo.summonObjective;
      if (!summonObjective) throw new Error('Не указана причина запроса');

      const summonDate = this.data.listInfo.turnoutDate
        ? formatDate(this.data.listInfo.turnoutDate, 'YYYY-MM-DDTHH:mm:ss.SSSZ')
        : '';
      const { traceId } = await this.$store.dispatch(
        'wfActions/processes/dispatchProcess',
        {
          processKey: 'milBaseRouteProcess',
          personIds: this.personIds,
          data: {
            actionType: this.actionType,
            summonObjective,
            summonDate,
            sendInfo: this.sendInfo,
            listId: this.data?.listInfo?.id || null,
          },
        }
      );

      this.registerListener((message, removeListener) => {
        if (message.body.type === 'task' && message.body.successId) {
          this.addUserOnProgress();
        }
        if (traceId !== message.traceId) return;
        if (
          message.body.type === 'endEvent' ||
          message.body.type === 'finish'
        ) {
          // this.addUserOnProgress();
          this.operationDialog.toResult();
          removeListener();
        }
      });
    } catch (error) {
      console.error(error);
      this.operationDialog.toResult();
    }
  }

  // метод нужен для создания списка рекрутов в процессе подписания
  addUserOnProgress(): void {
    this.model[this.modalCounter] &&
      this.onSigned(this.model[this.modalCounter]);
    this.modalCounter++;
  }

  onSigned(data: PersonInfo): void {
    console.log('signed', data);
    this.resultList.push(data);
  }

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

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

  close(): void {
    this.$emit('onBeforeAction', 'summons_form_cancel', 'shape');
    this.opened = false;
    this.resultList = [];
    this.operationDialog.reset();
    this.$emit('close');
  }
}
</script>
