import * as api from "../api/api.js";

export default {
    namespaced: true,
    state: {
        form_order: {
            podate: moment(new Date()).format('YYYY-MM-DD'),
            supplierID: "",
            reference: "",
            branchID: "",
            gudangID: "",
            typepajak: "percent",
            valuepajak: 0,
            typediskon: "percent",
            valuediskon: 0,
            catatan: ""
        },
        form_kontrak: {
            nama_kontrak: '',
            tanggal_kontrak: moment(new Date()).format('YYYY-MM-DD'),
            tanggalAwal_kontrak: moment(new Date()).format('YYYY-MM-DD'),
            tanggalAkhir_kontrak: moment(new Date()).format('YYYY-MM-DD'),
            durasi_cicilan: 1,
            jumlah_cicilan: 1,
            tanggalBayar_cicilan: 1,
            besarNilai_cicilan: 0,
            type_downpayment: 'percent',
            besarNilai_downpayment: 0
        },
        received_order: [],
        summary_order: {
            subtotal: 0,
            diskon: 0,
            pajak: 0,
            downpayment: 0,
            total_before_downpayment: 0,
            total: 0
        }
    },
    mutations: {
        update_form_order(state, val) {
            state.form_order = val
        },
        update_form_kontrak(state, val) {
            state.form_kontrak = val
        },
        update_received_order(state, val) {
            state.received_order = val
        },
        update_summary_order(state, val) {
            state.summary_order = val
        }
    },
    actions: {
        async getDetailDataPO(context, poID) {
            try {
                const params = {
                    token: one_token(),
                    poID: poID,
                };
                const resp = await api.getDataKontrakPoAset(params);
                if (resp.status != 'OK') {
                    throw new Error(resp.message);
                }

                let formOrder = {
                    podate: resp.data.podate,
                    supplierID: resp.data.supplierID,
                    reference: resp.data.reference,
                    branchID: resp.data.branchID,
                    gudangID: resp.data.gudangID,
                    typepajak: resp.data.typepajak,
                    valuepajak: parseFloat(resp.data.valuepajak),
                    typediskon: resp.data.typediskon,
                    valuediskon: parseFloat(resp.data.valuediskon),
                    catatan: resp.data.catatan
                };
                let formKontrak = {
                    nama_kontrak: resp.data.contractName,
                    tanggal_kontrak: resp.data.contractDate,
                    tanggalAwal_kontrak: resp.data.contractStart,
                    tanggalAkhir_kontrak: resp.data.contractEnd,
                    durasi_cicilan: resp.data.contractDuration,
                    jumlah_cicilan: resp.data.installmentNumber,
                    tanggalBayar_cicilan: resp.data.installmentDate,
                    besarNilai_cicilan: parseFloat(resp.data.installmentPayAmount),
                    type_downpayment: resp.data.installmentDownPaymentType,
                    besarNilai_downpayment: parseFloat(resp.data.installmentDownPayment),
                };
                let summary = resp.data.summary;
                let selected_request = resp.data.detail;
                selected_request.forEach(item => {
                    item.SupplierPrice = parseFloat(item.SupplierPrice)
                    item.DiskonAmount = parseFloat(item.DiskonAmount)
                });

                context.dispatch('orderAsset/listingGudang', resp.data.branchID, { root: true });

                context.commit('update_form_kontrak', formKontrak);
                context.commit("update_form_order", formOrder);
                context.commit("update_received_order", selected_request);
                context.commit("update_summary_order", summary);

                context.dispatch('recalculateOrderSummary');
            } catch (e) {
                const snac = { color: 'error', msg: e.message, state: true };
                context.commit("orderAsset/update_snackbar", snac, { root: true });
            }
        },
        async recalculateOrderSummary(context) {
            const formOrder = context.state.form_order;
            const formKontrak = context.state.form_kontrak;
            const items = JSON.parse(JSON.stringify(context.state.received_order));

            const calculatedItems = items.map(item => {
                const supplierPrice = parseCurrency(item.SupplierPrice);
                const requestQty = item.detail.reduce((sum, detail) => {
                    return sum + parseCurrency(detail.RequestQty);
                }, 0);

                let itemDiscount = 0;

                if (item.DiskonType == 'P') {
                    itemDiscount = supplierPrice * parseCurrency(item.DiskonAmount) / 100;
                } else {
                    itemDiscount = parseCurrency(item.DiskonAmount);
                }

                const endPrice = Math.max(supplierPrice - itemDiscount, 0);
                const tempTotal = requestQty * endPrice;

                return {
                    ...item,
                    RequestQty: requestQty,
                    EndPrice: endPrice,
                    TempTotal: tempTotal,
                    detail: item.detail.map(detail => ({
                        ...detail,
                        SupplierPrice: supplierPrice
                    }))
                };
            });

            const subtotal = calculatedItems.reduce((sum, item) => {
                return sum + parseCurrency(item.TempTotal);
            }, 0);

            const diskon = calculateByType(
                formOrder.typediskon,
                formOrder.valuediskon,
                subtotal
            );
            const subtotalAfterDiskon = Math.max(subtotal - diskon, 0);

            const pajak = calculateByType(
                formOrder.typepajak,
                formOrder.valuepajak,
                subtotalAfterDiskon
            );
            const totalBeforeDownpayment = subtotalAfterDiskon + pajak;

            const downpayment = calculateByType(
                formKontrak.type_downpayment,
                formKontrak.besarNilai_downpayment,
                totalBeforeDownpayment
            );

            const total = Math.max(totalBeforeDownpayment - downpayment, 0);

            context.commit('update_received_order', calculatedItems);
            context.commit('update_summary_order', {
                subtotal: subtotal,
                diskon: diskon,
                pajak: pajak,
                downpayment: downpayment,
                total_before_downpayment: totalBeforeDownpayment,
                total: total
            });
        }
    }
}

function parseCurrency(value) {
    let cleanValue = String(value || 0).replace(/\./g, '');
    cleanValue = cleanValue.replace(',', '.');
    return parseFloat(cleanValue) || 0;
}

function calculateByType(type, value, base) {
    const amount = parseCurrency(value);

    if (type == 'percent') {
        return base * amount / 100;
    }

    return amount;
}
