<template>
  <div class="register-new-recruit">
    <r-btn
      dense
      positive
      :disable="disable"
      label="Подписать"
      @click="open"
      no-wrap
    />
    <operation-dialog
      sign
      persistent
      ref="dialog"
      :title="title"
      :sub="sub"
      v-model="opened"
      @hide="close"
      v-if="!toDecline"
    >
      <div class="SignRejectApplication-Document">
        <q-icon
          class="SignRejectApplication-DocumentIcon"
          name="pgs-document"
          size="18px"
        />
        <span class="SignRejectApplication-DocumentName">
          {{ document.name }}
        </span>
        <span style="flex: 1 1 auto"></span>
        <base-preview
          :s3Url="document.fileInfo.s3url"
          :extension="document.fileInfo.format"
        >
          <q-btn flat round color="primary" icon="pgs-view">
            <q-tooltip>Предпросмотр</q-tooltip>
          </q-btn>
        </base-preview>
      </div>
      <template #process>
        <result-block type="info" header="Подписываем">
          {{ document.name }}
        </result-block>
      </template>
      <template #result>
        <result-block :type="resultType" :header="resultMessage">
          {{ document.name }}
        </result-block>
      </template>
      <template #right-actions>
        <r-btn
          label="Отклонить"
          icon="pgs-close"
          negative
          :disable="disable || !certificateIsActive"
          @click="() => (toDecline = true)"
        />
        <r-btn
          action
          label="Подписать"
          icon="pgs-sign"
          :disable="disable || !certificateIsActive"
          @click="action"
        />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          label="Продолжить"
          icon-right="pgs-shevron-right-off"
          @click="finish"
        />
      </template>
      <template #sign-form>
        <crypto-pro-sign-form
          ref="signForm"
          class="no-right-border-radius"
          bucket="ervu-attachment"
          :process-key="processKey"
          :user-task="userTask"
          :task-process="taskProcess"
          @update:certificateIsActive="certificateIsActive = $event"
          @error="onError"
          @finish="onFinish"
        />
      </template>
    </operation-dialog>
    <operation-dialog
      persistent
      ref="dialog"
      :title="declineTitle"
      :sub="model.reason"
      :process-key="processKey"
      v-model="opened"
      @hide="close"
      @reset="() => (toDecline = false)"
      v-else
    >
      <div class="RevertApplication">
        <r-textarea label="Комментарий" v-model="returnText" />
      </div>
      <template #process>
        <result-block type="info" header="Решение отправляется на доработку" />
      </template>
      <template #result>
        <result-block :type="resultType" :header="resultMessage" />
      </template>
      <template #right-actions>
        <r-btn
          action
          label="Вернуть"
          icon="pgs-interagency"
          :disable="disable"
          @click="start"
        />
      </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} решений",
      "signing": " | Документ подписывается | Документы подписываются | Документы подписываются",
      "signed": " | Документ подписан | Документы подписаны | Документы подписаны",
      "error": " | Документ не подписан | Документы не подписаны | Документы не подписаны"
    }
  }
}
</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);
}
// 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);
}

.SignRejectApplication {
  &-Document {
    background: #ffffff;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
    box-shadow: none;
    padding: 8px 0;
    display: flex;
    flex-flow: row;
    align-items: center;
  }
  &-DocumentName,
  &-DocumentIcon {
    color: #6c7276;
  }
  &-DocumentIcon {
    transform: translateX(-2px);
  }
  &-Attention {
    overflow: scroll;
    height: 80vh;
    &__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;
    }
  }
}
</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 RTextarea from '@/recruits/components/common/r-textarea.vue';
import get from 'lodash/get';
import ProcessStarter from '@/mixins/ProcessStarter';
import { notifyError } from '@/utils/notify';

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

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

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

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

  @Prop({ default: () => null }) declare processKey: string;

  @Prop()
  actionType: 'confirmRecruit';

  @Prop()
  activityRecorderOptions: any;

  @Ref('dialog') operationDialog: OperationDialog;

  @Ref('signForm') signForm: CryptoProSignForm;

  opened = false;

  certificateIsActive = false;

  hasError = false;

  toDecline = false;

  returnText = '';

  get sub(): string {
    return this.model.name;
  }

  get formModel() {
    return {
      personIds: this.model.personIds,
      applicationIds: this.model.applicationIds,
    };
  }

  get document() {
    return this.model.document;
  }

  get resultType(): string {
    return this.hasError ? 'negative' : 'positive';
  }

  get resultMessage(): string {
    return this.hasError ? 'Произошла ошибка подписания' : 'Подписано';
  }

  get declineTitle(): string {
    return `Возврат на доработку решения об отказе по заявлению № ${this.model.number}`;
  }

  async action(): Promise<void> {
    this.operationDialog.toProcess();
    try {
      await this.signForm.sendDataForSign(this.formModel);
    } catch (error) {
      console.error(error);
      this.close();
    }
  }

  async start(): Promise<void> {
    if (!this.returnText) {
      notifyError('Не введен комментарий');
      return;
    }
    this.operationDialog.toProcess();
    try {
      const { traceId } = await this.$store.dispatch(
        'wfActions/processes/dispatchProcess',
        {
          processKey: 'milBaseRouteProcess',
          data: {
            personIds: this.formModel.personIds,
            applicationsId: this.formModel.applicationIds,
            actionType: 'rejectBackToReview',
            reasonCode: this.model.reasonCode,
            returnText: this.returnText,
          },
        }
      );

      this.registerListener((message, removeListener) => {
        if (traceId !== message.traceId) return;
        if (message.body.type === 'finish') {
          this.operationDialog.toResult();
          this.finish();
          removeListener();
        }
      });
    } catch (error) {
      if (error instanceof Error) notifyError(error.message);
      this.onError();
    }
  }

  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.operationDialog.reset();
    this.$emit('close');
  }
}
</script>
