<template>
    <div>
        <!-- COD Option -->
        <div class="row">
            <div class="col-lg-12 mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" v-model="orderFeeModel.IsCOD" id="codCheckbox">
                    <label class="form-check-label" for="codCheckbox">
                        COD (Thu hộ)
                    </label>
                </div>
            </div>
        </div>

        <!-- COD Amount - Only show when COD is enabled -->
        <div class="row" v-if="orderFeeModel.IsCOD">
            <div class="col-lg-12 mb-3">
                <label>Số tiền thu hộ:</label>
                <VueNumberFormat v-model:value="orderFeeModel.CollectAmount" class="form-control"
                    :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"
                    @input="validateCollectAmount"></VueNumberFormat>
                <small class="text-danger" v-if="collectAmountError">{{ collectAmountError }}</small>
            </div>
        </div>
        <div class="row bd-b mb-3">
            <div class="col-6 mb-2" v-if="orderFeeModel.IsCOD && orderFeeModel.CollectAmount > 0">
                Phí thu hộ:
            </div>
            <div class="col-6 mb-2" v-if="orderFeeModel.IsCOD && orderFeeModel.CollectAmount > 0">
                {{ vueNumberFormat(codFee,
                    { precision: 0, prefix: '', suffix: 'đ', decimal: ',', thousand: '.' }) }}
            </div>
            <div class="col-6 mb-2">
                Cước phí:
            </div>
            <div class="col-6 mb-2">
                {{ vueNumberFormat(orderFeeModel.Fee,
                    { precision: 0, prefix: '', suffix: 'đ', decimal: ',', thousand: '.' }) }}
            </div>

            <div class="col-6 mb-2 mt-2">
                Phụ phí lấy hàng:
            </div>
            <div class="col-6 mb-2">

                <VueNumberFormat v-model:value="orderFeeModel.PickupSubFee" class="form-control"
                    :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"></VueNumberFormat>
            </div>

            <div class="col-6 mb-2 mt-2">
                Phụ phí giao hàng:
            </div>
            <div class="col-6 mb-2">

                <VueNumberFormat v-model:value="orderFeeModel.DeliverySubFee" class="form-control"
                    :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"></VueNumberFormat>
            </div>


            <div class="col-6 mb-2 mt-2">
                Giảm giá:
            </div>
            <div class="col-6 mb-2">
                <!-- <input type="text" v-model="orderFee.Discount" class="form-control" placeholder="0.000đ"> -->
                <VueNumberFormat v-model:value="orderFeeModel.Discount" class="form-control"
                    :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"></VueNumberFormat>
            </div>
        </div>
        <div class="row">
            <div class="col-6 mb-2">
                <h5 class="tx-15">Tổng cước tạm tính:</h5>
            </div>
            <div class="col-6 mb-2">
                <h5> {{ vueNumberFormat(totalFee,
                    { precision: 0, prefix: '', suffix: 'đ', decimal: ',', thousand: '.' }) }}</h5>
            </div>
            <div class="col-lg-12 mb-2">
                <label>Thanh toán cước:</label>
                <v-select label="Name" :options="availablePayFeeTypes" v-model="orderFeeModel.PayFeeType"
                    :reduce="(option) => option.Id" :disabled="orderFeeModel.IsCOD"></v-select>
            </div>
            <div class="col-6 mb-2" v-show="orderFeeModel.PayFeeType == 4">
                Bên gửi:
            </div>
            <div class="col-6 mb-2" v-show="orderFeeModel.PayFeeType == 4">
                <VueNumberFormat v-model:value="orderFeeModel.SourceFee" class="form-control"
                    :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"></VueNumberFormat>

            </div>
            <div class="col-6 mb-2" v-show="orderFeeModel.PayFeeType == 4">
                Bên nhận:
            </div>
            <div class="col-6 mb-2" v-show="orderFeeModel.PayFeeType == 4">
                {{ vueNumberFormat(destFee,
                    { precision: 0, prefix: '', suffix: 'đ', decimal: ',', thousand: '.' }) }}
            </div>
        </div>

        <!-- VAT Section -->
        <div class="row bd-t pt-3">
            <div class="col-lg-12 mb-2">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" v-model="orderFeeModel.IsVatRequired"
                        id="vatCheckbox">
                    <label class="form-check-label" for="vatCheckbox">
                        Xuất hóa đơn VAT
                    </label>
                </div>
            </div>
            <div class="col-lg-12 mb-2" v-if="orderFeeModel.IsVatRequired">
                <label>Thông tin VAT:</label>
                <div class="d-flex gap-2">
                    <v-select label="CompanyName" :options="vatInfoOptions" v-model="selectedVatInfo"
                        :reduce="(option) => option.Id" placeholder="Chọn thông tin VAT..." :loading="loadingVatInfo"
                        class="flex-grow-1">
                        <template #option="option">
                            <div>
                                <strong>{{ option.CompanyName }}</strong>
                                <br>
                                <small class="text-muted">{{ option.TaxCode }} - {{ option.InvoiceEmail }}</small>
                            </div>
                        </template>
                        <template #selected-option="option">
                            <div>
                                <strong>{{ option.CompanyName }}</strong>
                                <br>
                                <small class="text-muted">{{ option.TaxCode }}</small>
                            </div>
                        </template>
                    </v-select>
                    <button type="button" class="btn btn-outline-primary btn-sm" @click="openCreateVatModal"
                        :disabled="!currentCustomerId" title="Tạo thông tin VAT mới">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
                <small class="text-muted" v-if="orderFeeModel.IsVatRequired && !selectedVatInfo">
                    Vui lòng chọn thông tin VAT để tiếp tục
                </small>
                <small class="text-info d-block mt-1"
                    v-if="vatInfoOptions.length === 0 && !loadingVatInfo && currentCustomerId">
                    Khách hàng chưa có thông tin VAT. <a href="#" @click.prevent="openCreateVatModal">Tạo mới</a>
                </small>

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

    <!-- Modal tạo thông tin VAT mới -->

    <LadaDialog :visible="showCreateVatModal">
        <template #header>
            <div class="modal-header">
                <h5 class="modal-title">Tạo thông tin VAT mới</h5>
                <button @click="closeCreateVatModal" type="button" class="close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        </template>
        <template #body>
            <CreateOrUpdateVatInfo :id="0" :customerId="currentCustomerId" @cancel="closeCreateVatModal"
                @success="onVatCreated" />
        </template>
    </LadaDialog>
</template>
<script setup>

import { ref, reactive, computed, watch } from 'vue';


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

//#region Components
import CreateOrUpdateVatInfo from "@/views/crm/customer/detail/components/CreateOrUpdateVatInfo.vue";
//#endregion

//#region Toast
import { useToast } from "vue-toastification";
const toast = useToast();
//#endregion

//#region DATA
const payFeeTypes = [
    { Id: 1, Name: 'Bên gửi' },
    { Id: 2, Name: 'Bên nhận' },
    { Id: 3, Name: 'Chuyển khoản kế toán' },
    { Id: 4, Name: 'Thu cước 2 đầu' },
    { Id: 5, Name: 'Cấn trừ COD' },
];

const orderFeeModel = reactive({
    PayFeeType: 1,
    CollectAmount: 0,
    SourceFee: 0,
    DestFee: 0,
    Discount: 0,
    PickupSubFee: 0,
    DeliverySubFee: 0,
    Fee: 0,
    SubFee: 0,
    CODFee: 0,
    RouteName: '',
    IsVatRequired: false,
    VatInfoId: null,
    IsCOD: false
});

// VAT related data
const vatInfoOptions = ref([]);
const selectedVatInfo = ref(null);
const loadingVatInfo = ref(false);
const currentCustomerId = ref(null);
const showCreateVatModal = ref(false);
const collectAmountError = ref('');

// const checkFeeModel = reactive({
//     SourceWardId: null,
//     DestWardId: null,
//     Weight: 0
// });

const destFee = computed(() => {
    return totalFee.value - orderFeeModel.SourceFee;
})

const codFee = computed(() => {
    if (orderFeeModel.CollectAmount <= 1000000) {
        return 0;
    } else {
        return orderFeeModel.CollectAmount * 1 / 100;
    }

})

const totalFee = computed(() => {
    return orderFeeModel.Fee + orderFeeModel.SubFee + codFee.value - orderFeeModel.Discount;
})

// Available payment types based on COD selection
const availablePayFeeTypes = computed(() => {
    if (orderFeeModel.IsCOD) {
        // When COD is selected, only allow "Cấn trừ COD"
        return payFeeTypes.filter(type => type.Id === 5);
    } else {
        // When COD is not selected, show all payment types except "Cấn trừ COD"
        return payFeeTypes.filter(type => type.Id !== 5);
    }
})



//#endregion



//#region VAT Methods
const loadVatInfoByCustomer = async (customerId) => {
    if (!customerId) return;

    try {
        loadingVatInfo.value = true;
        currentCustomerId.value = customerId;
        const result = await vatInfoService.getByCustomerId(customerId);
        vatInfoOptions.value = result.Items || result || [];

        // Auto select default VAT info if available
        const defaultVat = vatInfoOptions.value.find(vat => vat.IsDefault);
        if (defaultVat) {
            selectedVatInfo.value = defaultVat.Id;
            orderFeeModel.VatInfoId = defaultVat.Id;
        }
    } catch (error) {
        console.error('Error loading VAT info:', error);
        toast.error('Có lỗi xảy ra khi tải thông tin VAT');
    } finally {
        loadingVatInfo.value = false;
    }
};

// Watch for VAT selection changes
watch(selectedVatInfo, (newValue) => {
    orderFeeModel.VatInfoId = newValue;
});

// Watch for VAT requirement changes
watch(() => orderFeeModel.IsVatRequired, (newValue) => {
    if (!newValue) {
        selectedVatInfo.value = null;
        orderFeeModel.VatInfoId = null;
    }
});

// Watch for COD changes
watch(() => orderFeeModel.IsCOD, (newValue) => {
    if (newValue) {
        // When COD is enabled, set payment type to "Cấn trừ COD" (Id: 5)
        orderFeeModel.PayFeeType = 5;
    } else {
        // When COD is disabled, reset collect amount and set payment type to default
        orderFeeModel.CollectAmount = 0;
        orderFeeModel.PayFeeType = 1; // Default to "Bên gửi"
    }
});

// Modal VAT functions
const openCreateVatModal = () => {
    if (!currentCustomerId.value) {
        toast.error('Vui lòng chọn khách hàng trước');
        return;
    }
    showCreateVatModal.value = true;
};

const closeCreateVatModal = () => {
    showCreateVatModal.value = false;
};

const onVatCreated = async () => {
    // Close modal
    closeCreateVatModal();

    // Reload VAT info for current customer
    if (currentCustomerId.value) {
        await loadVatInfoByCustomer(currentCustomerId.value);
        toast.success('Tạo thông tin VAT thành công!');
    }
};
//#endregion

//#region Expose
const getModel = () => {
    return orderFeeModel;
};

const checkFee = async (checkFeeModel) => {
    if (checkFeeModel.SourceWardId > 0 && checkFeeModel.DestWardId > 0 && checkFeeModel.Weight > 0) {
        var result = await priceService.checkFee(checkFeeModel);
        console.log(result);
        if (result.Result === 1) {
            orderFeeModel.Fee = result.Fee;
            orderFeeModel.RouteName = result.RouteName;
            //orderFeeModel.TotalFee = result.Fee + result.SubFee - feeResult.Discount;
            console.log(orderFeeModel);
        } else {
            toast.error('Thất bại: ' + result.Message);

        }
    }
};

const setCustomerId = (customerId) => {
    currentCustomerId.value = customerId;
    loadVatInfoByCustomer(customerId);
};

const validateVat = () => {
    if (orderFeeModel.IsVatRequired && !orderFeeModel.VatInfoId) {
        return {
            isValid: false,
            message: 'Vui lòng chọn thông tin VAT khi yêu cầu xuất hóa đơn VAT'
        };
    }

    // Validate collect amount
    if (orderFeeModel.IsCOD && orderFeeModel.CollectAmount > 0) {
        if (orderFeeModel.CollectAmount < totalFee.value) {
            return {
                isValid: false,
                message: `Số tiền thu hộ phải lớn hơn hoặc bằng tổng cước phí (${totalFee.value.toLocaleString('vi-VN')}đ)`
            };
        }
    }

    return { isValid: true };
};

// Validate collect amount
const validateCollectAmount = () => {
    if (orderFeeModel.IsCOD && orderFeeModel.CollectAmount > 0) {
        if (orderFeeModel.CollectAmount < totalFee.value) {
            collectAmountError.value = `Số tiền thu hộ phải lớn hơn hoặc bằng tổng cước phí (${totalFee.value.toLocaleString('vi-VN')}đ)`;
        } else {
            collectAmountError.value = '';
        }
    } else {
        collectAmountError.value = '';
    }
};

// Watch for total fee changes to revalidate collect amount
watch(totalFee, () => {
    validateCollectAmount();
});

//#endregion






defineExpose({
    checkFee,
    getModel,
    setCustomerId,
    validateVat
})

</script>