<template>
    <section v-if="!addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <h2 :class="['issueSlip-name', darkMode ? 'h2-darkmode' : 'h2-lightmode']">{{ issueSlip.primaryID }}</h2>
        <div class="issueSlip-data">
            <div class="client">
                <div class="data-field" id="client">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer:</pre>
                    <pre v-if="!editable"
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ issueSlip.customer }}</pre>
                    <select v-if="editable" id="customersDropDownChosenCI" v-model="issueSlip.customer"
                        @change="updateCustomerID()" :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                        <option v-for="cust in customers" :key="cust.primaryID">
                            {{ cust.customername }}
                        </option>
                    </select>
                </div>
            </div>
            <div class="info">
                <div class="ticketNo-user">
                    <div class="data-field" id="ticketNo">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Ticket No.:</pre>
                        <pre
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ issueSlip.ticketNo }}</pre>
                    </div>
                    <div class="data-field" id="user">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">User:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ issueSlip.user }}</pre>
                        <input v-if="editable" v-model="issueSlip.user" @change="updateIssueSlip()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
            </div>
        </div>
        <div class="issueSlip-data">
            <div class="additional">
                <div class="notes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Notes:</h3>
                    <input v-model="issueSlip.notes" :readonly="!editable" @change="updateIssueSlip()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
                </div>
            </div>
            <div class="additional">
                <div class="deliveryAddress">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Different delivery address:
                    </h3>
                    <input v-model="issueSlip.deliveryAddress" :readonly="!editable" @change="updateIssueSlip()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="deliveryAddress">
                </div>
            </div>
        </div>
    </section>
    <section v-if="addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <h2 :class="['issueSlip-name', darkMode ? 'h2-darkmode' : 'h2-lightmode']">Issue slip ID</h2>
        <div class="issueSlip-data">
            <div class="client">
                <div class="data-field" id="client">
                    <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>
            <div class="info">
                <div class="ticketNo-user">
                    <div class="data-field" id="ticketNo">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Ticket No.:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']"></pre>
                        <!-- <select id="ticketNoDropDownChosenCI" v-model="newTicketNo" @change="updateIS()"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="po in productionOrders" :key="po.ticketNumber">
                                {{ po.ticketNumber }}
                            </option>
                        </select> -->
                    </div>
                    <div class="data-field" id="user">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">User:</pre>
                        <input v-model="newUser" @change="updateIS()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
            </div>
        </div>
        <div class="issueSlip-data">
            <div class="additional">
                <div class="notes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Notes:</h3>
                    <input v-model="newNotes" @change="updateIS()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
                </div>
            </div>
            <div class="additional">
                <div class="deliveryAddress">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Different delivery address:
                    </h3>
                    <input v-model="newDeliveryAddress" @change="updateIS()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="deliveryAddress">
                </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 chosenIssueSlipId = computed(() => store.state.chosenIssueSlipId);
const deleteBool = computed(() => store.state.deleteBool);
const addBool = computed(() => store.state.new);

const darkMode = ref(true)
const issueSlip = ref({});
const customer = ref({});
const productionOrders = ref([]);
const customers = ref([]);

const newTicketNo = ref('');
const newCustomerID = ref('');
const newCustomer = ref('');
const newUser = ref('');
const newNotes = ref('');
const newDeliveryAddress = ref('');

// get issue slip from id
const getIssueSlipById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getIssueSlip/${chosenIssueSlipId.value}`
            );
            issueSlip.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

// update issue slip fields in the store
const updateIS = () => {
    const is = {
        customerId: newCustomerID.value,
        customer: newCustomer.value,
        // ticketNo: newTicketNo.value,
        ticketNo: 1,
        notes: newNotes.value,
        user: newUser.value,
        deliveryAddress: newDeliveryAddress.value,
    };
    store.commit('updateIssueSlipComponent', is);
}

//update data
const updateIssueSlip = async () => {
    // delete later
    issueSlip.value.ticketNo = 1;
    if (issueSlip.value.ticketNo.length === 0) {
        alert("Please add a ticket Number!");
        return;
    }
    try {
        await Axios.put(
            `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateIssueSlip`,
            {
                primaryID: issueSlip.value.primaryID,
                customerID: issueSlip.value.customerID,
                customer: issueSlip.value.customer,
                ticketNo: issueSlip.value.ticketNo,
                creationDate: issueSlip.value.creationDate,
                lastView: issueSlip.value.lastView,
                user: issueSlip.value.user,
                notes: issueSlip.value.notes,
                deliveryAddress: issueSlip.value.deliveryAddress,
                supplierRequestDate: issueSlip.value.supplierRequestDate,
                supplierRequest: issueSlip.value.supplierRequest,
                supplierOfferDate: issueSlip.value.supplierOfferDate,
                supplierOffer: issueSlip.value.supplierOffer,
                clientOfferDate: issueSlip.value.clientOfferDate,
                clientOffer: issueSlip.value.clientOffer,
                clientOrderDate: issueSlip.value.clientOrderDate,
                clientOrder: issueSlip.value.clientOrder,
                supplierOrder: issueSlip.value.supplierOrder,
                supplierOrderDate: issueSlip.value.supplierOrderDate,
                ingressDate: issueSlip.value.ingressDate,
                ingress: issueSlip.value.ingress,
                egressDate: issueSlip.value.egressDate,
                egress: issueSlip.value.egress,
                ingressBillDate: issueSlip.value.ingressBillDate,
                ingressBill: issueSlip.value.ingressBill,
                egressBillDate: issueSlip.value.egressBillDate,
                egressBill: issueSlip.value.egressBill,
            }
        )
        await getIssueSlipById();
    } catch (err) {
        console.log(err.response.statusText);
    }
}

//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);
    }
}

//get all production orders
const getProductionOrders = 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);
    // }
}

const confirmDeleteIssueSlip = async () => {
    if (deleteBool.value === true) {
        if (confirm("Do you really want to delete this issue slip? It cannot be undone!")) {
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteIssueSlip/${chosenIssueSlipId.value}`);
            } catch (err) {
                console.log(err.response.statusText);
            }
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteTodosOI/${chosenIssueSlipId.value}`);
            } catch (err) {
                console.log(err.response.statusText);
            }
            store.commit('undoDelete');
            store.commit('resetStore');
            store.commit('changeToIssueSliplist');
        } else {
            store.commit('undoDelete');
        }
    }
}

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

// 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;
    } catch (err) {
        console.log(err.response.statusText);
    }
    updateIS();
}

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

watch(deleteBool, confirmDeleteIssueSlip);

onMounted(() => {
    getIssueSlipById();
    getProductionOrders();
    triggerBackendCallsWithDelay(getCustomers);
});
</script>

<script>
export default {
    name: "IssueSlip",
};
</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);
}

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

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



.issueSlip-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;
}

.h2-darkmode {
    color: #fff;
}

.h2-lightmode {
    color: #000;
}

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

.data-field#street-name {
    width: 70%;
}

.data-field#street-no {
    width: 30%;
}

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

.pre-darkmode {
    color: #fff;
}

.pre-lightmode {
    color: #000;
}

.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;
}

.input {
    border: none;
}

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

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

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

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

.additional {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    line-height: normal;
    width: 50%;
    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;
}

.ticketNo-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,
.data#deliveryAddress {
    align-self: stretch;
}

.deliveryAddress,
.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;
}

.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;
}
</style>