<template>
  <div class="ButtonsBlock" v-if="selected.length">
    <r-selection-filter
      v-if="
        $AC.haveOneOfScope([
          $AC.scopes.MILITARY_RECRUIT_SPECIALIST,
          $AC.scopes.SYSTEM_ADMINISTRATOR,
        ])
      "
      tooltip="для снятия с учёта"
      :selected="selected"
      :filter="checkStatuses(['1.2', '14'])"
    >
      <template #default="props">
        <multi-cancel
          :model="props.filtred"
          process-key="milBaseRouteProcess"
          action-type="cancelRegistration"
          document-code="СancelRegistration"
          label="Снять с учёта"
          title="Решение о снятии с воинского учёта:"
          icon="pgs-add-form"
          @done="onReload"
        />
      </template>
    </r-selection-filter>
    <r-selection-filter
      v-if="
        $AC.haveOneOfScope([
          $AC.scopes.MILITARY_RECRUIT_SPECIALIST,
          $AC.scopes.SYSTEM_ADMINISTRATOR,
        ])
      "
      :selected="selected"
      :filter="checkStatuses(['1.2'])"
    >
      <template #default="props">
        <multi-add-to-list
          :model="props.filtred"
          class="DopButton-Button"
          process-key="milBaseMassSignProcess"
          action-type="addToSummonList"
          label="Добавить в список на вызов"
          icon="pgs-add-form"
          default-time="09:00"
          :disabled-reason="blockCriminalRecruit.message"
          :personRegistryListFilter="clearedPersonRegistryListFilter"
          :disable="props.filtred.length > 50 || blockCriminalRecruit.result"
          @done="onReload"
        />
      </template>
    </r-selection-filter>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import MultiInit from '@/recruits/components/dialogs/MultiInit.vue';
import MultiCancel from '@/recruits/components/dialogs/MultiCancel.vue';
import MultiAddToList from '@/recruits/components/dialogs/MultiAddToList.vue';
import RSelectionFilter from '@/recruits/components/common/r-selection-filter.vue';
import { RecruitsForListsRecord } from '@/recruits/openapi/person-registry';

const differentAgeMessage =
  'Выбраны записи граждан, имеющие разные ограничения к вызову в военный комиссариат. Обратите внимание на индикатор около ФИО гражданина с указанием ограничения вызова';

@Component({
  components: {
    MultiInit,
    MultiAddToList,
    MultiCancel,
    RSelectionFilter,
  },
})
export default class ListButtons extends Vue {
  @Prop({ default: () => [] }) selected: any[];

  personRegistryListFilter = {
    statuses: ['1'],
    summonObjectiveAny: [] as string[],
    summonObjectiveNotAll: ['101'],
  };

  @Watch('selected')
  filterRequest() {
    (this.selected as any[]).forEach((item) => {
      if (item.status === '1.2') {
        if (
          !item.stateRecruit?.recruitmentEighteen ||
          item.stateRecruit?.recruitmentConscriptionDisable
        ) {
          this.personRegistryListFilter.summonObjectiveNotAll = [];
          this.personRegistryListFilter.summonObjectiveAny = [
            '102',
            '103',
            '104',
            '105',
            '106',
            '107',
          ];
        } else {
          this.personRegistryListFilter.summonObjectiveAny = [];
          this.personRegistryListFilter.summonObjectiveNotAll = ['101'];
        }
      }
    });
  }

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

  get blockCriminalRecruit(): { result: boolean; message: string } {
    let result = true;
    const { adult, teen } = this.selected.reduce<{
      adult: number;
      teen: number;
    }>(
      (acc, recruit) => {
        const {
          stateRecruit: { recruitmentEighteen },
        } = recruit;
        recruitmentEighteen ? ++acc.adult : ++acc.teen;
        return acc;
      },
      { adult: 0, teen: 0 }
    );
    if (teen && adult === 0) {
      result = this.selected.length !== teen;
    } else if (adult && teen === 0) {
      result = this.selected.length !== adult;
    }
    return { result, message: result ? differentAgeMessage : '' };
  }

  get clearedPersonRegistryListFilter() {
    return Object.fromEntries(
      Object.entries(this.personRegistryListFilter).filter(
        ([, value]) => value.length
      )
    );
  }

  public showAddListDialog = false;
  public addList(): void {
    this.showAddListDialog = true;
  }

  public checkStatuses(statuses: string[]) {
    return function (
      item: RecruitsForListsRecord,
      i: number,
      array: RecruitsForListsRecord[]
    ): boolean {
      return statuses.includes(item.status);
    };
  }
}
</script>

<style lang="scss">
.ButtonsBlock {
  display: flex;
  flex-flow: row;
  align-items: flex-start;
  gap: 16px;
}
.DopButton {
  box-sizing: border-box;
  background-color: rgba(15, 32, 160, 0.08);
  border-radius: 20px;
  padding: 4px;
  margin-top: -5px;
  margin-bottom: -5px;
  &-TextFiled {
    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);
      }
    }
  }
}
</style>
