<template>
    <v-dialog v-model="dialogCreate" persistent max-width="90%">
        <v-card>
            <v-card-title class="headline grey lighten-2" primary-title>
                {{ this.is_create ? "FORM PURCHASE INVOICE" : "EDIT FORM PURCHASE INVOICE" }}
            </v-card-title>

            <v-card-text class="pt-0 pb-0 mt-4">
                <v-form ref="formCreate" v-model="validationForm" lazy-validation>
                    <v-layout row wrap>
                        <v-flex pr-2 xs3>
                            <v-menu readonly
                                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 v-on="on"
                                        outline hide-details :value="DateFormated"
                                    ></v-text-field>
                                </template>
                                <v-date-picker readonly
                                    no-title v-model="form_faktur.form_date" @input="menuDateForm = false"
                                ></v-date-picker>
                            </v-menu>
                        </v-flex>
                        <v-flex pr-2 xs3>
                            <v-menu readonly
                                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 v-on="on"
                                        outline hide-details :value="DueDateFormated"
                                    ></v-text-field>
                                </template>
                                <v-date-picker readonly
                                    no-title v-model="form_faktur.form_duedate"
                                    @input="menuDueDateForm = false"
                                ></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 v-on="on"
                                        :value="DraftDateFormated" outline :rules="rules_text"
                                    ></v-text-field>
                                </template>
                                <v-date-picker
                                    no-title v-model="form_faktur.form_draftdate"
                                    @input="menuDraftDateForm = false"
                                ></v-date-picker>
                            </v-menu>
                        </v-flex>
                        <v-flex pr-2 xs3>
                            <v-autocomplete
                                v-model="form_faktur.form_supplier"
                                label="Supplier" menu-icon="mdi-chevron-down"
                                item-text="SupplierName" @input="searchPO"
                                :items="list_supplier.records" readonly
                                :rules="rules_text" outline
                                return-object required
                            ></v-autocomplete>
                        </v-flex>

                        <!-- 2nd row -->
                        <v-flex pr-2 xs3>
                            <v-text-field
                                v-model="form_faktur.form_po.ReceiveOrderPoNumber"
                                label="Nomor GRN" outline :rules="rules_text" readonly
                            ></v-text-field>
                        </v-flex>
                        <v-flex pr-2 xs3>
                            <v-text-field
                                v-model="form_faktur.form_refnumber" readonly
                                label="Nomor Referensi Penerimaan" outline :rules="rules_text"
                            ></v-text-field>
                        </v-flex>
                        <v-flex pr-2 xs3>
                            <v-text-field
                                v-model="form_faktur.form_supplier_invoicenum"
                                label="Nomor Invoice Supplier" outline :rules="rules_text"
                            ></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 Supplir" readonly v-on="on"
                                        :value="SupplierInvoiceDateFormated" outline :rules="rules_text"
                                    ></v-text-field>
                                </template>
                                <v-date-picker
                                    no-title v-model="form_faktur.form_supplier_invoicedate"
                                    @input="menuSupplierDateForm = false"
                                ></v-date-picker>
                            </v-menu>
                        </v-flex>

                        <!-- 5th row -->
                        <v-flex xs12>
                            <v-textarea
                                v-model="form_faktur.form_note"
                                label="Catatan" outline rows="2"
                            ></v-textarea>
                        </v-flex>
                    </v-layout>
                </v-form>
                <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 }} {{ props.item.ReceiveOrderPoItemUnitName }} </td>
                            <td class="text-xs-right">Rp. {{ toRupiah(props.item.ReceiveOrderPoDetailPrice) }}</td>
                            <td class="text-xs-right">
                                <kbd v-if="props.item.PurchaseOrderSummaryDiscountType == 'P'">{{ props.item.Discount }}%</kbd>
                                Rp. {{ calcItemDisc(props.item) }}
                            </td>
                            <td class="text-xs-right">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">
                                <strong>Rp. {{ toRupiah(form_faktur.form_disc_amount) }}</strong>
                            </td>
                        </tr>
                        <!-- <tr>
                            <td :colspan="6" class="text-xs-right">
                                <strong class="ml-2">PAJAK (PPN)</strong>
                            </td>
                            <td :colspan="1" class="text-xs-right">
                                <strong>Rp. {{ toRupiah(form_faktur.form_tax_amount_ppn) }}</strong>
                            </td>
                        </tr> -->
                        <!-- <tr>
                            <td :colspan="6" class="text-xs-right">
                                <strong class="ml-2">PAJAK PENGHASILAN (PPH)</strong>
                            </td>
                            <td :colspan="1" class="text-xs-right">
                                <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()" :disabled="isSubmitting">
                    Tutup
                </v-btn>
                <v-btn color="primary" dark @click="simpanFaktur()" :disabled="isSubmitting" :loading="isSubmitting">
                    Simpan
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script>
    module.exports = {
        components: {},
        mounted() {},
        data() {
            return {
                isSubmitting: false,
                validationForm: false,
                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: {
            dialogCreate: {
                get() {
                    return this.$store.state.form.opendialog;
                },
                set(val) {
                    this.$store.commit("form/update_opendialog", val)
                }
            },
            form_faktur: {
                get() {
                    return this.$store.state.form.form_faktur
                },
                set(val) {
                    this.$store.commit("form/update_form_faktur", val)
                }
            },
            dialog_item: {
                get() {
                    return this.$store.state.form.dialog_item;
                },
                set(val) {
                    this.$store.commit("form/update_dialog_item", val)
                }
            },
            form_item: {
                get() {
                    return this.$store.state.form.form_item
                },
                set(val) {
                    this.$store.commit("form/update_form_item", val)
                }
            },
            is_create: {
                get() {
                    return this.$store.state.form.is_create
                },
                set(val) {
                    this.$store.commit("form/update_is_create", 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: {
            simpanFaktur() {
                if (this.$refs.formCreate.validate()) {
                    this.isSubmitting = true;
                    console.log("isSubmitting should be true=> ", this.isSubmitting)

                    if (this.is_create) {
                        this.$store.dispatch("form/createFaktur")
                        this.isSubmitting=false;
                        console.log("isSubmitting should be false=> ", this.isSubmitting)
                    } else {
                        this.$store.dispatch("form/updateFaktur")
                        this.isSubmitting=false;
                    }
                }
            },
            closeDialog() {
                this.dialogCreate = false
                this.$store.commit("data/update_list_item", {records: [], total: 0})
                this.$store.dispatch("form/resetForm")
                this.$refs.formCreate.resetValidation()
            },
            formatDate(date) {
                if (!date) return null
                const [year, month, day] = date.split("-")
                return `${day}-${month}-${year}`;
            },
            searchPO() {
                /* add tanggal jatuh tempo */
                let faktur = JSON.parse(JSON.stringify(this.form_faktur));
                let supplier_top = faktur.form_supplier.SupplierTermOfPayment;

                let tempdate = new Date(faktur.form_date);
                tempdate.setDate(tempdate.getDate() + Number(supplier_top));

                faktur.form_duedate = tempdate.toISOString().split('T')[0];
                this.form_faktur = faktur;

                /* get listting po */
                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})
            },
            isObjectEmpty(obj) {
                return Object.keys(obj).length === 0 && obj.constructor === Object;
            },
            dialogAddItem() {
                this.dialog_item = true
                this.$store.dispatch("data/getListRO");
                this.$store.commit("data/update_selected_item", this.form_item)
            },
            deleteItemFaktur(item) {
                let arr = this.form_item
                if (!arr) {
                    return
                }

                let newArr = arr.filter(x => x.ReceiveOrderPoDetailID !== item.ReceiveOrderPoDetailID)
                this.form_item = newArr
            },
            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>
