<template>
    <div>
        <v-dialog v-model="dialog_batchitem" persistent width="30vw">
            <v-card>
                <v-card-title class="headline grey lighten-2" primary-title>
                    Pengeluaran Item
                </v-card-title>

                <v-card-text>
                    <v-layout row wrap>
                        <v-flex xs12 class="mb-2">
                            <v-autocomplete
                                v-model="form_batchitem" multiple label="Pilih Batch Item" item-text="StockBatchNo"
                                chips outline return-object :items="list_batchitemform.records" hide-details
                            >
                                <template v-slot:selection="data">
                                    <v-chip
                                        :selected="data.selected"
                                        close class="chip--select-multi" 
                                         @input="removeChips(data.item)"
                                    >
                                        {{ data.item.StockBatchNo }}
                                    </v-chip>
                                </template>
                                <template v-slot:item="data">
                                    <v-list-tile-content>
                                        <v-list-tile-title>
                                            Batch {{ data.item.StockBatchNo }}
                                        </v-list-tile-title>
                                        <v-list-tile-sub-title>
                                            Expired: {{ data.item.StockED }}
                                        </v-list-tile-sub-title>
                                    </v-list-tile-content>
                                </template>
                            </v-autocomplete>
                        </v-flex>
                        <v-flex xs12 v-for="(item, index) in form_batchitem" :key="item.StockStockNumber" class="mt-2">
                            <v-layout row wrap>
                                <v-flex xs6 class="pr-2">
                                    <p class="body-2 mb-0">Nomor batch: {{ item.StockBatchNo }}</p>
                                    <p class="body-2 mb-0">Expired: {{ item.StockED }}</p>
                                    <p class="body-2 mb-0">{{ item.WarehouseName }}</p>
                                </v-flex>
                                <v-flex xs3 class="pr-1">
                                    <p class="body-2 mb-0">Stock:</p>
                                    <p class="body-2 mb-0">{{ item.StockQty }} {{ item.ItemUnitName }}</p>
                                </v-flex>
                                <v-flex xs3 class="pl-1">
                                    <p class="text-xs-center">Isi Qty: </p>
                                    <v-text-field
                                        single-line 
                                        type="number" min="0" step="1"
                                        label="Jumlah" v-model="item.QtyReq"
                                        outline hide-details
                                    ></v-text-field>
                                </v-flex>
                            </v-layout>
                            <v-divider v-if="index + 1 < form_batchitem.length" :key="`divider-${index}`" class="mt-2"></v-divider>
                        </v-flex>
                    </v-layout>
                </v-card-text>

                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="error" @click="batalItem()">BATAL</v-btn>
                    <v-btn color="primary" @click="simpanItem()">SIMPAN</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </div>
</template>

<script>
    module.exports = {
        components: {},
        mounted() {},
        data() {
            return {
                
            }
        },
        computed: {
            dialog_batchitem: {
                get() {
                    return this.$store.state.requester.dialog_batchitem
                },
                set(val) {
                    this.$store.commit("requester/update_dialog_batchitem", val)
                }
            },
            buffer_detailitem: {
                get() {
                    return this.$store.state.requester.buffer_detailitem
                },
                set(val) {
                    this.$store.commit("requester/update_buffer_detailitem", val)
                }
            },
            list_batchitemform: {
                get() {
                    return this.$store.state.requester.list_batchitemform
                },
                set(val) {
                    this.$store.commit("requester/update_list_batchitemform", val)
                }
            },
            form_batchitem: {
                get() {
                    return this.$store.state.requester.form_batchitem
                },
                set(val) {
                    this.$store.commit("requester/update_form_batchitem", val)
                }
            },
            selectedItems: {
                get() {
                    return this.$store.state.requester.selectedItems;
                },
                set(val) {
                    this.$store.commit("requester/updateSelectedItems", val);
                }
            },
        emptycheck: {
            get() {
                return this.$store.state.requester.emptycheck;
            },
            set(val) {
                this.$store.commit("requester/updateEmptycheck", val);
            }
        },
        },
        methods: {
            batalItem() {
                this.buffer_detailitem = {}
                this.list_batchitemform = {}
                this.form_batchitem = []
                this.dialog_batchitem = false
            },
            simpanItem_old() {
                let current_detail = this.selectedItems
                let current_item = this.buffer_detailitem
                let new_batchitem = this.form_batchitem 

                let qty = 0
                let isError = false
                new_batchitem.forEach(element => {
                    let req = Number(element.QtyReq)
                    let stock = Number(element.StockQty)
                    if (!req || req <= 0 || req > stock) {
                        isError = true
                        this.$store.commit("requester/updateErrMessage", `[Error] jumlah tidak boleh <0 atau melebihi stock (${stock})`);
                        this.$store.commit("requester/updateAlertError", true);
                        return
                    }

                    qty = qty + req
                });
                if (isError) {
                    return
                }

                current_detail.forEach(element => {
                    if (element.rioDID == current_item.rioDID) {
                        element.ItemRequest = new_batchitem
                        element.QtyFilled = qty
                        element.rioDReceiveQty = qty
                    }
                });

                this.selectedItems = current_detail
                this.form_batchitem = []
                this.list_batchitemform = {}
                this.buffer_detailitem = {}
                this.dialog_batchitem = false

                // validasi qty receive jika melebihi qty request
                this.validateReceiveQty(current_item)
            },
            simpanItem(){
                let current_detail = this.selectedItems
                let current_item = this.buffer_detailitem
                let new_batchitem = this.form_batchitem 

                // console.log('before current_detail', current_detail)
                // console.log('current_item', current_item)
                // console.log('new_batchitem', new_batchitem)

                let qty = 0
                let isError = false
                
                // Validasi terlebih dahulu
                new_batchitem.forEach(element => {
                    let req = Number(element.QtyReq)
                    let stock = Number(element.StockQty)
                    if (!req || req <= 0 || req > stock) {
                        isError = true
                        this.$store.commit("requester/updateErrMessage", `[Error] jumlah tidak boleh <0 atau melebihi stock (${stock})`);
                        this.$store.commit("requester/updateAlertError", true);
                        return
                    }
                    qty = qty + req
                });
                
                if (isError) {
                    return
                }

                // Update StockQty di list_batchitemform berdasarkan BatchNo
                if (this.list_batchitemform && this.list_batchitemform.records) {

                    let updatedBatchRecords = [...this.list_batchitemform.records];

                    new_batchitem.forEach(batchItem => {
                        // Cari record yang sesuai berdasarkan StockID atau BatchNo
                        let recordIndex = updatedBatchRecords.findIndex(record => 
                            record.StockBatchNo === batchItem.StockBatchNo &&
                            record.StockItemID === batchItem.StockItemID &&
                            record.StockItemUnitID === batchItem.StockItemUnitID
                        );

                        if (recordIndex !== -1) {
                            // Kurangi StockQty dengan QtyReq
                            let currentStock = Number(updatedBatchRecords[recordIndex].StockQty);
                            let qtyReq = Number(batchItem.QtyReq);
                            let newStock = currentStock - qtyReq;
                            
                            // Update StockQty
                            updatedBatchRecords[recordIndex].StockQty = String(newStock);
                            
                            // Atau hapus record jika StockQty menjadi 0
                            // if (newStock <= 0) {
                            //     updatedBatchRecords.splice(recordIndex, 1);
                            //     updatedBatchRecords.total = updatedBatchRecords.length;
                            // }
                        }
                    });

                    let tempBatch = {
                        records: updatedBatchRecords,
                        total: updatedBatchRecords.length
                    };

                    this.$store.commit("requester/updateTempBatchNumber", tempBatch)
                }


                // Update current_detail dengan ItemRequest baru
                current_detail.forEach(element => {
                    if (element.rioDID == current_item.rioDID) {
                        // Jika sudah ada ItemRequest sebelumnya, gabungkan dengan yang baru
                        if (element.ItemRequest && element.ItemRequest.length > 0) {
                            // Merge atau update ItemRequest yang sudah ada
                            new_batchitem.forEach(newItem => {
                                let existingIndex = element.ItemRequest.findIndex(existing => 
                                    existing.StockBatchNo === newItem.StockBatchNo
                                );
                                
                                if (existingIndex !== -1) {
                                    // Update QtyReq jika batch yang sama sudah ada
                                    let existingQty = Number(element.ItemRequest[existingIndex].QtyReq);
                                    let newQty = Number(newItem.QtyReq);
                                    element.ItemRequest[existingIndex].QtyReq = String(existingQty + newQty);
                                } else {
                                    // Tambahkan batch baru
                                    element.ItemRequest.push(newItem);
                                }
                            });
                        } else {
                            // Jika belum ada ItemRequest, set yang baru
                            element.ItemRequest = new_batchitem;
                        }
                        
                        element.QtyFilled = qty;
                        element.rioDReceiveQty = qty;
                    }
                });

                this.selectedItems = current_detail
                this.form_batchitem = []
                // this.list_batchitemform = {}
                this.buffer_detailitem = {}
                this.dialog_batchitem = false

                // console.log('after current_detail', current_detail)

                // validasi qty receive jika melebihi qty request
                this.validateReceiveQty(current_item)
            },
            removeChips(data) {
                let tempo = this.form_batchitem.filter(item => item.StockBatchNo !== data.StockBatchNo)
                this.form_batchitem = tempo
            },
            validateReceiveQty(item) {
                let totalRequestQty = parseInt(item.rioDQty) || 0;
                let inputReceiveQty = parseInt(item.rioDReceiveQty) || 0;

                if (inputReceiveQty > totalRequestQty) {
                    if (!this.emptycheck.includes(item.rioDID)) {
                    this.emptycheck.push(item.rioDID);
                    }
                } else {
                    this.emptycheck = this.emptycheck.filter(id => id !== item.rioDID);
                }
            },
        },
    }
</script>