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

const router = useRouter();

const authStore = useAuthStore();
const displayMap = useDisplayMapStore();
const pointPlans = ref({point_plans: []});

const requestsList = ref([]);
const selectedRequest = ref(null);

const selectedYear = ref(null);
const selectedMonth = ref(null);
const selectedManager = ref(null);
const selectedDistrict = ref(null);
const selectedFrequency = ref(null);

const plans = () => {
  authStore
      .getPointPlanList()
      .then((response) => {
        pointPlans.value = response.response.data;
      })
      .catch((error) => console.log(error));
};

function formatDate(dateStr) {
  const date = new Date(dateStr);
  return date.toLocaleDateString('ru-RU');
}

onMounted(async () => {
  plans();
  try {
    const {response: rq} = await authStore.getRequests();
    if (rq) requestsList.value = rq.data;
  } catch (e) {
    console.error('Не удалось загрузить список заявок', e);
  }
});

const deletePlan = async (id) => {
  try {
    const {error} = await authStore.deletePointPlan(id);

    if (!error) {
      pointPlans.value.point_plans = pointPlans.value.point_plans.filter(p => p.id !== id);
      displayMap.triggerMapRefresh();
    }
  } catch (e) {
    console.error('Ошибка при удалении плана:', e);
  }
};

const availableYears = computed(() => {
  const years = pointPlans.value.point_plans.map((p) => p.schedule?.year).filter(Boolean);
  return [...new Set(years)].sort((a, b) => b - a);
});
const managers = computed(() => [
  ...new Map(
      pointPlans.value.point_plans
          .map((plan) => plan.point.district.manager)
          .filter((manager) => manager)
          .map((manager) => [manager.id, manager]),
  ).values(),
]);
const districts = computed(() => [
  ...new Map(
      pointPlans.value.point_plans.map((plan) => plan.point.district).map((district) => [district.id, district]),
  ).values(),
]);

const filteredPlans = computed(() => {
  return pointPlans.value.point_plans
      .filter((plan) => {
        const yearMatch = selectedYear.value ? plan.schedule.year === selectedYear.value : true;
        const monthMatch = selectedMonth.value ? new Date(plan.day).getMonth() + 1 === selectedMonth.value : true;
        const matchManager = selectedManager.value ? plan.point.district.manager?.id === selectedManager.value : true;
        const matchDistrict = selectedDistrict.value ? plan.point.district.id === selectedDistrict.value : true;
        const matchRequest = selectedRequest.value ? plan.request_id === selectedRequest.value : true;
        const matchFrequency = selectedFrequency.value
            ? Number(plan.point.monitoring_freq) === Number(selectedFrequency.value)
            : true;
        return yearMatch && monthMatch && matchManager && matchDistrict && matchRequest && matchFrequency;
      })
      .sort((a, b) => new Date(a.day) - new Date(b.day));
});
</script>

<template>
  <div class="container py-4">
    <div class="row justify-content-center">
      <div class="col-md-12">
        <div class="d-flex gap-3 mb-3">
          <select v-model="selectedYear" class="form-select w-auto">
            <option :value="null">Все года</option>
            <option v-for="year in availableYears" :key="year" :value="year">{{ year }}</option>
          </select>

          <select v-model="selectedMonth" class="form-select w-auto">
            <option :value="null">Все месяцы</option>
            <option v-for="month in 12" :key="month" :value="month">
              {{ new Date(0, month - 1).toLocaleString('ru-RU', {month: 'long'}) }}
            </option>
          </select>
          <select class="form-select" v-model="selectedDistrict">
            <option :value="null">Все районы</option>
            <option v-for="district in districts" :key="district.id" :value="district.id">
              {{ district.name }}
            </option>
          </select>
          <select class="form-select" v-model="selectedManager">
            <option :value="null">Все районные менеджеры</option>
            <option v-for="manager in managers" :key="manager.id" :value="manager.id">
              {{ manager.last_name }} {{ manager.first_name }} ({{ manager.middle_name }})
            </option>
          </select>
          <select class="form-select" v-model="selectedFrequency">
            <option :value="null">Все частоты</option>
            <option :value="1">Ежемесячно</option>
            <option :value="2">Ежеквартально</option>
          </select>
          <!-- Фильтр по заявке -->
          <select v-model="selectedRequest" class="form-select w-auto">
            <option :value="null">Все заявки</option>
            <option v-for="r in requestsList" :key="r.id" :value="r.id">
              {{ r.name }}
            </option>
          </select>
        </div>

        <table class="table table-bordered 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" style="width: 160px">
              Действия
            </th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="item in filteredPlans" :key="item.id" class="align-middle">
            <td class="text-center">{{ formatDate(item.day) }}</td>
            <td class="text-center">{{ item.timeStart }} - {{ item.timeEnd }}</td>
            <td class="text-center">{{ item.point.district.region.name }}</td>
            <td class="text-center">{{ item.point.district.name }}</td>
            <td class="text-center">
              {{ `${item.point.record_number ?? '-'}` }}
            </td>
            <td class="text-center">{{ item.point.name }}</td>
            <td class="text-center">
              <div v-if="item.subgroup_manager">
                Менеджер: {{ item.subgroup_manager.last_name }} {{ item.subgroup_manager.first_name }}
                {{ item.subgroup_manager.middle_name }}
              </div>
              <div v-if="item.counter">
                Учетчик: {{ item.counter.last_name }} {{ item.counter.first_name }}
              </div>
            </td>
            <td class="text-center">
              <div class="d-flex gap-1">
                <button v-if="authStore.hasPermission(['update-plan-chart-list'])"
                        type="button" class="btn btn-primary btn-sm"
                        @click="router.push({ name: 'point-plan-edit', params: { id: item.id } })">
                  Редактировать
                </button>
                <button v-if="authStore.hasPermission(['delete-plan-chart-list'])"
                        type="button" class="btn btn-danger btn-sm"
                        @click="deletePlan(item.id)">
                  Удалить
                </button>
              </div>
            </td>
          </tr>
          <tr v-if="!filteredPlans.length">
            <td class="text-center" colspan="6">Нет данных за выбранный период</td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
