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

export default {
    namespaced: true,
    state: {
        /* dialog create order */
        dialog_create_order: false,
        form_order_asset: {
            podate: moment(new Date()).format('YYYY-MM-DD'),
            supplierID: "",
            reference: "",
            branchID: "",
            gudangID: "",
            typepajak: "percent",
            valuepajak: 0,
            typediskon: "percent",
            valuediskon: 0,
            catatan: ""
        },
        list_supplier: [],
        list_cabang: [],
        list_gudang: [],

        /* item request */
        dialog_select_asset: false,
        requested_asset: {
            records: [],
            total: 0,
        },
        selected_request_asset: [],
        summary_order: {
            subtotal: 0,
            diskon: 0,
            pajak: 0,
            downpayment: 0,
            total_before_downpayment: 0,
            total: 0
        }
    },
    mutations: {
        update_dialog_create_order(state, val) {
            state.dialog_create_order = val
        },
        update_form_order_asset(state, val) {
            state.form_order_asset = val
        },
        update_list_supplier(state, val) {
            state.list_supplier = val
        },
        update_list_cabang(state, val) {
            state.list_cabang = val
        },
        update_list_gudang(state, val) {
            state.list_gudang = val
        },
        update_dialog_select_asset(state, val) {
            state.dialog_select_asset = val
        },
        update_requested_asset(state, val) {
            state.requested_asset = val
        },
        update_selected_request_asset(state, val) {
            state.selected_request_asset = val
        },
        update_summary_order(state, val) {
            state.summary_order = val
        }
    },
    actions: {
        async listingCabang(context) {
            try {
                let param = { token: one_token() }

                const resp = await api.getListCabang(param);
                if (resp.status != "OK") {
                    throw new Error(resp.message);
                }

                context.commit('update_list_cabang', resp.data);
            } catch (e) {
                const snac = { color: 'error', msg: e.message, state: true };
                context.commit("common/update_snackbar", snac, { root: true });
            }
        },
        async listingGudang(context, branchID) {
            try {
                let param = {
                    token: one_token(),
                    M_BranchID: branchID
                }

                const resp = await api.getListGudang(param);
                if (resp.status != "OK") {
                    throw new Error(resp.message);
                }

                context.commit('update_list_gudang', resp.data);
            } catch (e) {
                const snac = { color: 'error', msg: e.message, state: true };
                context.commit("common/update_snackbar", snac, { root: true });
            }
        },
        async listingSupplier(context) {
            try {
                const params = { token: one_token() };
                const resp = await api.getListSupplier(params);
                if (resp.status != 'OK') {
                    throw new Error(resp.message);
                }

                context.commit('update_list_supplier', resp.data);
            } catch (e) {
                const snac = { color: 'error', msg: e.message, state: true };
                context.commit("update_snackbar", snac, { root: true });
            }
        },
        async searchItemRequest(context, keyword) {
            try {
                const form = context.state.form_order_asset;
                const params = {
                    token: one_token(),
                    search: keyword,
                    branchID: form.branchID,
                    supplierID: form.supplierID
                };
                const resp = await api.searchRequestAset(params);
                if (resp.status != 'OK') {
                    throw new Error(resp.message);
                }

                context.commit('update_requested_asset', resp.data)
            } catch (e) {
                const snac = { color: 'error', msg: e.message, state: true };
                context.commit("update_snackbar", snac, { root: true });
            }
        },
        async recalculateOrderSummary(context) {
            const formOrder = context.state.form_order_asset;
            const formKontrak = context.rootState.kontrakAsset.form_kontrak;
            const items = JSON.parse(JSON.stringify(context.state.selected_request_asset));

            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_selected_request_asset', 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;
}
