<template>
  <div class="SingleSubpoenaSign">
    <r-btn
      :disable="disable"
      :label="label"
      dense
      :icon="cancelBtnForm ? 'pgs-close' : 'pgs-sign'"
      no-wrap
      :class="cancelBtnForm ? 'RButton__Negative' : 'RButton__Positive'"
      @click="open"
    />
    <operation-dialog
      ref="dialog"
      v-model="opened"
      :sub="sub"
      :title="titleWindow"
      persistent
      sign
      @hide="close"
    >
      <div v-if="!cancelBtnForm" class="SingleSubpoenaSign__Recruits">
        <div class="SignRecruit">
          <div class="SignRecruit__Documents">
            <div class="SignRecruit__Document">
              <q-icon
                class="SignRecruit__DocumentIcon"
                name="pgs-document"
                size="18px"
              />
              <span class="SignRecruit__DocumentName">
                {{ file.s3Name }}
              </span>
              <span style="flex: 1 1 auto"></span>
              <base-preview
                v-if="file.format && file.s3Url"
                :extension="file.format"
                :s3Url="file.s3Url"
              >
                <q-icon class="SignRecruit__TableIcon" name="pgs-view">
                  <q-tooltip>Предпросмотр</q-tooltip>
                </q-icon>
              </base-preview>
            </div>
          </div>
        </div>
      </div>
      <r-input
        v-if="cancelBtnForm"
        v-model="cancelComment"
        label="Комментарий"
      />
      <template #process>
        <result-block :header="processMessage" icon="pgs-sign" type="info">
          <TransitionGroup name="results" tag="div">
            <div v-for="res in resultList" :key="res.id">
              <q-icon color="info" name="pgs-sign-2" size="sm" />
              <span>{{ get(res, 'fullName') }}</span>
            </div>
          </TransitionGroup>
        </result-block>
      </template>
      <template #result>
        <result-block
          :header="resultMessage"
          :type="hasError ? 'negative' : 'positive'"
        >
          <div class="results">
            <div v-for="res in resultList" :key="res.id">
              <q-icon color="positive" name="pgs-check" size="sm" />
              <span>{{ get(res, 'fullName') }}</span>
            </div>
          </div>
        </result-block>
      </template>
      <template #right-actions>
        <r-btn
          v-if="needCancelButton && !cancelBtnForm"
          icon="pgs-close"
          label="Отклонить"
          negative
          @click="openRejectModal()"
        >
        </r-btn>
        <r-btn
          v-if="!cancelBtnForm"
          :disable="disable || !certificateIsActive"
          action
          icon="pgs-sign"
          label="Подписать"
          @click="action"
        />
        <r-btn
          v-if="cancelBtnForm"
          :disable="disable"
          action
          icon="pgs-check"
          label="Продолжить"
          @click="action"
        />
      </template>
      <template
        v-if="operationDialog && operationDialog.formState === 'start'"
        #left-actions-panel
      >
        <r-btn
          color="primary"
          icon="pgs-close"
          label="Отмена"
          outline
          @click="closeModal"
        />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          icon-right="pgs-shevron-right-off"
          label="Продолжить"
          @click="finish"
        />
      </template>
      <template v-if="!cancelBtnForm" #sign-form>
        <crypto-pro-sign-form
          ref="signForm"
          process-key="milBaseMassSignProcess"
          :enable-submit-form="!model.signEntity"
          :task-process="taskProcess"
          :user-task="userTask"
          bucket="ervu-attachment"
          class="no-right-border-radius"
          @error="onError"
          @finish="onFinish"
          @signed="onSigned"
          @update:certificateIsActive="certificateIsActive = $event"
        />
      </template>
    </operation-dialog>
  </div>
</template>

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

<style lang="scss" scoped>
.SingleSubpoenaSign {
  &__Recruits {
    display: flex;
    flex-flow: column;
  }
}

.SignTooltip {
  margin-bottom: 8px;

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

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

.SignRecruit {
  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;
  }

  &__DocumentName,
  &__DocumentIcon {
    color: #6c7276;
  }

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

  &__TableIcon {
    overflow: hidden;
    color: #1491cf;
    font-size: 26px;
    padding: 6px 3px;
    cursor: pointer;
  }
}

.results-enter-active,
.results-leave-active {
  transition: all 0.5s ease;
}

.results-enter-from,
.results-leave-to {
  opacity: 0;
  transform: translateY(-30px);
}
</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 CryptoProSignForm from '@/components/common/cryptopro-sign-form/index.vue';
import { RecruitV4, S3File } from '@/recruits/openapi/person-registry';
import get from 'lodash/get';
import { FormModel, SignData } from '@/mixins/CriptoProPlugin';
import isEmpty from 'lodash/isEmpty';
import RInput from '@/recruits/components/common/r-input.vue';
import { notifyError } from '@utils/notify';
import { convertDateFromBackendFormat, DateFormat } from '@utils/format-date';
import ProcessStarter from '@/mixins/ProcessStarter';
import { SubpoenaOneResponseV3 } from '@/recruits/openapi/subpoena-service';

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

interface SubpoenaWithRecruit extends SubpoenaOneResponseV3 {
  recruit: RecruitV4;
}

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

  @Prop({ default: () => ({}) }) declare readonly model: SubpoenaWithRecruit;
  declare processKey: string;

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

  @Ref('dialog') operationDialog: OperationDialog;
  @Ref('signForm') signForm: CryptoProSignForm;

  opened = false;
  certificateIsActive = false;
  hasError = false;
  resultList: PersonInfo[] = [];
  flagCancelButton = false;
  cancelComment = '';

  get cancelBtnForm() {
    return this.flagCancelButton;
  }

  get processMessage(): string {
    return this.flagCancelButton
      ? this.$tc('SingleReject.rejecting', this.personsCount)
      : this.$tc('SingleSign.signing', this.personsCount);
  }

  get resultMessage(): string {
    if (this.hasError) {
      return this.flagCancelButton
        ? this.$tc('SingleReject.error', this.personsCount)
        : this.$tc('SingleSign.error', this.personsCount);
    }
    return this.flagCancelButton
      ? this.$tc('SingleReject.rejected', this.personsCount)
      : this.$tc('SingleSign.signed', this.personsCount);
  }

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

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

  get personIds(): string[] {
    return [this.model?.mainInfo?.recruitId || ''];
  }

  get formModel(): FormModel {
    const signDate = convertDateFromBackendFormat(
      Date.now(),
      DateFormat.backend
    );
    return {
      id: this.flagCancelButton ? 'cancel_decision' : null,
      personIds: this.personIds,
      cancelComment: this.cancelComment || null,
      signDate,
    };
  }

  get needCancelButton(): boolean {
    // @ts-ignore
    return !!this.userTask?.outData?.options?.sign_registration?.hasCancel;
  }

  get titleWindow(): string {
    return this.flagCancelButton ? 'Отклонение' : 'Подписание';
  }

  get file(): S3File {
    return {
      s3Name: '',
      s3url: '',
      format: '',
      ...this.model.file,
    };
  }

  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: any) {
        this.operationDialog.reset();
        notifyError(error.message);
        console.error(error);
      }
    } else {
      try {
        await this.signForm.sendDataForSign(this.formModel);
      } catch (error: any) {
        this.operationDialog.reset();
        notifyError(error.message);
        console.error(error);
      }
    }
  }

  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');
  }

  closeModal(): void {
    if (!this.declineProp && this.flagCancelButton) {
      this.flagCancelButton = false;
    } else {
      this.close();
    }
  }

  openRejectModal(): void {
    this.flagCancelButton = true;
  }

  created() {
    this.flagCancelButton = this.declineProp;
  }

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