<template>
  <div class="multi-sign">
    <r-btn
      negative
      :disable="disable"
      :label="label"
      icon="pgs-close"
      no-wrap
      @click="open"
    />
    <operation-dialog
      sign
      persistent
      ref="dialog"
      :title="$props.title"
      :sub="sub"
      v-model="opened"
      @hide="close"
    >
      <div v-if="!!summons.length" class="multi-sign-recruits">
        <div
          v-for="rec in summons"
          :key="`recruit-${rec.recruitId}`"
          class="multi-sign-recruit"
        >
          <div class="multi-sign-recruit__name" v-if="!onePerson">
            {{ rec.recruitFullName }}
          </div>

          <div class="multi-sign-recruit__documents">
            <div
              v-for="doc in rec.attachments"
              :key="`document-${doc.recruitId}`"
              class="multi-sign-recruit__document"
            >
              <q-icon
                class="multi-sign-recruit__document-icon"
                name="pgs-document"
                size="18px"
              />
              <span class="multi-sign-recruit__document-name">
                {{ doc.name || get(doc, 's3Name') }}
              </span>
              <span style="flex: 1 1 auto"></span>
              <base-preview
                :s3Url="doc.s3url || get(doc, 's3Url')"
                :extension="doc.format"
              >
                <q-icon class="SummonsTable-Icon" name="pgs-view">
                  <q-tooltip>Предпросмотр</q-tooltip>
                </q-icon>
              </base-preview>
            </div>
          </div>
        </div>
        <r-input
          v-if="flagCancelButton"
          label="Комментарий"
          v-model="cancelComment"
        />
      </div>
      <template #process>
        <result-block type="info" icon="pgs-sign" :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
          :type="hasError ? 'negative' : 'positive'"
          :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
          v-if="flagCancelButton"
          action
          label="Продолжить"
          icon="pgs-check"
          :disable="disable"
          @click="action"
        />
      </template>
      <template #left-actions-panel>
        <r-btn
          v-if="flagCancelButton"
          outline
          label="Отмена"
          icon="pgs-close"
          color="primary"
          @click="close"
        />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          label="Продолжить"
          icon-right="pgs-shevron-right-off"
          @click="finish"
        />
      </template>
      <template #sign-form v-if="!flagCancelButton">
        <crypto-pro-sign-form
          ref="signForm"
          class="no-right-border-radius"
          :enable-submit-form="enableSubmitForm"
          :process-key="processKey"
          :user-task="userTask"
          :task-process="taskProcess"
          bucket="ervu-attachment"
          @update:certificateIsActive="certificateIsActive = $event"
          @signed="onSigned"
          @error="onError"
          @finish="onFinish"
        />
      </template>
    </operation-dialog>
  </div>
</template>

<i18n>
{
  "ru": {
    "MultiReject": {
      "selected": "не выбрано | {n} документ | {n} документа | {n} документов",
      "rejecting": " | Документ отклоняется | Документы отклоняются | Документы отклоняются",
      "rejected": " | Документ отклонен | Документы отклонены | Документы отклонены",
      "error": " | Документ не отклонен | Документы не отклонены | Документы не отклонены"
    }
  }
}
</i18n>

<style lang="scss" scoped>
.SummonsTable-Icon {
  overflow: hidden;
  color: #1491cf;
  font-size: 26px;
  padding: 6px 3px;
  cursor: pointer;
}

.tooltipe-recruit {
  margin-bottom: 8px;

  &:last-child {
    margin-bottom: 0;
  }

  &__name {
    margin-bottom: 2px;
    font-weight: 500;
  }
}

.multi-sign-recruits {
  display: flex;
  flex-flow: column;
}

.multi-sign-recruit {
  background: #ffffff;
  border-bottom: 1px solid rgba(1, 72, 116, 0.11);
  box-shadow: none;
  padding: 8px 0;

  &__name {
    font-weight: bold;
  }

  &__documents {
    display: flex;
    flex-flow: column;
  }

  &__document {
    display: flex;
    flex-flow: row;
    align-items: center;
  }

  &__document-name,
  &__document-icon {
    color: #6c7276;
  }

  &__document-icon {
    transform: translateX(-2px);
  }
}

.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);
}
</style>

<script lang="ts">
import { Component, Mixins, Prop, Ref, Watch } 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 ProcessStarter from '@/mixins/ProcessStarter';
import CryptoProSignForm from '@/components/common/cryptopro-sign-form/index.vue';
import {
  PersonRegistryApi,
  RecruitV4,
} from '@/recruits/openapi/person-registry';
import { AttachedDocument } from '@/recruits/interfaces/deprecated/attached-document';
import {
  SubpoenaRegistryApi,
  SubpoenaByRecruitV2,
} from '@/recruits/openapi/subpoena-service';
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 RInput from '@/recruits/components/common/r-input.vue';
import { notifyError } from '@utils/notify';

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

interface RecruitAttachment {
  recruitFullName: string;
  recruitId: string;
  attachments: AttachedDocument[];
}

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

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

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

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

  @Prop({ default: () => null })
  // @ts-ignore
  processKey: string | null;

  @Ref('dialog') operationDialog: OperationDialog;

  @Ref('signForm') signForm: CryptoProSignForm;

  pagination = {
    sortBy: 'createDate',
    descending: true,
    page: 1,
    rowsPerPage: 50,
  };

  opened = false;

  certificateIsActive = false;

  hasError = false;

  resultList: PersonInfo[] = [];

  get enableSubmitForm(): boolean {
    return !Array.isArray(this.model) && !this.model.signEntity;
  }

  get processMessage(): string {
    return this.flagCancelButton
      ? this.$tc('MultiReject.rejecting', this.personLength)
      : this.$tc('MultiSign.signing', this.personLength);
  }

  get resultMessage(): string {
    if (this.hasError) {
      return this.flagCancelButton
        ? this.$tc('MultiReject.error', this.personLength)
        : this.$tc('MultiSign.error', this.personLength);
    }
    return this.flagCancelButton
      ? this.$tc('MultiReject.rejected', this.personLength)
      : this.$tc('MultiSign.signed', this.personLength);
  }

  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().getSubpoenaByRecruitV6(
      id,
      this.pagination
    );
    return data.subpoenas || [];
  }

  @Watch('personIds', { immediate: true })
  async fetchRecruits(ids: string[]): Promise<void> {
    if (!isArray(this.model)) {
      if (this.model.status === '3.14') {
        this.summonsByRecruit = {};
        for (const id of ids) {
          try {
            this.summonsByRecruit[id] = await this.getSummon(id);
          } catch {}
        }
      }
      this.recruits = [this.model];
    } else {
      this.recruits = await Promise.all(
        ids.map(async (id) => {
          const recruitInfo = await this.getRecruit(id);
          if (recruitInfo.status === '3.14') {
            try {
              this.summonsByRecruit[id] = await this.getSummon(id);
            } catch {}
          }
          return recruitInfo;
        })
      );
    }
  }

  get onePerson(): boolean {
    return !isArray(this.model) && this.summons.length === 1;
  }

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

  get sub(): string {
    if (isArray(this.model)) {
      return this.flagCancelButton
        ? `${this.$tc('MultiReject.selected', this.model.length)}`
        : `${this.$tc('MultiSign.selected', this.model.length)}`;
    }
    return this.model.mainInfo?.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];
  }

  recruits: RecruitV4[] = [];

  summonsByRecruit: Record<string, SubpoenaByRecruitV2[]> = {};

  get summons(): RecruitAttachment[] {
    return this.recruits.flatMap(({ id, mainInfo }) => {
      const notSigned = this.summonsByRecruit[id]
        ?.filter(({ status }) => status === '3.14')
        ?.map(({ file }) => file);
      if (!notSigned || !notSigned.length) return [];
      return {
        recruitId: id,
        recruitFullName: mainInfo?.fullName,
        attachments: notSigned,
      };
    });
  }

  get formModel() {
    return {
      id: 'cancel_decision',
      personIds: this.personIds,
      cancelComment: this.cancelComment || null,
    };
  }

  flagCancelButton = true;
  cancelComment = '';

  async action(): Promise<boolean | void> {
    if (this.flagCancelButton && !this.cancelComment) {
      notifyError('Поле комментарий обязательно к заполнению');
      return false;
    }
    this.operationDialog.toProcess();
    if (this.flagCancelButton) {
      try {
        await this.$store.dispatch('wfActions/processes/submitForm', {
          taskId: this.userTask.taskId,
          traceId: this.taskProcess.traceId,
          formModel: this.formModel,
        });

        this.registerListener((message, removeListener) => {
          if (this.taskProcess.traceId !== message.traceId) return;
          if (message.body.type === 'finish') {
            this.operationDialog.toResult();
            removeListener();
          }
        });
      } catch (error) {
        this.operationDialog.toResult();
        console.error(error);
      }
    } else {
      try {
        await this.signForm.sendDataForSign(this.formModel);
      } catch (error) {
        console.error(error);
        this.operationDialog.toResult();
      }
    }
  }

  onSigned(data: SignData): void {
    console.log('signed', data);
    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 = [];
    this.operationDialog.reset();
    this.$emit('close');
  }
}
</script>
