<template>
    <div>
        <loader class="m-3" v-if="loading"></loader>
        <Form v-show="!loading" class="row" @submit="onSubmit" :validation-schema="schema"
            v-slot="{ errors, isSubmitting }">
            <div class="col-md-6">
                <div class="row">
                    <div class="col-lg-12 mb-3">
                        <label>Thu hộ:</label>
                        <VueNumberFormat v-model:value="orderFinModel.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 class="col-lg-12 mb-3">
                        <label>Phụ phí lấy hàng:</label>
                        <VueNumberFormat v-model:value="orderFinModel.PickupSubFee" class="form-control"
                            :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"></VueNumberFormat>
                    </div>
                    <div class="col-lg-12 mb-3">
                        <label>Phụ phí giao hàng:</label>
                        <VueNumberFormat v-model:value="orderFinModel.DeliverySubFee" class="form-control"
                            :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"></VueNumberFormat>
                    </div>
                    <div class="col-lg-12 mb-3">
                        <label>Giảm giá:</label>
                        <VueNumberFormat v-model:value="orderFinModel.Discount" class="form-control"
                            :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"></VueNumberFormat>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="col-lg-12 mb-3">
                    <label>Phí thu hộ:</label>
                    {{ vueNumberFormat(codFee, { precision: 0, prefix: '', suffix: 'đ', decimal: ',', thousand: '.' })
                    }}
                </div>
                <div class="col-lg-12 mb-3">
                    <label>Cước phí:</label>
                    {{ vueNumberFormat(orderFinModel.Fee,
                        { precision: 0, prefix: '', suffix: 'đ', decimal: ',', thousand: '.' }) }}
                </div>
                <hr class="bd" />
                <div class="col-lg-12 mb-3">
                    <h5 class="tx-15">Tổng cước tạm tính: {{ vueNumberFormat(totalFee,
                        { precision: 0, prefix: '', suffix: 'đ', decimal: ',', thousand: '.' }) }}</h5>

                </div>
                <div class="col-lg-12 mb-3">
                    <label>Thanh toán cước:</label>
                    <v-select label="Name" :options="availablePayFeeTypes" v-model="orderFinModel.PayFeeType"
                        :reduce="(option) => option.Id" :disabled="hasCOD"></v-select>
                </div>
                <div class="col-lg-12 mb-3" v-show="orderFinModel.PayFeeType == 4">
                    <label>Bên gửi:</label>
                    <VueNumberFormat v-model:value="orderFinModel.SourceFee" class="form-control"
                        :options="{ precision: 0, prefix: '', suffix: 'đ', isInteger: true }"></VueNumberFormat>
                </div>
                <div class="col-lg-12 mb-3" v-show="orderFinModel.PayFeeType == 4">
                    <label>Bên nhận:</label>
                    {{ vueNumberFormat(destFee,
                        { precision: 0, prefix: '', suffix: 'đ', decimal: ',', thousand: '.' }) }}
                </div>

                <!-- VAT Section -->
                <div class="col-lg-12 mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" v-model="orderFinModel.IsVatRequired"
                            id="vatCheckboxUpdate">
                        <label class="form-check-label" for="vatCheckboxUpdate">
                            Xuất hóa đơn VAT
                        </label>
                    </div>
                </div>
                <div class="col-lg-12 mb-3" v-if="orderFinModel.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="orderFinModel.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 class="card-footer">
                <div class="row">
                    <div class="col-12 ">
                        <div class="d-flex">
                            <button @click="cancel" type="button" class="btn btn-main-default">
                                Bỏ qua
                            </button>
                            <button type="submit" class="btn ms-auto btn-main-primary" :disabled="isSubmitting">
                                <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                                Xác nhận
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Form>

    </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, onMounted, watch } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
import * as Yup from 'yup';

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

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

//#region Props
const props = defineProps({
    orderFinId: Number,
    customerId: Number
});
//#endregion

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

const emit = defineEmits(['cancel']);

//#region Validations
const schema = Yup.object().shape({
    // Name: Yup.string().required('Họ và tên không để trống'),
    // PhoneNumber1: Yup.string().required('Số điện thoại không để trống'),
    // Address1: Yup.string().required('Địa chỉ không để trống'),
    // //WardId: Yup.string().required('Vui lòng nhập đầy đủ tỉnh, quận, phường'),
});
//#endregion


//#region DATA
const payFeeTypes = [
    { Id: 1, Name: 'Người gửi thanh toán' },
    { Id: 2, Name: 'Người nhận thanh toá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 loading = ref(false);
const orderFinModel = reactive({
    PayFeeType: 1,
    CollectAmount: 0,
    SourceFee: 0,
    DestFee: 0,
    Discount: 0,
    PickupSubFee: 0,
    DeliverySubFee: 0,
    Fee: 0,
    CODFee: 0,
    RouteName: '',
    IsVatRequired: false,
    VatInfoId: null
});

// 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 destFee = computed(() => {
    return totalFee.value - orderFinModel.SourceFee;
})

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

})

const totalFee = computed(() => {
    return orderFinModel.Fee + orderFinModel.PickupSubFee + orderFinModel.DeliverySubFee + codFee.value - orderFinModel.Discount;

})

const hasCOD = computed(() => {
    return orderFinModel.CollectAmount > 0;
});

const availablePayFeeTypes = computed(() => {
    if (hasCOD.value) {
        // 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





async function getOrderFin() {
    loading.value = true;
    var result = await orderFinService.getById(props.orderFinId);
    Object.assign(orderFinModel, result);

    // Load customer ID and VAT info
    const customerId = result.CustomerId || props.customerId;
    console.log('Debug updateFin - result.CustomerId:', result.CustomerId, 'props.customerId:', props.customerId, 'final customerId:', customerId);

    if (customerId) {
        currentCustomerId.value = customerId;
        await loadVatInfoByCustomer(customerId);

        // Set selected VAT if exists
        if (result.VatInfoId) {
            selectedVatInfo.value = result.VatInfoId;
        }
    } else {
        // Fallback: Nếu không có CustomerId từ cả OrderFin và props
        console.warn('Không có CustomerId, một số tính năng VAT có thể không hoạt động');
    }

    loading.value = false;
}

async function onSubmit() {
    // Validate VAT requirements
    if (orderFinModel.IsVatRequired && !orderFinModel.VatInfoId) {
        toast.error('Vui lòng chọn thông tin VAT khi yêu cầu xuất hóa đơn VAT');
        return;
    }

    // Validate collect amount
    if (hasCOD.value && orderFinModel.CollectAmount < totalFee.value) {
        toast.error(`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;
    }

    loading.value = true;
    console.log(orderFinModel);
    var result = await orderFinService.update(orderFinModel);
    if (result != null && result.Result === 1) {
        toast.success('Thành công!');
        cancel();

    } else {
        toast.error('Thất bại: ' + result.Message);
    }
    loading.value = false;
}



function cancel() {
    emit('cancel');
}

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

    try {
        loadingVatInfo.value = true;
        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) {
            selectedVatInfo.value = defaultVat.Id;
            orderFinModel.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) => {
    orderFinModel.VatInfoId = newValue;
});

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

// Watch for collect amount changes
watch(() => orderFinModel.CollectAmount, (newValue) => {
    if (newValue > 0) {
        // When COD is enabled, set payment type to "Cấn trừ COD" (Id: 5)
        orderFinModel.PayFeeType = 5;
    } else {
        // When COD is disabled, set payment type to default
        orderFinModel.PayFeeType = 1; // Default to "Người gửi thanh toán"
    }
    validateCollectAmount();
});

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

// Validate collect amount
const validateCollectAmount = () => {
    if (hasCOD.value && orderFinModel.CollectAmount > 0) {
        if (orderFinModel.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 = '';
    }
};

// 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 Events
onMounted(async () => {

    if (props.orderFinId != null && props.orderFinId > 0) {
        await getOrderFin();
    } else {
        alert("Yêu cầu không hợp lệ");
        cancel();
    }
})
//#endregion


</script>