<template>
  <div class="ConfirmationChange">
    <q-icon
      class="ConfirmationChange-WarnButton"
      name="pgs-warning"
      @click="open"
    >
      <q-tooltip>Необходимо проверить изменения сведений гражданина</q-tooltip>
    </q-icon>
    <operation-dialog ref="dialog" v-model="opened" :title="title">
      <div class="ConfirmationChange-Content">
        <div v-if="!!preparedToBeConfirmed.added.length">
          Добавленные поля
          <q-badge color="red">{{
            get(preparedToBeConfirmed, 'added.length', 0)
          }}</q-badge>
          <q-toggle v-model="addedShow" label="Показать изменения" />
        </div>
        <q-slide-transition v-if="!!get(preparedToBeConfirmed, 'added.length')">
          <div v-show="addedShow" class="ConfirmationChange-ChangesBlock">
            <template v-for="added in preparedToBeConfirmed.added">
              <div
                v-if="!added.is_technical"
                :key="added.path"
                class="ConfirmationChange-Change"
              >
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name">
                    Наименование поля:
                  </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ added.label }}
                  </span>
                </div>
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name"> Группа: </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ added.group }}
                  </span>
                </div>
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name">
                    Добавляемое значение:
                  </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ added.newValue }}
                  </span>
                </div>
                <div>
                  <q-checkbox
                    v-model="added.status"
                    :label="getLabel(added.status)"
                  />
                </div>
              </div>
            </template>
          </div>
        </q-slide-transition>

        <div v-if="!!preparedToBeConfirmed.deleted.length">
          Удаленные поля
          <q-badge color="red">{{
            get(preparedToBeConfirmed, 'deleted.length', 0)
          }}</q-badge>
          <q-toggle v-model="showDeleted" label="Показать изменения" />
        </div>
        <q-slide-transition
          v-if="!!get(preparedToBeConfirmed, 'deleted.length')"
        >
          <div v-show="showDeleted" class="ConfirmationChange-ChangesBlock">
            <template v-for="deleted in preparedToBeConfirmed.deleted">
              <div
                v-if="!deleted.is_technical"
                :key="deleted.path"
                class="ConfirmationChange-Change"
              >
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name">
                    Наименование поля:
                  </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ deleted.label }}
                  </span>
                </div>
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name"> Группа: </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ deleted.group }}
                  </span>
                </div>
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name">
                    Удаляемое значение:
                  </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ deleted.oldValue }}
                  </span>
                </div>
                <div>
                  <q-checkbox
                    v-model="deleted.status"
                    :label="getLabel(deleted.status)"
                  />
                </div>
              </div>
            </template>
          </div>
        </q-slide-transition>

        <div v-if="!!preparedToBeConfirmed.updated.length">
          Измененные поля
          <q-badge color="red">{{
            get(preparedToBeConfirmed, 'updated.length', 0)
          }}</q-badge>
          <q-toggle v-model="showUpdated" label="Показать изменения" />
        </div>
        <q-slide-transition
          v-if="!!get(preparedToBeConfirmed, 'updated.length')"
        >
          <div v-show="showUpdated" class="ConfirmationChange-ChangesBlock">
            <template v-for="updated in preparedToBeConfirmed.updated">
              <div
                v-if="!updated.is_technical"
                :key="updated.path"
                class="ConfirmationChange-Change"
              >
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name">
                    Наименование поля:
                  </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ updated.label }}
                  </span>
                </div>
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name"> Группа: </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ updated.group }}
                  </span>
                </div>
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name">Было:</span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ updated.oldValue }}
                  </span>
                </div>
                <div class="ConfirmationChange-Change__Field">
                  <span class="ConfirmationChange-Change__Name"> Стало: </span>
                  <span class="ConfirmationChange-Change__Value">
                    {{ updated.newValue }}
                  </span>
                </div>
                <div>
                  <q-checkbox
                    v-model="updated.status"
                    :label="getLabel(updated.status)"
                  />
                </div>
              </div>
            </template>
          </div>
        </q-slide-transition>
      </div>
      <template #process></template>
      <template #result></template>
      <template #right-actions>
        <r-btn
          :label="textSuccessBtn"
          action
          icon-right="pgs-check"
          @click="action"
        />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          icon-right="pgs-shevron-right-off"
          label="Закрыть"
          @click="finish"
        />
      </template>
    </operation-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Mixins, Prop, Ref, Watch } from 'vue-property-decorator';
import TaskButton from '@mixins/TaskButton';
import OperationDialog from '@components/common/operation-dialog/index.vue';
import {
  DiffObject,
  GetUpdateResponse,
} from '@/recruits/openapi/data-update-controller';
import { notifyError } from '@utils/notify';
import get from 'lodash/get';

interface Prepare extends DiffObject {
  status: boolean | null;
  /**
   * Название поля на фронте (человеко читаемое)
   * @type {string}
   */
  label: string;
  /**
   * Группа принадлежности поля
   * @type {string}
   */
  group: string;
  /**
   * Означение поля как технического
   * @type {boolean}
   */
  // eslint-disable-next-line camelcase
  is_technical: boolean;
}

type PreparedData = Record<string, Prepare[]>;

const defaultData = (data: DiffObject): Prepare => {
  // @ts-ignore
  // eslint-disable-next-line camelcase
  const { is_technical = false } = data;
  return {
    label: '',
    group: '',
    is_technical,
    ...data,
    // eslint-disable-next-line camelcase
    status: is_technical || null,
  };
};

@Component({
  methods: {
    get,
  },
})
export default class ConfirmationChanges extends Mixins(TaskButton) {
  get: typeof get;

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

  @Prop({ default: 'Отправить' })
  readonly textSuccessBtn: string;

  @Prop()
  declare readonly model: GetUpdateResponse;

  @Ref('dialog') operationDialog: OperationDialog;

  opened = false;
  preparedData: PreparedData = {
    added: [],
    deleted: [],
    updated: [],
  };

  addedShow = false;
  showDeleted = false;
  showUpdated = true;

  // Списки отфильтрованы, но обекты в них все-еще те-же что и в оригинальной коллекции
  get preparedToBeConfirmed(): PreparedData {
    return Object.entries(this.preparedData).reduce((data, [key, list]) => {
      // eslint-disable-next-line camelcase
      data[key] = list.filter(({ is_technical }) => !is_technical);
      return data;
    }, {} as PreparedData);
  }

  async open(): Promise<void> {
    this.opened = true;
  }

  @Watch('model', {
    deep: true,
    immediate: true,
  })
  prepare(model: GetUpdateResponse): void {
    this.preparedData.added = model.added.map(defaultData) || [];

    this.preparedData.deleted = model.deleted.map(defaultData) || [];

    this.preparedData.updated = model.updated.map(defaultData) || [];
  }

  getLabel(status: null | boolean): string {
    return status === true
      ? 'Подтверждено'
      : status === false
      ? 'Не подтверждено'
      : 'Выберите что делать';
  }

  checkPrepared(preparedList: Prepare[]): boolean {
    for (const prep of preparedList) {
      if (prep.status === null) {
        return true;
      }
    }
    return false;
  }

  action(): void | boolean {
    let errFlag = false;
    for (const list of Object.values(this.preparedData)) {
      if (errFlag) break;
      errFlag = this.checkPrepared(list);
    }
    console.log(errFlag);
    if (errFlag) {
      notifyError('Вы отметили не все поля');
      return false;
    }
    this.$emit('action', this.preparedData);
  }

  finish(): void {
    this.$emit('done');
  }
}
</script>

<style lang="scss">
.ConfirmationChange {
  &-WarnButton {
    font-size: 24px;
    color: red;
    background-color: orange;
    border-radius: 50%;
    padding: 5px;
    animation-name: blink;
    animation-iteration-count: infinite;
    animation-duration: 1s;
    cursor: pointer;
  }
  &-Header {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
    margin-bottom: 28px;
  }
  &-Actions {
    background: rgba(15, 32, 160, 0.08);
    display: flex;
    justify-content: space-between;
    padding: 5px;
  }
  &-Change {
    border-radius: 3px;
    background-color: rgba(53, 126, 172, 0.05);
    padding: 5px;
    &:not(:last-child) {
      margin-bottom: 4px;
    }
    &__Field {
      padding: 2px 0;
      font-family: 'Golos text', sans-serif;
    }
    &__Name {
      font-weight: 500;
      margin-right: 5px;
    }
    &__Value {
    }
  }
}

@keyframes blink {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(1.2);
  }
}
</style>
