<template>
    <div style="width: 100%;">
        <!-- SNACKBAR -->
        <v-snackbar
            v-model="snackbar"
            :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-layout row wrap>
            <v-flex xs12 fill-height pa-1>
                <v-toolbar color="primary" dark>
                <v-toolbar-title class="white--text"
                    >PAYMENT VOUCHER</v-toolbar-title
                >
                <v-spacer></v-spacer>
                <v-btn icon @click="openDialogVoucher()">
                    <v-icon>add_box</v-icon>
                </v-btn>
                </v-toolbar>
                <v-card class="pa-2">
                        <v-layout>
                            <v-flex xs6 pl-2>
                                <v-menu
                                    v-model="menuStartDate"
                                    :close-on-content-click="false"
                                    transition="scale-transition"
                                    :nudge-right="40"
                                    lazy
                                    offset-y
                                    max-width="290px"
                                    min-width="290px"
                                    >
                                    <template v-slot:activator="{ on }">
                                        <v-text-field
                                        v-model="startDateFormatted"
                                        label="Tanggal Awal"
                                        readonly
                                        style="max-width: 250px"
                                        outline
                                        hide-details
                                        v-on="on"
                                        @blur="dStartDate = deFormatedDate(startDateFormatted)"
                                        ></v-text-field>
                                    </template>
                                    <v-date-picker
                                        no-title
                                        v-model="xStartDate"
                                        @input="menuStartDate = false"
                                    ></v-date-picker>
                                </v-menu>
                            </v-flex>
                            <v-flex xs6 pl-2>
                                <v-menu
                                    v-model="menuEndDate"
                                    :close-on-content-click="false"
                                    transition="scale-transition"
                                    :nudge-right="40"
                                    lazy
                                    offset-y
                                    max-width="290px"
                                    min-width="290px"
                                    >
                                    <template v-slot:activator="{ on }">
                                        <v-text-field
                                        v-model="endDateFormatted"
                                        label="Tanggal Akhir"
                                        readonly
                                        style="max-width: 250px"
                                        outline
                                        hide-details
                                        v-on="on"
                                        @blur="dEndDate = deFormatedDate(endDateFormatted)"
                                        ></v-text-field>
                                    </template>
                                    <v-date-picker
                                        no-title
                                        v-model="xEndDate"
                                        @input="menuEndDate = false"
                                    ></v-date-picker>
                                </v-menu>
                            </v-flex>
                            <v-flex xs6 pl-2>
                                <v-autocomplete
                                    return-object
                                    item-text="text"
                                    label="Status"
                                    :items="statusOptions"
                                    v-model="selected_status"
                                    outline
                                    hide-details
                                ></v-autocomplete>
                            </v-flex>
                            <v-flex xs6 pl-2>
                                <v-text-field
                                    label="Cari..."
                                    placeholder="NO."
                                    outline
                                    hide-details
                                    v-model="xsearch"
                                ></v-text-field>
                            </v-flex>
                            <v-flex pl-2 pr-2>
                                <v-btn
                                    dark
                                    color="primary"
                                    style="min-width: 50px; height: 50px; margin: 0"
                                    @click="mainTableSearch()"
                                    >
                                    <v-icon>search</v-icon>
                                </v-btn>
                            </v-flex>
                        </v-layout>
                </v-card>
                <v-card class="pa-2 mt-2">
                    <v-layout row wrap>
                        <v-flex xs12 pl-2>
                            <div>
                                <span>Ada approved : </span>
                                <span>{{ totalApproved }}</span>
                            </div>
                        </v-flex>
                    </v-layout>
                    <v-layout row style="max-height: 600px; overflow: auto">
                        <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                            <v-data-table
                                :items="xvoucehrList"
                                :headers="headers"
                                :loading="isLoading"
                                hide-actions
                                class="elevation-1"
                            >
                                <template slot="items" slot-scope="props">
                                    <td
                                        class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)"
                                    >
                                        <p class="mb-0 font-weight-bold" style="color:#000000">{{ props.item.PaymentVoucherNumber }}</p>
                                        <p class="mb-0 info--text mono font-weight-bold caption">{{ formatDateHeader(props.item.PaymentVoucherDate) }}</p>
                                    </td>
                                    <td
                                        class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)"
                                    >
                                        <p  class="mb-0">{{ props.item.M_BranchName }}</p>
                                        <p class="mb-0 font-weight-bold" style="color:#000000">Total : Rp {{ props.item.PaymentVoucherTotal.toString().replace(
                                            /\B(?=(\d{3})+(?!\d))/g,
                                            "."
                                        ) }}</p>
                                    </td>
                                    <td
                                        class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)"
                                    >{{ formatDateHeader(props.item.PaymentVoucherRealitationDate) }}</td>
                                    <td
                                        class="text-xs-center pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)"
                                    >
                                    <!-- :text-color="props.item.PaymentVoucherStatus === 'Draft' ? 'black' : 'white'" -->
                                        <v-chip
                                        small
                                        :color="getChipStatusColor(props.item.PaymentVoucherStatus)">
                                        {{ props.item.PaymentVoucherStatus }}
                                        </v-chip>
                                    </td> 
                                    <template v-if="props.item.PaymentVoucherStatus == 'Draft'">
                                        <td class="text-xs-center pa-2"
                                            v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                            @click="selectMe(props.item)"
                                        >
                                            <v-icon small @click="openUpdateVoucher(props.item)"
                                            >edit</v-icon
                                            >
                                            <v-icon small @click="deleteVoucher(props.item)"
                                            >delete</v-icon
                                            >
                                        </td>
                                    </template>
                                    <template v-else>
                                        <td
                                        class="text-xs-center pa-2"
                                        v-bind:class="{
                                            'amber lighten-4': isSelected(props.item),
                                        }"
                                        ></td>
                                    </template>
                                </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>
            </v-flex>
        </v-layout>

        <dialog-form-voucher></dialog-form-voucher>

        <one-dialog-alert
        :status="dialogAlertDelete"
        :msg="msgAlertDelete"
        @forget-dialog-alert="dialogAlertDelete = false"
        @close-dialog-alert="closeAndDelete()"
        ></one-dialog-alert>
    </div>
</template>

<style scoped>
.date-type-table {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.table.v-table tbody td,
table.v-table tbody th {
  height: 40px;
}

.table.v-table thead tr {
  height: 40px;
}

.scroll-container {
  scroll-padding: 50px 0 0 50px;
}
</style>

<script>
module.exports = {
    components: {
        "dialog-form-voucher": httpVueLoader("./dialogFormVoucher.vue"),
        "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
        "one-dialog-error": httpVueLoader("../../common/oneDialogError.vue")
    },
    data() {
        return {
            msgAlertDelete: "",
            dialogAlertDelete: false,
            xPVID: 0,
            xPVNumber: "",
            headers: [
                {
                    text: "NO / TANGGAL",
                    align: "left",
                    sortable: false,
                    value: "no",
                    width: "25%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "PENERIMA",
                    align: "left",
                    sortable: false,
                    value: "supplier",
                    width: "30%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "TANGGAL REALISASI",
                    align: "left",
                    sortable: false,
                    value: "total",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "STATUS",
                    align: "left",
                    sortable: false,
                    value: "status",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "AKSI",
                    align: "left",
                    sortable: false,
                    value: "status",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
            ],
        }
    },
    mounted() {
        this.$store.dispatch("voucher/search");
        this.$store.dispatch("voucher/getTotalApproved");
    },
    computed: {
        statusOptions() {
            return this.$store.state.voucher.status_options;
        },
        selected_status: {
            get() {
                return this.$store.state.voucher.selected_status;
            },
            set(val) {
                this.$store.commit("voucher/update_selected_status", val);
                this.mainTableSearch();
            },
        },
        menuStartDate: {
            get() {
                return this.$store.state.voucher.menuStartDate;
            },
            set(val) {
                this.$store.commit("voucher/update_menuStartDate", val);
            },
        },
        menuEndDate: {
            get() {
                return this.$store.state.voucher.menuEndDate;
            },
            set(val) {
                this.$store.commit("voucher/update_menuEndDate", val);
            },
        },
        startDateFormatted() {
            return this.formatDate(this.xStartDate);
        },
        endDateFormatted() {
            return this.formatDate(this.xEndDate);
        },
        xStartDate: {
            get() {
                return this.$store.state.voucher.xStartDate;
            },
            set(val) {
                this.$store.commit("voucher/update_xStartDate", val);
            },
        },
        xEndDate: {
            get() {
                return this.$store.state.voucher.xEndDate;
            },
            set(val) {
                this.$store.commit("voucher/update_xEndDate", val);
            },
        },
        dEndDate: {
            get() {
                return this.$store.state.voucher.dEndDate;
            },
            set(val) {
                this.$store.commit("voucher/update_dEndDate", val);
            },
        },
        dStartDate: {
            get() {
                return this.$store.state.voucher.dStartDate;
            },
            set(val) {
                this.$store.commit("voucher/update_dStartDate", val);
            },
        },
        xvoucehrList() {
            return this.$store.state.voucher.voucherList;
        },
        curr_page: {
            get() {
                return this.$store.state.voucher.currentPage;
            },
            set(val) {
                this.$store.commit("voucher/update_currentPage", val);
                this.mainTableSearch();
            },
        },
        xtotal_page: {
            get() {
                return this.$store.state.voucher.total_page_voucher;
            },
            set(val) {
                this.$store.commit("voucher/update_total_page_voucher", val);
            },
        },
        xsearch: {
            get() {
                return this.$store.state.voucher.xsearch;
            },
            set(val) {
                this.$store.commit("voucher/update_xsearch", val);
            },
        },
        isLoading() {
            return this.$store.state.voucher.search_status === 1;
        },
        msgSnackbar() {
            return this.$store.state.voucher.success_message;
        },
        snackbar: {
            get() {
                return this.$store.state.voucher.alert_success;
            },
            set(val) {
                this.$store.commit("voucher/update_alert_success", val);
            },
        },
        dialog_error: {
            get() {
                return this.$store.state.voucher.alert_error;
            },
            set(val) {
                this.$store.commit("voucher/update_alert_error", val);
            },
        },
        msgError() {
            return this.$store.state.voucher.error_message;
        },
        totalApproved() {
            return this.$store.state.voucher.totalApproved
        }
    },
    methods: {
        convertMoney(money){
            return one_money(money)
        },
        isSelected(o) {
            return o.PaymentVoucherID == this.$store.state.voucher.selected_voucher.PaymentVoucherID;
        },
        selectMe(sc) {
            this.$store.commit("voucher/update_selected_voucher", sc);
            this.$store.dispatch("voucher/searchdetail", sc.PaymentVoucherID)
        },
        openDialogVoucher() {
            this.$store.commit("voucher/update_dialog_voucher", true);
            this.$store.commit("voucher/update_act", "new");
            this.$store.commit("voucher/update_selected_branch", {});
            this.$store.commit("voucher/update_branchList", []);
            this.$store.commit("voucher/update_selected_accountDana", {});
            this.$store.commit("voucher/update_accountDanaList", []);
            this.$store.commit("voucher/update_selected_accountBiaya", {});
            this.$store.commit("voucher/update_accountBiayaList", []);
            this.$store.commit("voucher/update_selected_accountTemp", {});
            this.$store.commit("voucher/update_accountTempList", []);
            this.$store.commit("voucher/update_selected_purchase", []);
            this.$store.commit("voucher/update_purchaseList", []);
            this.$store.commit("voucher/update_resume_total", {"totalRealitation": 0});
        },
        formatDate(date) {
            if (!date) return null;

            const [year, month, day] = date.split("-");
            return `${day}-${month}-${year}`;
        },
        formatDateHeader(date) {
            if (!date) return null;
            const cleanDate = date.split(" ")[0];
            const [year, month, day] = cleanDate.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")}`;
        },
        getChipStatusColor(status) {
            switch (status) {
                case "Realitation":
                    return "warning";
                case "Paid":
                    return "success";
                case "Partial":
                    return "warning";
                case "Completed":
                    return "success";
                default:
                    return "";
            }
        },
        mainTableSearch() {
            this.$store.dispatch("voucher/search");
        },
        thr_searchDate: _.debounce(function () {
            this.$store.dispatch("voucher/search")
        }, 1000),
        thr_search: _.debounce(function () {
            this.$store.dispatch("voucher/search")
        }, 1000),
        deleteVoucher(data) {
            this.xPVID = data.PaymentVoucherID;
            this.xPVNumber = data.PaymentVoucherNumber;
            
            this.msgAlertDelete = `Yakin, mau hapus Payment Voucher [${data.PaymentVoucherNumber}] ?`;
            this.dialogAlertDelete = true;
        },
        closeAndDelete() {
            this.$store.dispatch("voucher/delete", {
                PVID: this.xPVID,
                PVNumber: this.xPVNumber
            });
            this.dialogAlertDelete = false
        },
        openUpdateVoucher(data) {
            this.$store.commit("voucher/update_act", "edit");
            this.$store.commit("voucher/update_dialog_voucher", true);
            this.$store.commit("voucher/update_branchList", [{
                M_BranchCode: data.M_BranchCode,
                M_BranchName: data.M_BranchName
            }])
            this.$store.commit("voucher/update_selected_branch", {
                M_BranchCode: data.M_BranchCode,
                M_BranchName: data.M_BranchName
            })

            // source
            this.$store.commit("voucher/update_accountDanaList", [{
                coaID: data.PaymentVoucherCoaSourceID,
                coaDescription: data.coaDescriptionSource
            }])
            this.$store.commit("voucher/update_selected_accountDana", {
                coaID: data.PaymentVoucherCoaSourceID,
                coaDescription: data.coaDescriptionSource
            })

            // expense
            this.$store.commit("voucher/update_accountBiayaList", [{
                coaID: data.PaymentVoucherCoaSourceID,
                coaDescription: data.coaDescriptionExpense
            }])
            this.$store.commit("voucher/update_selected_accountBiaya", {
                coaID: data.PaymentVoucherCoaSourceID,
                coaDescription: data.coaDescriptionExpense
            })

            // 
            this.$store.commit("voucher/update_accountTempList", [{
                coaID: data.PaymentVoucherCoaTemporaryID,
                coaDescription: data.coaDescriptionTemporary
            }])
            this.$store.commit("voucher/update_selected_accountTemp", {
                coaID: data.PaymentVoucherCoaTemporaryID,
                coaDescription: data.coaDescriptionTemporary
            })

            this.$store.dispatch("voucher/getPurchaseUpdateNew", {"branchcode": this.$store.state.voucher.selected_branch.M_BranchCode, "voucherID": data.PaymentVoucherID});
            this.$store.commit("voucher/update_selected_purchase", this.$store.state.voucher.details);

            this.$store.commit("voucher/update_resume_total", {"totalRealitation": data.PaymentVoucherTotal} );
        }
    },
    watch: {
        xStartDate(val, old) {
            this.xStartDate = val;
            this.thr_searchDate();
        },
        xEndDate(val, old) {
            this.xEndDate = val;
            this.thr_searchDate();
        },
        xsearch(val, old) {
            this.xsearch = val;
            this.thr_search();
        },
    }
}
</script>