// 1 => LOADING
// 2 => DONE
// 3 => ERROR
import * as api from "../api/journal.js";

export default {
    namespaced: true,
    state: {
        search_status: 0,
        current_page: 1,
        x_search: "",
        search_error_message: "",
        last_id: -1,
        coas: [],
        total_coas: 0,
        selected_coa: {},
        dialog_form_coa: false,
        act: "new",
        save_status: 0,
        save_error_message: "",
        errors: [],
        alert_success: false,
        msg_success: "",
        alert_error: false,
        dialog_error: false,
        open_print: false,

        // ----
        xdate: moment(new Date()).format("YYYY-MM-DD"),
        end_date: moment(new Date()).format("YYYY-MM-DD"),
        journals: [],
        selected_journal: {},
        summary: { debit: 0, credit: 0, balance: 0 },
        dialog_form_detail: false,
        periodeList: [],
        selected_periode: {},
        loading: false,
        dialog_form_periode: false,
        autocomplete_status: 0,
        search_status: 0,
        total_journal: 0,
        user: one_user(),
        jurnaldetails: [],
        dialog_error_jurnal: false,
        msgerrjurnallist: [],
        regionals: [],
        selected_regional: {},
        branchs: [],
        selected_branch: {},
        open_dialog_info: false,
        msg_info: "",
        xsearch: "",

        // --
        dialog_edit_journal: false,
        user_level: {},
        list_coa: [],
        journal_edit: [],
        dialog_confirm_posting: false,
        total_jurnal_not_posted: [],
        dialog_request_edit: false,

        // ---
        dialog_close_jurnal: false,
        jurnal_to_close: []
    },
    mutations: {
        update_search_status(state, val) {
            state.search_status = val;
        },
        update_current_page(state, val) {
            state.current_page = val;
        },
        update_x_search(state, val) {
            state.x_search = val;
            state.current_page = 1;
        },
        update_search_error_message(state, val) {
            state.search_error_message = val;
        },
        update_last_id(state, val) {
            state.last_id = val;
        },
        update_coas(state, val) {
            state.coas = val;
        },
        update_total_coas(state, val) {
            state.total_coas = val;
        },
        update_selected_coa(state, val) {
            state.selected_coa = val;
        },
        update_dialog_form_coa(state, val) {
            state.dialog_form_coa = val;
        },
        update_act(state, val) {
            state.act = val;
        },
        update_save_status(state, val) {
            state.save_status = val;
        },
        update_save_error_message(state, val) {
            state.save_error_message = val;
        },
        update_errors(state, val) {
            state.errors = val;
        },
        update_alert_success(state, val) {
            state.alert_success = val;
        },
        update_msg_success(state, val) {
            state.msg_success = val;
        },
        update_alert_error(state, val) {
            state.alert_error = val;
        },
        update_dialog_error(state, val) {
            state.dialog_error = val;
        },
        update_open_print(state, value) {
            state.open_print = value;
        },

        // ---
        update_xdate(state, val) {
            state.xdate = val;
        },
        update_end_date(state, val) {
            state.end_date = val;
        },
        update_journals(state, val) {
            state.journals = val;
        },
        update_selected_journal(state, val) {
            state.selected_journal = val;
        },
        update_summary(state, val) {
            state.summary = val;
        },
        update_dialog_form_detail(state, val) {
            state.dialog_form_detail = val;
        },
        update_periodeList(state, val) {
            state.periodeList = val;
        },
        update_selected_periode(state, val) {
            state.selected_periode = val;
        },
        update_loading(state, val) {
            state.loading = val;
        },
        update_dialog_form_periode(state, val) {
            state.dialog_form_periode = val;
        },
        update_autocomplete_status(state, val) {
            state.autocomplete_status = val;
        },
        update_search_status(state, val) {
            state.search_status = val;
        },
        update_total_journal(state, val) {
            state.total_journal = val;
        },
        update_user(state, val) {
            state.user = val;
        },
        update_jurnaldetails(state, val) {
            state.jurnaldetails = val;
        },
        update_dialog_error_jurnal(state, val) {
            state.dialog_error_jurnal = val;
        },
        update_msgerrjurnallist(state, val) {
            state.msgerrjurnallist = val;
        },
        update_regionals(state, val) {
            state.regionals = val;
        },
        update_selected_regional(state, val) {
            state.selected_regional = val;
        },
        update_branchs(state, val) {
            state.branchs = val;
        },
        update_selected_branch(state, val) {
            state.selected_branch = val;
        },
        update_open_dialog_info(state, val) {
            state.open_dialog_info = val;
        },
        update_msg_info(state, val) {
            state.msg_info = val;
        },
        update_xsearch(state, val) {
            state.xsearch = val;
            state.current_page = 1;
        },

        update_dialog_edit_journal(state, val) {
            state.dialog_edit_journal = val;
        },
        update_user_level(state, val) {
            state.user_level = val;
        },
        update_list_coa(state, val) {
            state.list_coa = val;
        },
        update_journal_edit(state, val) {
            state.journal_edit = val;
        },
        update_dialog_confirm_posting(state, val) {
            state.dialog_confirm_posting = val;
        },
        update_total_jurnal_not_posted(state, val) {
            state.total_jurnal_not_posted = val;
        },
        update_dialog_request_edit(state, val) {
            state.dialog_request_edit = val;
        },

        update_dialog_close_jurnal(state, val) {
            state.dialog_close_jurnal = val;
        },
        update_jurnal_to_close(state, val) {
            state.jurnal_to_close = val;
        }
    },
    actions: {
        async getPeriode(context) {
            context.commit("update_autocomplete_status", 1);
            try {
                let prm = {};
                prm.token = one_token();
                let resp = await api.getPeriode(prm);
                if (resp.status != "OK") {
                    context.commit("update_autocomplete_status", 3);
                } else {
                    context.commit("update_autocomplete_status", 2);
                    let data = resp.data;
                    context.commit("update_periodeList", resp.data);

                    // Ambil bulan dan tahun sekarang
                    let now = new Date();
                    let currentMonth = now.getMonth() + 1; // getMonth() dimulai dari 0 (Jan = 0)
                    let currentYear = now.getFullYear().toString(); // Ambil tahun dalam bentuk string

                    // Cari data dengan periodeMonth dan periodeYear yang cocok
                    let selectedPeriode = data.find(
                        (p) =>
                            p.periodeMonth == currentMonth.toString() &&
                            p.periodeYear == currentYear
                    );

                    // Jika tidak ditemukan, gunakan data pertama sebagai default
                    if (!selectedPeriode) {
                        selectedPeriode = data[0];
                    }

                    context.commit("update_selected_periode", selectedPeriode);
                }
            } catch (e) {
                context.commit("update_autocomplete_status", 3);
            }
        },
        async search(context, prm) {
            context.commit("update_search_status", 1);
            try {
                let resp = await api.search(
                    one_token(),
                    prm.xdate,
                    prm.periodeid,
                    prm.current_page,
                    prm.search,
                    prm.branchCode,
                    prm.regionalId
                );
                if (resp.status != "OK") {
                    context.commit("update_search_status", 3);
                    context.commit("update_search_error_message", resp.message);
                } else {
                    context.commit("update_search_status", 2);
                    context.commit("update_search_error_message", "");
                    let data = {
                        records: resp.data.records,
                        total: resp.data.total
                    };

                    context.commit("update_journals", data.records);
                    context.commit("update_total_journal", data.total);
                }
            } catch (e) {
                context.commit("update_search_status", 3);
                context.commit("update_search_error_message", e.message);
            }
        },

        async insertSales(context, prm) {
            context.commit("update_save_status", 1);
            try {
                let branchCode = prm.branchCode;
                let date = prm.date;
                let jurnalno = prm.jurnalno;
                let resp = await api.insertSales(branchCode, date, jurnalno);
                if (resp.status != "OK") {
                    context.commit("update_save_status", 3);
                    context.commit("update_save_error_message", resp.message);
                    context.commit("update_alert_error", true);
                } else {
                    context.commit("update_save_status", 2);
                    context.commit("update_save_error_message", resp.message);
                    let data = {
                        total: resp.data.total
                    };

                    context.commit("update_alert_success", true);
                    var msg = resp.data.msg;
                    context.commit("update_msg_success", msg);
                    context.dispatch("search", {
                        branchCode: prm.branchCode,
                        regionalId: context.state.selected_regional.S_RegionalID,
                        search: context.state.x_search,
                        current_page: context.state.current_page,
                        xdate: context.state.xdate,
                        periodeid: context.state.selected_periode.id
                    });
                }
            } catch (e) {
                context.commit("update_save_status", 3);
                context.commit("update_save_error_message", e.message);
                context.commit("update_alert_error", true);
            }
        },

        async getRegional(context) {
            context.commit("update_autocomplete_status", 1);
            try {
                let resp = await api.getRegional({
                    token: one_token(),
                    regionalId: context.state.user.S_RegionalID
                });
                if (resp.status != "OK") {
                    context.commit("update_search_error_message", resp.message);
                    context.commit("update_autocomplete_status", 3);
                } else {
                    context.commit("update_search_error_message", "");
                    context.commit("update_autocomplete_status", 2);
                    let data = {
                        records: resp.data.records,
                        selected: resp.data.selected
                    };

                    context.commit("update_regionals", data.records);
                    context.commit("update_selected_regional", data.selected);
                }
            } catch (e) {
                context.commit("update_search_error_message", e.message);
                context.commit("update_autocomplete_status", 3);
            }
        },

        async getBranch(context) {
            context.commit("update_autocomplete_status", 1);
            try {
                let resp = await api.getBranch({
                    token: one_token(),
                    regionalId: context.state.selected_regional.S_RegionalID,
                    branchCode: context.state.user.M_BranchCode
                });
                if (resp.status != "OK") {
                    context.commit("update_search_error_message", resp.message);
                    context.commit("update_autocomplete_status", 3);
                } else {
                    context.commit("update_search_error_message", "");
                    context.commit("update_autocomplete_status", 2);
                    let data = {
                        records: resp.data.records,
                        selected: resp.data.selected
                    };

                    context.commit("update_branchs", data.records);
                    context.commit("update_selected_branch", data.selected);
                }
            } catch (e) {
                context.commit("update_search_error_message", e.message);
                context.commit("update_autocomplete_status", 3);
            }
        },

        async postingJurnal(context, typeid) {
            try {
                let param = {
                    token: one_token(),
                    jurnalTypeID: typeid,
                    periodeID: context.state.selected_periode.id
                };
                const resp = await api.changeJurnalToPosted(param);
                if (resp.status != "OK") {
                    context.commit("update_alert_error", true);
                    context.commit("update_save_error_message", resp.message);
                } else {
                    context.commit("update_msg_success", resp.data);
                    context.commit("update_alert_success", true);

                    context.dispatch("search", {
                        branchCode: context.state.selected_branch.M_BranchCode ?? "",
                        regionalId: context.state.selected_regional.S_RegionalID,
                        search: context.state.x_search,
                        current_page: context.state.current_page,
                        xdate: context.state.xdate,
                        periodeid: context.state.selected_periode.id
                    });

                    context.commit("update_total_jurnal_not_posted", []);
                    context.commit("update_dialog_confirm_posting", false);
                }
            } catch (error) {
                context.commit("update_alert_error", true);
                context.commit("update_save_error_message", error.message);
            }
        },

        async getUserApprovalLevel(context) {
            try {
                let param = { token: one_token() };
                const resp = await api.getUserApproveLevel(param);
                if (resp.status != "OK") {
                    context.commit("update_alert_error", true);
                    context.commit("update_save_error_message", resp.message);
                } else {
                    context.commit("update_user_level", resp.data);
                }
            } catch (error) {
                context.commit("update_alert_error", true);
                context.commit("update_save_error_message", error.message);
            }
        },

        async getListingCOA(context) {
            try {
                let param = {
                    token: one_token(),
                    keyword: ""
                };
                const resp = await api.getListingCOA(param);
                if (resp.status != "OK") {
                    context.commit("update_alert_error", true);
                    context.commit("update_save_error_message", resp.message);
                } else {
                    context.commit("update_list_coa", resp.data);
                }
            } catch (error) {
                context.commit("update_alert_error", true);
                context.commit("update_save_error_message", error.message);
            }
        },

        async requestEditJurnal(context) {
            try {
                let param = {
                    token: one_token(),
                    jurnalID: context.state.selected_journal.jurnalID,
                    staffID: context.state.user.M_UserID,
                    staffName: context.state.user.M_UserUsername
                };
                const resp = await api.requestEditJurnal(param);
                if (resp.status != "OK") {
                    context.commit("update_alert_error", true);
                    context.commit("update_save_error_message", resp.message);
                } else {
                    context.commit("update_msg_success", resp.data);
                    context.commit("update_alert_success", true);
                    context.commit("update_dialog_request_edit", false);
                }
            } catch (error) {
                context.commit("update_alert_error", true);
                context.commit("update_save_error_message", error.message);
            }
        },

        async saveEditJurnal(context, newdetail) {
            try {
                let param = {
                    token: one_token(),
                    jurnalID: context.state.selected_journal.jurnalID,
                    jurnalRequestEditID: context.state.selected_journal.JurnalRequestEditID,
                    oldjurnaltx: context.state.selected_journal.detailtx,
                    newjurnaltx: newdetail
                };
                const resp = await api.saveEditJurnal(param);
                if (resp.status != "OK") {
                    context.commit("update_alert_error", true);
                    context.commit("update_save_error_message", resp.message);
                } else {
                    context.dispatch("search", {
                        branchCode: context.state.selected_branch.M_BranchCode ?? "",
                        regionalId: context.state.selected_regional.S_RegionalID,
                        search: context.state.x_search,
                        current_page: context.state.current_page,
                        xdate: context.state.xdate,
                        periodeid: context.state.selected_periode.id
                    });

                    context.commit("update_dialog_edit_journal", false);
                    context.commit("update_msg_success", resp.data);
                    context.commit("update_alert_success", true);
                }
            } catch (error) {
                context.commit("update_alert_error", true);
                context.commit("update_save_error_message", error.message);
            }
        },

        async totalJurnalNotPostedPerPeriod(context) {
            try {
                let param = {
                    token: one_token(),
                    periodeID: context.state.selected_periode.id
                };
                const resp = await api.getTotalJurnalNotPostedPerPeriod(param);
                if (resp.status != "OK") {
                    context.commit("update_alert_error", true);
                    context.commit("update_save_error_message", resp.message);
                } else {
                    context.commit("update_total_jurnal_not_posted", resp.data.total_jurnal ?? []);
                }
            } catch (error) {
                context.commit("update_alert_error", true);
                context.commit("update_save_error_message", error.message);
            }
        },

        async getDataJurnalNotClosedPerPeriod(context) {
            try {
                let param = {
                    token: one_token(),
                    periodeID: context.state.selected_periode.id
                };
                const resp = await api.getDataJurnalNotClosedPerPeriod(param);
                if (resp.status != "OK") {
                    context.commit("update_alert_error", true);
                    context.commit("update_save_error_message", resp.message);
                } else {
                    context.commit("update_jurnal_to_close", resp.data ?? []);
                }
            } catch (error) {
                context.commit("update_alert_error", true);
                context.commit("update_save_error_message", error.message);
            }
        },

        async closeJurnalPerPeriode(context, typeid) {
            try {
                let param = {
                    token: one_token(),
                    jurnalTypeID: typeid,
                    periodeID: context.state.selected_periode.id
                };
                const resp = await api.closeJurnalPerPeriode(param);
                if (resp.status != "OK") {
                    context.commit("update_alert_error", true);
                    context.commit("update_save_error_message", resp.message);
                } else {
                    context.commit("update_msg_success", resp.data);
                    context.commit("update_alert_success", true);

                    context.dispatch("search", {
                        branchCode: context.state.selected_branch.M_BranchCode ?? "",
                        regionalId: context.state.selected_regional.S_RegionalID,
                        search: context.state.x_search,
                        current_page: context.state.current_page,
                        xdate: context.state.xdate,
                        periodeid: context.state.selected_periode.id
                    });

                    context.commit("update_jurnal_to_close", []);
                    context.commit("update_dialog_close_jurnal", false);
                }
            } catch (error) {
                context.commit("update_alert_error", true);
                context.commit("update_save_error_message", error.message);
            }
        }
    }
};
