<template>
    <v-dialog v-model="viewfakturDialog" persistent max-width="90%">
        <v-card>
            <v-card-title class="headline grey lighten-2" primary-title>
                FAKTUR PO
            </v-card-title>

            <v-card-text>
                <v-layout row wrap>
                    <!-- 1st row -->
                    <v-flex pr-2 xs3>
                        <v-menu
                            v-model="menuDateForm" transition="scale-transition"
                            full-width offset-y lazy :nudge-right="40"
                            max-width="290px" min-width="290px"
                            :close-on-content-click="false"
                        >
                            <template v-slot:activator="{on}">
                                <v-text-field
                                    label="Tanggal" readonly disabled
                                    outline hide-details :value="DateFormated"
                                ></v-text-field>
                            </template>
                            <v-date-picker
                                no-title v-model="form_faktur.form_date" 
                                readonly disabled
                            ></v-date-picker>
                        </v-menu>
                    </v-flex>
                    <v-flex pr-2 xs3>
                        <v-menu
                            v-model="menuDueDateForm" transition="scale-transition"
                            full-width offset-y lazy :nudge-right="40"
                            max-width="290px" min-width="290px"
                            :close-on-content-click="false"
                        >
                            <template v-slot:activator="{on}">
                                <v-text-field
                                    label="Tanggal Jatuh Tempo" readonly disabled
                                    outline hide-details :value="DueDateFormated"
                                ></v-text-field>
                            </template>
                            <v-date-picker
                                no-title v-model="form_faktur.form_duedate" 
                                readonly disabled 
                            ></v-date-picker>
                        </v-menu>
                    </v-flex>
                    <v-flex pr-2 xs3>
                        <v-menu
                            v-model="menuDraftDateForm" transition="scale-transition"
                            full-width offset-y lazy :nudge-right="40"
                            max-width="290px" min-width="290px"
                            :close-on-content-click="false"
                        >
                            <template v-slot:activator="{on}">
                                <v-text-field
                                    label="Tanggal Rencana Bayar" readonly disabled v-on="on"
                                    :value="DraftDateFormated" outline :rules="rules_text"
                                ></v-text-field>
                            </template>
                            <v-date-picker
                                no-title v-model="form_faktur.form_draftdate"
                                readonly disabled 
                            ></v-date-picker>
                        </v-menu>
                    </v-flex>
                    <v-flex pr-2 xs3>
                        <v-text-field
                            :value="form_faktur.form_supplier ? form_faktur.form_supplier.SupplierName : ''"
                            label="Supplier" readonly disabled outline
                        ></v-text-field>
                    </v-flex>

                    <!-- 2nd row -->
                    <v-flex pr-2 xs3>
                        <v-text-field
                            :value="form_faktur.form_po 
                                ? form_faktur.form_po.ReceiveOrderPoNumber 
                                : ''"
                            label="Nomor GRN" readonly disabled outline
                        ></v-text-field>
                    </v-flex>
                    <v-flex pr-2 xs3>
                        <v-text-field
                            v-model="form_faktur.form_refnumber" readonly disabled
                            label="Nomor Referensi" outline 
                        ></v-text-field>
                    </v-flex>
                    <v-flex pr-2 xs3>
                        <v-text-field
                            v-model="form_faktur.form_supplier_invoicenum" readonly disabled
                            label="Nomor Invoice Supplier" outline 
                        ></v-text-field>
                    </v-flex>
                    <v-flex pr-2 xs3>
                        <v-menu
                            v-model="menuSupplierDateForm" transition="scale-transition"
                            full-width offset-y lazy :nudge-right="40"
                            max-width="290px" min-width="290px"
                            :close-on-content-click="false"
                        >
                            <template v-slot:activator="{on}">
                                <v-text-field
                                    label="Tanggal Invoice Supplier" readonly disabled
                                    :value="SupplierInvoiceDateFormated" outline hide-details
                                ></v-text-field>
                            </template>
                            <v-date-picker
                                no-title v-model="form_faktur.form_supplier_invoicedate"
                                @input="menuSupplierDateForm = false" readonly disabled
                            ></v-date-picker>
                        </v-menu>
                    </v-flex>

                    <!-- 3rd row -->
                    <v-flex xs12>
                        <v-textarea
                            v-model="form_faktur.form_note"  readonly disabled
                            label="Catatan" outline rows="2"
                        ></v-textarea>
                    </v-flex>
                </v-layout>

                <v-data-table
                    v-if="form_item.length > 0"
                    :headers="headers" hide-actions
                    :items="form_item" class="elevation-1 mt-2"
                    item-key="ReceiveOrderPoDetailID"
                >
                    <template slot="items" slot-scope="props">
                        <tr>
                            <td class="text-xs-center">{{ props.item.PurchaseOrderNumber }}</td>
                            <td class="text-xs-center">{{ props.item.M_ItemDesc }}</td>
                            <td class="text-xs-center">{{ props.item.ReceiveOrderPoDetailQty }}</td>
                            <td class="text-xs-center">Rp. {{ toRupiah(props.item.ReceiveOrderPoDetailPrice) }}</td>
                            <td class="text-xs-center">
                                <kbd v-if="props.item.PurchaseOrderSummaryDiscountType == 'P'">{{ props.item.Discount }}%</kbd>
                                Rp. {{ calcItemDisc(props.item) }}
                            </td>
                            <td class="text-xs-center">Rp. {{ calcSubtal(props.item) }}</td>
                            <td class="text-xs-right">Rp. {{ calcTotal(props.item) }}</td>
                        </tr>
                    </template>
                    <template v-slot:footer>
                        <tr>
                            <td :colspan="6">
                                <strong class="ml-2">SUBTOTAL</strong>
                            </td>
                            <td :colspan="1" class="text-xs-right">
                                <strong>Rp. {{ toRupiah(form_faktur.form_subtotal) }}</strong>
                            </td>
                        </tr>
                        <tr v-if="form_faktur.form_shipping_cost > 0.00">
                            <td :colspan="6">
                                <strong class="ml-2">BIAYA PENGIRIMAN</strong>
                            </td>
                            <td :colspan="1" class="text-xs-right">
                                <strong>Rp. {{ toRupiah(form_faktur.form_shipping_cost) }}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td :colspan="6">
                                <strong class="ml-2">DISKON</strong>
                            </td>
                            <td :colspan="1" class="text-xs-right">
                                <!-- <kbd v-if="form_faktur.form_disc_type == 'P'">{{ parseFloat(form_faktur.form_disc_po).toFixed(2) }}%</kbd> -->
                                <strong>Rp. {{ toRupiah(form_faktur.form_disc_amount) }}</strong>
                            </td>
                        </tr>
                        <!-- <tr>
                            <td :colspan="5" class="text-xs-left">
                                <strong class="ml-4">PAJAK PENDAPATAN (PPN)</strong>
                            </td>
                            <td :colspan="1" class="text-xs-center">
                                <strong>Rp. {{ toRupiah(form_faktur.form_tax_amount_ppn) }}</strong>
                            </td>
                        </tr> -->
                        <!-- <tr>
                            <td :colspan="5" class="text-xs-left">
                                <strong class="ml-4">PAJAK PENGHASILAN (PPH)</strong>
                            </td>
                            <td :colspan="1" class="text-xs-center">
                                <strong>Rp. {{ toRupiah(form_faktur.form_tax_amount_pph) }}</strong>
                            </td>
                        </tr> -->
                        <tr>
                            <td :colspan="6">
                                <strong class="ml-2">PAJAK</strong>
                            </td>
                            <td :colspan="1" class="text-xs-right">
                                <strong>Rp. {{ toRupiah(form_faktur.form_tax_amount_ppn + form_faktur.form_tax_amount_pph) }}</strong>
                            </td>
                        </tr>
                        <tr>
                            <td :colspan="6">
                                <strong class="ml-2">GRAND TOTAL</strong>
                            </td>
                            <td :colspan="1" class="text-xs-right">
                                <strong>Rp. {{ toRupiah(form_faktur.form_grandtotal) }}</strong>
                            </td>
                        </tr>
                    </template>
                </v-data-table>

            </v-card-text>

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

<script>
    module.exports = {
        components: {},
        mounted() {},
        data() {
            return {
                menuDateForm: false,
                menuDueDateForm: false,
                menuDraftDateForm: false,
                menuTaxDateForm: false,
                menuSupplierDateForm: false,
                rules_text: [(v) => !!v || "Tidak boleh kosong"],
                rules_number: [(v) => !isNaN(v) || "Tidak boleh kosong"],
                headers: [
                    {
                        text: 'NOMOR PO', align: 'center', sortable: false, value: 'item', 
                        width: '15%', class: 'blue lighten-3 white--text'
                    },
                    {
                        text: 'ITEM', align: 'center', sortable: false, value: 'item', 
                        width: '15%', class: 'blue lighten-3 white--text'
                    },
                    {
                        text: 'QTY', align: 'center', sortable: false, value: 'qty', 
                        width: '10%', class: 'blue lighten-3 white--text'
                    },
                    {
                        text: 'HARGA', align: 'center', sortable: false, value: 'price', 
                        width: '15%', class: 'blue lighten-3 white--text'
                    },
                    {
                        text: 'DISKON', align: 'center', sortable: false, value: 'disc', 
                        width: '15%', class: 'blue lighten-3 white--text'
                    },
                    {
                        text: 'HARGA DISKON', align: 'center', sortable: false, value: 'pricedisc', 
                        width: '15%', class: 'blue lighten-3 white--text'
                    },
                    {
                        text: 'JUMLAH', align: 'center', sortable: false, value: 'total', 
                        width: '15%', class: 'blue lighten-3 white--text'
                    }
                ]
            }
        },
        computed: {
            viewfakturDialog: {
                get() {
                    return this.$store.state.data.viewfaktur
                },
                set(val) {
                    this.$store.commit("data/update_viewfaktur", val)
                }
            },
            form_faktur: {
                get() {
                    return this.$store.state.form.form_faktur
                },
                set(val) {
                    this.$store.commit("form/update_form_faktur", val)
                }
            },
            form_item: {
                get() {
                    return this.$store.state.form.form_item
                },
                set(val) {
                    this.$store.commit("form/update_form_item", val)
                }
            },
            DateFormated() {
                return this.formatDate(this.form_faktur.form_date);
            },
            DueDateFormated() {
                return this.formatDate(this.form_faktur.form_duedate);
            },
            SupplierInvoiceDateFormated() {
                return this.formatDate(this.form_faktur.form_supplier_invoicedate);
            },
            DraftDateFormated() {
                return this.formatDate(this.form_faktur.form_draftdate);
            },
            list_supplier() {
                return this.$store.state.data.list_supplier;
            },
            list_po() {
                return this.$store.state.data.list_po;
            },
            rupiah() {
                return this.toRupiah(this.form_faktur.form_grandtotal);
            }
        },
        methods: {
            closeDialog() {
                this.viewfakturDialog = false
                this.$store.commit("data/update_list_item", {records: [], total: 0})
                this.$store.dispatch("form/resetForm")
            },
            formatDate(date) {
                if (!date) return null
                const [year, month, day] = date.split("-")
                return `${day}-${month}-${year}`;
            },
            searchPO() {
                this.$store.dispatch("data/getListPO");
            },
            detailPO() {
                this.$store.dispatch("data/getDetailPO");
                this.form_item = []
                this.$store.commit("form/update_form_ro", {})
                this.$store.commit("data/update_list_item", {records: [], total: 0})
            },
            toRupiah(data) {
                // Input validation
                if (!data) return '0,00'
                
                // Ensure we're working with a number
                if (typeof data !== 'number') {
                    data = parseFloat(data)
                }
                
                // Handle invalid numbers
                if (isNaN(data)) return '0,00'
                
                // Convert to string with exactly 2 decimal places without rounding
                // This preserves the exact value for display
                const parts = data.toString().split('.')
                const wholePart = parts[0]
                let decimalPart = parts.length > 1 ? parts[1] : '00'
                
                // Ensure we have exactly 2 decimal digits for display
                if (decimalPart.length > 2) {
                    decimalPart = decimalPart.substring(0, 2)
                } else if (decimalPart.length < 2) {
                    decimalPart = decimalPart.padEnd(2, '0')
                }
                
                // Format the whole number part with dots as thousand separators
                const formatted = wholePart.replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                
                // Return the formatted number
                return `${formatted},${decimalPart}`
            },
            calcItemDisc(item) {
                if (item.PurchaseOrderSummaryDiscountType == 'R') {
                    this.form_item.find(a => a.ReceiveOrderPoDetailID === item.ReceiveOrderPoDetailID).disc_amount = item.Discount
                    return this.toRupiah(item.Discount)
                }

                let d = (Number(item.ReceiveOrderPoDetailPrice) * Number(item.Discount)) / 100
                this.form_item.find(a => a.ReceiveOrderPoDetailID === item.ReceiveOrderPoDetailID).disc_amount = d
                return this.toRupiah(d.toString())
            },
            calcSubtal(item) {
                price = Number(item.ReceiveOrderPoDetailPrice)
                disc = Number(item.Discount)

                if (item.PurchaseOrderSummaryDiscountType == 'R') {
                    return this.toRupiah((price - disc).toString())
                }

                let d = (price * disc) / 100
                return this.toRupiah((price - d).toString())
            },
            calcTotal(item) {
                qty = Number(item.ReceiveOrderPoDetailQty)
                price = Number(item.ReceiveOrderPoDetailPrice)
                disc = Number(item.Discount)
                let tl = 0

                if (item.PurchaseOrderSummaryDiscountType == 'R') {
                    tl = qty * (price - disc)
                    this.form_item.find(a => a.ReceiveOrderPoDetailID === item.ReceiveOrderPoDetailID).subtotal = tl
                    return this.toRupiah((tl).toString())
                }
                
                let d = (price * disc) / 100
                tl = qty * (price - d)
                this.form_item.find(a => a.ReceiveOrderPoDetailID === item.ReceiveOrderPoDetailID).subtotal = tl
                return this.toRupiah((tl).toString())
            },
            fn_calcSummary: _.debounce(function () {
                this.$store.dispatch("form/calcSummary")
            }, 1000),
            fn_adjust: _.debounce(function () {
                this.$store.dispatch("form/calcSummary")
            }, 1000)
        },
        watch: {
            form_item(newValue, oldValue) {
                this.fn_calcSummary();
            },
        }
    }
</script>