<template>
  <div class="ButtonsBlock" v-if="selectedItems.length">
    <r-selection-filter v-if="checkScope()" :selected="selectedItems">
      <template #default="props">
        <multi-add-to-list
          :button-code="buttonCode"
          :model="props.filtred"
          process-key="milBaseMassSignProcess"
          action-type="addToSummonList"
          label="Добавить в список на вызов"
          icon="pgs-add-form"
          default-time="09:00"
          :disabled-reason="blockCriminalRecruit.message"
          :personRegistryListFilter="clearedPersonRegistryListFilter()"
          :disable="selectedItems.length > 50 || blockCriminalRecruit.result"
          @done="onReload"
        />
      </template>
    </r-selection-filter>

    <q-dialog v-model="errorShow" no-backdrop-dismiss>
      <process-api-error :errorObject="errorObject" />
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, PropSync, Vue, Watch } from 'vue-property-decorator';
import MultiAddToList, {
  ButtonCode,
} from '@/recruits/components/dialogs/MultiAddToList.vue';
import { RecruitV3 } from '@/recruits/openapi/person-registry';
import RSelectionFilter from '@/recruits/components/common/r-selection-filter.vue';
import { hasPermissionToAddToList } from '@/recruits/components/recruits-to-call/scope';
import ProcessApiError from '@/recruits/components/dialogs/ProcessApiError.vue';

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

@Component({
  components: {
    MultiAddToList,
    RSelectionFilter,
    ProcessApiError,
  },
})
export default class ListButtons extends Vue {
  @PropSync('selected')
  selectedItems: RecruitV3[];

  @Watch('selected')
  checkStatuses() {
    let isToBeCalled = false;
    let isProvided = false;
    let isRegistered = false;
    this.errorShow = false;

    this.selectedItems.forEach((item) => {
      switch (item.status) {
        case '1':
          isToBeCalled = true;
          break;
        case '1.2':
          isProvided = true;
          break;
        case '15':
          isRegistered = true;
          break;
      }

      if (isRegistered) this.personRegistryListFilter.summonObjectiveAny = [];

      isToBeCalled
        ? (this.personRegistryListFilter.summonObjectiveAny = ['101'])
        : (this.personRegistryListFilter.summonObjectiveAny = []);

      if (isProvided) {
        this.personRegistryListFilter.summonObjectiveNotAll = ['101'];
        if (!(item.stateRecruit?.recruitmentEighteen) || item.stateRecruit?.recruitmentConscriptionDisable) {
          this.personRegistryListFilter.summonObjectiveNotAll = [];
          this.personRegistryListFilter.summonObjectiveAny = ['102', '103', '104', '105', '106', '107']
        }
      } else {
        this.personRegistryListFilter.summonObjectiveNotAll = [];
      }

      if (isToBeCalled && isProvided) {
        this.errorShow = true;
      }
    });
  }

  errorShow = false;
  errorObject = {
    data: {
      description:
        'Выбраны записи граждан с разными статусами, для которых нет общих целей вызова в военкомат. Необходимо разбить список граждан на несколько.',
    },
  };

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

  get blockCriminalRecruit(): { result: boolean; message: string } {
    let result = true;
    const { adult, teen } = this.selectedItems.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.selectedItems.length !== teen;
    } else if (adult && teen === 0) {
      result = this.selectedItems.length !== adult;
    }
    return { result, message: result ? differentAgeMessage : '' };
  }

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

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

  checkScope(): boolean {
    return hasPermissionToAddToList(this.$AC);
  }

  get buttonCode(): ButtonCode {
    return {
      addToList: 'citizens_list_add',
      addToNewList: 'citizens_list_new',
    };
  }
}
</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>
