<template>
    <v-dialog v-model="dialog_form_receive_item" width="80vw" persistent>
        <v-card>
            <v-card-title class="headline grey lighten-2" primary-title>
                RECEIVE ITEM INVENTARIS
                <v-spacer></v-spacer>
            </v-card-title>

            <v-card-text>
                <v-form ref="formro" lazy-validation v-model="valid_formro">
                    <v-layout row>
                        <v-flex xs6 pr-1>
                            <v-menu v-model="menuReceiveDateForm" 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="receiveDateForm" label="Tanggal" outline hide-details
                                        v-on="on" readonly></v-text-field>
                                </template>
                                <v-date-picker v-model="form_receive.receive_date" no-title
                                    @input="menuReceiveDateForm = false"></v-date-picker>
                            </v-menu>
                        </v-flex>
                        <v-flex xs6 pl-1>
                            <v-autocomplete v-model="form_receive.supplier" :rules="rules_supplier"
                                :items="list_supplier" return-object outline item-value="SupplierID"
                                item-text="SupplierName" label="Supplier*" required></v-autocomplete>
                        </v-flex>
                        <!-- <v-flex xs4 pl-1>
                            <v-text-field label="Nomor Delivery Order (DO)*" outline required
                                v-model="form_receive.number_do" :rules="rules_do"></v-text-field>
                        </v-flex> -->
                    </v-layout>

                    <v-layout row>
                        <v-flex xs4 pr-1>
                            <v-text-field label="Referensi (No Pengiriman/No Supplier)*" :rules="rules_ref"
                                v-model="form_receive.referensi" outline required
                                placeholder="salah satu nomor pengiriman / supplier"></v-text-field>
                        </v-flex>
                        <v-flex xs4 px-1>
                            <v-autocomplete v-model="form_receive.warehouse" :rules="rules_warehouse"
                                :items="list_warehouse" outline required item-text="WarehouseName" label="Gudang*"
                                return-object></v-autocomplete>
                        </v-flex>
                        <v-flex xs4 pl-1>
                            <v-text-field label="Biaya Ekspedisi" outline prefix="Rp. "
                                v-model="form_receive.shipping_cost" hide-details></v-text-field>
                        </v-flex>
                    </v-layout>

                     <!-- <v-layout row>
                         <v-flex xs6 pr-1>
                            <v-autocomplete v-model="form_receive.lokasi" :rules="rules_lokasi" :items="list_lokasi"
                                return-object outline item-value="M_RuanganID" item-text="M_RuanganName"
                                label="Lokasi/Ruangan*" required></v-autocomplete>
                        </v-flex>
                    </v-layout> -->

                    <v-layout row wrap>
                        <v-flex xs12>
                            <v-textarea v-model="form_receive.note" hide-details auto-grow rows="1" label="Catatan"
                                outline></v-textarea>
                        </v-flex>
                        <v-flex xs3 pt-2>
                            <v-btn block color="info" class="mt-2" @click="pilihItemRO()"
                                :disabled="checkObjectEmpty(form_receive.supplier) || checkObjectEmpty(form_receive.warehouse)">
                                TAMBAH ITEM
                            </v-btn>
                        </v-flex>
                    </v-layout>

                    <v-layout row mt-2 wrap>
                        <v-flex v-for="shp in shipping_info" :key="shp.num_po" xs3>
                            <v-card class="pa-2">
                                <div>
                                    <span class="font-weight-bold">{{ shp.num_po }}</span><br />
                                    <span>Rp. {{ oneMoney(shp.cost) }}</span><br />
                                    <span v-if="shp.isUpfront === 'Y'" class="green--text">
                                        Biaya Ekspedisi sudah dibayar
                                    </span>
                                    <span v-else class="red--text">
                                        Biaya Ekspedisi belum dibayar
                                    </span>
                                </div>
                            </v-card>
                        </v-flex>
                    </v-layout>

                    <v-layout row mt-4 wrap>
                        <v-flex xs12>
                            <v-data-table v-if="form_receive_item.length > 0" :headers="headers"
                                :items="form_receive_item" hide-actions item-key="keyID" class="elevation-1">
                                <template v-slot:items="props">
                                    <tr>
                                        <td class="text-xs-left">{{ props.item.PurchaseOrderNumber }}</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>
                                            <!-- <p class="p-0 mb-0">{{ props.item.WarehouseName }}</p> -->
                                        </td>
                                        <td class="text-xs-center">{{ props.item.qty }} {{ props.item.ItemUnitName }}
                                        </td>
                                        <td class="text-xs-center">
                                            <div v-if="props.item.M_ItemItem_CategoryID == 2">
                                                <p class="mb-0 pb-0" v-for="batch in props.item.batchlist">
                                                    Qty: {{ batch.qty || '' }}
                                                </p>
                                            </div>
                                        </td>
                                        <td class="text-xs-center">
                                            <div v-if="props.item.inspeksi_item">
                                                <p v-if="props.item.inspeksi_item.summary == 'accept'">
                                                    Diterima
                                                </p>
                                                <p v-else-if="props.item.inspeksi_item.summary == 'reject'"
                                                    class="mb-0 pb-0">
                                                    Ditolak <br>
                                                    {{ props.item.inspeksi_item.catatan }}
                                                </p>
                                                <p v-else class="mb-0 pb-0">
                                                    Diterima dengan Catatan <br>
                                                    {{ props.item.inspeksi_item.catatan }}
                                                </p>
                                            </div>
                                        </td>
                                        <td class="text-xs-center">
                                            <v-tooltip bottom>
                                                <template v-slot:activator="{ on }">
                                                    <v-btn style="min-width: 30px; height: 30px; margin: 0;" outline
                                                        small @click="inspekItem(props)" color="green lighten-2">
                                                        <v-icon small color="green" v-on="on">note_add</v-icon>
                                                    </v-btn>
                                                </template>
                                                <span>Inspek Item</span>
                                            </v-tooltip>
                                            <!-- <v-tooltip bottom>
                                                <template v-slot:activator="{ on }">
                                                    <v-btn style="min-width: 30px; height: 30px; margin: 0;" outline
                                                        small @click="editBatch(props)" color="blue lighten-2">
                                                        <v-icon small color="blue" v-on="on">edit</v-icon>
                                                    </v-btn>
                                                </template>
                                                <span>Edit</span>
                                            </v-tooltip> -->
                                            <v-tooltip bottom>
                                                <template v-slot:activator="{ on }">
                                                    <v-btn style="min-width: 30px; height: 30px; margin: 0;" outline
                                                        small @click="removeItem(props)" color="red lighten-2">
                                                        <v-icon small color="red" v-on="on">delete</v-icon>
                                                    </v-btn>
                                                </template>
                                                <span>Hapus</span>
                                            </v-tooltip>
                                        </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="batalRO()">Batal</v-btn>
                <v-btn color="green" flat outline @click="simpanRO()">Simpan</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script>
module.exports = {
    components: {},
    data() {
        return {
            menuReceiveDateForm: false,
            valid_formro: true,
            rules_ref: [v => !!v || 'Tidak boleh kosong / harus diisi'],
            rules_supplier: [v => (v && Object.keys(v).length > 0) || 'Supplier harus diisi'],
            rules_lokasi: [v => (v && Object.keys(v).length > 0) || 'Lokasi harus diisi'],
            rules_warehouse: [v => (v && Object.keys(v).length > 0) || 'Gudang harus diisi'],
            headers: [
                {
                    text: "PO NUMBER", align: "center", sortable: false, value: "ItemUnitName",
                    width: "18%", class: "pa-2 blue lighten-3 white--text",
                },
                {
                    text: "ITEM", align: "center", sortable: false, value: "M_ItemDesc",
                    width: "25%", class: "pa-2 blue lighten-3 white--text",
                },
                {
                    text: "QTY", align: "center", sortable: false, value: "qty",
                    width: "10%", class: "pa-2  blue lighten-3 white--text",
                },
                {
                    text: "QTY TO STOCK", align: "center", sortable: false, value: "qty",
                    width: "22%", class: "pa-2  blue lighten-3 white--text",
                },
                {
                    text: "INSPEKSI", align: "center", sortable: false, value: "inspeksi",
                    width: "10%", class: "pa-2  blue lighten-3 white--text",
                },
                {
                    text: "AKSI", align: "center", sortable: false, value: "qty",
                    width: "15%", class: "pa-2  blue lighten-3 white--text",
                },
            ]
        }
    },
    computed: {
        dialog_form_receive_item: {
            get() {
                return this.$store.state.form.dialog_form_receive_item;
            },
            set(val) {
                this.$store.commit("form/update_dialog_form_receive_item", val);
            }
        },
        receiveDateForm() {
            return this.formatDate(this.form_receive.receive_date)
        },
        form_receive: {
            get() {
                return this.$store.state.form.form_receive;
            },
            set(val) {
                this.$store.commit("form/update_form_receive", val)
            }
        },
        form_receive_item: {
            get() {
                return this.$store.state.form.form_receive_item;
            },
            set(val) {
                this.$store.commit("form/update_form_receive_item", val)
            }
        },
        list_supplier() {
            return this.$store.state.ro.list_supplier
        },
        list_warehouse() {
            return this.$store.state.ro.list_warehouse
        },
        shipping_info() {
            return this.$store.state.form.shipping_info
        },
        list_lokasi() {
            return this.$store.state.ro.list_lokasi
        },
    },
    methods: {
        checkObjectEmpty(obj) {
            if (obj === null || obj === undefined || typeof obj !== "object") {
                return true;
            }
            return Object.keys(obj).length === 0 && obj.constructor === Object;
        },
        formatDate(date) {
            if (!date) return null;
            const [year, month, day] = date.split("-");
            return `${day}-${month}-${year}`;
        },
        oneMoney(value) {
            if (typeof value !== 'number') {
                value = parseFloat(value);
            }

            if (isNaN(value)) return '0,00';

            // Bulatkan dulu ke 2 desimal
            const fixed = value.toFixed(2); // hasil string, misal "16200000.00" atau "123456.70"
            const splitValue = fixed.split(".");

            const val = splitValue[0];       // bagian ribuan
            const decimal = splitValue[1];   // bagian desimal

            const formatted = val.replace(/\B(?=(\d{3})+(?!\d))/g, ".");

            return `${formatted},${decimal}`;
        },
        pilihItemRO() {
            let temp = this.form_receive_item
            if (temp.length > 0) {
                this.$store.commit("form/update_select_item_temp", temp);
            }

            this.$store.dispatch("form/getPurchaseOrder");
            this.$store.commit("form/update_dialog_select_item", true);
        },
        editBatch(props) {
            const curr_item = JSON.parse(JSON.stringify(props.item));
            if (!curr_item.batchlist || curr_item.batchlist.length <= 0) {
                let val = [
                    {
                        qty: 0,
                        batchno: '',
                        item_category: curr_item.M_ItemItem_CategoryID,
                        menuDate: false
                    }
                ];
                this.$store.commit("form/update_item_batch_temp", val)
            }

            this.$store.commit("form/update_selected_item_forbatch", curr_item);
            this.$store.commit("form/update_dialog_batch_item", true);
        },
        removeItem(props) {
            let temp = JSON.parse(JSON.stringify(this.form_receive_item));
            let newt = temp.filter((item) => item.PoItemReceiveID !== props.item.PoItemReceiveID);

            let shipInfo = [];
            newt.forEach(element => {
                let ship = {
                    num_po: element.PurchaseOrderNumber,
                    cost: element.PurchaseOrderShippingCost,
                    isUpfront: element.PurchaseOrderShippingCostStatus
                }

                const isExist = this.shipping_info.some(
                    item => item.num_po == element.PurchaseOrderNumber
                );
                if (!isExist) {
                    shipInfo.push(ship);
                }
            });

            this.form_receive_item = newt;
            this.$store.commit("form/update_shipping_info", shipInfo);
        },
        inspekItem(props) {
            const curr_item = JSON.parse(JSON.stringify(props.item));
            this.$store.commit("form/update_selected_item_received", curr_item);

            let inspeksi = this.$store.state.form.form_inspeksi

            if (curr_item.inspeksi_item) {
                inspeksi = curr_item.inspeksi_item
            } else {
                inspeksi.qty_po = curr_item.originalQty
                inspeksi.qty_ro = curr_item.qty
                inspeksi.price_po = curr_item.PoItemReceivePrice
                inspeksi.price_ro = curr_item.PoItemReceivePrice
            }

            this.$store.dispatch("ro/getListStaff");
            this.$store.commit("form/update_form_inspeksi", inspeksi);
            this.$store.commit("form/update_dialog_form_inspeksi", true);
        },
        batalRO() {
            this.$store.dispatch("form/resetForm");
            this.$refs.formro.resetValidation()
            this.error_num_do = false
            this.error_supplier = false
            this.error_warehouse = false
            this.dialog_form_receive_item = false;
        },
        simpanRO() {
            if (this.$refs.formro.validate()) {
                const form_detail = JSON.parse(JSON.stringify(this.form_receive_item));

                let empty = this.checkRODetail(form_detail);
                if (empty.length == 0) {
                    for (const element of form_detail) {
                        let total = element.batchlist.reduce((sum, item) => sum + Number(item.qty), 0);
                        if (total != Number(element.qty)) {
                            this.$store.commit("ro/update_snackbar", {
                                color: 'warning',
                                msg: `Jumlah item ${element.M_ItemDesc} tidak sama dengan pengaturan batch`,
                                isOpen: true
                            }, { root: true });
                            return;
                        }

                        if (!element.inspeksi_item) {
                            this.$store.commit("ro/update_snackbar", {
                                color: 'warning',
                                msg: `Form inspeksi item ${element.M_ItemDesc} belum di-isi`,
                                isOpen: true
                            }, { root: true });
                            return;
                        }
                    }

                    this.$store.dispatch("form/saveRO");
                    this.$refs.formro.resetValidation();
                } else {
                    const message = empty.map(item => item.M_ItemDesc).join(', ')
                    this.$store.commit("ro/update_snackbar", {
                        color: 'warning',
                        msg: 'QTY to Stock berikut masih belum terisi ' + message,
                        isOpen: true
                    }, { root: true });
                    return;
                }
            }
        },
        checkRODetail(data) {
            const emptyBatch = data.filter(element => {
                return Array.isArray(element.batchlist) && element.batchlist.length === 0;
            })

            return emptyBatch
        }
    },
    watch: {
        dialog_form_receive_item(val) {
            if (val) {
                this.$nextTick(() => {
                    this.$refs.formro?.resetValidation();
                });
            }
        }
    },
}
</script>
