<template>
  <div v-if="requisition" class="deal-req-card mr-4 sm:w-1/2 md:w-1/3 lg:w-full p-2 flex">
    <div class="p-4 w-full">
      <div class="stage mb-3">{{ typeReq }}</div>
      <div class="flex items-center">
        <div class="created_at">{{ formattedDate }}</div>

        <div class="progress-bar-container ml-4 flex w-full">
          <div class="progress-bar flex">
            <div
                v-for="(step, index) in steps"
                :key="index"
                class="progress-step"
                :class="{
                  'step-completed': index < requisition.stage_index,
                  'step-current': index === requisition.stage_index,
                  'step-pending': index > requisition.stage_index
                }"
            >
            </div>
          </div>
        </div>

        <div class="stage-current ml-4"> {{ requisition.current_stage_name || currentStageName }}</div>

        <div class="ml-auto cursor-pointer" @click="closeDealRequisition">
          <img src="@/shared/assets/icons/close.svg" alt="Close">
        </div>
      </div>
      <div class="mt-4 flex justify-between items-center">
        <p class="title">{{ requisition.name }}</p>
        <button class="history-task ml-auto flex req-events-new" :data-id="requisition.id">
          <img src="@/shared/assets/icons/history-task.svg" alt="История и задачи">
          <span class="ml-4">История и задачи</span>
        </button>
      </div>

      <div class="mt-4 grid grid-cols-1 min-[2560px]:grid-cols-2 gap-2">
        <!-- Основной клиент -->
        <div>
          <div class="client flex justify-between items-center">
            <div class="client-name flex space-x-1">
              <span>Клиент:</span>
              <p class="client-name-value cursor-pointer neweditClient" :data-id="props.requisition.client ? props.requisition.client.id : ''" :title="props.requisition.client ? props.requisition.client.fio : 'Клиент удален'">
                {{ truncatedClientName }}
              </p>
            </div>
            <div class="client-info flex items-center space-x-4">
              <div class="client-phone flex space-x-1">
                <span>Телефон:</span>
                <p class="client-phone-value">{{ props.requisition.client ? props.requisition.client.phone : 'Клиент удален' }}</p>
              </div>
              <button class="history-task flex client-events-new" :data-id="props.requisition.client ? props.requisition.client.id : ''" @click="openHistoryClient(props.requisition.client ? props.requisition.client.id : '')">
                <img src="@/shared/assets/icons/history-task.svg" alt="История и задачи">
              </button>
            </div>
          </div>
        </div>

        <!-- Дополнительные клиенты стороны 1 -->
        <template v-if="props.deal.side_one_clients && props.deal.side_one_clients.length > 0 && props.side === 'sideOne'">
          <div v-for="(client, index) in props.deal.side_one_clients" :key="index">
            <div class="client flex justify-between items-center">
              <div class="client-name flex space-x-1">
                <span>Клиент:</span>
                <p class="client-name-value cursor-pointer neweditClient" :data-id="client.id" :title="client.fio">
                  {{ truncateText(client.fio, 12) }}
                </p>
              </div>
              <div class="client-info flex items-center space-x-4">
                <div class="client-phone flex space-x-1">
                  <span>Телефон:</span>
                  <p class="client-phone-value">{{ client.phone }}</p>
                </div>
                <button class="history-task flex client-events-new" :data-id="client.id" @click="openHistoryClient(client ? client.id : '')">
                  <img src="@/shared/assets/icons/history-task.svg" alt="История и задачи">
                </button>
              </div>
            </div>
          </div>
        </template>

        <!-- Дополнительные клиенты стороны 2 -->
        <template v-if="props.deal.side_two_clients && props.deal.side_two_clients.length > 0 && props.side === 'sideTwo'">
          <div v-for="(client, index) in props.deal.side_two_clients" :key="index">
            <div class="client flex justify-between items-center">
              <div class="client-name flex space-x-1">
                <span>Клиент:</span>
                <p class="client-name-value cursor-pointer neweditClient" :data-id="client.id" :title="client.fio">
                  {{ truncateText(client.fio, 12) }}
                </p>
              </div>
              <div class="client-info flex items-center space-x-4">
                <div class="client-phone flex space-x-1">
                  <span>Телефон:</span>
                  <p class="client-phone-value">{{ client.phone }}</p>
                </div>
                <button class="history-task flex client-events-new" :data-id="client.id" @click="openHistoryClient(client ? client.id : '')">
                  <img src="@/shared/assets/icons/history-task.svg" alt="История и задачи">
                </button>
              </div>
            </div>
          </div>
        </template>

        <!-- Dropdown для выбора клиентов -->
        <div>
          <div class="client flex justify-between items-center">
            <div class="flex-grow">
              <MultiSelect
                  v-if="Array.isArray(clientsList)"
                  v-model="selectedClientIds"
                  :options="clientsList"
                  optionLabel="fio"
                  optionValue="id"
                  placeholder="Выбрать клиента"
                  class="w-full choiceDealClient hide-selected-values"
                  :maxSelectedLabels="3"
                  :filter="true"
                  :virtualScrollerOptions="{ itemSize: 40 }"
              >
                <template #value>
                  <span class="p-multiselect-placeholder">Выбрать клиента</span>
                </template>
                <template #dropdownicon>
                  <DropdownIcon />
                </template>
              </MultiSelect>
            </div>
            <div class="ml-2">
              <a href="javascript:{}" class="add_client_new" style="border: none;" @click="onAddClientClick">
                <img src="@/shared/assets/icons/plus-green.svg" alt="Добавить клиента" class="w-6 h-6">
              </a>
            </div>
          </div>
        </div>

      </div>

      <div class="mt-4 flex items-center req-id">
        <p>ID: {{ requisition.id }}</p>
        <p v-if="requisition.user" class="ml-4">Добавил {{ requisition.user.full_name }}</p>
        <p v-if="requisition.worker" class="ml-4">В работе у {{ requisition.worker.full_name }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch, nextTick } from 'vue';

import dayjs from 'dayjs';
import ru from 'dayjs/locale/ru';

import DropdownIcon from "@/shared/assets/icons/dropdown-icon.vue";

const props = defineProps({
  requisition: {
    type: Object,
    required: true
  },
  side: {
    type: String, // 'sideOne' или 'sideTwo'
    required: true
  },
  deal: {
    type: Object,
    required: true
  },
  clientsList: {
    type: Array,
    required: true,
  },
});

const emit = defineEmits(['closeDealRequisition', 'refreshClients']);

const selectedClientIds = ref([]);
let isUpdating = false;

watch(() => props.deal.side_one_clients, (newVal) => {
  if (isUpdating) return;
  if (props.side === 'sideOne' && newVal) {
    selectedClientIds.value = newVal.map(c => c.id);
  }
}, { deep: true });

watch(() => props.deal.side_two_clients, (newVal) => {
  if (isUpdating) return;
  if (props.side === 'sideTwo' && newVal) {
    selectedClientIds.value = newVal.map(c => c.id);
  }
}, { deep: true });

watch(selectedClientIds, (newIds) => {
  isUpdating = true;
  const selectedClients = props.clientsList.filter(c => newIds.includes(c.id));
  if (props.side === 'sideOne') {
    props.deal.side_one_clients = selectedClients;
  } else if (props.side === 'sideTwo') {
    props.deal.side_two_clients = selectedClients;
  }
  nextTick(() => { isUpdating = false; });
});

// // Выбранные клиенты
// const selectedClient = ref([]);
//
// // Инициализация выбранных клиентов при монтировании
// onMounted(() => {
//   if (props.side === 'sideOne' && props.deal.side_one_clients) {
//     selectedClient.value = props.deal.side_one_clients;
//   } else if (props.side === 'sideTwo' && props.deal.side_two_clients) {
//     selectedClient.value = props.deal.side_two_clients;
//   }
// });
//
// // Следим за изменениями selectedClient
// watch(selectedClient, (newValue) => {
//   if (props.side === 'sideOne') {
//     props.deal.side_one_clients = newValue;
//   } else if (props.side === 'sideTwo') {
//     props.deal.side_two_clients = newValue;
//   }
// });


const formattedDate = computed(() => {
  dayjs.locale(ru);
  return dayjs(props.requisition.created_at).locale('ru').format('D MMMM YYYY');
});

const truncateText = (text, maxLength) => {
  if (text.length > maxLength) {
    return text.slice(0, maxLength) + '...';
  }
  return text;
};

const truncatedClientName = computed(() => {
  return props.requisition.client ? truncateText(props.requisition.client.fio, 12) : 'Клиент удален';
});

// Обработка закрытия заявки
const closeDealRequisition = () => {
  //isVisible.value = false; // Скрываем компонент
  emit('closeDealRequisition', props.side); // Отправляем событие родителю
};

const openHistoryClient = (clientId) => {
  if (clientId) {
    openClientEventsWindowNew(clientId, 'Array', 0);
  } else {
    console.error('ID клиента не найден!');
  }
};

const onAddClientClick = () => {
  console.log('[RequisitionDetails] onAddClientClick — registruem listener deal:clientCreated');
  window.addEventListener('deal:clientCreated', function handler(e) {
    console.log('[RequisitionDetails] deal:clientCreated poluchen:', e.detail);
    window.removeEventListener('deal:clientCreated', handler);
    console.log('[RequisitionDetails] listener udalen, emit refreshClients');
    emit('refreshClients');
  });
  console.log('[RequisitionDetails] listener zaregistrirovan');
};


// Переменные для шагов
const steps = ref([]);
const currentStageName = ref("");

watch(
    () => props.requisition,
    (newRequisition) => {
      // if (newRequisition.funnel_id === 0) {
      //   steps.value = [
      //     "Новый",
      //     "В работе",
      //     "Презентация",
      //     "Показ",
      //     "Бронь",
      //     "Подаем на ипотеку",
      //     "Сделка",
      //     "Закрыт",
      //   ];
      //   currentStageName.value =
      //       steps.value[newRequisition.stage - 1] || "Неизвестный шаг";
      // } else {
      //
      //   // Берём шаги из funnel_steps
      //   if (newRequisition.funnel_steps && Array.isArray(newRequisition.funnel_steps)) {
      //     steps.value = newRequisition.funnel_steps.map(step => step.name);
      //   } else {
      //     steps.value = [];
      //   }
      //
      //   currentStageName.value =
      //       newRequisition.funnel_steps?.[newRequisition.stage - 1]?.name ||
      //       "Неизвестный шаг";
      // }

      if (newRequisition.funnel_steps && Array.isArray(newRequisition.funnel_steps)) {
        steps.value = newRequisition.funnel_steps.map(step => step.name);
      } else if (newRequisition.funnel_id === 0) {
        // Дефолтная воронка
        steps.value = ["Новый", "В работе", "Презентация", "Показ", "Бронь", "Подаем на ипотеку", "Сделка", "Закрыт"];
      } else {
        steps.value = [];
      }
      console.log('newRequisition:', newRequisition);
      console.log('steps:', steps.value);
    },
    { immediate: true }
);


const typeReq = computed(() => {
  if (props.requisition?.type?.name) {
    return props.requisition.type.name;
  }

  if (props.requisition?.type_name) {
    return props.requisition.type_name;
  }

  const REQ_TYPES = {
    1: "Подбор объекта",
    2: "Реализация объекта",
    3: "Другие услуги",
    4: "Спрос по нашему объекту",
  };
  return REQ_TYPES[props.requisition?.type_id] || "Неизвестный тип услуги";
});

</script>

<style>
.deal-req-card {
  background: linear-gradient(360deg, #F5F5F5 0%, #FFFFFF 100%);
  border: 1px solid #E0E0E0;
  border-radius: 5px;
  padding: 10px;

  .created_at, .stage, .stage-current, .req-id p {
    font-family: 'Lato',sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 100%;
    color: #757575;
  }
  .title {
    font-family: 'Lato',sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 18px;
    line-height: 22px;
    text-decoration-line: underline;
    color: #000000;
  }
  .history-task {
    box-sizing: border-box;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 10px;
    background: linear-gradient(360deg, #F5F5F5 0%, #FFFFFF 100%);
    border: 1px solid #CDCED0;
    border-radius: 3px;

    span {
      font-family: 'Lato', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 14px;
      line-height: 100%;
      display: flex;
      align-items: center;
      text-align: center;
      color: #848484;
    }
  }

  .client {
    font-family: 'Lato', sans-serif;
    font-weight: 400;
    font-style: normal;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: center;
    font-size: 14px;
    line-height: 17px;
    align-content: flex-start;
    padding: 5px 10px;
    background: #FFFFFF;
    opacity: 0.8;
    border: 1px solid #E0E0E0;
    border-radius: 3px;
    height: 48px;
    box-sizing: border-box;

    .client-name {
      padding: 0;
      border: none;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      min-width: 0;
    }

    .client-info {
      height: auto;
      width: auto;
      white-space: nowrap;
    }

    span {
      color: #757575;
      margin-right: 5px;
    }
    p {
      text-decoration-line: underline;
      color: #000000;
      margin: 0;
    }
    .p-multiselect.p-inputwrapper.choiceDealClient {
      width: 100%!important;
      border: none;
      padding: 0 !important;
    }
    .p-multiselect .p-multiselect-label.p-placeholder {
      font-family: 'Lato', sans-serif;
      font-style: normal;
      font-weight: 400;
      color: #000000;
    }
  }

  .progress-bar-container {
    max-width: 250px;
  }

  .progress-bar {
    display: flex;
    width: 100%;
    height: 10px;
    overflow: hidden;
    border-radius: 4px;
    border: 1px solid #DEDEDE;
    background-color: #fff;
  }

  .progress-step {
    flex: 1;
    position: relative;
  }
  .step-completed {
    background-color: #5cb85c;
  }
  .step-current {
    background-color: #e2574c;
    opacity: 0.2;
  }
  .step-pending {
    background-color: #fff;
  }
  .progress-step::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 2px;
    background-color: #DEDEDE;
    z-index: 1;
  }
  .progress-step:first-child::before {
    display: none;
  }

  .hide-selected-value .p-multiselect-chip-item {
    display: none !important;
  }

}
</style>
