<template>
    <div class="row mt-3 mt-md-0">
        <div class="col">
            <div class="row">
                <div class="col">
                    <div class="row align-items-end m-b-10">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Supplier:</div>
                        </div>
                        <div class="col-auto">
                            <div class="font-heading fs-10">{{ supplier.name }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-5 text-info">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Order Total:</div>
                        </div>
                        <div class="col-auto text-right">
                            <div class="font-heading fs-11">{{ payments.length > 0 ? payments[0].original_currency.short_code : "CNY"}} {{ formatNumber(originalTotal) }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-5 text-info" v-if="!is1688Supplier">
                        <div class="col">
                            <div class="font-heading all-caps fs-10"></div>
                        </div>
                        <div class="col-auto text-right">
                            <div class="font-heading fs-11">MYR {{ formatNumber(total) }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-5 text-info" v-if="!is1688Supplier">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Service Charges:</div>
                        </div>
                        <div class="col-auto text-right">
                            <div class="font-heading fs-11">MYR {{parameters.service_charges}}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-10 text-primary" v-if="is1688Supplier">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Currency Rate:</div>
                        </div>
                        <div class="col-auto text-right">
                            <div class="font-heading bold">{{ billGroupCurrencyRate }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-10 text-danger" v-if="refundTotal > 0">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Bill Refund Total:</div>
                        </div>
                        <div class="col-auto text-right" v-if="is1688Supplier">
                            <div class="font-heading bold">- {{ supplierRefunds.length > 0 ? supplierRefunds[0].currency.short_code : 'MYR' }} {{ inputPaymentTotal > 0 ?  refundTotal > inputPaymentTotal ? inputPaymentTotal : formatNumber(refundTotal) : '0.00' }}</div>
                        </div>
                        <div class="col-auto text-right" v-else>
                            <div class="font-heading bold">- {{ supplierRefunds.length > 0 ? supplierRefunds[0].currency.short_code : 'MYR' }} {{ formatNumber(refundTotal > paymentTotal ? paymentTotal : refundTotal) }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-10 text-success">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Payment Total:</div>
                        </div>
                        <div class="col-auto text-right" v-if="is1688Supplier">
                            <div class="font-heading bold">MYR {{ formatNumber(inputPaymentTotal) }}</div>
                        </div>
                        <div class="col-auto text-right" v-else>
                            <div class="font-heading bold">MYR {{ formatNumber(paymentTotal - refundTotal > 0 ? (paymentTotal - refundTotal) : 0) }}</div>
                        </div>
                    </div>
                    <div class="row align-items-end m-b-10 text-primary" v-if="refundTotal > 0 && is1688Supplier && inputPaymentTotal > 0">
                        <div class="col">
                            <div class="font-heading all-caps fs-10">Payment Total After Refund:</div>
                        </div>
                        <div class="col-auto text-right">
                            <div class="font-heading bold">{{ supplierRefunds.length > 0 ? supplierRefunds[0].currency.short_code : 'MYR' }} {{ refundTotal > inputPaymentTotal ? '0.00' : formatNumber(inputPaymentTotal - refundTotal) }}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row" v-if="is1688Supplier">
                <div class="col p-r-0">
                    <validation-wrapper-component :validator="v$.payment_total">
                        <label class="all-caps">Payment Total</label>
                        <input type="text" class="form-control" v-model="parameters.payment_total" v-money3="productPrice">
                    </validation-wrapper-component>
                </div>
                <div class="col-auto b-r b-t b-b b-grey m-r-15">
                    <div class="row h-100 align-items-center">
                        <div class="col">
                            <div class="font-heading fs-10 muted">MYR</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row" v-else>
                <div class="col">
                    <validation-wrapper-component :validator="v$.service_charges">
                        <label class="all-caps">Service Charges</label>
                        <input type="text" class="form-control" :value="parameters.service_charges" v-money3="money" @change="parameters.service_charges = ($event.target as HTMLInputElement).value">
                    </validation-wrapper-component>
                </div>
            </div>
            <div class="row" v-if="paymentTotal > 0">
                <div class="col">
                    <button class="btn btn-xs btn-success b-rad-none p-t-5 p-b-5 all-caps fs-10 btn-block" @click="submitForm()">Create Bill Group</button>
                </div>
            </div>
            <div class="row" v-if="supplier.id !== ''">
                <div class="col mx-3 m-t-20">
                    <div class="m-b-20">
                        <small class="all-caps muted fs-15">Supplier Refund</small>
                    </div>
                    <list-component :key="supplierRefundListKey" section="supplierRefundListSection" :options="{'per_page': 20, 'type': 15, 'currency_rate_is_not_equal': 1, ...(supplier.id == 4548 && { 'created_after_or_equal': '01-08-2024' }), 'status': 2, 'receiver_in': [supplier.id]}" :endpoint="route('api.transaction.list')">
                        <template #list="{ data }">
                            <supplier-refund-component section="supplierRefundListSection" :data="data" :is1688Supplier="is1688Supplier" :payments="payments" :supplierRefunds="supplierRefunds" :refundTotal="refundTotal" :paymentTotal="paymentTotal" :inputPaymentTotal="inputPaymentTotal" @update:modelValue="refundOrder($event)"></supplier-refund-component>
                        </template>
                    </list-component>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useFormHandler } from '@/composables/useFormHandler';
import { useUiStore } from '@/stores/ui';
import { requiredIf } from '@vuelidate/validators';
import useVuelidate from '@vuelidate/core';
import { Money3Directive as vMoney } from 'v-money3';
import route from '@/general/functions/router';
import ValidationWrapperComponent from '@/components/general/forms/ValidationWrapperComponent.vue';

const props = defineProps<{
    section: string;
    data?: any;
    payments: any[];
    supplier: any;
    refreshList: () => void;
}>();

const uiStore = useUiStore();
const { isLoading, parameters, submit } = useFormHandler(props);

const supplierRefunds = ref<any[]>([]);
const supplierRefundListKey = ref(1);

parameters.value = {
    service_charges: '0',
    payment_total: '0',
};

const is1688Supplier = computed(() => false);

const rules = {
    service_charges: {
        required: requiredIf(() => !is1688Supplier.value)
    },
    payment_total: {
        required: requiredIf(() => is1688Supplier.value),
        minValue: (value: string) => {
            if (!is1688Supplier.value) return true;
            if (!value) return false;
            const amount = parseFloat(value.replace(/,/g, ''));
            return amount >= 1;
        }
    }
};

const money = {
    decimal: '.',
    thousands: ',',
    precision: 2
};
const productPrice = {
    decimal: '.',
    thousands: ',',
    precision: 2
};

const v$ = useVuelidate(rules, parameters);

const inputPaymentTotal = computed(() => {
    if (typeof parameters.value.payment_total !== 'string') return 0;
    return parseFloat(parameters.value.payment_total.replace(/,/g, ''));
});
const originalTotal = computed(() => props.payments.reduce((total, cur) => total + cur.original_amount, 0));
const total = computed(() => props.payments.reduce((total, cur) => total + cur.amount, 0));
const paymentTotal = computed(() => {
    const charges = typeof parameters.value.service_charges === 'string' ? parseFloat(parameters.value.service_charges.replace(/,/g, '')) : 0;
    return total.value ? total.value + charges : 0;
});
const refundTotal = computed(() => supplierRefunds.value.reduce((total, cur) => total + cur.amount, 0));
const billGroupCurrencyRate = computed(() => {
    const pTotal = inputPaymentTotal.value;
    return originalTotal.value && pTotal > 0 ? (originalTotal.value / pTotal).toFixed(5) : '1.00000';
});

const formatNumber = (value: number) => {
    return (Math.round((value + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

const refundOrder = (supplierRefund: any) => {
    const index = supplierRefunds.value.findIndex(item => item.id === supplierRefund.id);
    if (index > -1) {
        supplierRefunds.value.splice(index, 1);
    } else {
        supplierRefunds.value.push(supplierRefund);
    }
};

const successHandler = () => {
    props.refreshList();
    supplierRefunds.value = [];
    supplierRefundListKey.value++;

    const isShowing = uiStore.isShowing('paymentInProgressBillGroupList');
    uiStore.toggleSection('paymentInProgressBillGroupList', !isShowing);

    parameters.value = {
        service_charges: '0',
        payment_total: '0',
    };
};

const submitForm = () => {
    const sortedRefunds = [...supplierRefunds.value].sort((a, b) => a.amount - b.amount);
    const apiParams = {
        payments: props.payments,
        supplierRefunds: sortedRefunds,
        service_charges: is1688Supplier.value ? '0' : parameters.value.service_charges,
        payment_total: is1688Supplier.value ? parameters.value.payment_total : '0',
    };
    submit(route('api.transaction.supplier.bill_group.create', props.supplier.id), 'post', 'transactionGroupsListPaymentSection', true, true, apiParams, { successHandler });
};

watch(() => props.supplier, () => {
    supplierRefundListKey.value++;
    supplierRefunds.value = [];
}, { deep: true });
</script>
