<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"
                    >KASIR</v-toolbar-title
                >
                <v-spacer></v-spacer>
                <v-btn v-if="(status != '' || status != null) && (xdate != '' && xdate != null)" @click="goBack()" color="orange darken-2" title="Kembali ke listing pending approval" dark>
                    <v-icon dark left>arrow_back</v-icon>Back
                </v-btn>
                </v-toolbar>
                <v-card class="pa-2">
                        <v-layout>
                        <v-flex xs3 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 xs3 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 xs3 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 xs3 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 v-if="selected_status.text == 'Draft'">
                                <span>Total belum di bayar : </span>
                                <span>{{ totalDraft }}</span>
                            </div>
                            <div v-if="selected_status.text == 'Paid'">
                                <span>Total belum di realisasi : </span>
                                <span>{{ totalPaid }}</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 {{ convertMoney(props.item.PaymentVoucherTotal) }}</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)"
                                    >
                                        <v-chip
                                        small
                                        :text-color="props.item.PaymentVoucherStatus === 'Draft' ? 'black' : 'white'"
                                        :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-btn small color="lime darken-2" dark @click="openDialogPay(props.item)">Bayar</v-btn>
                                        </td>

                                    </template>
                                    <template v-else-if="props.item.PaymentVoucherStatus == 'Paid'">
                                        <td class="text-xs-center pa-2"
                                            v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                            @click="selectMe(props.item)"
                                        >
                                            <v-icon class="mr-2" color="orange" small @click="doPrintPaid(props.item)">picture_as_pdf</v-icon>
                                            <v-btn small color="teal darken-2" dark @click="openDialogUpdate(props.item)">Realisasi</v-btn>
                                        </td>
                                    </template>
                                    <template v-else-if="props.item.PaymentVoucherStatus == 'Realitation'">
                                        <td
                                        class="text-xs-center pa-2"
                                        v-bind:class="{
                                            'amber lighten-4': isSelected(props.item),
                                        }"
                                        >
                                            <v-icon class="mr-2" color="orange" small @click="doPrintPaid(props.item)">picture_as_pdf</v-icon>
                                            <v-icon class="mr-2" color="teal" small @click="doPrintRealitation(props.item)">picture_as_pdf</v-icon>
                                        </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></dialog-form> -->
        <!-- <dialog-realized-item></dialog-realized-item> -->
        <dialog-form-realise></dialog-form-realise>
        <dialog-view-img></dialog-view-img>
        <dialog-form-pay></dialog-form-pay>

        <one-dialog-alert
          :status="dialogAlertDelete"
          :msg="msgAlertDelete"
          @forget-dialog-alert="dialogAlertDelete = false"
          @close-dialog-alert="closeAndDelete()"
        ></one-dialog-alert>
        <one-dialog-print :title="printtitle" :width="printwidth" :height="700" :status="openprint" :urlprint="urlprint"
        @close-dialog-print="openprint = false"></one-dialog-print>
    </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;
}

.wrap-header {
  white-space: normal !important;
  line-height: 1.2;
  word-break: break-word;
  text-align: center;
}

</style>

<script>
module.exports = {
    components: {
        "dialog-form": httpVueLoader("./dialogForm.vue"),
        "dialog-form-pay": httpVueLoader("./dialogFormPay.vue"),
        "dialog-realized-item": httpVueLoader("./dialogItemRealize.vue"),
        "dialog-form-realise": httpVueLoader("./dialogFormRealise.vue"),
        "dialog-view-img": httpVueLoader("./dialogViewImg.vue"),
        "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
        "one-dialog-error": httpVueLoader("../../common/oneDialogError.vue"),
        'one-dialog-print': httpVueLoader('../../common/oneDialogPrintX.vue')
    },
    data() {
        return {
            msgAlertDelete: "",
            dialogAlertDelete: false,
            xPVID: 0,
            xPVNumber: "",
            formatreport: "pdf",
            urlprint: "",
            printtitle: '',
            printwidth: '100%',
            headers: [
                {
                    text: "NO / TANGGAL",
                    align: "center",
                    sortable: false,
                    value: "no",
                    width: "20%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "PENERIMA",
                    align: "center",
                    sortable: false,
                    value: "supplier",
                    width: "19%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "TANGGAL REALISASI",
                    align: "center",
                    sortable: false,
                    value: "total",
                    width: "16%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "STATUS",
                    align: "center",
                    sortable: false,
                    value: "status",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "AKSI",
                    align: "center",
                    sortable: false,
                    value: "status",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
            ],
        }
    },
    mounted() {
        this.$store.dispatch("cashier/search");
        this.$store.dispatch("cashier/getTotalDraft");
        this.$store.dispatch("cashier/getTotalPaid");
    },
    computed: {
        status() {
            return this.$store.state.cashier.status;
        },
        xdate() {
            return this.$store.state.cashier.xdate;
        },
        statusOptions() {
            return this.$store.state.cashier.status_options;
        },
        selected_status: {
            get() {
                return this.$store.state.cashier.selected_status;
            },
            set(val) {
                this.$store.commit("cashier/update_selected_status", val);
                this.mainTableSearch();
            },
        },
        menuStartDate: {
            get() {
                return this.$store.state.cashier.menuStartDate;
            },
            set(val) {
                this.$store.commit("cashier/update_menuStartDate", val);
            },
        },
        menuEndDate: {
            get() {
                return this.$store.state.cashier.menuEndDate;
            },
            set(val) {
                this.$store.commit("cashier/update_menuEndDate", val);
            },
        },
        startDateFormatted() {
            return this.formatDate(this.xStartDate);
        },
        endDateFormatted() {
            return this.formatDate(this.xEndDate);
        },
        xStartDate: {
            get() {
                return this.$store.state.cashier.xStartDate;
            },
            set(val) {
                this.$store.commit("cashier/update_xStartDate", val);
            },
        },
        xEndDate: {
            get() {
                return this.$store.state.cashier.xEndDate;
            },
            set(val) {
                this.$store.commit("cashier/update_xEndDate", val);
            },
        },
        dEndDate: {
            get() {
                return this.$store.state.cashier.dEndDate;
            },
            set(val) {
                this.$store.commit("cashier/update_dEndDate", val);
            },
        },
        dStartDate: {
            get() {
                return this.$store.state.cashier.dStartDate;
            },
            set(val) {
                this.$store.commit("cashier/update_dStartDate", val);
            },
        },
        xvoucehrList() {
            return this.$store.state.cashier.cashierList;
        },
        curr_page: {
            get() {
                return this.$store.state.cashier.currentPage;
            },
            set(val) {
                this.$store.commit("cashier/update_currentPage", val);
                this.mainTableSearch();
            },
        },
        xtotal_page: {
            get() {
                return this.$store.state.cashier.total_page_cashier;
            },
            set(val) {
                this.$store.commit("cashier/update_total_page_cashier", val);
            },
        },
        xsearch: {
            get() {
                return this.$store.state.cashier.xsearch;
            },
            set(val) {
                this.$store.commit("cashier/update_xsearch", val);
            },
        },
        isLoading() {
            return this.$store.state.cashier.search_status === 1;
        },
        msgSnackbar() {
            return this.$store.state.cashier.success_message;
        },
        snackbar: {
            get() {
                return this.$store.state.cashier.alert_success;
            },
            set(val) {
                this.$store.commit("cashier/update_alert_success", val);
            },
        },
        dialog_error: {
            get() {
                return this.$store.state.cashier.alert_error;
            },
            set(val) {
                this.$store.commit("cashier/update_alert_error", val);
            },
        },
        msgError: {
            get() {
                return this.$store.state.cashier.error_message;
            },
            set(val) {
                this.$store.commit("cashier/update_error_message", val);
            }
        },
        totalDraft() {
            return this.$store.state.cashier.totalDraft
        },
        totalPaid() {
            return this.$store.state.cashier.totalPaid
        },
        openprint: {
            get() {
                return this.$store.state.cashier.openprint;
            },
            set(val) {
                this.$store.commit("cashier/update_openprint", val);
            },
        },
        voucher_details() {
            return this.$store.state.cashier.details
        }
    },
    methods: {
        goBack() {
            window.history.back();
            // location.href = "/one-ui/test/vuex/one-accone-approve-all/"
        },
        convertMoney(money){
            return one_money(money)
        },
        doPrintPaid(val) {
            // console.log(val)
            this.printwidth = 1028
            this.printtitle = ""
            let user = one_user()
            tm = Date.now()
            var rptname = 'rpt_payment_voucher_paid_001'
            var formatrpt = this.formatreport

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

            this.$store.commit("cashier/update_openprint", true)
        },
        doPrintRealitation(val) {
            // console.log(val)
            this.printwidth = 1028
            this.printtitle = ""
            let user = one_user()
            tm = Date.now()
            var rptname = 'rpt_payment_voucher_realitation_001'
            var formatrpt = this.formatreport

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

            this.$store.commit("cashier/update_openprint", true)
        },
        isSelected(o) {
            return o.PaymentVoucherID == this.$store.state.cashier.selected_cashier.PaymentVoucherID;
        },
        selectMe(sc) {
            this.$store.commit("cashier/update_selected_cashier", sc);
            this.$store.dispatch("cashier/searchdetail", sc.PaymentVoucherID);
            this.$store.dispatch("cashier/getVoucherDetail");
        },
        openDialogVoucher() {
            this.$store.commit("cashier/update_dialog_cashier", true);
            this.$store.commit("cashier/update_act", "new");
            this.$store.commit("cashier/update_selected_branch", {});
            this.$store.commit("cashier/update_selected_accountDana", {});
            this.$store.commit("cashier/update_selected_accountBiaya", {});
            this.$store.commit("cashier/update_selected_accountTemp", {});
            this.$store.commit("cashier/update_selected_purchase", []);
            this.$store.commit("cashier/update_purchaseList", []);
            this.$store.commit("cashier/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 "Paid":
                    return "warning";
                case "Realitation":
                    return "success";
                default:
                    return "";
            }
        },
        mainTableSearch() {
            this.$store.dispatch("cashier/search");
        },
        thr_searchDate: _.debounce(function () {
            this.$store.dispatch("cashier/search")
        }, 1000),
        thr_search: _.debounce(function () {
            this.$store.dispatch("cashier/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("cashier/delete", {
            //     PVID: this.xPVID,
            //     PVNumber: this.xPVNumber
            // });
            this.dialogAlertDelete = false
        },
        openDialogUpdate(data) {
            this.$store.commit("cashier/update_act", "edit");
            this.$store.commit("cashier/update_dialog_cashier", true);
            this.$store.commit("cashier/update_imageRelationPreviews", []);
            this.$store.commit("cashier/update_imageRelationFiles", []);

            const fileBaseUrl = BASE_URL + "/one-media/cashier/";

            const allImageUrls = [];

            for (let index = 0; index < data.dataAttachment.length; index++) {
                const element = data.dataAttachment[index];

                if (element.PurchaseDirectAttachmentName == null || element.PurchaseDirectAttachmentName == '') {
                    continue;
                }
                allImageUrls.push(fileBaseUrl + element.PurchaseDirectAttachmentName)
            }

            this.$store.commit("cashier/update_imagePrevPaid", allImageUrls);
        },
        openDialogPay(data) {
            // cek detail sudah terisi account biaya atau belum
            const voucherdetails = this.voucher_details;
            const incomplete = voucherdetails.some(element => {
                const acc = element.account_biaya
                const splitacc = acc.split(';').map(part => part.trim())
                return splitacc.some(account => account === 'notset')
            });
            if (incomplete) {
                this.dialog_error = true
                this.msgError = 'Terdapat item voucher yang belum diset account biayanya'
                return;
            }

            this.$store.dispatch("cashier/getUserReceive");
            this.$store.commit("cashier/update_act", "edit");
            this.$store.commit("cashier/update_dialog_cashier_pay", true);
            this.$store.commit("cashier/update_imagePayPreviews", []);

            const fileBaseUrl = BASE_URL + "/one-media/cashier/";

            const allImageUrls = [];
            const allNumberRequest = [];
            let descriptions = '';

            for (let index = 0; index < data.dataAttachment.length; index++) {
                const element = data.dataAttachment[index];

                if (element.PurchaseDirectAttachmentName == null || element.PurchaseDirectAttachmentName == '') {
                    continue;
                }
                allImageUrls.push(fileBaseUrl + element.PurchaseDirectAttachmentName)
            }

            this.$store.commit("cashier/update_imagePreviews", allImageUrls);

            for (let index = 0; index < data.requestNumber.length; index++) {
                const element = data.requestNumber[index];

                allNumberRequest.push(element.PurchaseRequestDirectNumber)

                let desc = element.PurchaseRequestDirectDescription;

                descriptions += desc;
                if (index !== data.requestNumber.length - 1) {
                    descriptions += ', ';
                }
            }
            this.$store.commit("cashier/update_numberRequest", allNumberRequest);
            this.$store.commit("cashier/update_requestDescription", descriptions);
            
        }
    },
    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>