<template>
    <v-dialog v-model="dialog_form_mutasi_approve" width="80vw" persistent>
        <v-card>
            <v-card-title class="headline grey lighten-2" primary-title>
                FORM APPROVE MUTASI INVENTARIS & ASSET
                <v-spacer></v-spacer>
                <v-icon @click="batalApprove()" color="black" right dark>close</v-icon>
            </v-card-title>

            <v-card-text>
            <v-form ref="formmutasi" lazy-validation v-model="valid_formmutasi">
                <v-layout row>
                    <v-flex xs6 pr-1>
                        <v-menu
                            v-model="menuMutasiDateForm" lazy offset-y max-width="290px"
                            full-width transition="scale-transition" min-width="290px"
                            :nudge-right="40" :close-on-content-click="false" 
                        >
                            <template v-slot:activator="{ on }">
                                <v-text-field
                                    :value="mutasiDateForm" label="Tanggal" 
                                    outline hide-details v-on="on" readonly 
                                ></v-text-field>
                            </template>
                            <v-date-picker
                                v-model="mutasi_date" no-title
                                @input="menuMutasiDateForm = false"
                            ></v-date-picker>
                        </v-menu>
                    </v-flex>
                    <v-flex xs6 px-1>
                        <v-autocomplete
                            v-model="selected_category" :rules="rules_category" disabled
                            :items="list_category" return-object outline item-value="itemCategoryID"
                            item-text="itemCategoryName" label="Kategori*" required 
                        ></v-autocomplete>
                    </v-flex>
                </v-layout>

                <v-layout row>
                    <v-flex xs6 pr-1>
                        <v-autocomplete
                            v-model="selected_branch_asal" :rules="rules_branch_asal"
                            :items="list_branch_asal" outline required disabled
                            item-text="M_BranchName" label="Cabang Asal*" return-object
                        ></v-autocomplete>
                    </v-flex>
                    <v-flex xs6 px-1>
                        <v-autocomplete
                            v-model="selected_branch_tujuan" :rules="rules_branch_tujuan"
                            :items="list_branch_tujuan" outline required 
                            item-text="M_BranchName" label="Cabang Tujuan*" return-object
                        ></v-autocomplete>
                    </v-flex>
                </v-layout>

                <v-layout row wrap>
                    <v-flex xs12 pl-1>
                        <v-textarea
                            v-model="note" hide-details 
                            auto-grow rows="1" label="Catatan" outline
                        ></v-textarea>
                    </v-flex>
                </v-layout>

                <v-layout row mt-4 wrap>
                    <v-flex xs12>
                        <v-data-table
                            v-if="list_mutasi_item.length > 0"
                            :headers = "headers" :items="list_mutasi_item"
                            hide-actions item-key="ReceiveOrderPoID" class="elevation-1"
                        >
                            <template v-slot:items="props">
                                <tr>
                                    <td class="text-xs-left">{{ props.item.ReceiveOrderPoNumber }}</td>
                                    <td class="text-xs-left">
                                        <p class="p-0 mb-0">{{ props.item.M_ItemCode }}</p>
                                        <p class="p-0 mb-0">{{ props.item.M_ItemDesc }}</p>
                                    </td>
                                    <td class="text-xs-center">{{ props.item.stock_total }} {{ props.item.ItemUnitName }}</td>
                                    <td class="text-xs-center">{{ props.item.qty_available }} {{ props.item.ItemUnitName }}</td>
                                    <td class="text-xs-center">{{ props.item.qty_mutasi }}</td>
                                </tr>
                            </template>
                        </v-data-table>
                    </v-flex>
                </v-layout>
            </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="red" flat outline @click="btnReject()">Reject</v-btn>
                <v-btn color="green" flat outline @click="btnApprove()">Approve</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script>
module.exports = {
    components: {},
    data() {
        return {
            menuMutasiDateForm: false,
            valid_formmutasi: true,
            rules_category: [v => (v && Object.keys(v).length > 0) || 'Kategori harus diisi'], 
            rules_lokasi: [v => (v && Object.keys(v).length > 0) || 'Lokasi harus diisi'], 
            rules_branch_asal: [v => (v && Object.keys(v).length > 0) || 'Cabang Asal harus diisi'],
            rules_branch_tujuan: [v => (v && Object.keys(v).length > 0) || 'Cabang Tujuan harus diisi'],
            headers: [
                {
                    text: "RO NUMBER", align: "center", sortable: false, value: "ItemUnitName", 
                    width: "25%", class: "pa-2 blue lighten-3 white--text",
                },
                {
                    text: "ITEM", align: "center", sortable: false, value: "M_ItemDesc",
                    width: "30%", class: "pa-2 blue lighten-3 white--text",
                },
                {
                    text: "TOTAL STOCK", align: "center", sortable: false, value: "qty",
                    width: "15%", class: "pa-2  blue lighten-3 white--text",
                },
                {
                    text: "QTY TERSEDIA BY BARCODE", align: "center", sortable: false, value: "qty",
                    width: "15%", class: "pa-2  blue lighten-3 white--text",
                },
                {
                    text: "QTY MUTASI", align: "center", sortable: false, value: "qty",
                    width: "15%", class: "pa-2  blue lighten-3 white--text",
                }
            ]
        }
    },
    computed: {
        dialog_form_mutasi_approve: {
            get() {
                return this.$store.state.form.dialog_form_mutasi_approve;
            },
            set(val) {
                this.$store.commit('form/update_dialog_form_mutasi_approve', val);
            }
        },
        mutasiDateForm() {
            return this.formatDate(this.mutasi_date)
        },
        mutasi_date: {
            get() {
                return this.$store.state.form.mutasi_date;
            },
            set(val) {
                this.$store.commit('form/update_mutasi_date', val);
            }
        },
        selected_category: {
            get() {
                return this.$store.state.form.selected_category;
            },
            set(val) {
                this.$store.commit('form/update_selected_category', val);
            }
        },
        selected_branch_asal: {
            get() {
                return this.$store.state.form.selected_branch_asal;
            },
            set(val) {
                this.$store.commit('form/update_selected_branch_asal', val);
            }
        },
        selected_branch_tujuan: {
            get() {
                return this.$store.state.form.selected_branch_tujuan;
            },
            set(val) {
                this.$store.commit('form/update_selected_branch_tujuan', val);
            }
        },
        note: {
            get() {
                return this.$store.state.form.note;
            },
            set(val) {
                this.$store.commit('form/update_note', val);
            }
        },
        list_category() {
            return this.$store.state.form.list_category
        },
        list_branch_asal() {
            return this.$store.state.form.list_branch_asal
        },
        list_branch_tujuan() {
            return this.$store.state.form.list_branch_tujuan
        },
        dialog_select_item: {
            get() {
                return this.$store.state.form.dialog_select_item;
            },
            set(val) {
                this.$store.commit('form/update_dialog_select_item', val);
            }
        },
        list_mutasi_item: {
            get() {
                return this.$store.state.form.list_mutasi_item;
            },
            set(val) {
                this.$store.commit('form/update_list_mutasi_item', val);
            }
        },
        select_item_temp: {
            get() {
                return this.$store.state.form.select_item_temp;
            },
            set(val) {
                this.$store.commit('form/update_select_item_temp', val);
            }
        },
    },
    methods: {
        formatDate(date) {
            if (!date) return null;
            const [year, month, day] = date.split("-");
            return `${day}-${month}-${year}`;
        },
        batalApprove() {
            this.list_mutasi_item = [];
            this.dialog_form_mutasi_approve = false;
        },
        pilihItem() {
            let temp = this.list_mutasi_item
            if (temp.length > 0) {
                this.$store.commit("form/update_select_item_temp", temp);
            }

            this.dialog_select_item = true;
            this.$store.dispatch('form/getReceiveOrderPo');
        },
        removeItem(props) {
            let temp = JSON.parse(JSON.stringify(this.list_mutasi_item));
            this.list_mutasi_item = temp.filter(ele => ele.ReceiveOrderPoID !== props.item.ReceiveOrderPoID);
        },
        simpanEdit() {
            if (this.$refs.formmutasi.validate()) {
                const list_mutasi = JSON.parse(JSON.stringify(this.list_mutasi_item));

                for (let i = 0; i < list_mutasi.length; i++) {
                    const qtyMutasi = Number(list_mutasi[i].qty_mutasi);
                    const qtyAvailable = Number(list_mutasi[i].qty_available);

                    if (!qtyMutasi || qtyMutasi <= 0) {
                        this.$store.commit("mutasi/update_snackbar", {
                            color: 'error',
                            msg: `QTY MUTASI pada item ${list_mutasi[i].M_ItemCode} - ${list_mutasi[i].M_ItemDesc} harus diisi dan lebih dari 0`,
                            isOpen: true
                        });
                        return;
                    }
                    if (qtyMutasi > qtyAvailable) {
                        this.$store.commit("mutasi/update_snackbar", {
                            color: 'error',
                            msg: `QTY MUTASI pada item ${list_mutasi[i].M_ItemCode} - ${list_mutasi[i].M_ItemDesc} tidak boleh lebih dari QTY tersedia`,
                            isOpen: true
                        });
                        return;
                    }
                }

                this.$store.dispatch("form/saveEditMutasi");
                this.$refs.formmutasi.resetValidation();
            }
        },
        async btnApprove() {
            try {
                let selected = this.$store.state.mutasi.selected_list_data
                if (selected.MutasiRequestID != '') {
                    await this.$store.dispatch("mutasi/approveMutasiRequest", {mutasiRequestID: selected.MutasiRequestID});
                }
            } catch (error) {
                console.error("Error approve mutasi:", error);
                this.$store.commit("mutasi/update_snackbar", {
                    color: 'error',
                    msg: 'Gagal Approve mutasi request',
                    isOpen: true
                });
            }
        },
        btnReject() {
            this.$store.commit("mutasi/update_dialog_reject", true)
            this.$store.commit('form/update_dialog_form_mutasi_approve', false);
        }
    },
    watch: {
        dialog_form_mutasi(val) {
            if (val) {
                this.$nextTick(() => {
                    this.$refs.formmutasi?.resetValidation();
                });
            }
        }
    },
}
</script>