<template>
  <div class="masthead">
    <div class="row details-bar q-px-md q-pt-md">
      <div class="q-pr-xs">
        <q-btn
          class="back-button q-px-xs"
          icon="pgs-arrow-left"
          dense
          size="sm"
          @click="returnToParentViews('')"
        />
      </div>
      <div>
        <div class="row header-details">
          <div class="col-shrink source">
            <span>Инцидент</span>
          </div>

          <template v-if="loading">
            <div class="col-shrink badge">
              <q-skeleton type="circle" size="32px" />
            </div>
          </template>
          <div class="col-shrink status">
            <status-box :loading="loading" :status="status" type="incidents" />
          </div>
          <div class="Masthead-DataBlock">
            <div class="Masthead-DataBlock__Name">Номер</div>
            <div class="Masthead-DataBlock__Value">
              {{ number }}
            </div>
          </div>
          <div class="Masthead-DataBlock" v-if="data.mainInfo.recruitId">
            <div class="Masthead-DataBlock__Name">ФИО гражданина</div>
            <div class="Masthead-DataBlock__Link">
              <router-link
                class="cursor-pointer"
                :to="{
                  name: 'recruit-personal',
                  params: { id: data.mainInfo.recruitId },
                }"
              >
                {{ fio }}
                <q-icon name="pgs-shevron-right-off"></q-icon>
                <q-tooltip>Перейти в карточку гражданина</q-tooltip>
              </router-link>
            </div>
          </div>
          <div class="Masthead-DataBlock" v-else>
            <div class="Masthead-DataBlock__Name">ФИО гражданина</div>
            <div class="Masthead-DataBlock__Value">{{ fio }}</div>
          </div>
          <div class="Masthead-DataBlock">
            <div class="Masthead-DataBlock__Name">Дата рождения</div>
            <div class="Masthead-DataBlock__Value">
              {{ formatDate(birthDate) }}
            </div>
          </div>
        </div>
      </div>
      <div v-if="checkIncidentStatus && $AC.haveOneOfScope([
          $AC.scopes.MILITARY_RECRUIT_SPECIALIST,
          $AC.scopes.MILITARY_COMMISSAR,
          $AC.scopes.GOMU_SPECIALIST,
        ])" class="optionBlock">
        <div class="optionBlock">
          <r-btn :loading="isRequestSending" class="accept" @click="action">
            Закрыть инцидент
            <template v-slot:loading
              ><q-spinner-oval size="1em" color="primary"
            /></template>
          </r-btn>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.optionBlock {
  flex-grow: 1;
  display: flex;
  justify-content: flex-end;
  gap: 0.5em;
  //font-size: 32px;
  .accept {
    //background: green;
  }
  .decline {
    //background: red;
  }
}
.masthead {
  background-color: rgb(237, 243, 247);
  .action-buttons {
    .refresh-button {
      height: 34px;
      &::v-deep i {
        margin-top: -2px;
        transform: scaleX(-1);
      }
    }
  }
}

.details-bar {
  display: flex;
  flex-flow: row;

  .back-button {
    border: 1px solid rgba(1, 72, 116, 0.18) !important;
    border-radius: 24px !important;
    color: #1491cf !important;
  }

  .header-details {
    gap: 8px;

    > div {
      overflow-x: hidden;
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      font-weight: 600;
      font-size: 12px;
      line-height: 16px;

      &.badge {
        max-height: 32px;
        overflow: hidden;
      }

      &.source {
        display: inline-flex;
        text-align: center;

        padding-left: 4px;
        font-family: 'Golos Text', sans-serif;
        font-style: normal;
        font-weight: 600;
        font-size: 12px;
        line-height: 26px;
        color: rgba(2, 12, 18, 0.58);
      }

      &.status {
        padding: 0;
        display: flex;
        flex-flow: column;
        width: 12em;
        min-height: 30px;
      }

      &.assignee {
        align-items: center;

        .user-icon {
          padding-left: 1px;
          width: 30px;
          color: #1491cf;
          background-color: white;
          border-radius: 15px;
        }

        .user-name {
          padding-left: 4px;
          display: flex;
          flex-flow: column;
          max-width: 200px;

          span:first-child {
            color: rgba(2, 12, 18, 0.58);
            font-weight: 400;
            line-height: 14px;
          }
          span:not(:first-child) {
            font-weight: 500;
            line-height: 16px;
          }
          span {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }
}

.masthead {
  display: flex;
  flex-flow: column;
  margin-bottom: 5px;
  span.fio {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 28px;
    line-height: 32px;
    letter-spacing: -0.02em;
    color: rgba(2, 12, 18, 0.9);
  }
}
.calendar__title {
  font-weight: 400;
  color: #cf5f14;
}
.calendar__value {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #cf5f14;
}

.Masthead {
  &-DataBlock {
    padding-left: 4px;
    &__Name {
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      font-weight: 600;
      font-size: 12px;
      color: rgba(2, 12, 18, 0.58);
    }
    &__Link {
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      color: #1487CF;
      font-size: 12px;
      font-weight: 400;
      color: rgba(2, 12, 18, 0.9);
      a {
        color: inherit;
        cursor: pointer;
        text-decoration-thickness: 15%;
        text-decoration-color: #1487CF;
        &:hover {
          color: #00A0C6;
        }
      }
      i {
        font-size: 25px;
        width: 20px;
        height: 20px;
        overflow: hidden;
      }
    }
    &__Value {
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      font-size: 12px;
      font-weight: 400;
      color: rgba(2, 12, 18, 0.9);
    }
  }
}
</style>

<script lang="ts">
import { Component, Emit, Mixins, Watch } from 'vue-property-decorator';
import moment from 'moment';
import { formatDate } from '@/recruits/utils';
import {
  ErvuIncidentsServiceApi,
  IncidentResponseV2,
} from '@/recruits/openapi/ervu-service';
import ReturnToParentView from '@mixins/ReturnToParentView';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import ProcessStarter from '@/mixins/ProcessStarter';
import RefreshKeyInterceptor from '@/recruits/mixins/refresh-key-interceptor';

@Component({
  components: { StatusBox },
  methods: {
    moment,
    formatDate,
  },
})
export default class Masthead extends Mixins(
  ReturnToParentView,
  ProcessStarter,
  RefreshKeyInterceptor
) {
  IncidentsServiceApi = new ErvuIncidentsServiceApi();
  public loading = false;
  public isRequestSending = false;
  public data: IncidentResponseV2 = {
    history: [],
    mainInfo: {},
  };

  private get currentUserFieldsForCloseIncident(): {
    userId: string;
    userName: string;
    status: string;
  } {
    const { sub: userId, name: userName } =
      this.$store.getters['oidcClient/currentUser'] || {};
    return { userId, userName, status: '1000' };
  }

  private get checkIncidentStatus() {
    return this.data?.mainInfo?.status
      ? !['6', '7', '1000'].includes(this.data?.mainInfo?.status)
      : false;
  }

  get activityRecorderForCloseIncident() {
    return this.data.mainInfo
      ? {
          id: this.data.mainInfo.id,
          idERN: this.data.mainInfo.idERN,
          birthDate: formatDate(this.data.mainInfo.birthDate || ''),
          fio: this.fio,
          type: 'incident',
        }
      : {};
  }

  model: {
    incidentId: 'идентификатор';
    actionType: 'incidentProcess';
  };

  public readonly incidentId: string = this.$route.params.id;

  @Watch('loading')
  @Emit('data-loading')
  private loadingWatcher(): { loading: boolean; data: IncidentResponseV2 } {
    return {
      loading: this.loading,
      data: this.data,
    };
  }

  async action() {
    if (this.data.mainInfo) {
      this.isRequestSending = true;
      try {
        const result = await this.IncidentsServiceApi.changeStatusIncidentV1(
          this.incidentId,
          this.currentUserFieldsForCloseIncident
        );
        console.log(result);
        this.returnToParentViews();
        this.$recordActivity({
          buttonCode: 'incident_closed',
          extraInfo: {
            number: this.number,
            ...this.activityRecorderForCloseIncident,
          },
        });
      } catch (e) {
        console.warn(e);
      } finally {
        this.isRequestSending = false;
      }
    }
  }

  public onReload(): void {
    this.$emit('onReload');
  }

  get status(): string {
    return this.data?.mainInfo?.status || '';
  }

  get number(): number {
    return this.data.mainInfo?.number || 0;
  }

  get birthDate(): string {
    return this.data.mainInfo?.birthDate || '';
  }

  get fio(): string {
    return `${this.data.mainInfo?.lastName} ${this.data.mainInfo?.firstName} ${this.data.mainInfo?.middleName}`;
  }

  refresh(): void {
    this.init();
  }

  async fetch(): Promise<void> {
    this.loading = true;
    try {
      const { data } = await this.IncidentsServiceApi.getIncidentV3(
        this.incidentId
      );
      this.data = data;
    } catch (e) {
      console.log(e);
    } finally {
      this.loading = false;
    }
  }

  async init(): Promise<void> {
    await this.fetch();
  }

  async mounted(): Promise<void> {
    console.log('incident mounted');
    await this.init();
  }

  destroyed(): void {
    this.$store.dispatch('wfActions/userTasks/resetUserData');
  }
}
</script>
