<template>
    <div style="width: 100%" class="">
        <!-- SNACKBAR -->
        <v-snackbar v-model="snackbar" color="success" :timeout="5000" :multi-line="false" :vertical="false"
            :top="true">
            {{ msgSnackbar }}
            <v-btn flat @click="updateAlertSuccess(false)"> Tutup </v-btn>
        </v-snackbar>

        <!-- ERROR DIALOG -->
        <v-dialog v-model="dialog_error" max-width="500px">
            <v-card>
                <v-card-title>
                    <span>ERROR !</span>
                    <v-spacer></v-spacer>
                </v-card-title>
                <v-divider></v-divider>
                <div class="ma-3 red--text">{{ msgError }}</div>
                <v-divider></v-divider>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="primary" flat @click="dialog_error = false">Tutup</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <!-- END ERROR DIALOG -->

        <v-toolbar dark class="blue lighten-3 white--text">
            <v-toolbar-title class="white--text">JOURNAL PENERIMAAN BARANG</v-toolbar-title>
            <v-spacer></v-spacer>
        </v-toolbar>

        <!-- filter -->
        <v-card class="pa-2">
            <v-layout row align-center>
                <v-flex grow>
                    <span>
                        <v-chip outline color="red">
                            {{ this.$store.state.journal.selected_periode.periode }}
                        </v-chip>
                    </span>
                </v-flex>
                <v-flex xs2 pl-2>
                    <v-menu v-model="menufilterdate" :close-on-content-click="false" :nudge-right="40" lazy
                        transition="scale-transition" offset-y full-width max-width="290px" min-width="290px">
                        <template v-slot:activator="{ on }">
                            <v-text-field v-model="filterComputedDateFormatted" label="Tanggal" outline hide-details
                                readonly v-on="on"
                                @blur="date = deFormatedDate(filterComputedDateFormatted)"></v-text-field>
                        </template>
                        <v-date-picker no-title v-model="xdate" @input="menufilterdate = false"
                            :min="selectedPeriode.periode_start" :max="selectedPeriode.periode_end"></v-date-picker>
                    </v-menu>
                </v-flex>
                <v-flex xs2 pl-2>
                    <v-autocomplete :items="regionals" v-model="selected_regional" return-object clearable
                        item-text="S_RegionalName" label="Regional" outline hide-details></v-autocomplete>
                </v-flex>
                <v-flex xs2 pl-2>
                    <v-autocomplete :disabled="_.isEmpty(this.selected_regional) ||
                        this.selected_regional === undefined
                        " :items="branchs" v-model="selected_branch" return-object item-text="M_BranchName"
                        label="Cabang" outline hide-details clearable></v-autocomplete>
                </v-flex>
                <v-flex xs2 pl-2>
                    <v-text-field v-model="xsearch" label="Cari No." outline hide-details></v-text-field>
                </v-flex>
                <v-flex shrink pl-2>
                    <v-btn dark color="primary" style="min-width: 50px; height: 50px; margin: 0"
                        @click="searchJurnal()">
                        <v-icon>search</v-icon>
                    </v-btn>
                </v-flex>
                <v-flex shrink pl-2>
                    <v-tooltip bottom>
                        <template v-slot:activator="{ on }">
                            <v-btn dark v-on="on" color="info" @click="postingJurnal()"
                                style="min-width: 50px; height: 50px; margin: 0">
                                <v-icon>book</v-icon>
                            </v-btn>
                        </template>
                        <span>Posting Jurnal</span>
                    </v-tooltip>
                </v-flex>
                <v-flex shrink pl-2>
                    <v-tooltip bottom>
                        <template v-slot:activator="{ on }">
                            <v-btn dark v-on="on" color="warning" @click="closeJurnal()"
                                style="min-width: 50px; height: 50px; margin: 0">
                                <v-icon>collections_bookmark</v-icon>
                            </v-btn>
                        </template>
                        <span>Tutup Jurnal</span>
                    </v-tooltip>
                </v-flex>
                <v-flex text-xs-right>
                    <v-btn color="orange" class="white--text" @click="openDialogPeriode()">
                        Accounting Period
                    </v-btn>
                </v-flex>
            </v-layout>
        </v-card>

        <!-- listing table -->
        <v-card class="pa-2 mt-2">
            <v-layout row wrap class="scroll-container" style="max-height: 600px; overflow: auto">
                <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                    <v-data-table :headers="headers" :items="xjournals" :loading="isLoading" hide-actions
                        class="elevation-1">
                        <template v-slot:items="props">
                            <tr>
                                <td class="text-xs-center pa-2"
                                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                    @click="selectMe(props.item)">
                                    {{ props.item.jurnalNo }}
                                    <span v-if="props.item.ErrStatus === 'Y'">
                                        <v-tooltip bottom>
                                            <template v-slot:activator="{ on, attrs }">
                                                <v-icon v-bind="attrs" v-on="on" class="ml-1" color="red" small
                                                    @click="viewError(props.item)">error</v-icon>
                                            </template>
                                            <span>error information</span>
                                        </v-tooltip>
                                    </span>
                                    <!-- <span v-if="props.item.ErrStatus === 'Y'"><v-icon small color="red" @click="viewError(props.item)">error</v-icon></span> -->
                                </td>
                                <td class="text-xs-center pa-2"
                                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                    @click="selectMe(props.item)">
                                    {{ props.item.jurnalDate }}
                                </td>
                                <td class="text-xs-left pa-2"
                                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                    @click="selectMe(props.item)">
                                    {{ props.item.jurnalTitle }}
                                </td>
                                <td class="text-xs-left pa-2"
                                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                    @click="selectMe(props.item)">
                                    {{ props.item.jurnalDescription }}
                                </td>
                                <td class="text-xs-center pa-2"
                                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                    @click="selectMe(props.item)">
                                    {{ props.item.JurnalTypeName }}
                                </td>
                                <td class="text-xs-center pa-2"
                                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                    @click="selectMe(props.item)">
                                    <span v-if="props.item.jurnalIsPosted == 'Y'">
                                        <v-chip color="indigo" class="ml-0" outline small>
                                            posted
                                        </v-chip>
                                    </span>
                                    <span v-else="props.item.jurnalIsPosted == 'N'">
                                        <v-chip color="red" class="ml-0" outline small>
                                            not posted
                                        </v-chip>
                                    </span>
                                    <span v-if="props.item.jurnalIsClosed == 'Y'">
                                        <v-chip color="warning" class="ml-1" outline small>
                                            closed
                                        </v-chip>
                                    </span>
                                </td>
                                <td class="text-xs-center pa-2"
                                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                    @click="selectMe(props.item)">
                                    <v-tooltip v-if="
                                        (user_level.DivisionID == '6' ||
                                            user_level.DivisionKodeSurat == 'KEU') &&
                                        props.item.jurnalIsPosted == 'N'
                                    " bottom class="pr-1">
                                        <template v-slot:activator="{ on, attrs }">
                                            <v-btn dark small v-on="on" color="warning" @click="editJurnal(props.item)"
                                                style="min-width: 30px; margin: 0">
                                                <v-icon v-bind="attrs" small>edit</v-icon>
                                            </v-btn>
                                        </template>
                                        <span>Edit</span>
                                    </v-tooltip>
                                    <v-tooltip bottom class="pr-1">
                                        <template v-slot:activator="{ on, attrs }">
                                            <v-btn dark small v-on="on" color="info" @click="vieDetail(props.item)"
                                                style="min-width: 30px; margin: 0">
                                                <v-icon v-bind="attrs" small>visibility</v-icon>
                                            </v-btn>
                                        </template>
                                        <span>Detail</span>
                                    </v-tooltip>
                                    <v-tooltip bottom class="pr-1">
                                        <template v-slot:activator="{ on, attrs }">
                                            <v-btn dark small v-on="on" color="red" @click="doPrint(props.item)"
                                                style="min-width: 30px; margin: 0">
                                                <v-icon v-bind="attrs" small>picture_as_pdf</v-icon>
                                            </v-btn>
                                        </template>
                                        <span>RPT PDF</span>
                                    </v-tooltip>
                                    <v-tooltip bottom>
                                        <template v-slot:activator="{ on, attrs }">
                                            <v-btn dark small v-on="on" color="green" @click="doPrintXlsx(props.item)"
                                                style="min-width: 30px; margin: 0">
                                                <v-icon v-bind="attrs" small>receipt</v-icon>
                                            </v-btn>
                                        </template>
                                        <span>RPT Excel</span>
                                    </v-tooltip>
                                </td>
                            </tr>
                        </template>
                    </v-data-table>
                </v-flex>
            </v-layout>
            <v-divider></v-divider>
            <v-pagination style="margin-top: 10px; margin-bottom: 10px" v-model="curr_page"
                :length="xtotal_page"></v-pagination>
        </v-card>

        <!-- dialog detail jurnal -->
        <template>
            <v-dialog v-model="dialogformdetail" persistent width="70vw">
                <v-card>
                    <v-card-title class="headline grey lighten-2" primary-title>
                        DETAIL JOURNAL PENERIMAAN BARANG
                    </v-card-title>

                    <v-card-text>
                        <v-layout wrap>
                            <v-flex xs12>
                                <v-layout>
                                    <v-flex xs6 pa-1 pr-3>
                                        <div class="font-weight-bold">
                                            <div>Company Name</div>
                                        </div>
                                        <div class="pa-2 grey lighten-2">
                                            <div>{{ selected_journal.M_BranchCompanyName }}</div>
                                        </div>
                                        <!-- <v-text-field :value="xcompanyname" label="Company Name"></v-text-field> -->
                                    </v-flex>
                                    <v-flex xs6 pa-1 pl-3>
                                        <div class="font-weight-bold">
                                            <div>Journal</div>
                                        </div>
                                        <div class="pa-2 grey lighten-2">
                                            <div>{{ selected_journal.jurnalTitle }}</div>
                                        </div>
                                        <!-- <v-text-field :value="xrefno" label="Ref No"></v-text-field> -->
                                    </v-flex>
                                </v-layout>
                            </v-flex>
                            <v-flex xs12>
                                <v-layout>
                                    <v-flex xs6 pa-1 pr-3>
                                        <div class="font-weight-bold">
                                            <div>Regional</div>
                                        </div>
                                        <div class="pa-2 grey lighten-2">
                                            <div>{{ selected_journal.S_RegionalName }}</div>
                                        </div>
                                        <!-- <v-text-field :value="xjournalno" label="Journal No"></v-text-field> -->
                                    </v-flex>
                                    <v-flex xs6 pa-1 pl-3>
                                        <div class="font-weight-bold">
                                            <div>Journal Date</div>
                                        </div>
                                        <div class="pa-2 grey lighten-2">
                                            <div>{{ selected_journal.jurnalDate }}</div>
                                        </div>
                                        <!-- <v-text-field :value="xjournaldate" label="Journal Date"></v-text-field> -->
                                    </v-flex>
                                </v-layout>
                            </v-flex>
                            <v-flex xs12>
                                <v-layout>
                                    <v-flex xs6 pa-1 pr-3>
                                        <div class="font-weight-bold">
                                            <div>Branch</div>
                                        </div>
                                        <div class="pa-2 grey lighten-2">
                                            <div>{{ selected_journal.M_BranchName }}</div>
                                        </div>
                                        <!-- <v-text-field :value="xaccount" label="Account"></v-text-field> -->
                                    </v-flex>
                                    <v-flex xs6 pa-1 pl-3>
                                        <div class="font-weight-bold">
                                            <div>Journal Type</div>
                                        </div>
                                        <div class="pa-2 grey lighten-2">
                                            <div>{{ selected_journal.JurnalTypeName }}</div>
                                        </div>
                                        <!-- <v-text-field :value="xjournaltype" label="Journal Type"></v-text-field> -->
                                    </v-flex>
                                </v-layout>
                            </v-flex>
                        </v-layout>

                        <v-layout row wrap pt-3>
                            <v-flex>
                                <v-data-table :headers="headerdetails" :items="xjurnaldetails" hide-actions
                                    class="elevation-1">
                                    <template slot="items" slot-scope="props">
                                        <td class="text-xs-center pa-2">
                                            {{ props.item.coaAccountNo }}
                                        </td>
                                        <td class="text-xs-left pa-2">
                                            {{ props.item.jurnalTxDescription }}
                                        </td>
                                        <td class="text-xs-left pa-2">
                                            {{ props.item.jurnalAddOnValue }} <br />
                                            {{ props.item.jurnalAddOnItem ?? "-" }}
                                        </td>
                                        <td class="text-xs-center pa-2">
                                            {{ props.item.coaCurrencyCode }}
                                        </td>
                                        <td class="text-xs-right pa-2">
                                            {{ formatCurrency(props.item.jurnalTxDebit) }}
                                        </td>
                                        <td class="text-xs-right pa-2">
                                            {{ formatCurrency(props.item.jurnalTxCredit) }}
                                        </td>
                                    </template>

                                    <template v-slot:footer>
                                        <tr>
                                            <td colspan="4" class="font-weight-bold pa-2">TOTAL</td>

                                            <td class="text-xs-right pa-2 font-weight-bold">
                                                {{ formatCurrency(xsummary.debit) }}
                                            </td>
                                            <td class="text-xs-right pa-2 font-weight-bold">
                                                {{ formatCurrency(xsummary.credit) }}
                                            </td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" class="font-weight-bold pa-2">
                                                BALANCE
                                            </td>
                                            <td width="10%" class="text-xs-right pa-2 font-weight-bold">
                                                {{ formatCurrency(xsummary.balance) }}
                                            </td>
                                        </tr>
                                    </template>
                                </v-data-table>
                            </v-flex>
                        </v-layout>
                    </v-card-text>

                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn color="error" flat @click="closeDialogFormDetail()">Tutup</v-btn>
                    </v-card-actions>
                </v-card>
            </v-dialog>
        </template>

        <template>
            <v-layout row justify-center>
                <v-dialog v-model="dialogperiode" persistent max-width="550px">
                    <v-toolbar dark class="blue lighten-3 white--text">
                        <v-toolbar-title class="white--text">PILIH PERIODE</v-toolbar-title>
                        <v-spacer></v-spacer>
                    </v-toolbar>
                    <v-card>
                        <v-card-text class="pt-4 pb-2">
                            <v-layout wrap>
                                <v-flex xs12>
                                    <v-autocomplete v-model="selectedPeriode" :items="periodeList" outline hide-details
                                        color="blue" label="Periode" item-text="periodeName" return-object>
                                        <template slot="item" slot-scope="{ item }">
                                            <template>
                                                <v-list-tile-content>
                                                    <v-list-tile-title v-text="item.periodeName"></v-list-tile-title>
                                                    <v-list-tile-sub-title
                                                        v-text="item.periode"></v-list-tile-sub-title>
                                                </v-list-tile-content>
                                            </template>
                                        </template>
                                    </v-autocomplete>
                                </v-flex>
                            </v-layout>
                        </v-card-text>
                        <v-card-actions class="pr-3">
                            <v-spacer></v-spacer>
                            <v-btn color="error" flat @click="closeDialogPeriode()">TUTUP</v-btn>
                            <v-btn color="primary" @click="choosePeriode()">PILIH</v-btn>
                        </v-card-actions>
                    </v-card>
                </v-dialog>
            </v-layout>
        </template>

        <template>
            <v-layout row justify-center>
                <v-dialog v-model="dialogerror" persistent max-width="650px">
                    <v-toolbar dark class="red lighten-1 white--text">
                        <v-toolbar-title class="white--text">ERROR INFORMATION</v-toolbar-title>
                        <v-spacer></v-spacer>
                    </v-toolbar>
                    <v-card>
                        <v-card-text class="pt-4 pb-2">
                            <v-layout wrap>
                                <v-flex xs12>
                                    <div v-for="(error, index) in msgerrjurnallist" :key="index">
                                        <p>
                                            <strong>Error Type:</strong>
                                            {{ error.JurnalErr_Msg.err_type }}
                                        </p>
                                        <p>
                                            <strong>Message:</strong>
                                            {{ error.JurnalErr_Msg.err_msg }}
                                        </p>
                                        <v-divider></v-divider>
                                    </div>
                                </v-flex>
                            </v-layout>
                        </v-card-text>
                        <v-card-actions class="pr-3">
                            <v-spacer></v-spacer>
                            <v-btn color="error" flat @click="closeDialogError()">TUTUP</v-btn>
                        </v-card-actions>
                    </v-card>
                </v-dialog>
            </v-layout>
        </template>

        <template>
            <v-dialog v-model="dialogregenerate" max-width="30%">
                <v-card>
                    <v-card-title class="headline grey lighten-2 pt-2 pb-2" primary-title>
                        Peringatan !
                    </v-card-title>
                    <v-card-text class="pt-2 pb-2">
                        <v-layout row>
                            <v-flex xs12 d-flex>
                                <v-layout row>
                                    <v-flex pb-1 xs12>
                                        <v-layout row>
                                            <v-flex pt-2 pr-2 xs12>
                                                Yakin, mau konfirmasi regenerate jurnal
                                                <span class="font-weight-bold">{{
                                                    msgalertgenerate
                                                    }}</span>
                                                ?
                                            </v-flex>
                                        </v-layout>
                                    </v-flex>
                                </v-layout>
                            </v-flex>
                        </v-layout>
                    </v-card-text>
                    <v-divider></v-divider>
                    <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn color="error" flat @click="dialogregenerate = false"> Tutup </v-btn>
                        <v-btn color="primary" @click="doRegenerateJurnal()"> Ya </v-btn>
                    </v-card-actions>
                </v-card>
            </v-dialog>
        </template>

        <one-dialog-print :title="printtitle" :width="printwidth" :height="700" :status="openprint" :urlprint="urlprint"
            @close-dialog-print="openprint = false"></one-dialog-print>

        <template>
            <one-dialog-info :status="opendialoginfo" :msg="msginfo"
                @close-dialog-info="opendialoginfo = false"></one-dialog-info>
        </template>

        <one-dialog-edit></one-dialog-edit>
        <one-dialog-posting></one-dialog-posting>
        <one-dialog-closing></one-dialog-closing>
        <one-dialog-request></one-dialog-request>
    </div>
</template>

<style scoped></style>

<script>
module.exports = {
    components: {
        "one-dialog-info": httpVueLoader("../../common/oneDialogInfo.vue"),
        "one-dialog-print": httpVueLoader("../../common/oneDialogPrintX.vue"),
        "one-dialog-edit": httpVueLoader("./dialogEditJurnal.vue"),
        "one-dialog-posting": httpVueLoader("./dialogPostingJurnal.vue"),
        "one-dialog-closing": httpVueLoader("./dialogCloseJurnal.vue"),
        "one-dialog-request": httpVueLoader("./dialogRequestEditJurnal.vue")
    },
    mounted() {
        this.$store.dispatch("journal/getListingCOA");
        this.$store.dispatch("journal/getUserApprovalLevel");
        this.$store.dispatch("journal/getRegional");
        this.$store
            .dispatch("journal/getPeriode")
            .then(() => {
                // Jika login sebagai branch, set selected_branch langsung
                if (this.$store.state.journal.user.loginLevel === "branch") {
                    const userBranchCode = this.$store.state.journal.user.M_BranchCode;
                    const branches = this.$store.state.journal.branchs || [];

                    // Cari branch yang sesuai dan set ke selected_branch
                    const selected = branches.find((b) => b.M_BranchCode === userBranchCode);
                    if (selected) {
                        this.selected_branch = selected;
                    }
                }

                this.searchJurnal();
            })
            .catch((error) => {
                console.error("Error fetching periode:", error);
            });
    },
    data: () => ({
        menufilterdate: false,
        menufilterdateend: false,
        date: new Date().toISOString().substr(0, 10),
        search_city: "",
        oldlabel: "",
        selectedData: {},
        debit: 0,
        credit: 0,
        btnUpload: false,
        xperiodeid: "",
        search_item_periode: "",
        xyearandmonth: "",
        xperiode: "",
        formatreport: "pdf",
        urlprint: "",
        printtitle: "",
        printwidth: "100%",
        dialogregenerate: false,
        msgalertgenerate: "",
        xbranchCode: "",
        xsearchDate: "",
        xjurnalID: "",
        xname: "",
        headers: [
            {
                text: "JOURNAL NO",
                align: "center",
                sortable: false,
                value: "action",
                width: "15%",
                class: "pa-1 blue lighten-3 white--text"
            },
            {
                text: "DATE",
                align: "center",
                sortable: false,
                value: "mr",
                width: "10%",
                class: "pa-1 blue lighten-3 white--text"
            },
            {
                text: "JOURNAL",
                align: "center",
                sortable: false,
                value: "lab",
                width: "20%",
                class: "pa-1 blue lighten-3 white--text"
            },
            {
                text: "JOURNAL DESCRIPTION",
                align: "center",
                sortable: false,
                value: "lab",
                width: "25%",
                class: "pa-1 blue lighten-3 white--text"
            },
            {
                text: "JOURNAL TYPE",
                align: "center",
                sortable: false,
                value: "lab",
                width: "10%",
                class: "pa-1 blue lighten-3 white--text"
            },
            {
                text: "STATUS",
                align: "center",
                sortable: false,
                value: "lab",
                width: "10%",
                class: "pa-1 blue lighten-3 white--text"
            },
            {
                text: "ACTION",
                align: "center",
                sortable: false,
                value: "lab",
                width: "10%",
                class: "pa-1 blue lighten-3 white--text"
            }
        ],
        headerdetails: [
            {
                text: "AKUN",
                align: "center",
                sortable: false,
                value: "action",
                width: "20%",
                class: "pa-2 pl-2 blue lighten-3 white--text"
            },
            {
                text: "DESKRIPSI",
                align: "center",
                sortable: false,
                value: "mr",
                width: "20%",
                class: "pa-2 blue lighten-3 white--text"
            },
            {
                text: "INFO",
                align: "center",
                sortable: false,
                value: "lab",
                width: "20%",
                class: "pa-2  blue lighten-3 white--text"
            },
            {
                text: "CURRENCY",
                align: "center",
                sortable: false,
                value: "lab",
                width: "10%",
                class: "pa-2  blue lighten-3 white--text"
            },
            {
                text: "DEBIT",
                align: "center",
                sortable: false,
                value: "lab",
                width: "15%",
                class: "pa-2 blue lighten-3 white--text"
            },
            {
                text: "CREDIT",
                align: "center",
                sortable: false,
                value: "lab",
                width: "15%",
                class: "pa-2 blue lighten-3 white--text"
            }
        ]
    }),
    computed: {
        isLoading() {
            return this.$store.state.journal.search_status === 1;
        },
        periodeList() {
            return this.$store.state.journal.periodeList;
        },
        dialogperiode() {
            return this.$store.state.journal.dialog_form_periode;
        },
        selectedPeriode: {
            get() {
                return this.$store.state.journal.selected_periode;
            },
            set(val) {
                this.$store.commit("journal/update_selected_periode", val);
            }
        },
        dialogformdetail() {
            return this.$store.state.journal.dialog_form_detail;
        },
        xjournals() {
            return this.$store.state.journal.journals;
        },
        xsummary() {
            return this.$store.state.journal.summary;
        },
        xdate: {
            get() {
                return this.$store.state.journal.xdate;
            },
            set(val) {
                this.$store.commit("journal/update_xdate", val);
            }
        },
        xdateend: {
            get() {
                return this.$store.state.journal.end_date;
            },
            set(val) {
                this.$store.commit("journal/update_end_date", val);
            }
        },
        filterComputedDateFormatted() {
            return this.formatDate(this.xdate);
        },
        filterComputedDateFormattedEnd() {
            return this.formatDate(this.xdateend);
        },
        curr_page: {
            get() {
                return this.$store.state.journal.current_page;
            },
            set(val) {
                this.$store.commit("journal/update_current_page", val);
                this.searchJurnal();
            }
        },
        xtotal_page: {
            get() {
                return this.$store.state.journal.total_journal;
            },
            set(val) {
                this.$store.commit("journal/update_total_journal", val);
            }
        },
        selected_journal: {
            get() {
                return this.$store.state.journal.selected_journal;
            },
            set(val) {
                this.$store.commit("journal/update_selected_journal", val);
            }
        },
        user() {
            return this.$store.state.journal.user;
        },
        xjurnaldetails() {
            return this.$store.state.journal.jurnaldetails;
        },
        openprint: {
            get() {
                return this.$store.state.journal.open_print;
            },
            set(val) {
                this.$store.commit("journal/update_open_print", val);
            }
        },
        dialogerror: {
            get() {
                return this.$store.state.journal.dialog_error_jurnal;
            },
            set(val) {
                this.$store.commit("journal/update_dialog_error_jurnal", val);
            }
        },
        msgerrjurnallist() {
            return this.$store.state.journal.msgerrjurnallist;
        },
        snackbar: {
            get() {
                return this.$store.state.journal.alert_success;
            },
            set(val) {
                this.$store.commit("journal/update_alert_success", val);
            }
        },
        msgSnackbar() {
            return this.$store.state.journal.msg_success;
        },
        dialog_error: {
            get() {
                return this.$store.state.journal.alert_error;
            },
            set(val) {
                this.$store.commit("journal/update_alert_error", val);
            }
        },
        msgError() {
            return this.$store.state.journal.save_error_message;
        },
        regionals() {
            return this.$store.state.journal.regionals;
        },
        selected_regional: {
            get() {
                return this.$store.state.journal.selected_regional;
            },
            set(val) {
                this.$store.commit("journal/update_selected_regional", val);
            }
        },
        branchs() {
            return this.$store.state.journal.branchs;
        },
        selected_branch: {
            get() {
                return this.$store.state.journal.selected_branch;
            },
            set(val) {
                this.$store.commit("journal/update_selected_branch", val);
            }
        },
        xsearch: {
            get() {
                return this.$store.state.journal.xsearch;
            },
            set(val) {
                this.$store.commit("journal/update_xsearch", val);
            }
        },
        opendialoginfo: {
            get() {
                return this.$store.state.journal.open_dialog_info;
            },
            set(val) {
                this.$store.commit("journal/update_open_dialog_info", val);
            }
        },
        msginfo: {
            get() {
                return this.$store.state.journal.msg_info;
            },
            set(val) {
                this.$store.commit("journal/update_msg_info", val);
            }
        },
        user_level() {
            return this.$store.state.journal.user_level;
        }
    },
    methods: {
        convertMoney(money) {
            return one_money(money);
        },
        doPrint(val) {
            // console.log(val)
            this.printwidth = 1028;
            this.printtitle = "";
            let user = one_user();
            tm = Date.now();
            var rptname = "rpt_jurnal_pendapatan_001";
            var formatrpt = this.formatreport;

            this.urlprint =
                "/birt/run?__report=report/one/accounting/" +
                rptname +
                ".rptdesign&__format=" +
                formatrpt +
                "&PID=" +
                val.jurnalID +
                "&username=" +
                user.M_StaffName +
                "&tm=" +
                tm;
            // console.log(this.urlprint)

            this.$store.commit("journal/update_open_print", true);
        },
        doPrintXlsx(val) {
            // console.log(val)
            this.printwidth = 1028;
            this.printtitle = "";
            let user = one_user();
            tm = Date.now();
            var rptname = "rpt_jurnal_pendapatan_001";

            this.urlprint =
                "/birt/run?__report=report/one/accounting/" +
                rptname +
                ".rptdesign&__format=xlsx&PID=" +
                val.jurnalID +
                "&username=" +
                user.M_StaffName +
                "&tm=" +
                tm;
            // console.log(this.urlprint)

            this.$store.commit("journal/update_open_print", true);
        },
        isSelected(p) {
            return p.jurnalID == this.$store.state.journal.selected_journal.jurnalID;
        },
        selectMe(sc) {
            this.$store.commit("journal/update_selected_journal", sc);
        },
        // thr_search: _.debounce(function () {
        //   this.$store.dispatch("journal/search", {
        //       current_page: this.$store.state.journal.current_page,
        //       xdate: this.xdate,
        //       periodeid: this.selectedPeriode.id,
        //       branchid: this.$store.state.journal.user.M_BranchID,
        //       regionalid: this.$store.state.journal.user.S_RegionalID,
        //   })
        // }, 1000),
        thr_get_branch: _.debounce(function () {
            this.$store
                .dispatch("journal/getBranch")
                .then(() => {
                    this.searchJurnal();
                })
                .catch((error) => {
                    console.error("Error fetching branch:", error);
                });
        }, 1000),
        closeDialogPeriode() {
            this.$store.commit("journal/update_dialog_form_periode", false);
        },
        openDialogPeriode() {
            this.$store.commit("journal/update_dialog_form_periode", true);
        },
        choosePeriode() {
            this.xperiodeid = this.$store.state.journal.selected_periode.id;
            this.xyearandmonth = this.$store.state.journal.selected_periode.yearandmonth;
            this.xperiode = this.$store.state.journal.selected_periode.periode;
            this.xdate = this.selectedPeriode.periode_start

            this.$store.commit("journal/update_dialog_form_periode", false);
            this.searchJurnal();
        },
        closeDialogFormDetail() {
            this.$store.commit("journal/update_dialog_form_detail", false);
        },
        vieDetail(val) {
            this.$store.commit("journal/update_dialog_form_detail", true);
            this.$store.commit("journal/update_jurnaldetails", val.detailtx);

            let totalDebit = 0;
            let totalKredit = 0;
            for (let item = 0; item < val.detailtx.length; item++) {
                const element = val.detailtx[item];
                totalDebit += parseFloat(element.jurnalTxDebit || "0");
                totalKredit += parseFloat(element.jurnalTxCredit || "0");
            }

            let totalBalance = totalDebit - totalKredit;
            let summary = {
                debit: totalDebit,
                credit: totalKredit,
                balance: totalBalance
            };
            this.$store.commit("journal/update_summary", summary);
        },
        formatDate(date) {
            if (!date) return null;

            const [year, month, day] = date.split("-");
            return `${day}-${month}-${year}`;
        },
        deFormatedDate(date) {
            if (!date) return null;

            const [day, month, year] = date.split("-");
            return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
        },
        isObjectEmpty(val) {
            let obj = val;
            return Object.keys(obj).length === 0 && obj.constructor === Object;
        },
        isPeriodeEmpty() {
            return Object.keys(this.selectedPeriode).length === 0;
        },
        openDialogEdit(val) {
            this.selectedData = val;
            if (val.type == "DB") {
                this.debit = val.value;
                this.credit = 0;
            }
            if (val.type == "CR") {
                this.credit = val.value;
                this.debit = 0;
            }
            this.dialogEdit = true;
        },
        formatCurrency(val) {
            // Format the price above to USD using the locale, style, and currency.
            let price = parseFloat(val);
            let USDollar = new Intl.NumberFormat("id-ID", {
                style: "currency",
                currency: "IDR"
            });

            // console.log(
            //   `The formated version of ${price} is ${USDollar.format(price)}`
            // );
            return `${USDollar.format(price)}`;
        },
        resetInputFile() {
            document.getElementById("csv_file").value = null;
            this.dialogImport = false;
        },
        viewError(val) {
            this.$store.commit("journal/update_dialog_error_jurnal", true);
            this.$store.commit("journal/update_msgerrjurnallist", val.ErrMsg);
        },
        closeDialogError() {
            this.$store.commit("journal/update_dialog_error_jurnal", false);
        },
        openGenerate(val) {
            // console.log(val)
            this.xbranchCode = val.jurnalM_BranchCode;
            this.xsearchDate = this.deFormatedDate(val.jurnalDate);
            this.xjurnalID = val.jurnalID;
            this.xname = val.jurnalTitle;
            this.msgalertgenerate = val.jurnalTitle;
            this.dialogregenerate = true;
        },
        doRegenerateJurnal() {
            this.dialogregenerate = false;

            // console.log(prm)
            let user = one_user();
            console.log(user.M_BranchID);
            if (user.M_BranchID === 0 || user.M_BranchID === "0") {
                // generate regional
                this.$store.dispatch("journal/insertSales", {
                    branchCode: "ZZ",
                    date: this.xsearchDate,
                    jurnalno: this.selected_journal.jurnalNo
                });
            } else {
                // generate cabang
                this.$store.dispatch("journal/insertSales", {
                    branchCode: this.xbranchCode,
                    date: this.xsearchDate,
                    jurnalno: this.selected_journal.jurnalNo
                });
            }
        },
        updateAlertSuccess(val) {
            this.$store.commit("journal/update_alert_success", val);
        },
        searchJurnal() {
            if (this.selected_regional === undefined && this.loginLevel != 'pusat') {
                this.opendialoginfo = true;
                this.msginfo = "Anda belum memilih regional";
            } else {
                this.$store.dispatch("journal/search", {
                    current_page: this.$store.state.journal.current_page,
                    xdate: this.xdate,
                    periodeid: this.selectedPeriode?.id || "",
                    search: this.xsearch || "",
                    branchCode: this.selected_branch?.M_BranchCode || "",
                    regionalId: this.selected_regional?.S_RegionalID || 0
                });
            }
        },
        editJurnal(val) {
            if (val.jurnalEditStatus == "Y") {
                let detail = JSON.parse(JSON.stringify(val.detailtx));
                this.$store.commit("journal/update_journal_edit", detail);

                let totalDebit = 0;
                let totalKredit = 0;
                for (let item = 0; item < val.detailtx.length; item++) {
                    const element = val.detailtx[item];
                    totalDebit += parseFloat(element.jurnalTxDebit || "0");
                    totalKredit += parseFloat(element.jurnalTxCredit || "0");
                }

                let totalBalance = totalDebit - totalKredit;
                let summary = {
                    debit: totalDebit,
                    credit: totalKredit,
                    balance: totalBalance
                };
                this.$store.commit("journal/update_summary", summary);
                this.$store.commit("journal/update_dialog_edit_journal", true);
            } else {
                this.$store.commit("journal/update_dialog_request_edit", true);
            }
        },
        postingJurnal() {
            this.$store.dispatch("journal/totalJurnalNotPostedPerPeriod");
            this.$store.commit("journal/update_dialog_confirm_posting", true);
        },
        closeJurnal() {
            this.$store.dispatch("journal/getDataJurnalNotClosedPerPeriod");
            this.$store.commit("journal/update_dialog_close_jurnal", true);
        }
    },
    watch: {
        selected_regional(val, old) {
            this.selected_regional = val;
            this.thr_get_branch();
        }
    }
};
</script>
