<template>
  <div class="reject-personal-file" :class="{ invisible: hidden }">
    <slot name="button" v-bind="{ open, label }">
      <r-btn :label="label" icon="pgs-paperclip" @click="open" />
    </slot>
    <operation-dialog
      persistent
      sign
      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">
          <div class="RTextarea">
            <label class="RTextarea__label">
              Комментарий к отклонению запроса
            </label>
            <textarea
              v-if="formModel"
              v-model="formModel.comment"
              class="RTextarea__control"
              placeholder="Напишите причину отклонения"
            ></textarea>
          </div>
        </div>
      </div>
      <template #process>
        <result-block header="запрос отклоняется" type="info">
          {{ fileName }}
        </result-block>
      </template>
      <template #result>
        <result-block header="Запрос отклонен">
          {{ fileName }}
        </result-block>
      </template>
      <template #right-actions>
        <r-btn
          action
          label="Отправить на подписание"
          icon="pgs-sign"
          :disable="disable || !isModelReady()"
          @click="action"
        />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          label="Продолжить"
          icon-right="pgs-shevron-right-off"
          @click="finish"
        />
      </template>
    </operation-dialog>
  </div>
</template>

<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 { notifyError } from '@/utils/notify';
import { DateFormat, convertDateFormat } from '@/utils/format-date';
import ProcessStarter from '@/mixins/ProcessStarter';

export interface ModelProps {
  id: string;
  fullName: string;
  birthDate: string;
  processTraceId: string;
}

interface FileInfo {
  fileName: string;
  fileSize: number;
  file: File;
  fileExt: string;
}

type FormModel = Record<string | symbol, unknown>;

interface ModelData extends FormModel {
  comment: string;
  file: File | null;
}

@Component({
  components: {
    DataBlock,
    OperationDialog,
  },
})
export default class RejectPersonalFile extends Mixins(
  TaskButton,
  ProcessStarter
) {
  @Prop({ default: false })
  hidden: boolean;

  @Prop({ default: () => ({}) })
  declare model: ModelProps;

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

  @Prop({ default: () => 'Отклонение запроса личного дела:' })
  title: string;

  @Ref('dialog') operationDialog: OperationDialog;

  // @Ref('signForm') signForm: CryptoProSignForm;

  opened = false;
  certificateIsActive = false;

  files: FileInfo[] = [];

  formModel: ModelData | null = null;

  get sub(): string {
    return `${this.model?.fullName}, ${this.birthDate}`;
  }

  get birthDate(): string {
    return convertDateFormat(
      this.model?.birthDate,
      DateFormat.invertedDate,
      DateFormat.date
    );
  }

  get fileName(): string {
    return this.formModel?.file?.name || '';
  }

  isModelReady(): boolean {
    return !!this.formModel?.comment;
  }

  isCertReady(): boolean {
    return this.certificateIsActive;
  }

  async action(): Promise<void> {
    if (!this.formModel) return;
    this.operationDialog.toProcess();
    try {
      const traceId = await this.startProcess({
        processTraceIds: [this.model.processTraceId],
        actionType: 'privateFileRejectCode',
        userComment: this.formModel.comment,
      });

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

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

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

  open(): void {
    if (this.disable) return;
    this.files = [];
    this.formModel = {
      comment: '',
      file: null,
    };
    this.opened = true;
  }

  close(): void {
    this.$emit('close');
    this.formModel = null;
    this.opened = false;
  }
}
</script>

<style lang="scss" scoped>
.RTextarea {
  display: flex;
  flex-flow: column nowrap;
  justify-content: stretch;
}
.RTextarea__control {
  background: rgba(242, 248, 253, 0.75);
  background-blend-mode: multiply;
  border: none;
  border-bottom: 1px solid rgba(1, 72, 116, 0.18);
  padding: 8px;
  border-start-start-radius: 8px;
}
.RTextarea__label {
  font-family: 'Golos Text', sans-serif;
  font-style: normal;
  font-weight: 600;
  font-size: 12px;
  line-height: 16px;
  margin-bottom: 4px;

  color: rgba(2, 12, 18, 0.58);
}
.attached-file__icon {
  font-size: 48px;
}
.attached-file {
  display: flex;
  flex-flow: row;
  align-items: center;
}
.attached-file__content {
  flex: 1 1 auto;
}
.attached-file__delete {
  flex: none;
}

.attached-file__capure {
  color: #cfcfcf;
  font-size: 10px;
  line-height: 15px;
}
.attached-file__name {
  font-weight: bold;
  line-height: 20px;
}
</style>
