<template>
  <div v-if="requisition" class="mt-3 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="flex items-center">
        <div class="created_at">{{ formattedDate }}</div>
        <div class="stage ml-4">{{ typeReq }}</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="{ 'bg-green-500': index < requisition.stage, 'bg-white': index >= requisition.stage }"
            >
            </div>
          </div>
        </div>

        <div class="stage-current ml-4"> {{ 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 flex flex-wrap">
        <!-- Основной клиент -->
        <div class="w-1/2 p-2">
          <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" class="w-1/2 p-2">
            <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" class="w-1/2 p-2">
            <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 class="w-1/2 p-2 flex justify-between items-center">
          <div class="client w-full">
            <MultiSelect
                v-if="Array.isArray(clientsList)"
                v-model="selectedClientIds"
                :options="clientsList"
                optionLabel="fio"
                optionValue="id"
                placeholder="Выбрать клиента"
                class="w-full choiceDealClient"
                :maxSelectedLabels="3"
                :filter="true"
                display="chip"
                :virtualScrollerOptions="{ itemSize: 40 }"
            >
              <template #dropdownicon>
                <DropdownIcon />
              </template>
            </MultiSelect>


          </div>

          <div class="p-4">
            <a href="javascript:{}" class="add_client_new" style="border: none;">
              <img src="@/shared/assets/icons/plus-green.svg" alt="Добавить клиента" class="w-6 h-6">
            </a>
          </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.fio }}</p>
        <p v-if="requisition.worker" class="ml-4">В работе у {{ requisition.worker.fio }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch } 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']); // Добавляем событие для закрытия

const selectedClientIds = ref([]);

onMounted(() => {
  if (props.side === 'sideOne' && props.deal.side_one_clients) {
    selectedClientIds.value = props.deal.side_one_clients.map(c => c.id);
  } else if (props.side === 'sideTwo' && props.deal.side_two_clients) {
    selectedClientIds.value = props.deal.side_two_clients.map(c => c.id);
  }
});

watch(selectedClientIds, (newIds) => {
  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;
  }
});

// // Выбранные клиенты
// 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 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 ||
            "Неизвестный шаг";
      }
      console.log('newRequisition:', newRequisition);
      console.log('steps:', steps.value);
    },
    { immediate: true }
);


const REQ_TYPES = {
  1: "Подбор объекта",
  2: "Реализация объекта",
  3: "Другие услуги",
  4: "Спрос по нашему объекту",
};

const typeReq = computed(() => {
  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: 10px 8px 8px 12px;
    background: #FFFFFF;
    opacity: 0.8;
    border: 1px solid #E0E0E0;
    border-radius: 3px;
    height: 60px;

    .client-name {
      padding: 0;
      border: none;
    }

    .client-info {
      height: auto;
      width: auto;
    }

    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;
    }
  }

  .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: #5cb85c;
  }

  .progress-step {
    flex: 1;
    position: relative;
  }
  .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;
  }

}
</style>
