<template>
  <div class="modal dealAddEmployee">
    <div class="modal-content">
      <span class="close" @click="closeModal">&times;</span>
      <h3 class="mb-4">Выберите сотрудников</h3>
      <MultiSelect
          v-model="selectedEmployeeIds"
          :options="employeesWithFullName"
          optionLabel="fullName"
          optionValue="id"
          placeholder="Выберите сотрудников"
          class="w-full"
          display="chip"
          :maxSelectedLabels="3"
          :filter="true"
      >
        <template #dropdownicon>
          <DropdownIcon />
        </template>
      </MultiSelect>
      <button @click="handleSelect" class="mt-4 p-2 rounded add-employee-btn">
        Выбрать
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits, watch, computed } from 'vue';
import MultiSelect from 'primevue/multiselect';
import DropdownIcon from "@/shared/assets/icons/dropdown-icon.vue";

const props = defineProps({
  employees: {
    type: Array,
    required: true,
  },
  selected: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['close', 'select']);

const selectedEmployeeIds = ref([]);

// Добавляем поле fullName для каждого сотрудника
const employeesWithFullName = computed(() => {
  return props.employees.map(employee => ({
    ...employee,
    fullName: employee.fio || `${employee.first_name} ${employee.last_name}`,
  }));
});

// Инициализируем selectedEmployeeIds при открытии модального окна
watch(() => props.selected, (newSelected) => {
  selectedEmployeeIds.value = newSelected.map(employee => employee.id);
}, { immediate: true });

const closeModal = () => {
  emit('close');
};

const handleSelect = () => {
  // Находим объекты сотрудников по их id
  const selectedEmployeeObjects = selectedEmployeeIds.value
      .map(id => props.employees.find(employee => employee.id === id))
      .filter(employee => employee !== undefined); // Убираем undefined, если сотрудник не найден

  // Передаем выбранных сотрудников в родительский компонент
  emit('select', selectedEmployeeObjects);
  closeModal();
};
</script>

<style>
.modal.dealAddEmployee {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);

  .modal-content {
    position: absolute;
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    width: 80%;
    max-width: 500px;
    text-align: center;
  }

  .close {
    position: absolute;
    top: 10px;
    right: 20px;
    font-size: 24px;
    cursor: pointer;
  }

  .p-multiselect {
    height: auto;
  }

  .add-employee-btn {
    background: #64A853;
    color: #fff;
    width: 50%;
  }
}
</style>