<template>
    <div>
        <BreadCrumb></BreadCrumb>
        <div class="row row-sm">
            <div class="col-lg-12">
                <!-- <a href="/bai-viet" class="btn btn-link button-icon"><i class="fe fe-arrow-left me-2"></i>Danh sách bài viết </a> -->
                <router-link class="btn btn-link button-icon mb-2" :to="{ name: 'listOrder' }">
                    <i class="fe fe-arrow-left me-2"></i>Danh sách đơn hàng
                </router-link>
            </div>

        </div>
        <div class="row g-0">

            <div class="col-sm-12 col-md-12 col-lg-9 grid-margin rounded-0">

                <div class="card shadow-none mb-5 rounded-0">
                    <div class="card-body">
                        <SelectCustomer v-model:customer-id="model.CustomerId"></SelectCustomer>
                    </div>
                    <div class="card-body" v-if="model.CustomerId > 0">

                        <div class="row">
                            <div class="col-sm-12 col-md-6 border-right mg-b-20">
                                <Address @check-fee="checkFee" ref="sourceAddressRef" :customer-id="model.CustomerId"
                                    :add-type="1">
                                </Address>
                            </div>
                            <div class="col-sm-12 col-md-6">
                                <Address @check-fee="checkFee" ref="destAddressRef" :customer-id="model.CustomerId"
                                    :add-type="2">
                                </Address>
                            </div>
                        </div>
                        <Package @check-fee="checkFee" ref="packageRef"></Package>
                    </div>
                </div>
            </div>
            <div class="col-sm-12  col-md-12 col-lg-3 grid-margin">
                <div class="card shadow-none rounded-0   ">
                    <div class="card-header pb-0">
                        <h5 class="card-title mb-0 pb-0">THU HỘ / CƯỚC PHÍ</h5>
                    </div>
                    <div class="card-body">
                        <Finance ref="finRef"></Finance>
                        <small class="text-danger" v-if="financeErrorMessage">{{ financeErrorMessage }}</small>
                    </div>
                    <div class="card-footer">
                        <button class="btn btn-block button-icon"
                            :class="canCreateOrder ? 'btn-primary' : 'btn-secondary'" :disabled="!canCreateOrder"
                            @click="createOrder">
                            <i class="fe fe-plus me-2"></i>
                            Tạo đơn hàng
                        </button>

                    </div>
                </div>
            </div>



        </div>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';

import { useToast } from "vue-toastification";
const toast = useToast();

//#region Services
import orderService from "@/services/orderService";
import vatInfoService from "@/services/vatInfoService";
//#endregion

//#region Components
import BreadCrumb from './components/breadcrumb.vue';
import SelectCustomer from "./components/customer.vue";
import Address from "./components/address.vue";
import Finance from "./components/finance.vue";
import Package from "./components/packages.vue";
//#endregion

//#region Refs
const finRef = ref(null);
const sourceAddressRef = ref(null);
const destAddressRef = ref(null);
const packageRef = ref(null);
//#endregion


//#region Validations
const schema = Yup.object().shape({
    CustomerId: Yup.number().required('Vui lòng chọn khách hàng').min(1, 'Vui lòng chọn khách hàng'),
});
//#endregion

//#region DATA
const model = reactive({
    Note: '',
    SaleId: 0,
    PartnerCode: '',
    ProductName: '',
    CustomerId: null,
    Addresses: [],
    Packages: [],
    OrderFin: null,
    NumberOfPackage: 0
});

// Computed properties for validation
const hasSourceAddress = computed(() => {
    if (!sourceAddressRef.value) return false;
    const sourceModel = sourceAddressRef.value.getModel();
    return sourceModel && sourceModel.WardId > 0;
});

const hasDestAddress = computed(() => {
    if (!destAddressRef.value) return false;
    const destModel = destAddressRef.value.getModel();
    return destModel && destModel.WardId > 0;
});

const hasPackages = computed(() => {
    if (!packageRef.value) return false;
    const packageModel = packageRef.value.getModel();
    return packageModel && packageModel.length > 0;
});

const canCreateOrder = computed(() => {
    const basicValidation = model.CustomerId > 0 && hasSourceAddress.value && hasDestAddress.value && hasPackages.value;

    if (!basicValidation) return false;

    // Check finance validation
    if (finRef.value) {
        const financeValidation = finRef.value.validateVat();
        if (!financeValidation.isValid) {
            return false;
        }
    }

    return true;
});

const financeErrorMessage = computed(() => {
    if (finRef.value) {
        const financeValidation = finRef.value.validateVat();
        if (!financeValidation.isValid) {
            return financeValidation.message;
        }
    }
    return '';
});

//#endregion

//#region Methods
const checkFee = async () => {
    var sourceAddressModel = sourceAddressRef.value.getModel();
    var destAddressModel = destAddressRef.value.getModel();
    var packageModel = packageRef.value.getFeeModel();
    console.log(packageModel);
    var checkFeeModel = {
        SourceWardId: sourceAddressModel.WardId,
        DestWardId: destAddressModel.WardId,
        Weight: packageModel.Weight,
        CustomerId: model.CustomerId
    }
    finRef.value.checkFee(checkFeeModel);
};

const createOrder = async () => {
    try {
        // Validate VAT requirements
        const vatValidation = finRef.value.validateVat();
        if (!vatValidation.isValid) {
            toast.error(vatValidation.message);
            return;
        }

        var sourceAddressModel = sourceAddressRef.value.getModel();
        var destAddressModel = destAddressRef.value.getModel();
        var packageModel = packageRef.value.getModel();
        var finModel = finRef.value.getModel();

        // Validate packages
        if (!packageModel || packageModel.length === 0) {
            toast.error('Chưa có thông tin hàng hóa');
            return;
        }

        var orderModel = {
            CustomerId: model.CustomerId,
            SourceAddress: sourceAddressModel,
            DestAddress: destAddressModel,
            Packages: packageModel,
            Note: model.Note,
            OrderFin: finModel
        }

        var result = await orderService.CreateOrder(orderModel);
        console.log(result);
        if (result != null && result.Result === 1) {
            toast.success('Thành công!');
            cancel();
        } else {
            toast.error('Thất bại: ' + result.Message);
        }
    } catch (error) {
        console.error('Error creating order:', error);
        toast.error('Có lỗi xảy ra khi tạo đơn hàng');
    }
};

const cancel = () => {
    // Reset form or navigate back
    window.history.back();
};

// Watch for customer changes to load VAT info
watch(() => model.CustomerId, (newCustomerId) => {
    if (newCustomerId && finRef.value) {
        finRef.value.setCustomerId(newCustomerId);
    }
});
//#endregion

</script>
<style scoped>
.border-right {
    border-right: 1px dashed #ccc;
}
</style>
