<template>
    <div>

        <loader v-if="loading" lass="mt-5 mb-5"></loader>
        <form v-if="!loading" @submit.prevent="submitForm">
            <!-- Image/Video upload input -->
            <div class="mb-3">
                <label class="form-label">Hình ảnh / video</label>
                <div class="d-flex flex-wrap">
                    <div v-for="(file, index) in files" :key="file.name"
                        class="position-relative me-2 mb-2 file-container">
                        <img v-if="file.type.startsWith('image/')" :src="file.url" class="img-thumbnail file-preview" />
                        <video v-else :src="file.url" controls class="video-thumbnail file-preview"></video>
                        <button type="button" class="position-absolute top-0 end-0 delete-btn"
                            @click="removeFile(index)">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                    <div v-if="files.length < 5"
                        class="d-flex justify-content-center align-items-center border border-secondary rounded file-container"
                        style="cursor: pointer;" @click="triggerFileInput">
                        <span class="fs-1">+</span>
                        <input type="file" class="d-none" accept="image/*,video/*" ref="fileInput"
                            @change="handleFileChange" />
                    </div>
                </div>
            </div>

            <detail :orderItem="orderItem" :detailType="2"></detail>

            <!-- Submit and Cancel buttons -->
            <div class="d-flex justify-content-between pd-t-20">
                <button v-if="!enableDelivery" type="button" class="btn btn-lg btn-success"
                    @click.prevent="handleCollectMoney">Thu
                    tiền</button>
                <button v-if="enableDelivery" type="button" class="btn btn-lg btn-success"
                    @click.prevent="submitForm">Giao hàng</button>
            </div>
        </form>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";

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

import operationService from "@/services/business/operationService";
import orderFinService from "@/services/orderFinService";
import { formatCurrency } from '@/infrastructure/utilities/currencyHelper';
//#region Components
import detail from "./detail.vue";
//#endregion

const props = defineProps({
    orderId: Number
});

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



//#region DATA
const loading = ref(false);
const orderItem = reactive({});
const files = ref([]);
const fileInput = ref(null);
const enableDelivery = ref(true);
const collectMoneyForm = reactive({
    Id: props.orderId,
    Type: 2
});
//#endregion




const handleFileChange = (event) => {
    const selectedFiles = Array.from(event.target.files);
    const validFiles = selectedFiles.filter(file => {
        if (file.type.startsWith('image/') || file.type.startsWith('video/')) {
            return true;
        }
        return false;
    }).slice(0, 5 - files.value.length);

    if (validFiles.length + files.value.length > 5) {
        alert("You can only upload a maximum of 5 files.");
        return;
    }

    validFiles.forEach(file => {
        const reader = new FileReader();
        reader.onload = e => {
            file.url = e.target.result;
            files.value.push(file);
        };
        reader.readAsDataURL(file);
    });
};

const removeFile = (index) => {
    files.value.splice(index, 1);
};

const triggerFileInput = () => {
    fileInput.value.click();
};


const submitForm = async () => {
    if (files.value.length === 0) {
        alert("Bạn cần phải chọn ít nhất 1 hình ảnh / video.");
        return;
    }
    // alert('o dau the');

    // const model = new FormData();
    // files.value.forEach((fileItem) => {
    //     model.append('MediaList', fileItem.file);
    // });

    const formData = new FormData();
    formData.append("Id", props.orderId);
    files.value.forEach((fileItem) => {
        formData.append("MediaList", fileItem);
    });


    var pickupResult = await operationService.delivery(formData);

    if (pickupResult != null && pickupResult.Result === 1) {
        toast.success('Thành công!');

    } else {
        toast.error('Thất bại vì ' + pickupResult.Message);
    }
    close();
};

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


async function getOrderDetail() {
    loading.value = true;
    if (props.orderId != null && props.orderId > 0) {
        var orderResult = await operationService.getById(props.orderId);
        if (orderResult.Id > 0) {
            Object.assign(orderItem, orderResult);
        }
        if (orderItem.OrderFin != null &&
            (orderItem.OrderFin.PayFeeType == 2 || orderItem.OrderFin.PayFeeType == 4) &&
            orderItem.OrderFin.DestFeeCashierId <= 0
        ) {
            enableDelivery.value = false;
        }
    }
    loading.value = false;
}

const handleCollectMoney = async () => {
    var totalCollect = formatCurrency(orderItem.OrderFin.DestFee + orderItem.OrderFin.CollectAmount);

    var cf = confirm('Bạn có chắc chắn đã thu được ' + totalCollect + ' không?');
    if (cf) {
        try {

            const response = await orderFinService.collectMoney(collectMoneyForm);
            if (response.Result === 1) {
                toast.success('Thu tiền thành công!');
                await getOrderDetail(); // Tải lại thông tin đơn hàng
            } else {
                toast.error('Thất bại vì ' + response.Message);
            }
        } catch (error) {
            toast.error('Có lỗi xảy ra khi thu tiền');
        }
    } else return false;
    return;
};

onMounted(async () => {
    await getOrderDetail();
});

</script>
<style scoped>
.file-container {
    width: 100px;
    height: 100px;
    position: relative;
    overflow: hidden;
}

.file-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.video-thumbnail {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.delete-btn {
    background-color: white;
    border: 1px solid black;
    border-radius: 50%;
    padding: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
}
</style>