<script setup>
    import { computed, onMounted, reactive } from 'vue';
    import CustomInput from './ui/CustomInput.vue';
    import Products from './ui/Products.vue';
    import TruckTypes from './ui/TruckTypes.vue';
    import { useAuthStore } from '../stores/auth';
    import { useCompanyStore } from '../stores/company';


    const props = defineProps({
        budget: {
            type: Object,
            required: false
        }
    })

    const authStore = useAuthStore();
    const companyStore = useCompanyStore();

    onMounted(() => {
        console.log('entra onmounted')
        console.log(props.budget);
        if(props.budget) {
            budgetForm.budget_id = props.budget._id;
			budgetForm.client = props.budget.client;
			budgetForm.material = props.budget.material._id;
			budgetForm.origin = props.budget.origin;
			budgetForm.destination = props.budget.destination;

			// let product = props.budget.material.name;
			// budgetForm.budgetproduct = {
			// 	name: product
			// }
			budgetForm.budgetproduct = props.budget.material

			budgetForm.budgetTrucktypes = props.budget.truck_type
			// let truck_type = props.budget.truck_type;
			// budgetForm.budgetTrucktypes = {
			// 	meta_value: truck_type
			// }

			budgetForm.num_tons = props.budget.num_tons;
			budgetForm.price_per_ton = props.budget.price_per_ton;
			budgetForm.tonnage = props.budget.tonnage;
			budgetForm.pickup_distance = props.budget.pickup_distance;
			budgetForm.delivery_distance = props.budget.delivery_distance;
			budgetForm.warehouse_distance = props.budget.warehouse_distance;

			budgetForm.cost_per_liter = props.budget.cost_per_liter;
			budgetForm.fuel_price_per_liter = props.budget.fuel_price_per_liter;
			budgetForm.other_fuel_expenses = props.budget.other_fuel_expenses;

			budgetForm.driver_salary = props.budget.driver_salary;
			budgetForm.accomadation_allowance = props.budget.accomadation_allowance;
			budgetForm.other_administrative_expenses = props.budget.other_administrative_expenses;
            budgetForm.total_administrative_expenses = props.budget.total_administrative_expenses;

			budgetForm.total_before_tax = props.budget.total_before_tax;
			budgetForm.total_utility_per_km = props.budget.total_utility_per_km;
			budgetForm.total_profit = props.budget.total_profit;
			budgetForm.profit_percentage = props.budget.profit_percentage;
        } else {
            Object.assign(budgetForm, initalState);
        }
    })

    defineEmits(['reset-budget']);

    const initalState = {
        client: '',
        material: '',
        origin: '',
        destination: '',
        num_tons: 0.0,
        price_per_ton: 0.0,
        tonnage: 0.0,
        pickup_distance: 0.0,
        delivery_distance: 0.0,
        warehouse_distance: 0.0,
        cost_per_liter: 0.0,
        fuel_price_per_liter: 0.0,
        other_fuel_expenses: 0.0,
        driver_salary: 0.0,
        accomadation_allowance: 0.0,
        other_administrative_expenses: 0.0,
        total_administrative_expenses: 0.0,
        total_before_tax: 0.0,
        total_utility_per_km: 0.0,
        total_profit: 0.0,
        profit_percentage: 0.0,
        total_travel: 0.0,
        total_fuel: 0.0,
        total_fuel_cost: 0.0,
        budgetproduct:[],
		budgetTrucktypes:[],
    }

    const budgetForm = reactive({
       ...initalState
    })

    // const total = computed(() => {

    // });

        const totalTravel = computed(()  => {
            budgetForm.total_travel = budgetForm.warehouse_distance * 1 + budgetForm.delivery_distance * 1 + budgetForm.pickup_distance * 1;
            budgetForm.total_travel = isNaN(budgetForm.total_travel) ? 0.0 : budgetForm.total_travel;
			return budgetForm.total_travel;
        });

        const totalFuel = computed(()  => {
           budgetForm.total_fuel = isNaN(budgetForm.total_travel / budgetForm.cost_per_liter) ? 0.0 : (budgetForm.total_travel / budgetForm.cost_per_liter);
		   return isNaN(budgetForm.total_fuel) ? '0.0' : parseFloat(budgetForm.total_fuel).toFixed(2);
        });

		const totalFuelCost = computed(() => {
           budgetForm.total_fuel_cost = isNaN(budgetForm.total_fuel * budgetForm.fuel_price_per_liter) ? 0.0 : budgetForm.total_fuel * budgetForm.fuel_price_per_liter;
		   return "$" + (isNaN(budgetForm.total_fuel_cost) ? '0.0' : parseFloat(budgetForm.total_fuel_cost).toFixed(2));
		});

		const totalAdminExpenses = computed(() => {
		    budgetForm.total_administrative_expenses = budgetForm.driver_salary*1 + budgetForm.accomadation_allowance*1 + budgetForm.other_administrative_expenses*1;
            budgetForm.total_administrative_expenses = isNaN(budgetForm.total_administrative_expenses) ? 0.0 : budgetForm.total_administrative_expenses;
		   return "$" + (isNaN(budgetForm.total_administrative_expenses) ? '0.0' : parseFloat(budgetForm.total_administrative_expenses).toFixed(2));
		});

		const totalBeforeTax = computed(() => {
			budgetForm.total_before_tax = budgetForm.tonnage * budgetForm.price_per_ton;
            budgetForm.total_before_tax = isNaN(budgetForm.total_before_tax) ? 0.0 : budgetForm.total_before_tax;
			return "$" + (isNaN(budgetForm.total_before_tax) ? '0.0' : parseFloat(budgetForm.total_before_tax).toFixed(2));
		});

		const totalUtilityPerKm = computed(() => {
			budgetForm.total_utility_per_km = isNaN(budgetForm.total_before_tax / budgetForm.total_travel) ? 0.0 : (budgetForm.total_before_tax / budgetForm.total_travel);
			return "$" + (isNaN(budgetForm.total_utility_per_km) ? '0.0' : parseFloat(budgetForm.total_utility_per_km).toFixed(2));
		});

		const totalProfit = computed(() => {
			budgetForm.total_profit = budgetForm.total_before_tax - budgetForm.total_fuel_cost - budgetForm.other_fuel_expenses - budgetForm.driver_salary - budgetForm.accomadation_allowance - budgetForm.other_administrative_expenses;
			return "$" + (isNaN(budgetForm.total_profit) ? '0.0' : parseFloat(budgetForm.total_profit).toFixed(2));
		});

		const totalPercentage = computed(() => {
			budgetForm.profit_percentage = budgetForm.total_profit / budgetForm.total_before_tax * 100;
            budgetForm.profit_percentage = isNaN(budgetForm.profit_percentage) ? 0.0 : budgetForm.profit_percentage;
			return  (isNaN(budgetForm.profit_percentage) ? '0.0' : parseFloat(budgetForm.profit_percentage).toFixed(2)) + "%";
		});

    const saveBudget = async() => {
        let budgetData ={
            client: budgetForm.client,
            material: budgetForm.budgetproduct.length <= 0 ? null : budgetForm.budgetproduct,
            origin: budgetForm.origin,
            destination: budgetForm.destination,
            truck_type: budgetForm.budgetTrucktypes.length <= 0 ? null : budgetForm.budgetTrucktypes,
            num_tons: budgetForm.num_tons,
            price_per_ton: budgetForm.price_per_ton,

            tonnage: budgetForm.tonnage,
            pickup_distance: budgetForm.pickup_distance,
            delivery_distance: budgetForm.delivery_distance,
            warehouse_distance: budgetForm.warehouse_distance,
            total_km_travel: budgetForm.total_travel,

            cost_per_liter: budgetForm.cost_per_liter,
            fuel_price_per_liter: budgetForm.fuel_price_per_liter,
            other_fuel_expenses: budgetForm.other_fuel_expenses,
            total_fuel_consumed: budgetForm.total_fuel,
            total_cost_fuel: budgetForm.total_fuel_cost,

            driver_salary: budgetForm.driver_salary,
            accomadation_allowance: budgetForm.accomadation_allowance,
            other_administrative_expenses: budgetForm.other_administrative_expenses,
            total_administrative_expenses: budgetForm.total_administrative_expenses,

            total_before_tax: budgetForm.total_before_tax,
            total_utility_per_km: budgetForm.total_utility_per_km,
            total_profit: budgetForm.total_profit,
            profit_percentage: (isNaN(budgetForm.profit_percentage) || isFinite(budgetForm.profit_percentage)) ? 0.0 : budgetForm.profit_percentage,
            company: authStore.user.company,
        }

        if(props.budget !== null) { // update
            const result = companyStore.updateBudgetCompany(props.budget._id, budgetData);
            console.log(result)
        } else { // create
            const result = companyStore.createBudgetCompany(budgetData);
            console.log(result)
        }
    }

</script>

<template>
    <div class="modal fade" id="budgetModal" tabindex="-1" role="dialog" aria-labelledby="editcompany" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="title mt-2 mb-3">Calculadora</h2>
                    <button 
                        id="btnClosebudgetModal" 
                        type="button" 
                        @click="$emit('reset-budget')"
                        class="close bg-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body form-content">
                    <div class="container-fluid">
                            <form action="" @submit.prevent="saveBudget" autocomplete="off" method="post">
                                <div class="calculator-card">
                                    <div class="calculator-card__title">
                                        <h2>CALCULADOR DE TARIFAS</h2>                
                                    </div>
                                    <div class="calculator-card__subtitle">
                                        <h4>DATOS DE CARGA</h4>
                                    </div>
                                    <div class="calculator-card__body">
                                        <div class="calculator-card__loads_data">
                                            <CustomInput
                                                label="CLIENTE*"
                                                type="text"
                                                :filled="false"
                                                name="client"
                                                :required="true"
                                                :error="(!budgetForm.client) ? 'Cliente es requerido' : null"
                                                v-model:field="budgetForm.client"
                                            />
                                            <div class="mb-4 mt-3">
                                                <label class="custom-label">MATERIAL</label>
                                                <Products
                                                    v-model="budgetForm.budgetproduct" 
                                                />
                                            </div>
                                            <CustomInput
                                                label="ORIGEN"
                                                type="text"
                                                :filled="false"
                                                name="origin"
                                                v-model:field="budgetForm.origin"
                                            />
                                            <CustomInput
                                                label="DESTINO"
                                                type="text"
                                                :filled="false"
                                                name="destination"
                                                v-model:field="budgetForm.destination"
                                            />
                                            <div class="mb-4 mt-3">
                                                <label class="custom-label">TIPO DE CAMIÓN</label>
                                                <TruckTypes
                                                    v-model="budgetForm.budgetTrucktypes" 
                                                />
                                            </div>
                                            <CustomInput
                                                label="TONELADAS"
                                                type="number"
                                                :filled="false"
                                                name="num_tons"
                                                v-model:field="budgetForm.num_tons"
                                            />
                                            <CustomInput
                                                label="PRECIO POR TONELADA"
                                                type="number"
                                                :filled="false"
                                                name="price_per_ton"
                                                v-model:field="budgetForm.price_per_ton"
                                            />
                                        </div>         
                                    </div>
                                    <div class="calculator-card__subtitle">
                                        <h4>TARIFA / KILOMETRAJE</h4>
                                    </div>
                                    <div class="calculator-card__body">
                                        <div class="calculator-card__loads_data">
                                            <CustomInput
                                                label="TONELAJE APROXIMADO DE CARGA"
                                                type="number"
                                                :filled="false"
                                                name="tonnage"
                                                v-model:field="budgetForm.tonnage"
                                            />
                                            <CustomInput
                                                label="PRECIO POR TONELADA"
                                                type="number"
                                                :filled="false"
                                                name="price_per_ton"
                                                v-model:field="budgetForm.price_per_ton"
                                            />
                                            <CustomInput
                                                label="ORIGEN DEL CAMION AL ORIGEN DE CARGA(KM)"
                                                type="number"
                                                :filled="false"
                                                name="pickup_distance"
                                                v-model:field="budgetForm.pickup_distance"
                                            />
                                            <CustomInput
                                                label="ORIGEN DE CARGA A DESTINO DE DESCARGA(KM)"
                                                type="number"
                                                :filled="false"
                                                name="delivery_distance"
                                                v-model:field="budgetForm.delivery_distance"
                                            />
                                            <CustomInput
                                                label="DESTINO DE DESCARGA AL PATIO-BASE (KM)"
                                                type="number"
                                                :filled="false"
                                                name="warehouse_distance"
                                                v-model:field="budgetForm.warehouse_distance"
                                            />
                                            <div class="calculator-card__totals">
                                                <div>
                                                    <h6>TOTAL KM RECORRIDOS</h6>
                                                </div>
                                                <div>
                                                    {{ totalTravel }}
                                                </div>
                                            </div>
                                        </div>         
                                    </div>
                                    <div class="calculator-card__subtitle">
                                        <h4>COSTOS DIRECTOS CAMION</h4>
                                    </div>
                                    <div class="calculator-card__body">
                                        <div class="calculator-card__loads_data">
                                            <CustomInput
                                                label="RENDIMIENTO CAMION - LITROS POR KILOMETRO RECORRIDO"
                                                type="number"
                                                :filled="false"
                                                name="cost_per_liter"
                                                v-model:field="budgetForm.cost_per_liter"
                                            />
                                            <CustomInput
                                                label="PRECIO DEL DIESEL POR LITRO"
                                                type="number"
                                                :filled="false"
                                                name="fuel_price_per_liter"
                                                v-model:field="budgetForm.fuel_price_per_liter"
                                            />
                                            <CustomInput
                                                label="OTROS GASTOS"
                                                type="number"
                                                :filled="false"
                                                name="other_fuel_expenses"
                                                v-model:field="budgetForm.other_fuel_expenses"
                                            />
                                            <div class="calculator-card__totals">
                                                <div>
                                                <h6>TOTAL LITROS DE DIESEL CONSUMIDOS</h6>
                                                </div>
                                                <div>
                                                    {{ totalFuel }}
                                                </div>
                                            </div>
                                            <div class="calculator-card__totals">
                                                <div>
                                                    <h6>TOTAL COSTO DEL DIESEL</h6>
                                                </div>
                                                <div>
                                                    {{ totalFuelCost }}
                                                </div>
                                            </div>
                                        </div>         
                                    </div>
                                    <div class="calculator-card__subtitle">
                                        <h4>SUELDO OPERADOR</h4>
                                    </div>
                                    <div class="calculator-card__body">
                                        <div class="calculator-card__loads_data">
                                            <CustomInput
                                                label="GASTOS ADMINISTRATIVOS"
                                                type="number"
                                                :filled="false"
                                                name="driver_salary"
                                                v-model:field="budgetForm.driver_salary"
                                            />
                                            <CustomInput
                                                label="CASETAS"
                                                type="number"
                                                :filled="false"
                                                name="accomadation_allowance"
                                                v-model:field="budgetForm.accomadation_allowance"
                                            />
                                            <CustomInput
                                                label="OTROS GASTOS"
                                                type="number"
                                                :filled="false"
                                                name="other_administrative_expenses"
                                                v-model:field="budgetForm.other_administrative_expenses"
                                            />
                                            <div class="calculator-card__totals">
                                                <div>
                                                    <h6>GASTOS ADMINISTRATIVOS TOTALES</h6>
                                                </div>
                                                <div>
                                                    {{ totalAdminExpenses }}
                                                </div>
                                            </div>
                                        </div>         
                                    </div>
                                    <div class="calculator-card__subtitle">
                                        <h4>UTILIDAD / PERDIDA</h4>
                                    </div>
                                    <div class="calculator-card__body">
                                        <div class="calculator-card__loads_data">
                                            <div class="calculator-card__totals">
                                                <div>
                                                    <h6>TOTAL ANTES DE IVA</h6>
                                                </div>
                                                <div>
                                                    {{ totalBeforeTax }}
                                                </div>
                                            </div>
                                            <div class="calculator-card__totals">
                                                <div>
                                                    <h6>TOTAL UTILIDAD POR KILOMETRO</h6>
                                                </div>
                                                <div>
                                                    {{ totalUtilityPerKm }}
                                                </div>
                                            </div>
                                            <div class="calculator-card__totals">
                                                <div>
                                                    <h6>TOTAL UTILIDAD</h6>
                                                </div>
                                                <div>
                                                    {{ totalProfit }}
                                                </div>
                                            </div>
                                            <div class="calculator-card__totals">
                                                <div>
                                                    <h6>PORCENTAJE DE UTILIDAD</h6>
                                                </div>
                                                <div>
                                                    {{ totalPercentage }}
                                                </div>
                                            </div>
                                        </div>         
                                    </div>
                                </div>
                                <div class="mt-4 text-center">
                                    <button class="btn btn-primary myshipper-btn" type="submit">Guardar</button>
                                </div> 
                            </form>
                        </div>
                </div>
                <div class="modal-footer">
                    <button 
                        type="button" 
                        class="btn btn-dark" 
                        @click="$emit('reset-budget')"
                        data-dismiss="modal">Cerrar</button>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>

    .form-content {
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-content: center;
        align-items: center;
        margin: 0 auto;
        border: 1px solid grey;
    }
    
    .calculator-card {
        justify-content: center;
        margin: 0 auto;
        width: 70%;
        border: 1px solid grey;
    }

    .calculator-card__title {
        background-color: #323030;
        padding: 10px 20px;
        color: #FFF;
        text-align: center;
        font-size: 1.2rem;
        font-weight: 700;
    }

    .calculator-card__subtitle {
        background-color: #50b1e5;
        padding: 10px 20px;
        color: #FFF;
        text-align: center;
        font-size: 1.2rem;
        font-weight: 700;
    }

    .calculator-card__loads_data {
        padding: 24px 24px;
    }
   
   .calculator-card__totals {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        padding: 8px 0px;
   }
</style>