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

            <v-card-text>
                <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" hide-details :items="list_supplier"
                            return-object outline item-text="SupplierName" label="Supplier"></v-autocomplete>
                    </v-flex>
                </v-layout>

                <v-layout row mt-2>
                    <v-flex xs4 pr-1>
                        <v-text-field label="Referensi (No Pengiriman/No Supplier)*" v-model="form_receive.referensi"
                            outline hide-details placeholder="salah satu nomor pengiriman / supplier"></v-text-field>
                    </v-flex>
                    <v-flex xs4 px-1>
                        <v-autocomplete v-model="form_receive.warehouse" hide-details :items="list_warehouse" outline
                            return-object item-text="WarehouseName" label="Gudang"></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 mt-2>
                    <v-flex xs6 pr-1>
                        <v-autocomplete v-model="form_receive.lokasi" :items="list_lokasi" return-object outline
                            item-value="M_RuanganID" item-text="M_RuanganName" label="Lokasi*" hide-details
                            required></v-autocomplete>
                    </v-flex>
                </v-layout> -->

                <v-layout row mt-2 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-card-text>

            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="red" outline flat @click="batalRO()">Batal</v-btn>
                <v-btn color="green" outline flat @click="simpanEditRO()">Simpan</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script>
module.exports = {
    components: {},
    data() {
        return {
            menuReceiveDateForm: false,
            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_edit: {
            get() {
                return this.$store.state.form.dialog_form_receive_item_edit
            },
            set(val) {
                this.$store.commit("form/update_dialog_form_receive_item_edit", val);
            }
        },
        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)
            }
        },
        form_receive_item_del: {
            get() {
                return this.$store.state.form.form_receive_item_del
            },
            set(val) {
                this.$store.commit("form/update_form_receive_item_del", val)
            }
        },
        receiveDateForm() {
            return this.formatDate(this.form_receive.receive_date)
        },
        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';

            const fixed = value.toFixed(2);
            const splitValue = fixed.split(".");

            const val = splitValue[0];
            const decimal = splitValue[1];

            const formatted = val.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
            return `${formatted},${decimal}`
        },
        batalRO() {
            this.$store.dispatch("form/resetForm");
            this.form_receive_item_del = [];
            this.dialog_form_receive_item_edit = false
        },
        simpanEditRO() {
            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/saveEditRO");
            } 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;
            }
            // this.$store.dispatch("form/saveEditRO")
        },
        checkRODetail(data) {
            const emptyBatch = data.filter(element => {
                return Array.isArray(element.batchlist) && element.batchlist.length === 0;
            })

            return emptyBatch
        },
        pilihItemRO() {
            let temp = JSON.parse(JSON.stringify(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);
        },
        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);
        },
        removeItem(props) {
            let temp = JSON.parse(JSON.stringify(this.form_receive_item));
            let newt = temp.filter((item) => item.PoItemReceiveID !== props.item.PoItemReceiveID);
            let del = temp.find((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_del.push(del);
            this.form_receive_item = newt;
            this.$store.commit("form/update_shipping_info", shipInfo);
        },
        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: '',
                        expiredate: moment(new Date()).format('YYYY-MM-DD'),
                        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);
        }
    },
}
</script>
