<template>
  <div class="register-new-recruit">
    <r-btn
      dense
      negative
      :disable="disable"
      :label="label"
      icon="pgs-sign"
      @click="open"
      no-wrap
    />
    <operation-dialog
      sign
      persistent
      ref="dialog"
      :title="title"
      :sub="sub"
      v-model="opened"
      @hide="close"
    >
      <r-select
        class="MultiConfirm-Description"
        label="Причина"
        :options="causes"
        v-model="cause"
        disable
      />
      <r-input
        type="text"
        class="MultiConfirm-Description"
        label="Комментарий"
        v-model="description"
      />
      <div class="MultiConfirm-Attention__Header q-mt-md">
        Вы подтверждаете направление записи гражданина
        на ручную конвертацию для определения военкомата
      </div>
      <div class="MultiConfirm-Attention">
        <div
          v-for="recruit in citizens"
          :key="recruit.id"
          class="MultiConfirm-Attention__List"
        >
          <div class="MultiConfirm-Attention__FIO">{{ recruit.fullName }}</div>
          <div class="MultiConfirm-Attention__VK">{{ recruit.currentVK }}</div>
        </div>
      </div>
      <template #process>
        <upload-status
          status="pending"
          label="В процессе подтверждения..."
          file-name="Отказ в постановке на учет"
          :label-size="16"
          :reverse-labels-order="true"
        />
      </template>
      <template #result>
        <upload-status
          :status="hasError ? 'error' : 'success'"
          :label="resultMessage"
          file-name="Отказ в постановке на учет"
          :label-size="16"
          success-label-color="black"
          :reverse-labels-order="true"
          success-icon="pgs-reply"
        />
      </template>
      <template #right-actions>
        <r-btn
          action
          label="Сформировать"
          icon="pgs-sign"
          :disable="disable"
          @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} решения | {n} решений",
      "formed": " | Сформировано решение об отклонении включения сведений в реестр | Сформированы решения об отклонении включения сведений в реестр | Сформированы решения об отклонении включения сведений в реестр",
      "error": " | Решение не сформировано | Решения не сформированы | Решения не сформированы"
    }
  }
}
</i18n>

<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 {
  RecruitV4,
  SearchRecruitResponse,
} from '@/recruits/openapi/person-registry';
import get from 'lodash/get';
import { SignData } from '@/mixins/CriptoProPlugin';
import isString from 'lodash/isString';
import isArray from 'lodash/isArray';
import isEmpty from 'lodash/isEmpty';
import UploadStatus from '@/components/common/upload-status/index.vue';

import { getDictionaryFormatedToOptions } from '@/recruits/utils';
import rSelect from '@/recruits/components/common/r-select.vue';
import rInput from '@/recruits/components/common/r-input.vue';
import { notifyError } from '@utils/notify';
import ProcessStarter from '@/mixins/ProcessStarter';

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

@Component({
  components: {
    dataBlock,
    rSelect,
    rInput,
    UploadStatus,
  },
  methods: {
    get,
  },
})
export default class MultiNotConfirm extends Mixins(
  TaskButton,
  ProcessStarter
) {
  get: typeof get;

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

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

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

  @Prop()
  actionType: 'sendConvertation';

  @Prop()
  activityRecorderOptions: any;

  @Ref('dialog') operationDialog: OperationDialog;

  opened = false;

  certificateIsActive = false;

  hasError = false;

  resultList: PersonInfo[] = [];

  get resultMessage(): string {
    if (this.hasError) return this.$tc('MultiSign.error', this.length);
    return this.$tc('MultiSign.formed', this.length);
  }

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

  get citizens(): Array<SearchRecruitResponse | RecruitV4> {
    if ((this.model as SearchRecruitResponse[])?.length !== undefined)
      return this.model as SearchRecruitResponse[];
    const recruit = this.model as RecruitV4;
    return [
      {
        ...recruit.mainInfo,
        ...recruit,
      } as RecruitV4,
    ];
  }

  cause = {
    value: '5',
    label:
      'Неверное определение целевого военного комиссариата для постановки на воинский учет гражданина',
  };

  get causes() {
    const dict = this.$store.getters[
      'ervuDictionaries/causeNotConfirmDictionary'
    ];
    return getDictionaryFormatedToOptions(dict);
  }

  description = '';

  get sub(): string {
    if (this.citizens.length > 1)
      return `${this.$tc('MultiSign.selected', this.citizens.length)}`;
    return (this.citizens[0] as SearchRecruitResponse).fullName || '';
  }

  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];
  }

  convertRecruits() {
    return isArray(this.model)
      ? {
          list: this.model.map((e: any) => ({
            id: e.id,
            idERN: e.idern,
            fio: e.fullName,
          })),
        }
      : {
          previewInfo: [
            {
              label: 'ИД ЕРН',
              value: this.model?.systemInfo?.idERN,
            },
            {
              label: 'ФИО',
              value: this.model?.mainInfo?.fullName,
            },
          ],
          id: this.model.id,
        };
  }

  get formModel() {
    return {
      personIds: this.personIds,
      actionType: this.actionType,
      cause: this.cause.value,
      description: this.description,
    };
  }

  async action(): Promise<void> {
    if (!this.cause.value) {
      notifyError('Не выбрана причина');
      return;
    }
    this.operationDialog.toProcess();
    try {
      const traceId = await this.startProcess(this.formModel);

      this.registerListener((message, removeListener) => {
        if (traceId !== message.traceId) return;
        if (message.body.type === 'finish') {
          this.operationDialog.toResult();
          removeListener();
        }
      });

      this.$recordActivity({
        buttonCode: 'sendConvertation',
        extraInfo: {
          ...this.convertRecruits(),
          type: 'conversion',
          detailedInfo: [
            {
              label: 'причина',
              value: this.cause.label,
            },
            {
              label: 'комментарий',
              value: this.description,
            },
          ],
        },
      });
    } catch (error) {
      console.error(error);
      this.operationDialog.toResult();
    }
  }

  onSigned(data: SignData): void {
    const personInfo: PersonInfo = {
      id: data.operationInfo?.recruitId,
      fullName: data.operationInfo?.recruitFullName,
    };
    if (!isEmpty(personInfo)) this.resultList.push(personInfo);
  }

  onError(): void {
    this.hasError = true;
    this.operationDialog.toResult();
  }

  onFinish(): void {
    this.operationDialog.toResult();
  }

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

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

  close(): void {
    this.opened = false;
    this.resultList = [];
    if (this.cause.value !== '5') {
      this.cause = {
        value: '',
        label: '',
      };
    }
    this.operationDialog.reset();
    this.$emit('close');
  }
}
</script>

<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);
}
// TODO вынести
.title-text {
  font-family: 'Golos Text', sans-serif;
  font-style: normal;
  font-weight: 500;
  font-size: 20px;
  line-height: 24px;
  letter-spacing: -0.015em;

  color: rgba(2, 12, 18, 0.9);
}

.MultiConfirm {
  &-Attention {
    overflow: scroll;
    max-height: 65vh;
    &__Header {
      font-family: 'Golos UI', sans-serif;
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    &__List {
      background-color: rgba(248, 248, 250, 1);
      border-left: 1px solid rgba(206, 206, 210, 1);
      padding: 5px;
    }
    &__FIO {
      font-family: 'Golos Text', sans-serif;
      font-size: 12px;
      font-weight: 500;
    }
    &__VK {
      font-family: 'Golos Text', sans-serif;
      font-size: 10px;
    }
  }
  &-ErrorMessage {
    &__Header {
      font-family: 'Golos UI', sans-serif;
      font-size: 20px;
      color: rgba(193, 5, 37, 1);
    }
    &__Icon {
      font-size: 30px;
    }
    &__Date {
      font-family: 'Golos Text', sans-serif;
      font-size: 12px;
      color: rgba(157, 157, 161, 1);
      margin-bottom: 5px;
    }
    &__DateText {
      margin-right: 5px;
    }
    &__Description {
      font-family: 'Golos Text', sans-serif;
      font-size: 14px;
      color: rgba(157, 157, 161, 1);
      &Text {
      }
      &Des {
        background-color: rgba(248, 248, 250, 1);
        border-left: 1px solid rgba(206, 206, 210, 1);
        padding: 5px;
      }
    }
  }
  &-SuccessMessage {
    width: 100%;
    padding: 10px;
    &__Header {
      font-family: 'Golos UI', sans-serif;
      font-size: 20px;
      color: rgba(4, 150, 125, 1);
    }
    &__HeaderIcon {
      font-size: 30px;
    }
    &__Text {
      font-family: 'Golos Text', sans-serif;
      font-size: 16px;
    }
    &__Count {
      font-family: 'Golos Text', sans-serif;
      font-size: 18px;
      font-weight: 500;
    }
    &__Total {
      color: rgba(207, 110, 20, 1);
    }
    &__Success {
      color: rgba(4, 150, 114, 1);
    }
    &__Error {
      color: rgba(193, 5, 37, 1);
    }
    &__ListHeader {
      font-family: 'Golos Text', sans-serif;
      font-size: 16px;
      color: rgba(157, 157, 161, 1);
      margin-bottom: 10px;
    }
    &__ListElement {
      font-family: 'Golos Text', sans-serif;
      font-size: 12px;
      color: rgba(157, 157, 161, 1);
      background-color: rgba(248, 248, 250, 1);
      border-left: 1px solid rgba(206, 206, 210, 1);
      padding: 5px;
    }
    &__ListBlock {
      overflow: auto;
      height: 70vh;
    }
  }
  &-Description {
    margin-bottom: 5px;
  }
}

.process-loader {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  ::v-deep .upload-status {
    margin-bottom: 16px;
  }
}
</style>
