<template>
    <div>
        <v-dialog v-model="dialog_detailform" persistent width="70vw">
            <v-card>
                <v-card-title class="headline grey lighten-2" primary-title>
                    DAFTAR PERMINTAAN ITEM
                </v-card-title>
                
                <v-card-text>
                    <v-data-table
                        class="elevation-1 mb-2" hide-actions xs12
                        v-model="temp_item" item-key="PurchaseRequestFlagID"
                        :headers="headers" :items="list_detailform.records" :key="list_detailform.records.length + '-' + JSON.stringify(list_detailform.records.map(i => i.CanDirectUse))"
                    >
                        <template v-slot:items="props">
                            <tr>
                                <td class="text-xs-center pa-2">{{ props.item.PurchaseRequestNumber }}</td> 
                                <td class="text-xs-center pa-2">{{ props.item.M_ItemDesc }}</td>  
                                <td class="text-xs-center pa-2">
                                    <div class="stock-container">
                                        <div 
                                            v-for="(stock, index) in props.item.StockGudang" 
                                            :key="index" class="stock-badge">
                                            <strong>{{ stock.StockQty }} {{ stock.StockItemUnitName }}</strong> -- <em>{{ stock.StockBatchNo }}</em>                                        
                                        </div>
                                    </div>
                                </td>
                                <td class="text-xs-center pa-2">{{ props.item.PurchaseRequestFlagQty }} {{ props.item.RequestItemUnitName }} </td> 
                                <td class="text-xs-center pa-2" style="white-space:nowrap;">
                                    <v-checkbox 
                                        v-if="props.item.CanDirectUse"
                                        hide-details primary class="d-inline-flex"
                                        v-model="props.selected"
                                        style="display:inline-block;vertical-align:middle;"
                                    ></v-checkbox>
                                    <v-tooltip bottom v-if="props.item.CanUnpack">
                                        <template v-slot:activator="{ on }">
                                            <v-btn 
                                                icon @click="unpackStock(props.item)" v-on="on" style="display:inline-block;vertical-align:middle;">
                                                <v-icon color="blue">inbox</v-icon>
                                            </v-btn>
                                        </template>
                                        <span>Unpack</span>
                                    </v-tooltip>
                                    <v-icon v-if="!props.item.CanDirectUse && !props.item.CanUnpack" color="red">
                                        block
                                    </v-icon>
                                </td>
                            </tr>
                            <tr v-if="props.item.MustUnpack && !props.item.UnpackData.CanUnpack">
                                <td :colspan="headers.length" class="pa-2 red lighten-5 red--text" style="font-size:13px;">
                                    <v-icon small left color="red">info</v-icon>
                                    <span>{{ props.item.UnpackData.ReasonCannotUnpack }}</span>
                                </td>
                            </tr>
                        </template>
                    </v-data-table>

                    <div class="text-xs-center mt-2">
                        <v-pagination v-model="list_detailform_page" :length="detail_length" :total-visible="5"></v-pagination>
                    </div>
                </v-card-text>

                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="error" flat @click="batalPick()">BATAL</v-btn>
                    <v-btn color="primary" @click="simpanPick()">TAMBAH</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </div>
</template>

<style scoped>
    .flex-centered {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .flex-centered {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .stock-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;
    }

    .stock-badge {
        background-color: #424242;
        color: white;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
        white-space: nowrap;
    }
</style>

<script>
    module.exports = {
        components: {},
        mounted() {
        },
        data() {
            return {
                temp_item: [],
                headers: [
                    {
                        text: "NO REQUEST", align: "center", sortable: false,
                        value: "no", width: "15%", class: "blue lighten-3 white--text",
                    },
                    {
                        text: "ITEM", align: "center", sortable: false,
                        value: "no", width: "40%", class: "blue lighten-3 white--text",
                    },
                    {
                        text: "STOK (Qty-Batch)", align: "center", sortable: false,
                        value: "no", width: "25%", class: "blue lighten-3 white--text",
                    },
                    {
                        text: "REQUEST", align: "center", sortable: false,
                        value: "no", width: "15%", class: "blue lighten-3 white--text",
                    },
                    {
                        text: "AKSI", align: "center", sortable: false,
                        value: "no", width: "5%", class: "blue lighten-3 white--text",
                    },
                ]
            }
        },
        computed: {
            dialog_detailform: {
                get() {
                    return this.$store.state.p_form.dialog_detailform
                },
                set(val) {
                    this.$store.commit("p_form/update_dialog_detailform", val)
                }
            },
            form_detail: {
                get() {
                    return this.$store.state.p_form.form_detail
                },
                set(val) {
                    this.$store.commit("p_form/update_form_detail", val)
                }
            },
            list_detailform: {
                get() {
                    return this.$store.state.p_form.list_detailform
                },
                set(val) {
                    this.$store.commit("p_form/update_list_detailform", val) 
                }
            },
            list_detailform_page: {
                get() {
                    return this.$store.state.p_form.list_detailform_page
                },
                set(val) {
                    this.$store.commit("p_form/update_list_detailform_page", val)
                    this.$store.dispatch("p_form/getListItemDetail")
                }
            },
            detail_length() {
                let total = this.list_detailform.total
                if (total == undefined || total == 0) {
                    return 1
                }
                return Math.ceil(total/5)
            }
        },
        methods: {
            batalPick() {
                this.temp_item = [];
                this.dialog_detailform = false;
            },
            simpanPick() {
                const current_detail = this.form_detail;
                const new_detail = this.temp_item;

                new_detail.forEach(element => {
                    element['PurchaseRequestFlagQtyRest'] = 0;
                    element['ItemRequest'] = [];
                });

                const merge = current_detail.concat(new_detail);
                this.temp_item = [];
                this.form_detail = merge;
                this.dialog_detailform = false;
            },
            async unpackStock(item){
                try {
                    this.$store.commit("p_form/update_buffer_itemrequestedunpack", item)

                    let unitIds = [];
                    // Get unique unitID untuk SQL Query: StockItemUnitID IN unitIds
                    if (item.UnpackData && Array.isArray(item.UnpackData.ConversionOptions)) {
                        unitIds = [...new Set(
                            item.UnpackData.ConversionOptions.map(option => option.FromItemUnitID)
                        )];
                    } else {
                        unitIds = [0]; // Agar SQL tidak error saja
                    }
                    
                    let prm = {
                        itemid: item.UnpackData.M_ItemID,
                        unitid: unitIds,
                        batchno: ""
                    }
                    await this.$store.dispatch("p_form/getBatchItemUnpackList", prm)
                    this.$store.commit("p_form/update_dialog_unpackform", true);
                } catch (error) {
                    console.error('Failed to load batch data:', error)
                }
            }
        }
    }
</script>