<template>
    <v-dialog persistent max-width="60%" v-model="dialog_item">
        <v-card>
            <v-card-title class="headline grey lighten-2" primary-title>
                TAMBAH ITEM
            </v-card-title>

            <v-card-text>
                <v-layout row wrap>
                    <v-flex pr-2 xs6>
                        <v-autocomplete
                            v-model="form_ro"
                            label="Cari Receive Order"
                            return-object outline @input="lookupItem"
                            :items="list_ro.records"
                            item-text="ReceiveOrderPoNumber"
                        ></v-autocomplete>
                    </v-flex>
                    <v-flex xs6>
                        <v-text-field
                            v-model="search_item"
                            label="Cari Item"
                            outline hide-details
                        ></v-text-field>
                    </v-flex>

                    <v-flex xs12>
                        <v-data-table
                            v-model="selected_item"
                            :headers="header"
                            :items="list_item.records" select-all
                            :loading="false" item-key="ReceiveOrderPoDetailID"
                            hide-actions class="elevation-1"
                        >
                            <template v-slot:headers="props">
                                <tr>
                                    <th width="5%" class="blue lighten-3 white--text">
                                        <v-checkbox
                                            :input-value="props.all" primary hide-details
                                            :indeterminate="props.indeterminate" @click.stop="checkItemAll"
                                        ></v-checkbox>
                                    </th>
                                    <th
                                        v-for="header in props.headers" :class="header.class"
                                        :key="header.text" :width="header.width">
                                        {{ header.text }}
                                    </th>
                                </tr>
                            </template>
                            <template v-slot:items="props">
                                <tr :active="props.selected" @click="">
                                    <td>
                                        <v-checkbox
                                            :input-value="props.selected"
                                            primary hide-details
                                            @click.stop="checkPerItem(props.item)"
                                        ></v-checkbox>
                                    </td>
                                    <td class="text-xs-center">{{ props.item.M_ItemCode }}</td>
                                    <td class="text-xs-center">{{ props.item.M_ItemDesc }}</td>
                                    <td class="text-xs-center">Rp {{ toRupiah(props.item.ReceiveOrderPoDetailPrice) }}</td>
                                    <td class="text-xs-center">{{ props.item.ReceiveOrderPoDetailQty }} {{ props.item.ReceiveOrderPoItemUnitName }}</td>
                                </tr>
                            </template>
                        </v-data-table>
                        <div class="text-xs-center my-2">
                            <v-pagination v-model="page_item" :length="length_page" :total-visible="5"></v-pagination>
                        </div>
                    </v-flex>
                </v-layout>
            </v-card-text>

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

<script>
    module.exports = {
        mounted() {
            
        },
        data() {
            return {
                temp: [],
                header: [
                    {
                        text: "KODE ITEM",
                        align: "center",
                        sortable: false,
                        value: "no",
                        width: "15%",
                        class: "blue lighten-3 white--text",
                    },
                    {
                        text: "NAMA ITEM",
                        align: "center",
                        sortable: false,
                        value: "no",
                        width: "35%",
                        class: "blue lighten-3 white--text",
                    },
                    {
                        text: "PRICE",
                        align: "center",
                        sortable: false,
                        value: "no",
                        width: "30%",
                        class: "blue lighten-3 white--text",
                    },
                    {
                        text: "QTY",
                        align: "center",
                        sortable: false,
                        value: "no",
                        width: "15%",
                        class: "blue lighten-3 white--text",
                    },
                ]
            }
        },
        computed: {
            search_item: {
                get() {
                    return this.$store.state.data.search_item;
                },
                set(val) {
                    this.$store.commit("data/update_search_item", val)
                }
            },
            dialog_item: {
                get() {
                    return this.$store.state.form.dialog_item
                },
                set(val) {
                    this.$store.commit("form/update_dialog_item", val)
                }
            },
            form_ro: {
                get() {
                    return this.$store.state.form.form_ro
                },
                set(val) {
                    this.$store.commit("form/update_form_ro", val)
                }
            },
            selected_item: {
                get() {
                    return this.$store.state.data.selected_item
                },
                set(val) {
                    this.$store.commit("data/update_selected_item", val)
                }
            },
            page_item: {
                get() {
                    return this.$store.state.data.page_item
                },
                set(val) {
                    this.$store.commit("data/update_page_item", val)
                    this.$store.dispatch("data/getListItemRO")
                }
            },
            length_page() {
                let total = this.list_item.total
                if (total == undefined || total == 0) return 1
                return Math.ceil(total/5)
            },
            list_ro() {
                return this.$store.state.data.list_ro;
            },
            list_item() {
                return this.$store.state.data.list_item;
            }
        },
        methods: {
            closeDialogItem() {
                this.dialog_item = false
                this.selected_item = []
            },
            lookupItem() {
                this.$store.dispatch("data/getListItemRO")
            },
            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}`
            },
            tambahItem() {
                let item = this.selected_item
                this.$store.commit("form/update_form_item", item)
                this.dialog_item = false
                this.selected_item = []
            },
            checkPerItem(item){
                const currentSelected = [...this.selected_item]
                const index = currentSelected.findIndex(selected => selected.ReceiveOrderPoDetailID === item.ReceiveOrderPoDetailID)
                
                if (index > -1) {
                    currentSelected.splice(index, 1) // Item is selected, remove it
                } else {
                    currentSelected.push(item) // Item is not selected, add it
                }
                
                this.selected_item = currentSelected
            },
            checkItemAll() {
                const allItems = this.list_item.records
                const currentSelected = this.selected_item
                
                const allSelected = allItems.length === currentSelected.length
                
                if (allSelected) {
                    this.selected_item = []
                } else {
                    this.selected_item = [...allItems]
                }
            },
            fn_searchItemRO: _.debounce(function () {
                this.$store.dispatch("data/getListItemRO")
            }, 1000)
        },
        watch: {
            search_item(val, old) {
                if (val === old) return;
                if (!val) return
                console.log("search");

                this.fn_searchItemRO()
            }
        }
    }
</script>