<template>
  <Centered1280Box>
    <white-card>
      <div class="row q-pa-sm">
        <div class="col-12 col-sm-3 header q-pb-sm">
          <block-header> Информация об инциденте </block-header>
        </div>
        <div class="col-12 col-sm-9">
          <div class="row q-col-gutter-xs">
            <!--            <div class="col-12 col-sm-6 col-md-2">-->
            <!--              <data-block-->
            <!--                :form-data="{-->
            <!--                  label: 'Номер инцидента',-->
            <!--                  value: get(data, 'mainInfo.number'),-->
            <!--                }"-->
            <!--                :loading="loading"-->
            <!--              />-->
            <!--            </div>-->
            <div class="col-12 col-sm-6 col-md-2">
              <data-block
                :form-data="{
                  label: 'Дата регистрации',
                  value: formatDate(get(data, 'mainInfo.registrationDate')),
                }"
                :loading="loading"
              />
            </div>
            <div
              class="col-12 col-sm-6 col-md-2"
              v-if="get(data, 'mainInfo.resolveDate')"
            >
              <data-block
                :form-data="{
                  label: 'Дата разрешения инцидента',
                  value: formatDate(get(data, 'mainInfo.resolveDate')),
                }"
                :loading="loading"
              />
            </div>
            <div
              v-if="get(data, 'mainInfo.reasonConflictDataDescription', '')"
              class="col-12 col-sm-6 col-md-2"
              style="padding: 8px 8px"
            >
              <div class="ErrorsImport-Body__Cell ErrorsImport-Body__CellFile">
                <q-icon
                  class="ErrorsImport-Icon ErrorsImport-Body__CellFile_Icon"
                  name="pgs-save"
                  @click.stop="downloadFile(get(data, 'mainInfo'))"
                >
                  <q-tooltip>Скачать</q-tooltip>
                </q-icon>
                <div>
                  <div>
                    {{ get(data, 'mainInfo.fileName') }}
                  </div>
                  <div class="ErrorsImport-Body__CellFile_Id">
                    {{ get(data, 'mainInfo.file.s3Name') }}
                  </div>
                </div>
              </div>
            </div>
            <div class="col-12 col-sm-6 col-md-10">
              <data-block
                :form-data="{
                  label: 'Поставщик',
                  value: sourceProvider,
                }"
                :loading="loading"
              />
            </div>
            <div class="col-12 col-sm-6 col-md-10">
              <data-block
                :form-data="{
                  label: 'Причина регистрации',
                  value: get(data, 'mainInfo.reasonDescription', 'Отсутствует'),
                }"
                :loading="loading"
              />
            </div>
            <div class="col-12 col-sm-6 col-md-10" v-if="organization">
              <data-block
                :form-data="{
                  label: 'Наименование органа, принявшего решение',
                  value: organization,
                }"
                :loading="loading"
              />
            </div>
            <div class="full-width q-mt-sm">
              <data-block bolder :form-data="{ label: 'Гражданин' }">
                <div class="row q-col-gutter-xs">
                  <div class="col-12 col-sm-6 col-md-4">
                    <data-block
                      :form-data="{
                        label: 'Фамилия',
                        value: get(data, 'mainInfo.lastName'),
                      }"
                      :loading="loading"
                      background="white"
                    />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4">
                    <data-block
                      :form-data="{
                        label: 'Имя',
                        value: get(data, 'mainInfo.firstName'),
                      }"
                      :loading="loading"
                      background="white"
                    />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4">
                    <data-block
                      :form-data="{
                        label: 'Отчество',
                        value: get(data, 'mainInfo.middleName'),
                      }"
                      :loading="loading"
                      background="white"
                    />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4">
                    <data-block
                      :form-data="{
                        label: 'Дата рождения',
                        value: formatDate(get(data, 'mainInfo.birthDate')),
                      }"
                      :loading="loading"
                      background="white"
                    />
                  </div>
                  <div
                    class="col-12 col-sm-6 col-md-4"
                    v-if="get(data, 'mainInfo.snils', '')"
                  >
                    <data-block
                      :form-data="{
                        label: 'СНИЛС',
                        value: get(data, 'mainInfo.snils', ''),
                      }"
                      :loading="loading"
                      background="white"
                    />
                  </div>
                  <div class="col-12 col-sm-6 col-md-4">
                    <data-block
                      :form-data="{
                        label: 'ИД ЕРН',
                        value: get(data, 'mainInfo.idERN', 'Отсутствует'),
                      }"
                      :loading="loading"
                      background="white"
                    />
                  </div>
                </div>
              </data-block>
            </div>
            <div
              class="col-12 col-sm-6 col-md-12"
              v-if="conflicts && conflicts.length"
            >
              <div v-if="conflicts.length" class="fix-class">
                <p>Конфликтные данные:</p>
                <div class="ConflictDataTable">
                  <div class="ConflictDataTable-Row">
                    <div
                      class="ConflictDataTable-Header"
                      v-if="showField.fieldName"
                    >
                      Название поля
                    </div>
                    <div
                      class="ConflictDataTable-Header"
                      v-if="showField.ervuData"
                    >
                      Данные ЕРВУ
                    </div>
                    <div
                      class="ConflictDataTable-Header"
                      v-if="showField.otherData"
                    >
                      Данные поставщика
                    </div>
                  </div>
                  <div
                    :key="conflict.fieldName"
                    v-for="conflict in conflicts"
                    class="ConflictDataTable-Row ConflictDataTable-Row--Hover"
                    :style="createColumnsForConflictData"
                  >
                    <div
                      v-if="showField.fieldName"
                      class="ConflictDataTable-Cal"
                    >
                      {{ conflict.fieldName }}
                    </div>
                    <div
                      v-if="showField.ervuData"
                      class="ConflictDataTable-Cal"
                    >
                      {{ conflict.ervuData }}
                    </div>
                    <div
                      v-if="showField.otherData"
                      class="ConflictDataTable-Cal"
                    >
                      {{ conflict.otherData }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </white-card>
  </Centered1280Box>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import WhiteCard from '@/recruits/components/common/white-card.vue';
import BlockHeader from '@/recruits/components/common/block-header.vue';
import dataBlock from '@components/cards/statements/components/dataBlock.vue';
import {
  DictionaryItem,
  IncidentResponseV1,
} from '@/recruits/openapi/ervu-service';
import { JournalErrorRecord } from '@/recruits/openapi/journal-service';
import get from 'lodash/get';
import { formatDate } from '@/recruits/utils';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveBlob } from '@utils/files';
import {isArray} from "lodash";

interface Conflict {
  fieldName: string;
  ervuData: string;
  otherData: string;
}

@Component({
  components: {
    WhiteCard,
    Centered1280Box,
    BlockHeader,
    dataBlock,
  },
  methods: {
    get,
    formatDate,
  },
})
export default class Main extends Vue {
  get: typeof get;
  formatDate: typeof formatDate;

  @Prop({ type: Object, default: {} })
  public data: IncidentResponseV1;

  @Prop({ type: Boolean, default: false })
  public loading: boolean;

  get organization() {
    return get(this.data, 'mainInfo.resolvedOrganisation');
  }

  get sourceProvider(): string {
    return this.$store.getters['ervuDictionaries/incidentsSource'].find(( incident: DictionaryItem )=> incident.code === get(this.data, 'mainInfo.sourceCode', ''))?.value  || '';
  }

  get conflictList() {
    return get(this.data, 'mainInfo.reasonConflictData', []);
  }

  get conflicts(): Conflict[] {
    return get(this.data, 'mainInfo.conflicts', []);
  }

  get actualList() {
    return get(this.data, 'mainInfo.reasonActualData', []);
  }

  get createColumnsForConflictData(){
    return `grid-template-columns: repeat(${Object.values(this.showField).reduce((acc:number,column)=> (!!column ? acc++ : acc),0 )},1fr);`
  }

  get showField(): {fieldName:number,ervuData:number,otherData:number} {
    if (isArray(this.conflicts)) {
      return this.conflicts.reduce(
        (acc, conf: Conflict) => {
          Object.keys(acc).forEach(
            (el)=>conf[el as keyof Conflict] && acc[el as keyof Conflict]++)
          return acc;
        },
        { fieldName: 0, ervuData: 0, otherData: 0 }
      );
    }
    return { fieldName: 0, ervuData: 0, otherData: 0 };
  }

  async downloadFile(fileInfo: JournalErrorRecord): Promise<void> {
    try {
      if (!fileInfo.file?.s3url) return;
      const { file: blob } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl(
        {
          url: fileInfo.file.s3url,
        }
      );
      saveBlob({
        blob,
        fileName: fileInfo.fileName,
        blobType: 'text/xml',
      });
    } catch (e) {
      console.log(e);
    }
  }
}
</script>
<style lang="scss">
.ConflictDataTable {
  display: grid;
  grid-template-columns: 1fr;

  &-Header {
    white-space: nowrap;
    border-bottom: 1px solid #e3ebf0;
    color: #676f73;
    padding: 4px 8px;
    font-size: 0.9em;
  }
  &-Cal {
    border-bottom: 1px solid #e3ebf0;
    border-left: 1px solid #e3ebf0;
    padding: 4px 8px;
    overflow-inline: clip;
    overflow-wrap: break-word;
    &:first-child {
      border-left: none;
    }
  }
  &-Row {
    display: grid;
    grid-template-columns: 2fr 3fr 3fr;
    padding: 0;

    &--Hover:hover {
      background-color: rgba(1, 72, 116, 0.11);
    }
  }
  &-Row:last-child &-Cal {
    border-bottom: none;
  }
}
.conflictData {
  display: flex;
  gap: 1rem;
  &-title {
    white-space: nowrap;
  }
}
.IncidentsTable {
  &-Row {
    display: grid;
    grid-template-columns: 0.5fr 0.5fr;
    > div {
      padding: 0;
    }
  }
}
.fix-class {
  background: rgba(53, 126, 172, 0.05);
  padding: 8px;
  p {
    font-size: 12px;
    color: gray;
  }
}
.ErrorsImport {
  &-Icon {
    margin-left: 5px;
    font-size: 22px;
    cursor: pointer;
  }

  &-Row {
    display: grid;
    grid-template-columns: 0.5fr 0.9fr 1fr 1.1fr 1fr 1.9fr 1.9fr;
  }

  &-TableHeader {
    padding: 16px 0 6px 0;

    &__Col {
      color: rgba(2, 12, 18, 0.58);
      overflow: hidden;
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      font-weight: 600;
      font-size: 10px;
      line-height: 12px;

      letter-spacing: 0.05em;
      text-transform: uppercase;
    }
  }

  &-Body {
    max-height: 10em;
    padding: 4px 0 4px 0;
    margin: 2px 0 2px 0;
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
    box-shadow: none;
    position: relative;
    overflow: hidden;
    color: rgba(2, 12, 18, 0.9);
    font-family: 'Golos UI', sans-serif;
    font-weight: 400;
    font-size: 12px;

    &__Cell {
      padding: 0 0 0 4px;

      &_UserInfo {
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      &_Main {
        font-size: 12px;
        font-weight: 500;
        margin-bottom: 3px;
      }

      &_Second {
        font-size: 10px;
        margin-bottom: 3px;
      }
    }

    &__CellFile {
      display: flex;
      align-items: center;

      &_Icon {
        margin-right: 6px;
      }

      &_Id {
        color: rgba(2, 12, 18, 0.58);
        font-size: 10px;
      }
    }
  }
}
</style>
