<i18n>
{
  "ru": {
    "changes": "0 изменений | {count} изменение | {count} изменения | {count} изменений"
  }
}
</i18n>

<template>
  <centered-1280-box class="RecruitCardVersions">
    <search-bar v-model="filter" :loading="loading" @search="executeSearch" />
    <sort-bar
      v-model="sortButtons"
      :pagination="pagination"
      :loading="loading"
      class="RecruitCardVersions-SortBar"
      @click="handleSortClick"
    />
    <re-table
      :loading="loading"
      :data="objectHistory"
      :pagination.sync="pagination"
      :columns="columns"
      max-row-height="100%"
      :rows-per-page-options="[10, 25, 50, 100]"
      class="RecruitCardVersions-Table"
      @request="onRequest"
    >
      <template #body-item-all="{ row }">
        <q-expansion-item
          v-model="row.open"
          :key="row.date"
          :disable="!row.changeSize"
          :duration="0"
          :class="{ 'RecruitCardVersions-ExpansionItem__Open': row.open }"
          class="RecruitCardVersions-ExpansionItem"
          expand-icon-toggle
        >
          <template #header>
            <div class="RecruitCardVersions-ExpansionHeader">
              <span
                class="RecruitCardVersions-Text RecruitCardVersions-Text__Blue"
              >
                Версия: {{ row.version }}
              </span>
              <div class="RecruitCardVersions-InfoBlock">
                <div class="RecruitCardVersions-Info">
                  <q-icon
                    class="RecruitCardVersions-InfoIcon"
                    name="pgs-time"
                  />
                  <span
                    class="RecruitCardVersions-Text RecruitCardVersions-Text__Grey"
                  >
                    Изменено:
                  </span>
                  <span class="RecruitCardVersions-Text">
                    {{ formatDate(row.date, dateFormat.dateTimeFull) }}
                  </span>
                </div>
                <div class="RecruitCardVersions-Info">
                  <q-icon
                    class="RecruitCardVersions-InfoIcon"
                    name="pgs-user"
                  />
                  <span
                    class="RecruitCardVersions-Text RecruitCardVersions-Text__Grey"
                  >
                    Инициатор изменений:
                  </span>
                  <span class="RecruitCardVersions-Text">
                    {{ row.initiator }}
                  </span>
                </div>
              </div>
              <span class="RecruitCardVersions-Badge">
                {{ row.source }}
              </span>
              <span
                class="RecruitCardVersions-Text RecruitCardVersions-Text__Blue"
              >
                {{ $tc('changes', row.changeSize) }}
              </span>
            </div>
          </template>
          <q-list separator>
            <q-item
              class="RecruitCardVersions-TableRow RecruitCardVersions-TitleTable"
            >
              <span>Измененное поле</span>
              <div class="RecruitCardVersions-Separator" />
              <span class="RecruitCardVersions-ColumnItem__Center">
                Тип изменения
              </span>
              <div class="RecruitCardVersions-Separator" />
              <span>Старое значение</span>
              <q-icon
                class="RecruitCardVersions-Arrow"
                name="pgs-arrow-right"
              />
              <span>Новое значение</span>
            </q-item>

            <q-item
              v-for="(change, i) in row.changes"
              :key="change.id + i"
              class="RecruitCardVersions-TableRow"
            >
              <div>
                <div
                  class="RecruitCardVersions-Text RecruitCardVersions-Text__Strong"
                >
                  {{ change.interfaceField }}
                </div>
                <div class="RecruitCardVersions-Field">
                  <span
                    class="RecruitCardVersions-Text RecruitCardVersions-Text__Grey"
                    >Технический путь:
                  </span>
                  {{ change.systemField }}
                </div>
              </div>
              <div
                class="RecruitCardVersions-Separator RecruitCardVersions-Separator__Visible"
              />
              <div
                class="RecruitCardVersions-Text RecruitCardVersions-Text__Grey RecruitCardVersions-ColumnItem__Center"
              >
                {{ change.type }}
              </div>
              <div
                class="RecruitCardVersions-Separator RecruitCardVersions-Separator__Visible"
              />
              <div
                class="RecruitCardVersions-Text RecruitCardVersions-Text__Grey"
              >
                {{ change.oldValue }}
              </div>
              <q-icon
                class="RecruitCardVersions-Arrow"
                name="pgs-arrow-right"
              />
              <div>{{ change.newValue }}</div>
            </q-item>
          </q-list>
        </q-expansion-item>
      </template>
    </re-table>
  </centered-1280-box>
</template>

<script lang="ts">
import { Component, Mixins, PropSync } from 'vue-property-decorator';
import get from 'lodash/get';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import { formatDate } from '@/recruits/utils';
import SortBar from '@/recruits/components/common/sort-bar.vue';
import { SortingOption, UrlQueryParams } from '@/recruits/models';
import { DateFormat } from '@constants/utils/format-date';
import {
  JournalServiceApi,
  ObjectHistoryV2,
} from '@/recruits/openapi/journal-service';
import UrlIntegratedSearch from '@/recruits/mixins/url-integrated-search';
import SearchBar from '@/recruits/components/recruit-card/versions/search-bar.vue';
import {
  INITIAL_PAGINATION,
  VersionSearchFilter,
} from '@/recruits/components/recruit-card/versions/search-filter';
import ReTable from '@/recruits/components/common/r-table/index.vue';
import { RTableColumn } from '@/interfaces';
import { DataForRecruit } from '@/recruits/components/recruit-card/masthead/interfaces';
import { QPagination } from '@models/models-ui';

const JOURNAL_SERVICE_API = new JournalServiceApi();

@Component({
  components: {
    SearchBar,
    SortBar,
    Centered1280Box,
    ReTable,
  },
  computed: {
    dateFormat() {
      return DateFormat;
    },
  },
  methods: {
    get,
    formatDate,
  },
})
export default class RecruitCardVersions extends Mixins(UrlIntegratedSearch) {
  @PropSync('data', { type: Object, default: () => ({}) })
  localData: DataForRecruit;

  filter = new VersionSearchFilter();
  pagination: QPagination = INITIAL_PAGINATION;

  created(): void {
    this.pagination.rowsNumber = this.localData.versions.totalRows;
  }

  get objectHistory(): ObjectHistoryV2[] {
    return this.localData.versions.data || [];
  }

  async fetchData(
    query: UrlQueryParams
  ): Promise<{ totalRows: number | undefined }> {
    try {
      const { data } = await JOURNAL_SERVICE_API.getObjectHistoryV1({
        search: {
          objectId: this.$route.params.id,
          ...this.filter.prepareRequestParams(),
        },
        pagination: {
          sortBy: query.sortby,
          descending: query.descending === 'true',
          page: Number(query.page),
          rowsPerPage: Number(query.perpage),
        },
      });
      this.localData = { ...this.localData, versions: data };
      return {
        totalRows: data.totalRows,
      };
    } catch (error) {
      console.error(
        `Ошибка получения данных об изменениях по гражданину ${this.$route.params.id}`,
        error
      );
      return {
        totalRows: 0,
      };
    }
  }

  get sortButtons(): Array<SortingOption<ObjectHistoryV2>> {
    return [
      { label: 'По дате изменения', value: 'date' },
      { label: 'По инициатору изменения', value: 'initiator' },
    ];
  }

  get columns(): RTableColumn[] {
    return [
      {
        name: 'all',
      },
    ];
  }
}
</script>

<style lang="scss" scoped>
.RecruitCardVersions {
  font-family: 'Golos UI', sans-serif;
  .q-item {
    padding: 6px 12px;
  }
  &-SortBar {
    margin-bottom: 12px;
  }
  &-Table {
    .RTable-Row {
      padding: 0;
    }
    .q-table__top {
      display: none;
    }

    .RTable-Col {
      padding: 0;
    }
  }

  &-ExpansionItem {
    width: 100%;

    &__Open {
      background: rgba(53, 126, 172, 0.05);
    }

    .q-item__section--side {
      padding-right: 0;
      padding-left: 12px;
      color: #020c12;
      opacity: 0.7;
    }
  }

  &-ExpansionHeader {
    width: calc(100% - 36px);
    display: grid;
    align-items: center;
    grid-gap: 20px;
    grid-template-columns: minmax(80px, auto) 1fr auto minmax(80px, auto);
  }
  &-InfoBlock {
    display: flex;
    gap: 12px;
  }
  &-Info {
    display: flex;
    gap: 4px;
  }
  &-InfoIcon {
    font-size: 24px;
    color: #020c12b2;
  }
  &-Badge {
    border-radius: 12px;
    background: rgba(15, 32, 160, 0.08);
    padding: 0 8px;
  }
  &-Text {
    font-size: 14px;
    letter-spacing: 0;
    font-style: normal;
    font-weight: 400;

    &__Grey {
      color: #020c1294;
      font-weight: 400;
    }
    &__Blue {
      font-weight: 500;
      color: #107abc;
    }

    &__Strong {
      font-weight: 500;
    }
  }
  &-TableRow {
    display: grid;
    grid-template-columns: 4fr auto 1fr auto 2fr auto 2fr;
    align-items: center;
    gap: 12px;
    background: #ffffff;
    min-height: 40px;
    &:hover {
      background: transparent;
      .RecruitCardVersions-Field {
        display: block;
      }
    }
  }
  &-ColumnItem {
    &__Center {
      justify-self: center;
    }
  }
  &-TitleTable {
    color: rgba(2, 12, 18, 0.58);
    font-size: 10px;
    font-style: normal;
    font-weight: 600;
    line-height: 12px;
    letter-spacing: 0.5px;
    text-transform: uppercase;
    background-color: transparent;
    min-height: 24px;
  }

  &-Arrow {
    font-size: 16px;
    color: rgba(2, 12, 18, 0.24);
  }

  &-Separator {
    height: 100%;
    width: 1px;
    margin: 8px 4px;

    &__Visible {
      background: rgba(1, 72, 116, 0.11);
    }
  }

  &-Field {
    display: none;
  }
}
</style>
