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

const authStore = useAuthStore();

const requests = ref([]);
const districts = ref([]);
const seasons = [
  {value: 1, label: 'Лето'},
  {value: 2, label: 'Зима'},
];

const selectedRequest = ref(null);
const selectedDistrict = ref(null);
const selectedSeason = ref(1);
const actDate = ref(null);

onMounted(async () => {
  // загрузить заявки
  const {response: reqR} = await authStore.getRequests();
  requests.value = reqR.data;

  // загрузить районы
  const {response: distR} = await authStore.getRefDistricts();
  districts.value = distR.data;
});

const districtName = computed( () => {
  return selectedDistrict.value
      ? districts.value.find(d => d.id === selectedDistrict.value)?.name
      : 'Оренбургская область'
})

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

  await authStore.downloadKc2Template({
    request_id: selectedRequest.value,
    district_id: selectedDistrict.value,
    season: selectedSeason.value,
    act_date: actDate.value,
  }, districtName.value);
};
</script>

<template>
  <div class="container py-4">
    <h3>Акт выполненных работ (КС-2)</h3>

    <div class="row g-3 align-items-end">
      <div class="col-auto">
        <label>Заявка</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-auto">
        <label>Район</label>
        <select v-model="selectedDistrict" class="form-select">
          <option :value="null">Оренбургская область</option>
          <option v-for="d in districts" :key="d.id" :value="d.id">
            {{ d.name }}
          </option>
        </select>
      </div>

      <div class="col-auto">
        <label>Сезон</label>
        <select v-model="selectedSeason" class="form-select">
          <option v-for="s in seasons" :key="s.value" :value="s.value">
            {{ s.label }}
          </option>
        </select>
      </div>

      <div class="col-auto">
        <label>Дата акта</label>
        <input
            v-model="actDate"
            type="date"
            class="form-control"
        />
      </div>

      <div class="col-auto">
        <button
            class="btn btn-primary"
            :disabled="!selectedRequest"
            @click="downloadExcel"
        >
          Скачать Excel
        </button>
      </div>
    </div>
  </div>
</template>