<template>
    <section v-if="!addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <h2 v-if="!editable" :class="['maintenance-visits-template-name', darkMode ? 'h2-darkmode' : 'h2-lightmode']">{{
            mvt.name }}</h2>
        <input v-if="editable" v-model="mvt.name" @change="updateMVT()"
            :class="['data', 'mvt-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
        <div class="maintenance-visits-template-data">
            <div class="customer-ID-type-user">
                <div class="data-field" id="customer">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer:</pre>
                    <pre v-if="!editable"
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvt.customer }}</pre>
                    <select v-if="editable" id="customersDropDownChosenCI" v-model="mvt.customer"
                        @change="updateCustomerID()" :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                        <option v-for="cust in customers" :key="cust.primaryID">
                            {{ cust.customername }}
                        </option>
                    </select>
                </div>
                <div class="data-field" id="info">
                    <div class="id-type-user" id="ID">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">ID:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvt.checklistID }}</pre>
                    </div>
                    <div class="id-type-user" id="type">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Type:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvt.type }}</pre>
                        <input v-if="editable" v-model="mvt.type" @change="updateMVT()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="id-type-user" id="user">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">User:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvt.user }}</pre>
                        <input v-if="editable" v-model="mvt.user" @change="updateMVT()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
            </div>
        </div>
        <div class="maintenance-visits-template-data">
            <div class="additional">
                <div class="notes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Notes:</h3>
                    <input v-model="mvt.notes" :readonly="!editable" @change="updateMVT()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
                </div>
            </div>
        </div>
    </section>
    <section v-if="addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <input v-model="newName" @change="updateMaintenanceVisit()"
            :class="['data', 'maintenance-visits-template-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
        <div class="maintenance-visits-template-data">
            <div class="customer-ID-type-user">
                <div class="data-field" id="customer">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer:</pre>
                    <select id="customersDropDownChosenCI" v-model="newCustomer" @change="updateNewCustomerID()"
                        :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                        <option v-for="cust in customers" :key="cust.primaryID">
                            {{ cust.customername }}
                        </option>
                    </select>
                </div>
                <div class="data-field" id="info">
                    <div class="id-type-user" id="ID">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">ID:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">...</pre>
                    </div>
                    <div class="id-type-user" id="type">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Type:</pre>
                        <input v-model="newType" @change="updateMaintenanceVisit()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="id-type-user" id="user">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">User:</pre>
                        <input v-model="newUser" @change="updateMaintenanceVisit()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
            </div>
        </div>
        <div class="maintenance-visits-template-data">
            <div class="additional">
                <div class="notes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Notes:</h3>
                    <input v-model="newNotes" @change="updateMaintenanceVisit()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
                </div>
            </div>
        </div>
    </section>
</template>
    
    
<script setup>
import { ref, onMounted, watch } from 'vue';
import Axios from '../axios.config.js';
import clientsideConfig from '../../clientsideConfig.js';
import { useStore } from 'vuex';
import { computed } from 'vue';

const store = useStore();
const editable = computed(() => store.state.editable);
const chosenMVTId = computed(() => store.state.chosenMVTId);
const deleteBool = computed(() => store.state.deleteBool);
const addBool = computed(() => store.state.new);

const darkMode = ref(true)
const mvt = ref({});
const customers = ref([]);
const customer = ref({});
const maintenanceVisitTemplates = ref([]);

const newName = ref('');
const newCustomerID = ref('');
const newCustomer = ref('');
const newUser = ref('');
const newType = ref('');
const newNotes = ref('');

//get all customers
const getCustomers = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getAllCustomers`
        );
        customers.value = response.data;
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// function to delete a maintenance visit template
const confirmDeleteMVT = async () => {
    if (deleteBool.value === true) {
        if (confirm("Do you really want to delete this maintenance visit template? It cannot be undone!")) {
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteMaintenanceVisitTemplate/${chosenMVTId.value}`);
                store.commit('undoDelete');
                store.commit('resetStore');
                store.commit('changeToTemplatelist');
            } catch (err) {
                console.log(err.response.statusText);
            }
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteTodosMVT/${chosenMVTId.value}`);
            } catch (err) {
                console.log(err.response.statusText);
            }
        } else {
            store.commit('undoDelete');
        }
    }
}

//get all maintenance visit templates
const getMaintenanceVisitTemplates = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getAllMaintenanceVisitTemplates`);
        maintenanceVisitTemplates.value = response.data;
    } catch (err) {
        console.log(err.response.statusText);
    }
}

//update data
const updateMVT = async () => {
    if (mvt.value.name.trim() === "") {
        alert("Please add a maintenance visit template name!");
        return;
    } else {
        var counter = 0;
        // check if maintenance visit template name already exists
        maintenanceVisitTemplates.value.forEach(m => {
            if (m.name === mvt.value.name) {
                counter += 1;
            }
        });
        if (counter == 2) {
            alert("This maintenance visit template name already exists. Please choose an unique production order template name or modify respectively delete the old one!");
            mvt.value.name = '';
            return;
        }
        try {
            await Axios.put(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateMaintenanceVisitTemplate`,
                {
                    checklistID: mvt.value.checklistID,
                    name: mvt.value.name,
                    customerID: mvt.value.customerID,
                    customer: mvt.value.customer,
                    lastView: mvt.value.lastView,
                    user: mvt.value.user,
                    type: mvt.value.type,
                    notes: mvt.value.notes,
                }
            )
            await getMVTById();
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

// update customerid if customer was changed
const updateCustomerID = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCustomerByName/${mvt.value.customer}`);
        customer.value = response.data;
        mvt.value.customerID = customer.value.customerID;
        store.commit('toggleCustomerChanged');
        store.commit('toggleCustomerId', mvt.value.customerID);
    } catch (err) {
        console.log(err.response.statusText);
    }
    await updateMVT();
}

// get maintenance visit template from id
const getMVTById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getMaintenanceVisitTemplate/${chosenMVTId.value}`
            );
            mvt.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

// update customerid if customer was changed
const updateNewCustomerID = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCustomerByName/${newCustomer.value}`);
        newCustomerID.value = response.data.customerID;
        store.commit('toggleCustomerChanged');
        store.commit('toggleCustomerId', newCustomerID.value)
    } catch (err) {
        console.log(err.response.statusText);
    }
    updateMaintenanceVisit();
}

// update maintenance visit template fields in the store
const updateMaintenanceVisit = () => {
    const maintenanceVisitTemplate = {
        name: newName.value,
        customerId: newCustomerID.value,
        customer: newCustomer.value,
        user: newUser.value,
        type: newType.value,
        notes: newNotes.value
    };
    store.commit('updateMaintenanceVisitTemplateComponent', maintenanceVisitTemplate);
}

// include delay to avoid 503 error
const triggerBackendCallsWithDelay = async (fetchDataFunc) => {
    setTimeout(() => {
        fetchDataFunc();
    }, 1500);
}

watch(deleteBool, confirmDeleteMVT);

onMounted(() => {
    getMVTById();
    triggerBackendCallsWithDelay(getMaintenanceVisitTemplates);
    triggerBackendCallsWithDelay(getCustomers);
});

</script>

<script>
export default {
    name: "MaintenanceVisitsTemplate",
};
</script>   
      
      
      
<style scoped>
.information {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    width: 100%;
    padding: 1.25rem 1.875rem;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.data {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    padding: 0 0.625rem;
    border-radius: 0.3125rem;
    box-shadow: 0.0625rem 0.0625rem 0.25rem 0rem rgba(0, 0, 0, 0.25) inset;
    letter-spacing: 5%;
    font: 400 0.75rem/250% Overpass, sans-serif;
}

.section-darkmode {
    background-color: #2c2c2c;
}

.section-lightmode {
    background-color: #fff;
}

.select-darkmode {
    border: none;
    color: white;
    background: #212121;
    padding: 0.4rem;
    border-radius: 0.3125rem;
}

.select-lightmode {
    border: none;
    color: black;
    background: #EBEBEB;
    padding: 0.4rem;
    border-radius: 0.3125rem;
}

.maintenance-visits-template-name {
    align-self: stretch;
    padding: 1rem 0;
    letter-spacing: 5%;
    text-decoration-line: underline;
    font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
        sans-serif;
}

.maintenance-visits-template-name-input {
    padding: 0 0.625rem;
    margin: 1rem;
    font-size: initial;
    letter-spacing: 5%;
    text-decoration-line: underline;
    font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
        sans-serif;
}

.h2-darkmode {
    color: #fff;
}

.h2-lightmode {
    color: #000;
}

.data-field {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    width: 95%;
    padding: 0.8rem 1.875rem;
    gap: 1.25rem;
    border-radius: 0.625rem;
}

.h2-input-darkmode {
    background-color: #212121;
}

.h2-input-lightmode {
    background-color: #EBEBEB;
}

.input {
    border: none;
}

.id-type-user {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    width: 100%;
    padding: 0 0rem;
    gap: 1.25rem;
    border-radius: 0.625rem;
}

.label {
    letter-spacing: 5%;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

.pre-darkmode {
    color: #fff;
}

.pre-lightmode {
    color: #000;
}

.data-darkmode {
    background-color: #212121;
    color: #fff;
}

.data-lightmode {
    background-color: #EBEBEB;
    color: #000;
}

.mvt-name-input {
    padding: 0 0.625rem;
    margin: 1rem;
    font-size: initial;
    letter-spacing: 5%;
    text-decoration-line: underline;
    font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
        sans-serif;
}

.maintenance-visits-template-data {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    align-self: stretch;
}

.customer-ID-type-user,
.info {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    line-height: normal;
    width: 100%;
    padding: 0 0;
    border-radius: 0.3125rem;
}

.additional {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    line-height: normal;
    width: 100%;
    padding: 0rem 0.625rem;
    border-radius: 0.3125rem;
}

.area-title {
    letter-spacing: 5%;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

.h3-darkmode {
    color: #fff;
}

.h3-lightmode {
    color: #000;
}

.type-user {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-self: stretch;
    padding: 0 1.875rem 0 0;
    gap: 0.625rem;
}

.data#notes {
    align-self: stretch;
}

.notes {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    align-self: stretch;
    padding: 0.625rem 1.875rem 0.625rem 1.25rem;
    padding-top: 0rem;
}
</style>