<template>
  <div class="ButtonsBlock" v-if="terminateStatusBlocked">
    <multi-send-registration
      v-if="
        $AC.haveOneOfScope([
          $AC.scopes.MILITARY_RECRUIT_SPECIALIST,
        ]) && showSendRegistrationInListBindingOnStatuses
      "
      :data="data"
      :disable="!!selected.length"
      label="Направить"
      :model="selectedForSend"
      @onBeforeAction="recordActivity"
      @done="onReload"
    />
    <multi-shape
      v-if="isShowShapeBtn"
      :model="checkRecruitsStatusForShape"
      :data="data"
      disabled-background-color="gray"
      :disable="!!selected.length || disabledShapeIfSendCodeEmpty"
      :disabled-shape-empty="disabledShapeIfSendCodeEmpty"
      :sign="false"
      process-key="milBaseMassSignProcess"
      action-type="addToSummonList"
      label="Сформировать"
      title="Формирование повесток:"
      @onBeforeAction="recordActivity"
      @done="onReload"
    />
    <multi-sign
      v-if="isShowSignBtn"
      :model="recruitIds"
      :data="data"
      :disable="!!selected.length"
      process-key="milBaseMassSignProcess"
      label="Подписать"
      title="Подписание:"
      @done="onReload"
    />
    <div class="DopButton" v-if="selected.length">
      <div
        v-if="
          $AC.haveOneOfScope([
            $AC.scopes.MILITARY_COMMISSAR,
            $AC.scopes.MILITARY_RECRUIT_SPECIALIST,
            $AC.scopes.SYSTEM_ADMINISTRATOR,
          ])
        "
        class="DopButton__FieldBlock"
      >
        <div>
          <span class="DopButton__TextField"> Выбрано: </span>
          <span class="DopButton__TextField DopButton__TextField_Bold">
            {{ selected.length }}
          </span>
        </div>
        <r-btn
          dense
          negative
          label="Удалить"
          icon="pgs-delete"
          no-wrap
          @click="open"
        />
      </div>
    </div>
    <q-dialog v-model="deleteListDialog" no-backdrop-dismiss>
      <q-card>
        <q-card-section class="DeleteInListDialog">
          <q-icon
            class="DeleteInListDialog__AttentionContentIcon"
            name="pgs-delete"
          />
          <p class="DeleteInListDialog__AttentionContentHeader">
            Вы уверены, что хотите удалить
            {{ selected.length === 1 ? 'гражданина' : 'граждан' }} из списка?
          </p>
        </q-card-section>
        <q-card-actions class="DeleteInListDialog__AttentionButtons">
          <r-btn
            class="DeleteInListDialog__AttentionButton"
            label="Закрыть"
            v-close-popup
          />
          <r-btn
            class="DeleteInListDialog__AttentionButton"
            label="Удалить"
            :action="true"
            @click="deleteList"
            v-activity-recorder="dataActivity"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog v-model="apiErrorShow" no-backdrop-dismiss>
      <process-api-error :errorObject="errorObject" />
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import MultiSign from '@/recruits/components/dialogs/MultiSign.vue';
import MultiShape from '@/recruits/components/dialogs/MultiShape.vue';
import MultiSendRegistration from '@/recruits/components/dialogs/MultiSendRegistration.vue';
import {
  SummonListRegistryApi,
  ListRecordV2,
  ListElementV2,
} from '@/recruits/openapi/summon-list-service';
import ProcessApiError from '@/recruits/components/dialogs/ProcessApiError.vue';
import get from 'lodash/get';

interface IRecruitInfo {
  id: string;
  fio: string;
  idERN: string;
}
const recruitsStatusForShape = ['1', '1.2', '15'];

@Component({
  components: {
    MultiSign,
    MultiShape,
    MultiSendRegistration,
    ProcessApiError,
  },
})
export default class ListButtons extends Vue {
  @Prop({ default: () => [] }) selected: string[];
  @Prop({}) private loading: boolean;
  @Prop() data: { data: Array<ListElementV2>; listInfo: ListRecordV2 };

  SummonListRegistryApi = new SummonListRegistryApi();

  public recruitIds: string[] = [];
  public statusList = '';
  public readonly listId: string = this.$route.params.id;

  public deleteListDialog = false;

  apiErrorShow = false;
  errorObject = {};

  get terminateStatusBlocked() {
    return this.data?.listInfo?.status !== '4';
  }

  get selectedForSend(): ListElementV2[] {
    return this.data?.data?.filter((row) => row?.status === '3.14') || [];
  }

  get extraInfo() {
    return {
      previewInfo: [
        {
          label: 'номер',
          value: this.data.listInfo?.number,
        },
      ],
      detailedInfo: [
        {
          label: 'цель вызова',
          value: this.options[Number(this.data?.listInfo?.summonObjective)],
        },
        {
          label: 'дата и время вызова',
          value: this.data.listInfo?.turnoutDate,
          type: 'date',
        },
      ],
    };
  }

  get dataActivity(): any {
    return {
      buttonCode: 'summons_delete',
      extraInfo: { ...this.extraInfo, list: this.personList },
    };
  }

  get options(): string {
    return (
      this.$store.getters[
        'ervuDictionaries/militaryRegistrationUpdatingGoalsDictionary'
      ] || []
    );
  }

  @Watch('loading')
  async loadingWatcher(): Promise<void> {
    if (this.loading) return;
    const { data } = await this.SummonListRegistryApi.getListIdsV1(this.listId);
    this.recruitIds = get(data, 'recruitIds', []);
    this.statusList = get(data, 'status', '');
  }



  get isShowShapeBtn(): boolean {
    return (
      this.$AC.haveOneOfScope([
        this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST,
      ]) && !!this.checkRecruitsStatusForShape.length
    );
  }

  get isShowSignBtn(): boolean {
    return (
      this.$AC.haveOneOfScope([
        this.$AC.scopes.MILITARY_COMMISSAR,
      ]) &&
      !!this.recruitIds.length &&
      this.showSingInListBindingOnStatuses
    );
  }

  get checkRecruitsStatusForShape() {
    if (this.data.data && this.data.listInfo.status === '1') {
      return this.data?.data?.filter((recruit) => recruit?.status && recruitsStatusForShape.includes(recruit.status)) || []
    }
    return [];
  }

  get showSingInListBindingOnStatuses() {
    if (this.data?.data?.length && this.data?.listInfo?.status === '2') {
      return (this.data?.data?.filter((recruit) => recruit.status === '3.7')).length === this.data?.data?.length
    } else {
      return false;
    }
  }

  get showSendRegistrationInListBindingOnStatuses() {
    if (this.data?.data?.length && this.data?.listInfo?.status === '3') {
      return (this.data?.data?.filter((recruit) => recruit.status === '3.14')).length === this.data?.data?.length
    } else {
      return false;
    }
  }

  get disabledShapeIfSendCodeEmpty() {
    return !!this.data?.data?.find((sub: ListElementV2) => {
      return (sub.sendInfo?.filter(send => send?.sendCode?.length))?.length !== sub.sendInfo?.length;
    });
  };

  public async onReload(): Promise<void> {
    this.$emit('on-reload');
  }

  get personList() {
    return this.data?.data?.reduce((acc: any, person) => {
        if (person.id && this.selected.includes(person.id)) {
          acc.push({
            id: person.id,
            idERN: person.idERN,
            fio: person.fullName,
          });
        }
        return acc;
      }, []) || [];
  }

  public open() {
    this.deleteListDialog = true;
    this.$recordActivity({
      buttonCode: 'summons_deletion',
      extraInfo: { ...this.extraInfo, list: this.personList },
    });
  }

  recordActivity(buttonCode: string, form: string){
    let list: IRecruitInfo[] = [];
    if (form === 'shape') list = this.checkRecruitsStatusForShape.map(el=>({ id: el.id || '', fio: el.fullName || '', idERN: el.idERN || '' }));
    if (form === 'send') list = this.selectedForSend.map(el=>({ id: el.id || '', fio: el.fullName || '', idERN: el.idERN || '' }));
    this.$recordActivity({
      buttonCode,
      extraInfo: { ...this.extraInfo, list },
    });
  }

  public async deleteList(): Promise<void> {
    this.$q.loading.show({
      message: `Удаление ${
        this.selected.length === 1 ? 'гражданина' : 'граждан'
      } из списка`,
    });
    try {
      await this.SummonListRegistryApi.removeRecruitsV1(this.listId, this.selected);
    } catch (error) {
      if (error.message !== 'Network Error') {
        if (error.response.status !== 400) {
          this.errorObject = {
            data: {
              message: 'Сервис временно недоступен, попробуйте повторить позже',
              description:
                'Возникла ошибка сетевого соединения. Удаленный сервер недоступен. ' +
                ' Проверьте сетевое соединение или обратитесь к системному администратору',
            },
          };
        } else {
          this.errorObject = error.response;
        }
      } else {
        this.errorObject = {
          data: {
            message: 'Сервис временно недоступен, попробуйте повторить позже',
            description:
              'Возникла ошибка сетевого соединения. Удаленный сервер недоступен. ' +
              ' Проверьте сетевое соединение или обратитесь к системному администратору',
          },
        };
      }
      this.apiErrorShow = true;
    } finally {
      this.$q.loading.hide();
      this.deleteListDialog = false;
      this.onReload();
    }
  }
}
</script>

<style lang="scss" scoped>
.ButtonsBlock {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 250px;
  gap: 16px;
  height: max-content;
}
.DopButton {
  box-sizing: border-box;
  background-color: rgba(15, 32, 160, 0.08);
  border-radius: 20px;
  padding: 4px;
  margin-top: 0;
  margin-bottom: 0;
  &__FieldBlock {
    gap: 1em;
    align-items: center;
    display: flex;
    flex-wrap: wrap;
  }
  &__TextFieled {
    margin-left: 8px;
    margin-right: 8px;
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;
    color: rgba(2, 12, 18, 0.58);
    &_Bold {
      font-weight: 500;
      color: #015e98;
    }
  }
  &__Button {
    &__Color {
      &__DarkBlue {
        background: linear-gradient(92.91deg, #1491cf 0%, #0f68a0 100%);
        box-shadow: 0 0.6px 1.8px rgba(7, 46, 71, 0.12),
          0 3.2px 8px rgba(7, 46, 71, 0.15);
        color: rgba(255, 255, 255, 0.92);
      }
    }
  }
}
.DeleteInListDialog {
  * {
    margin: 0;
    padding: 0;
  }
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 30px 40px;
  &__AttentionContentIcon {
    color: #1491cf;
    font-size: 40px;
    margin-bottom: 10px;
  }
  &__AttentionContentHeader {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    text-align: center;
    letter-spacing: -0.015em;
    color: #015e98;
    margin-bottom: 24px;
  }
  &__AttentionButtons {
    display: flex;
    justify-content: space-between;
    padding: 12px 20px;
  }
  &__AttentionButton {
    padding: 0 10px;
  }
}
</style>
