<template>
  <div class="register-new-recruit">
    <r-btn
      :disable="disable"
      :label="label"
      dense
      icon="pgs-user-check"
      no-wrap
      positive
      @click="open"
    />
    <operation-dialog
      ref="dialog"
      v-model="opened"
      :sub="fio"
      :title="title"
      @finish="onFinish"
    >
      <div class="row q-col-gutter-md">
        <div class="col-12">
          <data-block
            :form-data="{
              label: 'Тип документа',
              value:
                'Решение о постановке на воинский учёт по новому адресу места жительства',
              icon: 'pgs-document',
            }"
            bolder
          />
        </div>
        <div class="col-12 col-sm-4 col-md-3">
          <data-block
            :form-data="{
              label: 'Дата решения',
              value: resolutionDate,
              icon: 'pgs-calendar',
            }"
          />
        </div>
        <span class="col-12 MultiInit-UserInfo__Header">
          ФИО / ДАТА РОЖДЕНИЯ / Военный идентификатор
        </span>
        <div class="col-12 MultiInit-UserInfo">
          <span class="col-12 MultiInit-UserInfo__FullName">
            {{ fio }}
          </span>
          <span class="col-12 MultiInit-UserInfo__BirthDate">
            <q-icon class="MultiInit-UserInfo__Calendar" name="pgs-calendar" />
            <span class="MultiInit-UserInfo__Date">
              {{ formatDate(model.mainInfo.birthDate) }}
            </span>
          </span>
          <span class="col-12 MultiInit-UserInfo__Id">
            {{ model.systemInfo.docId }}
          </span>
        </div>
      </div>

      <template #process>
        <result-block
          :header="processMessage"
          :icon="sign ? 'pgs-sign' : 'pgs-document'"
          type="info"
        />
      </template>
      <template #result>
        <result-block :header="resultMessage" />
      </template>
      <template #right-actions>
        <r-btn
          action
          icon="pgs-double-check"
          label="Сформировать"
          @click="action"
        />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          icon-right="pgs-shevron-right-off"
          label="Продолжить"
          @click="finish"
        />
      </template>
    </operation-dialog>
  </div>
</template>

<style lang="scss" scoped>
.r-block {
  background: rgba(53, 126, 172, 0.05);
  border-radius: 4px;

  &__label {
    font-family: 'Golos', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 12px;
    line-height: 16px;

    color: rgba(2, 12, 18, 0.58);
  }
}
.r-field {
  background: rgba(53, 126, 172, 0.05);
  border-radius: 4px;

  &__label {
    font-family: 'Golos', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 12px;
    line-height: 16px;

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

  &__content {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 4px 4px 3px 8px;
    gap: 10px;

    background: rgba(242, 248, 253, 0.75);
    background-blend-mode: multiply;
    border-radius: 0;
  }
}
.MultiInit {
  &-UserInfo {
    display: flex;
    flex-direction: column;
    padding: 0 6px 6px 6px;
    margin-left: 15px;
    background-color: rgba(53, 126, 172, 0.05);
    border-radius: 4px;
    font-family: 'Golos Text', sans-serif;
    &__FullName {
      color: rgba(2, 12, 18, 0.58);
      font-size: 14px;
      font-weight: 500;
    }
    &__BirthDate {
      color: rgba(2, 12, 18, 0.9);
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    &__Calendar {
      font-size: 20px;
      margin-right: 5px;
    }
    &__Date {
      line-height: 1px;
    }
    &__Id {
      font-size: 14px;
      font-weight: 600;
    }
    &__Header {
      font-size: 12px;
      font-family: 'Golos Text', sans-serif;
      color: rgba(2, 12, 18, 0.58);
      font-weight: 600;
      text-transform: uppercase;
    }
    &:not(:last-child) {
      margin-bottom: 4px;
    }
  }
}
</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 { convertDateFormat, DateFormat } from '@/utils/format-date';
import now from 'lodash/now';
import { RecruitV4 } from '@/recruits/openapi/person-registry';
import ProcessStarter from '@/mixins/ProcessStarter';
import { isArray } from 'lodash';
import { formatDate } from '@/recruits/utils';

@Component({
  components: {
    dataBlock,
  },
  methods: {
    formatDate,
  },
})
export default class RegisterNewRecruitForm extends Mixins(
  TaskButton,
  ProcessStarter
) {
  @Prop({ default: () => ({}) })
  declare readonly model: RecruitV4;

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

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

  @Ref('dialog') operationDialog: OperationDialog;

  opened = false;

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

  get firstAndMiddleName(): string {
    if (isArray(this.model)) return '';
    const { firstName = '', middleName = '' } = this.model.mainInfo;
    return `${firstName} ${middleName}`;
  }

  get address(): string {
    return this.model?.mainInfo?.addresses.reduce((address, { type, reg }) => {
      if (type !== 'residentialAddress') return address;
      return reg;
    }, '');
  }

  get initial(): boolean {
    return this.model?.recruitSystemInfo?.departmentId === null;
  }

  get processMessage(): string {
    return 'Решение о постановке на учёт формируется';
  }

  get resultMessage(): string {
    return 'Решение о постановке на учёт сформировано';
  }

  get mil(): string {
    return this.$store.state.oidcClient.currentUser.realm || '';
  }

  get resolutionDate(): string {
    return convertDateFormat(new Date(now()), undefined, DateFormat.date);
  }

  get formModel() {
    return {
      personIds: [this.model.id],
      resolutionDate: this.resolutionDate,
      id: this.buttonSettings.id,
    };
  }

  async action(): Promise<void> {
    this.operationDialog.toProcess();
    try {
      const { traceId } = await this.$store.dispatch(
        'wfActions/processes/submitForm',
        {
          taskId: this.userTask?.taskId,
          traceId: this.taskProcess?.traceId,
          formModel: this.formModel,
        }
      );

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

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

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

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

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