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

export default {
    namespaced: true,
    state: {
        opendialog: false,
        user: one_user(),
        form_faktur: {
            form_date: moment(new Date()).format("YYYY-MM-DD"),
            form_duedate: moment(new Date()).format("YYYY-MM-DD"),
            form_draftdate: moment(new Date()).format("YYYY-MM-DD"),
            form_supplier: {},
            form_po: {},
            form_refnumber: "",
            form_supplier_invoicenum: "",
            form_supplier_invoicedate: moment(new Date()).format("YYYY-MM-DD"),
            form_tax_percent_pph: 0.00,
            form_tax_amount_pph: 0.00,
            form_tax_percent_ppn: 0.00,
            form_tax_amount_ppn: 0.00,
            form_disc_po: 0.00,
            form_disc_amount: 0.00,
            form_disc_type: "",
            form_subtotal: 0.00,
            form_grandtotal: 0.00,
            form_note: "",
            form_adjust_amount: 0.00,
            form_adjust_note: "",
            form_shipping_cost: 0.00,
        },

        // form tambah item
        dialog_item: false,
        form_ro: {},
        form_item: [],
        is_create: false,
    },
    mutations: {
        update_opendialog(state, data) {
            state.opendialog = data
        },
        update_form_faktur(state, data) {
            state.form_faktur = data
        },
        update_form_ro(state, data) {
            state.form_ro = data
        },
        update_form_item(state, data) {
            state.form_item = data
        },
        update_dialog_item(state, data) {
            state.dialog_item = data
        },
        update_is_create(state, data) {
            state.is_create = data
        }
    },
    actions: {
        resetForm(context) {
            const form_faktur = {
                form_date: moment(new Date()).format("YYYY-MM-DD"),
                form_duedate: moment(new Date()).format("YYYY-MM-DD"),
                form_draftdate: moment(new Date()).format("YYYY-MM-DD"),
                form_supplier: {},
                form_po: {},
                form_refnumber: "",
                form_supplier_invoicenum: "",
                form_supplier_invoicedate: moment(new Date()).format("YYYY-MM-DD"),
                form_tax_percent_pph: 0.00,
                form_tax_amount_pph: 0.00,
                form_tax_percent_ppn: 0.00,
                form_tax_amount_ppn: 0.00,
                form_disc_po: 0.00,
                form_disc_amount: 0.00,
                form_disc_type: "R",
                form_subtotal: 0.00,
                form_grandtotal: 0.00,
                form_note: "",
                form_adjust_amount: 0.00,
                form_adjust_note: "",
                form_shipping_cost: 0.00,
            }
            context.commit("update_form_faktur", form_faktur)
            context.commit("update_form_ro", {})
            context.commit("update_form_item", [])
            context.commit("data/update_list_po", {records: [], total: 0}, {root: true})
        },
        async calcSummary(context) {
            try {
                let item = context.state.form_item
                let faktur = context.state.form_faktur
                if (item.length > 0) {
                    let sub = 0
                    let podisc = 0
                    item.forEach(ite => {
                        let price = Number(ite.ReceiveOrderPoDetailPrice)
                        let disc = Number(ite.Discount)
                        let qty = Number(ite.ReceiveOrderPoDetailQty)
                  
                        if (ite.PurchaseOrderSummaryDiscountType == 'P') {
                            disc = (price * Number(ite.Discount)) / 100
                        }

                        sub = sub + (qty * (price - disc))
                        podisc = podisc + Number(ite.ReceiveOrderPoDetailDiskonPoProrata)
                    });

                    let pph = (sub - podisc) * (Number(faktur.form_tax_percent_pph) / 100)
                    let ppn = (sub - podisc) * (Number(faktur.form_tax_percent_ppn) / 100)
                    let grandtotal = (sub - podisc + pph + ppn) + Number(faktur.form_adjust_amount) + Number(faktur.form_shipping_cost)
                    
                    // Store exact values with 2 decimal places using floor instead of rounding
                    // This prevents rounding errors in financial calculations
                    faktur.form_subtotal = sub
                    faktur.form_disc_amount = podisc
                    faktur.form_tax_amount_ppn = ppn
                    faktur.form_tax_amount_pph = pph
                    faktur.form_grandtotal = grandtotal
                } else {
                    faktur.form_subtotal = 0.00
                    faktur.form_disc_amount = 0.00
                    faktur.form_grandtotal = 0.00
                    faktur.form_tax_amount_pph = 0.00
                    faktur.form_tax_amount_ppn = 0.00
                    faktur.form_adjust_amount = 0.00
                    faktur.form_adjust_note = ""
                }

                context.commit("update_form_faktur", faktur)
            } catch (error) {
                let snacc = {isOpen: true, message: error.message, color: "error"}
                context.commit("data/update_snack", snacc, {root: true})
            }
        },
        async createFaktur(context) {
            try {
                let item = context.state.form_item
                let para_item = []
                
                let param = {
                    SIPoID: context.state.form_faktur.form_po.PurchaseOrderID,
                    SIDate: context.state.form_faktur.form_date,
                    SIDueDate: context.state.form_faktur.form_duedate,
                    SIDraftDate: context.state.form_faktur.form_draftdate,
                    SISupplierID: context.state.form_faktur.form_supplier.SupplierID,
                    SIRefNumber: context.state.form_faktur.form_refnumber,
                    SISupplierInvoiceNumber: context.state.form_faktur.form_supplier_invoicenum,
                    SISupplierInvoiceDate: context.state.form_faktur.form_supplier_invoicedate,
                    SISubTotal: context.state.form_faktur.form_subtotal,
                    SIDiscountPercent: context.state.form_faktur.form_disc_type == 'P' ? context.state.form_faktur.form_disc_po : 0,
                    SIDiscountAmount: context.state.form_faktur.form_disc_amount,
                    SITaxPercentPph: context.state.form_faktur.form_tax_percent_pph,
                    SITaxAmountPph: context.state.form_faktur.form_tax_amount_pph,
                    SITaxPercentPpn: context.state.form_faktur.form_tax_percent_ppn,
                    SITaxAmountPpn: context.state.form_faktur.form_tax_amount_ppn,
                    SIShippingCost: context.state.form_faktur.form_shipping_cost,
                    SIAdjustmentAmount: context.state.form_faktur.form_adjust_amount,
                    SIAdjustmentNote: context.state.form_faktur.form_adjust_note,
                    SIGrandTotal: context.state.form_faktur.form_grandtotal,
                    SINote: context.state.form_faktur.form_note,
                    SIReceiveDate: moment(new Date()).format("YYYY-MM-DD"),
                    SIReceivedBy: context.state.user.M_UserID,
                    SIStatus: 'Draft',
                    SIDetail: [],
                    token: one_token()
                }

                item.forEach(ele => {
                    let a = {
                        SIDPOID: ele.ReceiveOrderPoDetailPurchaseOrderID,
                        SIDPOSummaryID: ele.ReceiveOrderPoDetailPurchaseOrderSummaryID,
                        SIDROID: ele.ReceiveOrderPoDetailReceiveOrderPoID,
                        SIDRODetailID: ele.ReceiveOrderPoDetailID,
                        SIDItemID: ele.M_ItemID,
                        SIDItemUnitID: ele.ReceiveOrderPoItemUnitID,
                        SIDDescription: ele.M_ItemDesc,
                        SIDQty: ele.ReceiveOrderPoDetailQty,
                        SIDPrice: ele.ReceiveOrderPoDetailPrice,
                        SIDDiscountPercent: ele.PurchaseOrderSummaryDiscountType == 'P' ? ele.Discount: 0,
                        SIDDiscountRupiah: ele.PurchaseOrderSummaryDiscountType == 'R' ? ele.Discount: 0,
                        SIDDiscountType: ele.PurchaseOrderSummaryDiscountType,
                        SIDDiscountAmount: ele.disc_amount,
                        SIDDiscountPOProrata: ele.ReceiveOrderPoDetailDiskonPoProrata,
                        SIDTotal: ele.subtotal
                    }
                    para_item.push(a)
                });

                param.SIDetail = para_item

                let resp = await api.CreateFaktur(param)
                if (resp.status != 'OK') {
                    let snacc = {isOpen: true, message: resp.message, color: "error"}
                    context.commit("data/update_snack", snacc, {root: true})
                } else {
                    let snacc = {isOpen: true, message: 'Success', color: "success"}
                    context.commit("data/update_snack", snacc, {root: true})
                    context.dispatch("data/getListFaktur", {}, {root: true})
                    context.commit("update_opendialog", false)
                }
            } catch (error) {
                let snacc = {isOpen: true, message: error.message, color: "error"}
                context.commit("data/update_snack", snacc, {root: true})
            }
        },
        async updateFaktur(context) {
            try {
                let faktur = context.state.form_faktur
                let param = {
                    SIPoID: faktur.form_po.PurchaseOrderID,
                    SIDate: faktur.form_date,
                    SIDueDate: faktur.form_duedate,
                    SIDraftDate: faktur.form_draftdate,
                    SISupplierID: faktur.form_supplier.SupplierID,
                    SIRefNumber: faktur.form_refnumber,
                    SISupplierInvoiceNumber: faktur.form_supplier_invoicenum,
                    SISupplierInvoiceDate: faktur.form_supplier_invoicedate,
                    SISubTotal: faktur.form_subtotal,
                    SIDiscountPercent: faktur.form_disc_type == 'P' ? faktur.form_disc_po : 0,
                    SIDiscountAmount: faktur.form_disc_amount,
                    SITaxPercentPph: faktur.form_tax_percent_pph,
                    SITaxAmountPph: faktur.form_tax_amount_pph,
                    SITaxPercentPpn: faktur.form_tax_percent_ppn,
                    SITaxAmountPpn: faktur.form_tax_amount_ppn,
                    SIShippingCost: faktur.form_shipping_cost,
                    SIAdjustmentAmount: faktur.form_adjust_amount,
                    SIAdjustmentNote: faktur.form_adjust_note,
                    SIGrandTotal: faktur.form_grandtotal,
                    SINote: faktur.form_note,
                    SIStatus: 'Draft',
                    SIDetail: [],
                    fakturID: faktur.fakturID,
                    token: one_token()
                }

                let item = context.state.form_item
                let detail = []
                item.forEach(ele => {
                    let a = {
                        SIDPOID: ele.ReceiveOrderPoDetailPurchaseOrderID,
                        SIDPOSummaryID: ele.ReceiveOrderPoDetailPurchaseOrderSummaryID,
                        SIDROID: ele.ReceiveOrderPoDetailReceiveOrderPoID,
                        SIDRODetailID: ele.ReceiveOrderPoDetailID,
                        SIDItemID: ele.M_ItemID,
                        SIDItemUnitID: ele.ReceiveOrderPoItemUnitID,
                        SIDDescription: ele.M_ItemDesc,
                        SIDQty: ele.ReceiveOrderPoDetailQty,
                        SIDPrice: ele.ReceiveOrderPoDetailPrice,
                        SIDDiscountPercent: ele.PurchaseOrderSummaryDiscountType == 'P' ? ele.Discount: 0,
                        SIDDiscountRupiah: ele.PurchaseOrderSummaryDiscountType == 'R' ? ele.Discount: 0,
                        SIDDiscountType: ele.PurchaseOrderSummaryDiscountType,
                        SIDDiscountAmount: ele.disc_amount,
                        SIDDiscountPOProrata: ele.ReceiveOrderPoDetailDiskonPoProrata,
                        SIDTotal: ele.subtotal
                    }
                    detail.push(a)
                })
                param.SIDetail = detail
                // console.log('param update', param)

                let resp = await api.UpdateFaktur(param)
                if (resp.status != 'OK') {
                    let snacc = {isOpen: true, message: resp.message, color: "error"}
                    context.commit("data/update_snack", snacc, {root: true})
                } else {
                    let snacc = {isOpen: true, message: 'Success', color: "success"}
                    context.commit("data/update_snack", snacc, {root: true})
                    context.dispatch("data/getListFaktur", {}, {root: true})
                    context.commit("update_opendialog", false)
                }
            } catch (error) {
                let snacc = {isOpen: true, message: error.message, color: "error"}
                context.commit("data/update_snack", snacc, {root: true})
            }
        },
        async deleteFaktur(context, params) {
            try {
                params.token = one_token()
                let resp = await api.DeleteFaktur(params)
                if (resp.status != 'OK') {
                    let snacc = {isOpen: true, message: resp.message, color: "error"}
                    context.commit("data/update_snack", snacc, {root: true})
                } else {
                    let snacc = {isOpen: true, message: 'Success', color: "success"}
                    context.commit("data/update_snack", snacc, {root: true})
                    context.dispatch("data/getListFaktur", {}, {root: true})
                }
            } catch (error) {
                let snacc = {isOpen: true, message: error.message, color: "error"}
                context.commit("data/update_snack", snacc, {root: true})
            }
        },
        async approveFaktur(context, param) {
            try {
                param.token = one_token()
                let resp = await api.ApproveFaktur(param)
                if (resp.status != 'OK') {
                    let snacc = {isOpen: true, message: resp.message, color: "error"}
                    context.commit("data/update_snack", snacc, {root: true})
                } else {
                    let snacc = {isOpen: true, message: 'Success', color: "success"}
                    context.commit("data/update_snack", snacc, {root: true})
                    context.dispatch("data/getListFaktur", {}, {root: true})
                }
            } catch (error) {
                let snacc = {isOpen: true, message: error.message, color: "error"}
                context.commit("data/update_snack", snacc, {root: true})
            }
        },
        async rejectFaktur(context, param) {
            try {
                param.token = one_token()
                let resp = await api.RejectFaktur(param)
                if (resp.status != 'OK') {
                    let snacc = {isOpen: true, message: resp.message, color: "error"}
                    context.commit("data/update_snack", snacc, {root: true})
                } else {
                    let snacc = {isOpen: true, message: 'Success', color: "success"}
                    context.commit("data/update_snack", snacc, {root: true})
                    context.dispatch("data/getListFaktur", {}, {root: true})
                }
            } catch (error) {
                let snacc = {isOpen: true, message: error.message, color: "error"}
                context.commit("data/update_snack", snacc, {root: true})
            }
        },
        async verifyFaktur(context, param) {
            try {
                param.token = one_token()
                let resp = await api.VerifyFaktur(param)
                if (resp.status != 'OK') {
                    let snacc = {isOpen: true, message: resp.message, color: "error"}
                    context.commit("data/update_snack", snacc, {root: true})
                } else {
                    let snacc = {isOpen: true, message: 'Success', color: "success"}
                    context.commit("data/update_snack", snacc, {root: true})
                    context.dispatch("data/getListFaktur", {}, {root: true})
                }
            } catch (error) {
                let snacc = {isOpen: true, message: error.message, color: "error"}
                context.commit("data/update_snack", snacc, {root: true})
            }
        }
    }
}