<template>
    <div class="text-center m-3">
        <p class="h3"> Ваша заявка: </p>
        <p class=""> Дата: {{ this.request['date'].slice(0,10) ?? ''}} </p>
        <div class="h4"> 
            Специализация: 
            <button class="btn btn-secondary dropdown-toggle" type="button" id="examResult" data-bs-toggle="dropdown" aria-expanded="false">
                {{ specialization['title'] ?? '' }}
            </button>
            <ul class="dropdown-menu" aria-labelledby="examResult">
                <li v-for="spec in specializations">
                    <a class="dropdown-item" href="#" v-on:click="specialization=spec ">{{ spec['title'] ?? ''}}</a>
                </li>
            </ul>
        </div>
        <div class="h4"> 
            Форма обучения: 
            <button class="btn btn-secondary dropdown-toggle" type="button" id="examResult" data-bs-toggle="dropdown" aria-expanded="false">
                {{ educationForm['title'] ?? ''}}
            </button>
            <ul class="dropdown-menu" aria-labelledby="examResult">
                <li v-for="form in forms">
                    <a class="dropdown-item" href="#" v-on:click="educationForm=form ">{{ form['title'] ?? ''}}</a>
                </li>
            </ul>
        </div>

        <p class='h6 mt-3'>Закрепленные результаты:</p>
        <ul class='text-start ms-5'>
            <li v-for='result in results'>
                <p>
                    Предмет: {{ result['title'] ?? ''}}
                </p>
                <p>
                    Результат: {{ result['result'] ?? ''}}
                </p>
                <p>
                    <button @click="deleteResultClick(result['id'])" type="button" class="btn btn-danger ms-3" >
                        Удалить
                    </button>
                </p>
            </li>
        </ul>

        <p class="h6"> Добавить ваши результаты к заявке </p>
        <!-- <div class="dropdown">
            <button class="btn btn-secondary dropdown-toggle" type="button" id="examResult" data-bs-toggle="dropdown" aria-expanded="false">
                <div  v-if="selectedExamResult == null" >Выберите результат</div>
                <div v-else>{{ selectedExamResult['title'] }}: {{ selectedExamResult['result'] }} </div>
            </button>
            <ul class="dropdown-menu" aria-labelledby="examResult">
                <li v-for="result in allResults">
                    <a class="dropdown-item" href="#" v-on:click="selectedExamResult=result ">{{ result['title'] + ': ' + result['result']}}</a>
                </li>
            </ul>

            <button type="button" @click="addResultToRequest" class="btn btn-success p-3 ms-5"> Добавить </button>
        </div> -->
        <div>
            <div v-for="res in allResults" >
                <p>
                    <span class="me-4">{{res['title'] ?? '' }}: {{ res['result'] ?? '' }} баллов</span>
                    <button class="btn btn-info" @click="addResultToRequest(res)">Добавить</button>
                </p>
            </div>
        </div>

        <button type="button" @click="saveRequest" class="btn btn-primary p-3 ps-5 pe-5 mt-5">Сохранить</button>
    </div>
</template>
<script>
import axios from 'axios'
export default {
    data() {
        return {
            requestId: -1,
            request: null,
            educationForm: null,
            specialization: null,
            results: [],
            allResults: [],
            selectedExamResult: null,
            specializations: [],
            forms: []
        }
    },

    methods: {
        async deleteResultClick(id) {
            
            let data = JSON.stringify({
                "request_id": this.requestId,
                "exam_result_id": id
            });

            let config = {
                method: 'delete',
                maxBodyLength: Infinity,
                url: 'http://127.0.0.1:8080/api/request_examresult',
                headers: { 
                    'Content-Type': 'application/json'
                },
                data : data
            };

            axios.request(config)
                .then((response) => {
                console.log(JSON.stringify(response.data));
                })
                .catch((error) => {
                console.log(error);
                });
            window.location.reload()
        },

        async addResultToRequest(res) {
            const axios = require('axios');
            console.log('Save new result')
            console.log(this.requestId)
            console.log(res)
            var request_result_pairs = (await axios.get('http://127.0.0.1:8080/api/request_examresult/' + this.requestId)).data
            for (const pair of request_result_pairs) {
                if (pair['request_id'] == this.requestId && pair['exam_result_id']==res['id']) {
                    return;
                }
            }


            let data = JSON.stringify({
                "request_id": this.requestId,
                "exam_result_id": res['id']
            });

            let config = {
                method: 'post',
                maxBodyLength: Infinity,
                url: 'http://127.0.0.1:8080/api/request_examresult',
                headers: { 
                    'Content-Type': 'application/json'
                },
                data : data
            };

            axios.request(config)
                .then((response) => {
                console.log(JSON.stringify(response.data));
                })
                .catch((error) => {
                console.log(error);
            });
            window.location.reload()
        },

        async saveRequest() {
            const axios = require('axios');
            let data = JSON.stringify({
                "id": this.requestId,
                "education_form_id": this.educationForm['id'],
                "specialization_id": this.specialization['id'],
                "date": this.request['date']
            });

            let config = {
            method: 'put',
            maxBodyLength: Infinity,
            url: 'http://127.0.0.1:8080/api/request',
            headers: { 
                'Content-Type': 'application/json'
            },
            data : data
            };

            axios.request(config)
            .then((response) => {
            console.log(JSON.stringify(response.data));
            })
            .catch((error) => {
            console.log(error);
            });

            this.$router.push(
                {
                    name: "AbiturMain",
                    params: {
                        abiturId: this.request['abitur_id']
                    }
                }
            );
        }
    },

    async created() {
        // получаем заявку
        this.requestId = this.$route.params.requestId
        console.log(this.requestId)
        this.request = (await axios.get('http://127.0.0.1:8080/api/request/' + this.requestId)).data
        console.log(this.request)
        // получаем ее специализацию и форму обучения
        this.educationForm = (await axios.get('http://127.0.0.1:8080/api/educationform/' + this.request['education_form_id'])).data
        //console.log(this.educationForm)
        this.specialization = (await axios.get('http://127.0.0.1:8080/api/specialization/' + this.request['specialization_id'])).data
        console.log(this.specialization)
        //получаем закрепленные за заявкой результаты
        var request_result_pairs = (await axios.get('http://127.0.0.1:8080/api/request_examresult/' + this.requestId)).data
        for(const pair of request_result_pairs) {
            //console.log(pair)
            this.results.push((await axios.get('http://127.0.0.1:8080/api/examresult/' + pair['exam_result_id'])).data)
        }
       // console.log(this.results)
        //получаем все результаты абитуриента
        var allResults = (await axios.get('http://127.0.0.1:8080/api/examresult/abitur/' + this.request['abitur_id'])).data
        //console.log(allResults)
        //

        var flag = true;
        for (const allRes of allResults) {
            flag = true;
            for(const res of this.results) {
                if (allRes['id'] == res['id'])
                flag = false
            }
            if (flag) {
                this.allResults.push(allRes)
            }
        }

        // получаем все формы обучения и специализации
        this.specializations = (await axios.get('http://127.0.0.1:8080/api/specialization')).data
        this.forms = (await axios.get('http://127.0.0.1:8080/api/educationform')).data

    }
}
</script>
<style lang="">
    
</style>