<script setup>
import {ref, computed, onMounted, watch} from 'vue'
import {useAuthStore} from '@/stores/Auth'
import Flatpickr from 'vue-flatpickr-component'
import 'flatpickr/dist/flatpickr.css'
import {Russian} from 'flatpickr/dist/l10n/ru.js'

const authStore = useAuthStore()

// Данные
const range = ref({start: '', end: ''})
const selectedFreq = ref(null)
const requests = ref([])
const selectedRequest = ref(null)
const points = ref([])
const selectedDistrict = ref(null)
const selectedSubManager = ref(null)
const districts = ref([])
const subManagers = ref([])
const duplicatedPoints = ref([]);
const duplicateMessage = ref('');

// Смены и расчёты
const shifts = ref([
  {start: '08:00', end: '12:00'},
  {start: '13:00', end: '17:00'},
])
const shiftsPerDay = shifts.value.length
const operatorsNeeded = computed(() => {
  const days = workingDaysCount.value
  const pts = filteredPoints.value.length
  const cap = days * shiftsPerDay
  return cap ? Math.ceil(pts / cap) : 0
})

// Праздники
const holidayDates = [
  '2025-01-01', '2025-01-07', '2025-03-08',
  '2025-05-01', '2025-05-02', '2025-05-08',
  '2025-05-09', '2025-06-12', '2025-06-13',
  '2025-11-03', '2025-11-04', '2025-12-31',
]

// Flatpickr config
const fpConfig = {
  dateFormat: 'Y-m-d',
  altInput: true,
  altFormat: 'd.m.Y',
  locale: {...Russian, firstDayOfWeek: 1},
  disable: [
    d => d.getDay() === 0 || d.getDay() === 6,
    ...holidayDates.map(d => new Date(d)),
  ],
}

// Вычисляемые свойства
const workingDays = computed(() => {
  const days = []
  const s = new Date(range.value.start)
  const e = new Date(range.value.end)
  for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) {
    const iso = d.toISOString().slice(0, 10)
    if (d.getDay() === 0 || d.getDay() === 6) continue
    if (holidayDates.includes(iso)) continue
    days.push(iso)
  }
  return days
})
const workingDaysCount = computed(() => workingDays.value.length)

const filteredByFreq = computed(() => {
  if (selectedFreq.value === null) return points.value
  return points.value.filter(pt => Number(pt.monitoring_freq) === selectedFreq.value)
})

const districtOptions = computed(() => districts.value)

const filteredPoints = computed(() => {
  let res = filteredByFreq.value
  // Фильтр по району
  if (selectedDistrict.value) {
    res = res.filter(pt => pt.district_id === selectedDistrict.value)
  }
  // Фильтр по менеджеру подгруппы (через район у точки)
  if (selectedSubManager.value) {
    // Найдём район для каждой точки
    res = res.filter(pt => {
      // Найди район по id
      const district = districts.value.find(d => d.id === pt.district_id)
      return district && district.subgroup_manager_id === selectedSubManager.value
    })
  }
  return res
})

const usedSubManagers = computed(() => {
  // Оставь только тех, кто есть хотя бы в одном районе
  const managerIds = new Set(districts.value.map(d => d.subgroup_manager_id).filter(Boolean))
  return subManagers.value.filter(mgr => managerIds.has(mgr.id))
})

// Загрузка данных
async function loadRequests() {
  const {response: reqRes, error: reqErr} = await authStore.getRequests()
  if (!reqErr) requests.value = reqRes.data
}

async function loadDistrictsAndSubManagers() {
  const {response, error} = await authStore.getDistrictsAndSubgroupManagers()
  if (!error) {
    districts.value = response.data.districts
    subManagers.value = response.data.subManagers
  }
}

async function loadPoints() {
  if (selectedRequest.value) {
    const {response: ptsRes, error: ptsErr} = await authStore.getPointsByRequest(selectedRequest.value)
    if (!ptsErr) points.value = ptsRes.data.points
  } else {
    const {response: allRes, error: allErr} = await authStore.getPointList()
    if (!allErr) points.value = allRes.data.points
  }
}

onMounted(async () => {
  const today = new Date().toISOString().slice(0, 10)
  range.value = {start: today, end: today}

  await loadRequests()
  await loadPoints()
  await loadDistrictsAndSubManagers()
})

// Ребнд по смене заявки
watch(selectedRequest, () => loadPoints())

// Генерация плана
async function generatePlan() {
  duplicatedPoints.value = [];
  duplicateMessage.value = '';

  if (!selectedRequest.value) {
    alert('Пожалуйста, выберите заявку.')
    return
  }

  const payload = {
    date_start: range.value.start,
    date_end: range.value.end,
    shifts: shifts.value,
    point_ids: filteredPoints.value.map(pt => pt.id),
    request_id: selectedRequest.value,
    district_id: selectedDistrict.value,
    subgroup_manager_id: selectedSubManager.value,
  }

  const {response, error} = await authStore.generatePointPlans(payload);

  // Проверка на дубли по точкам (422 или просто error.duplicated_points)
  if (error && error.duplicated_points) {
    duplicateMessage.value = error.message || 'Есть дубли по точкам:';
    duplicatedPoints.value = error.duplicated_points;
    return;
  }

  // Любая другая ошибка
  if (error) {
    alert(error.message || 'Ошибка генерации');
    return;
  }

  // Успешно
  duplicateMessage.value = '';
  duplicatedPoints.value = [];

  alert(`Создано записей: ${response.rows_created}`);
}

</script>

<template>
  <div class="container my-4">
    <!-- Выбор периода -->
    <div class="row mb-3">
      <div class="col-md-3">
        <label>С:</label>
        <Flatpickr v-model="range.start" :config="fpConfig" class="form-control"/>
      </div>
      <div class="col-md-3">
        <label>По:</label>
        <Flatpickr v-model="range.end" :config="fpConfig" class="form-control"/>
      </div>
      <div class="col-md-3 d-flex align-items-end">
        <button class="btn btn-success" @click="generatePlan">
          Сгенерировать работы
        </button>
      </div>
    </div>

    <!-- Фильтры и статистика -->
    <div class="row mb-3 align-items-center">
      <!-- Фильтр по заявке -->
      <div class="col-md-4">
        <label><strong>Заявка:</strong></label>
        <select v-model="selectedRequest" class="form-select">
          <option :value="null">Все заявки</option>
          <option v-for="r in requests" :key="r.id" :value="r.id">{{ r.name }}</option>
        </select>
      </div>
      <div class="col-md-4">
        <label><strong>Район:</strong></label>
        <select v-model="selectedDistrict" class="form-select">
          <option :value="null">Все районы</option>
          <option v-for="d in districtOptions" :key="d.id" :value="d.id">{{ d.name }}</option>
        </select>
      </div>
      <div class="col-md-4">
        <label><strong>Менеджер подгруппы:</strong></label>
        <select v-model="selectedSubManager" class="form-select">
          <option :value="null">Все менеджеры</option>
          <option v-for="mgr in usedSubManagers" :key="mgr.id" :value="mgr.id">
            {{ mgr.last_name }} {{ mgr.first_name }}
          </option>
        </select>
      </div>
      <div class="col-md-4">
        Точек для генерации: <strong>{{ filteredPoints.length }}</strong>
      </div>
      <div class="col-md-4">
        Рабочих дней: <strong>{{ workingDaysCount }}</strong>
      </div>
      <div class="col-md-12 alert alert-info">
        Необходимо операторов: <strong>{{ operatorsNeeded }}</strong>
      </div>
    </div>

    <div v-if="duplicatedPoints.length" class="alert alert-danger mb-3">
      <div v-if="duplicateMessage">{{ duplicateMessage }}</div>
      <ul class="mb-0">
        <li v-for="(name, idx) in duplicatedPoints" :key="idx">
          {{ name }}
        </li>
      </ul>
    </div>
    <!-- Список точек -->
    <ul class="list-group mb-3">
      <li
          v-for="pt in filteredPoints"
          :key="pt.id"
          class="list-group-item d-flex justify-content-between"
      >
        {{ pt.name }}
        <span class="badge bg-secondary">
          {{ pt.monitoring_freq === 1 ? 'ежемесячно' : 'ежеквартально' }}
        </span>
      </li>
    </ul>
  </div>
</template>