<script setup>
import {ref, onMounted, computed, watch} from 'vue';
import {useAuthStore} from '@/stores/Auth';
import {useRouter} from 'vue-router';

const router = useRouter();
const authStore = useAuthStore();
const fullResponse = ref({});
const selectedRequestLabel = ref('');

onMounted(async () => {
  const {response, error} = await authStore.getPointList();
  if (response) {
    fullResponse.value = response.data;
  } else {
    console.error('Ошибка загрузки точек:', error);
  }
});
const selectedRegion = ref('');
const selectedDistrict = ref('');

const regions = computed(() => {
  const uniqueRegions = new Set();
  fullResponse.value.points?.forEach((p) => {
    if (p.district?.region?.name) {
      uniqueRegions.add(p.district.region.name);
    }
  });
  return Array.from(uniqueRegions);
});

const districts = computed(() => {
  const uniqueDistricts = new Set();
  fullResponse.value.points?.forEach((p) => {
    if (
        p.district?.name &&
        (!selectedRegion.value || p.district.region.name === selectedRegion.value)
    ) {
      uniqueDistricts.add(p.district.name);
    }
  });
  return Array
      .from(uniqueDistricts)
      .sort((a, b) => a.localeCompare(b, 'ru'));  // сортировка по-русски
});

watch(selectedRegion, () => {
  selectedDistrict.value = '';
});
const resetFilters = () => {
  selectedRegion.value = '';
  selectedDistrict.value = '';
  selectedCategory.value = '';
  selectedFrequency.value = '';
  selectedRequestLabel.value = '';
};

const selectedCategory = ref('');

const frequencyLabels = {
  1: 'Ежемесячно',
  2: 'Ежеквартально'
};

const selectedFrequency = ref('');

const uniqueCategories = computed(() => {
  const set = new Set();
  fullResponse.value.points?.forEach(p => {
    if (!p.road_category || p.road_category.length === 0) {
      set.add('Без категории');
    } else {
      (Array.isArray(p.road_category) ? p.road_category : [p.road_category]).forEach(cat => set.add(cat));
    }
  });
  return Array.from(set);
});

const uniqueFrequencies = computed(() => {
  const set = new Set();
  fullResponse.value.points?.forEach(p => {
    if (p.monitoring_freq != null) {
      set.add(p.monitoring_freq);
    }
  });
  return Array.from(set).sort((a, b) => a - b);
});

const requestLabels = computed(() => {
  const set = new Set();
  (fullResponse.value.points || []).forEach(p => {
    (p.requests || []).forEach(r => {
      set.add(r.name);
    });
  });
  return Array.from(set);
});

const filteredPoints = computed(() => {
  return (
      (fullResponse.value.points || []).filter((point) => {
        const regionMatch = selectedRegion.value ? point.district.region.name === selectedRegion.value : true;
        const districtMatch = selectedDistrict.value ? point.district.name === selectedDistrict.value : true;

        const categories = Array.isArray(point.road_category)
            ? point.road_category
            : typeof point.road_category === 'string'
                ? [point.road_category]
                : [];

        const hasNoCategory = !point.road_category || categories.length === 0;
        const matchesCategory = !selectedCategory.value ||
            (selectedCategory.value === 'Без категории' && hasNoCategory) ||
            categories.includes(selectedCategory.value);

        const matchesFreq = !selectedFrequency.value ||
            Number(point.monitoring_freq) === Number(selectedFrequency.value);

        const matchesRequestLabel =
            !selectedRequestLabel.value ||
            (point.requests || []).some(r => r.name === selectedRequestLabel.value);

        return regionMatch && districtMatch && matchesCategory && matchesFreq && matchesRequestLabel;
      }) || []
  );
});

const totalLength = computed(() => {
  return filteredPoints.value.reduce((sum, p) => sum + (parseFloat(p.length) || 0), 0).toFixed(2);
});

const categorySummary = computed(() => {
  const map = new Map();
  filteredPoints.value.forEach(p => {
    const cats = Array.isArray(p.road_category)
        ? p.road_category
        : typeof p.road_category === 'string'
            ? [p.road_category]
            : [];

    if (!cats.length) {
      map.set('Без категории', (map.get('Без категории') || 0) + 1);
    } else {
      cats.forEach(c => map.set(c, (map.get(c) || 0) + 1));
    }
  });
  return Array.from(map.entries())
      .map(([cat, count]) => `${cat} (${count})`)
      .join(', ');
});

</script>

<template>
  <div class="p-3">
    <div class="mb-3">
      <strong>Итого:</strong>
      <ul>
        <li>Количество ПУИДД: {{ filteredPoints.length }}</li>
        <li>Суммарная протяжённость: {{ totalLength }} км</li>
        <li>Категории: {{ categorySummary }}</li>
      </ul>
    </div>
    <div class="mb-3 d-flex gap-3 align-items-center">
      <div class="mb-3 d-flex gap-3 align-items-end">
        <div>
          <label class="form-label">Область:</label>
          <select v-model="selectedRegion" class="form-select">
            <option value="">Все</option>
            <option v-for="region in regions" :key="region" :value="region">
              {{ region }}
            </option>
          </select>
        </div>
        <div>
          <label class="form-label">Район:</label>
          <select v-model="selectedDistrict" class="form-select">
            <option value="">Все</option>
            <option v-for="district in districts" :key="district" :value="district">
              {{ district }}
            </option>
          </select>
        </div>
        <div>
          <label class="form-label">Категория:</label>
          <select v-model="selectedCategory" class="form-select">
            <option value="">Все</option>
            <option v-for="cat in uniqueCategories" :key="cat" :value="cat">
              {{ cat }}
            </option>
          </select>
        </div>
        <div>
          <label class="form-label">Частота:</label>
          <select v-model="selectedFrequency" class="form-select">
            <option value="">Все</option>
            <option v-for="freq in uniqueFrequencies" :key="freq" :value="freq">{{ frequencyLabels[freq] ?? freq }}
            </option>
          </select>
        </div>
        <div>
          <label class="form-label">Заявка:</label>
          <select v-model="selectedRequestLabel" class="form-select">
            <option value="">Все</option>
            <option v-for="label in requestLabels" :key="label" :value="label">
              {{ label }}
            </option>
          </select>
        </div>
        <div>
          <button @click="resetFilters" class="btn btn-outline-secondary">Сбросить фильтр
          </button>
        </div>
      </div>
    </div>

    <div class="table-responsive">
      <table class="table table-bordered table-striped table-hover">
        <thead>
        <tr>
          <th class="text-center bg-secondary text-white align-middle">Номер ПУИДД</th>
          <th class="text-center bg-secondary text-white align-middle">Название</th>
          <th class="text-center bg-secondary text-white align-middle">Протяжённость</th>
          <th class="text-center bg-secondary text-white align-middle">Пункт учёта</th>
          <th class="text-center bg-secondary text-white align-middle">Категория</th>
          <th class="text-center bg-secondary text-white align-middle">Тип учёта</th>
          <th class="text-center bg-secondary text-white align-middle">Признак</th>
          <th class="text-center bg-secondary text-white align-middle">Частота</th>
          <th class="text-center bg-secondary text-white align-middle">Координаты</th>
          <th class="text-center bg-secondary text-white align-middle" style="width: 160px">Действия</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="point in filteredPoints" :key="point.id" class="align-middle">
          <td>{{ `${point.record_number ?? '-'}` }}
          </td>
          <td>{{ point.name }}</td>
          <td>{{ point.length ?? '-' }}</td>
          <td>{{ point.accounting_point ?? '-' }}</td>
          <td>
            <template v-if="Array.isArray(point.road_category)">
              <span v-for="cat in point.road_category" :key="cat" class="me-1">{{ cat }}</span>
            </template>
            <template v-else>
              {{ point.road_category ?? '-' }}
            </template>
          </td>
          <td>{{ point.accounting_type ?? '-' }}</td>
          <td>{{ point.accounting_flag === 1 ? 'Подъезд' : point.accounting_flag === 2 ? 'Перегон' : '-' }}</td>
          <td>{{ frequencyLabels[point.monitoring_freq] ?? point.monitoring_freq ?? "-" }}</td>
          <td>{{ point.latitude ?? '-' }}, {{ point.longitude ?? '-' }}</td>
          <td>
            <div class="d-flex gap-1">
              <button v-if="authStore.hasPermission('update-point')" type="button" @click="router.push({ name: 'point-edit', params: { id: point.id } })"
                      class="btn btn-primary btn-sm">
                Редактировать
              </button>
            </div>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped></style>
