<template>
    <v-card class="pa-2">
        <v-layout row wrap>
            <v-flex xs6 class="pr-1">
                <h3>FORM TRANSFER NON PERSEDIAAN</h3>
                <h3>TYPE FORM: {{ this.type_act }}</h3>
            </v-flex>
            <v-flex xs6 class="pl-1">
                <h3>NOMOR: {{ this.selected_tf.T_GoodsTransferNum ?? '-' }}</h3>
                <h3>STATUS: {{ this.selected_tf.T_GoodsTransferStatus ?? '-' }}</h3>
            </v-flex>

            <!-- first row -->
            <v-flex xs4 class="pr-2 mt-2">
                <v-menu
                    v-model="menuTFDate" transition="scale-transition"
                    lazy offset-y full-width :nudge-right="40"
                    max-width="290px" min-width="290px"
                    :close-on-content-click="false"
                >
                    <template v-slot:activator="{ on }">
                        <v-text-field 
                            v-model="computedTFDate" label="Tanggal Transfer" 
                            readonly v-on="on" outline hide-details :disabled="isVerif()"
                        ></v-text-field>
                    </template>
                    <v-date-picker v-model="form_transfer_date" @input="menuTFDate = false" no-title></v-date-picker>
                </v-menu>
            </v-flex>
            <v-flex xs4 class="pr-1 mt-2">
                <v-autocomplete
                    outline v-model="form_cabang" hide-details
                    :items="list_cabangform" label="Cabang" return-object item-key="M_BranchCode"
                    item-text="M_BranchName" @input="changeCabang" :disabled="isVerif()"
                ></v-autocomplete>
            </v-flex>
            <v-flex xs4 class="pl-1 mt-2">
                <v-autocomplete
                    outline v-model="form_divisi" hide-details
                    :items="list_divisiform" label="Divisi" return-object item-key="DivisionID"
                    item-text="DivisionName" @input="changeDivisi" :disabled="isVerif()"
                ></v-autocomplete>
            </v-flex>

            <!-- second row -->
            <v-flex xs12 class="mt-2">
                <v-textarea
                    outline hide-details label="Catatan" v-model="form_catatan" :disabled="isVerif()"
                ></v-textarea>
            </v-flex>

            <!-- button add detail -->
            <v-flex xs12 class="mt-4 flex-end">
                <v-btn icon @click="addItem()" :disabled="isVerif()">
                    <v-icon medium color="primary">add_box</v-icon>
                </v-btn>
            </v-flex>

            <!-- detail table row -->
            <v-flex xs12>
                <v-data-table
                    class="elevation-1 mb-2" hide-actions xs12 item-key="PurchaseRequestFlagID"
                    :headers="headers" :items="form_detail" :loading="false"
                >
                    <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">
                                <p v-for="obj in props.item.ItemRequest" class="body-1 mb-0">
                                    Nomor: {{ obj.StockStockNumber }}, Jumlah: {{ obj.QtyReq }}, {{ obj.WarehouseName }} 
                                </p>
                            </td> 
                            <td class="text-xs-center pa-2">
                                <!-- <v-text-field
                                    v-model="props.item.PurchaseRequestFlagQtyRest" single-line 
                                    type="number" outline hide-details :disabled="isVerif()" readonly
                                ></v-text-field> -->
                                <p class="body-2">{{ props.item.PurchaseRequestFlagQty }} / {{ props.item.PurchaseRequestFlagQtyRest }}  {{ props.item.ItemUnitName }}</p>
                                <p v-show="empty_id.includes(props.item.PurchaseRequestFlagID)" style="color: red;" class="ma-0 pa-0">Jumlah melebihi stok</p>
                            </td> 
                            <td class="text-xs-center pa-2">
                                <v-btn icon @click="editDetail(props.item)" :disabled="isVerif() && is_verif !='Verified'">
                                    <v-icon color="blue">edit</v-icon>
                                </v-btn>
                                <v-btn icon @click="removeDetail(props.item)" :disabled="isVerif()">
                                    <v-icon color="error">delete</v-icon>
                                </v-btn>
                            </td> 
                        </tr>
                    </template>
                </v-data-table>
                <v-divider></v-divider>
            </v-flex>

            <v-flex grow class="mt-4">
                <!-- <v-btn
                    color="primary" class="white--text" @click="doVerif()" 
                    :outline="!isVerif()" :disabled="isVerif()"
                >
                    {{ !isVerif() ? 'Verifikasi' : 'Verified' }}
                    <v-icon v-show="isVerif()" right>check_circle</v-icon>
                </v-btn> -->

                <v-btn
                    color="primary" class="white--text" @click="submitReq()"
                    :outline="!isVerif()" :disabled="isVerif()"
                    v-show="Object.keys(selected_tf).length <= 0 || selected_tf.T_GoodsTransferStatus == 'Draft'"
                >
                    Buat Request
                    <v-icon right small>assignment_turned_in</v-icon>
                </v-btn>

                <v-btn
                    color="primary" class="white--text" @click="submitTF('V')" 
                    :outline="selected_tf.T_GoodsTransferVerifiedBy == '0'"
                    v-show="Object.keys(selected_tf).length > 0 && selected_tf.T_GoodsTransferStatus != 'Draft'"
                >
                    {{ selected_tf.T_GoodsTransferVerifiedBy == '0' ? 'Verify' : 'Verified' }}
                    <v-icon right small>done</v-icon>
                </v-btn>
                <v-btn
                    color="primary" class="white--text" @click="submitTF('A')" 
                    :outline="selected_tf.T_GoodsTransferApprovedBy == '0'"
                    v-show="Object.keys(selected_tf).length > 0 && selected_tf.T_GoodsTransferStatus != 'Draft'"
                >
                    {{ selected_tf.T_GoodsTransferApprovedBy == '0' ? 'Approve' : 'Approved' }}
                    <v-icon right small>done_all</v-icon>
                </v-btn>
            </v-flex>
            <v-flex shrink class="mt-4">
                <v-btn 
                    outline color="primary" class="white--text" 
                    @click="batalForm()" :disabled="isVerif()"
                >Batal</v-btn>
                <v-btn 
                    color="primary" class="white--text" 
                    @click="simpanForm()" 
                    :disabled="selected_tf.T_GoodsTransferStatus != 'Verified' || selected_tf.T_GoodsTransferStatus != 'Draft'"
                    v-show="type_act == 'BARU' || (type_act == 'EDIT' && edit_qty != 'Eqty')"
                >Simpan</v-btn>
                <v-btn 
                    color="primary" class="white--text" 
                    @click="simpanForm()"
                    v-show="selected_tf.T_GoodsTransferStatus == 'Verified' && type_act == 'EDIT' && edit_qty == 'Eqty'"
                >Simpan qty</v-btn>
            </v-flex>
        </v-layout>
    </v-card>
</template>

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

<script>
    module.exports = {
        components: {},
        mounted() {
            
        },
        data() {
            return {
                menuTFDate: false,
                empty_id: [],
                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: "35%", class: "blue lighten-3 white--text",
                    },
                    {
                        text: "ITEM GUDANG", align: "center", sortable: false,
                        value: "no", width: "30%", class: "blue lighten-3 white--text",
                    },
                    {
                        text: "JUMLAH", align: "center", sortable: false,
                        value: "no", width: "5%", class: "blue lighten-3 white--text",
                    },
                    {
                        text: "AKSI", align: "center", sortable: false,
                        value: "no", width: "15%", class: "blue lighten-3 white--text",
                    },
                ]
            }
        },
        computed: {
            form_transfer_date: {
                get() {
                    return this.$store.state.np_form.form_transfer_date
                },
                set(val) {
                    this.$store.commit("np_form/update_form_transfer_date", val)
                }
            },
            form_cabang: {
                get() {
                    return this.$store.state.np_form.form_cabang
                },
                set(val) {
                    this.$store.commit("np_form/update_form_cabang", val)
                }
            },
            form_divisi: {
                get() {
                    return this.$store.state.np_form.form_divisi
                },
                set(val) {
                    this.$store.commit("np_form/update_form_divisi", val)
                }
            },
            form_catatan: {
                get() {
                    return this.$store.state.np_form.form_catatan
                },
                set(val) {
                    this.$store.commit("np_form/update_form_catatan", val)
                }
            },
            form_detail: {
                get() {
                    return this.$store.state.np_form.form_detail
                },
                set(val) {
                    this.$store.commit("np_form/update_form_detail", val)
                }
            },
            dialog_detailform: {
                get() {
                    return this.$store.state.np_form.dialog_detailform
                },
                set(val) {
                    this.$store.commit("np_form/update_dialog_detailform", val)
                }
            },
            list_cabangform: {
                get() {
                    return this.$store.state.np_form.list_cabangform
                },
                set(val) {
                    this.$store.commit("np_form/update_list_cabangform", val)
                }
            },
            list_divisiform: {
                get() {
                    return this.$store.state.np_form.list_divisiform
                },
                set(val) {
                    this.$store.commit("np_form/update_list_divisiform", val)
                }
            },
            list_detailform: {
                get() {
                    return this.$store.state.np_form.list_detailform
                },
                set(val) {
                    this.$store.commit("np_form/update_list_detailform", val)
                }
            },
            type_act: {
                get() {
                    return this.$store.state.np_form.type_act
                },
                set(val) {
                    this.$store.commit("np_form/update_type_act", val)
                }
            },
            is_verif: {
                get() {
                    return this.$store.state.np_form.is_verif
                },
                set(val) {
                    this.$store.commit("np_form/update_is_verif", val)
                }
            },
            selected_tf: {
                get() {
                    return this.$store.state.np_data.selected_tf
                },
                set(val) {
                    this.$store.commit("np_data/update_selected_tf", val)
                }
            },
            edit_qty: {
                get() {
                    return this.$store.state.np_form.edit_qty
                },
                set(val) {
                    this.$store.commit("np_form/update_edit_qty", val)
                }
            },
            act_verif: {
                get() {
                    return this.$store.state.np_form.act_verif
                },
                set(val) {
                    this.$store.commit("np_form/update_act_verif", val)
                }
            },
            computedTFDate() {
                return this.formatDate(this.form_transfer_date)
            },
            approve_level() {
                return this.$store.state.np_data.user_level
            }
        },
        methods: {
            formatDate(date) {
                if (!date) return null
                const [year, month, day] = date.split('-')
                return `${day}-${month}-${year}`
            },
            isVerif() {
                let stat = this.is_verif
                if (stat == 'Draft') {
                    return false
                } else {
                    return true
                }
            },
            changeCabang() {
                this.empty_id = []
            },
            changeDivisi() {
                this.empty_id = []
            },
            addItem() {
                if (!this.form_cabang.M_BranchCode || !this.form_transfer_date || !this.form_divisi.DivisionID) {
                    const snac = { isOpen: true, color: 'error', msg: 'Form harus diisi' };
                    this.$store.commit("p_data/update_snackbar", snac);
                    return
                }

                this.$store.dispatch("np_form/getListItemDetail")
                this.dialog_detailform = true
            },
            editDetail(item) {
                let params = {
                    itemid: item.PurchaseRequestDetailM_ItemID,
                    unitid: item.PurchaseRequestDetailItemUnitID
                }
                this.$store.dispatch("np_form/getListStock", params);

                if (item.ItemRequest.length > 0) {
                    this.$store.commit("np_form/update_form_barnote", item.ItemRequest);
                }

                this.$store.commit("np_form/update_buffer_detailitem", item)
                this.$store.commit("np_form/update_dialog_batchitem", true)
            },
            removeDetail(item) {
                const old = this.form_detail
                let nwd = old.filter((val) => val.PurchaseRequestFlagID !== item.PurchaseRequestFlagID)
                this.form_detail = nwd
            },
            batalForm() {
                this.$store.dispatch("np_form/newForm")
                this.empty_id = []
            },
            simpanForm() {
                let empty = []
                let temp_detail = this.form_detail

                if (Object.keys(this.form_cabang).length <= 0 || Object.keys(this.form_divisi).length <= 0) {
                    this.empty_id = empty
                    return
                }

                temp_detail.forEach(element => {
                    let qty = parseInt(element.PurchaseRequestFlagQtyRest)
                    let stock = parseInt(element.StockGudang)
                    if (qty > stock) {
                        empty.push(element.PurchaseRequestFlagID)
                        return
                    }
                });

                if (this.form_cabang.T_GoodsTransferStatus == 'Verified' && this.edit_qty == 'NoEqty') {
                    return
                }

                // jika type_act BARU maka inser
                // jika type_act EDIT dan edit_qty == NoEqty maka update data
                // jika type_act EDIT dan edit_qty == Eqty maka update qty
                if (this.type_act == 'BARU' && empty.length == 0) {
                    this.empty_id = empty
                    this.$store.dispatch("np_form/createTFReq")
                } else if (this.type_act == 'EDIT' && this.edit_qty == 'NoEqty' && empty.length == 0) {
                    this.empty_id = empty
                    this.$store.dispatch("np_form/updateTFReq")
                } else if (this.type_act == 'EDIT' && this.edit_qty == 'Eqty' && empty.length == 0) {
                    this.empty_id = empty
                    this.$store.dispatch("np_form/updateTFReq")
                } else {
                    this.empty_id = empty
                }
            },
            submitReq() {
                let error_id = []
                let act = this.type_act
                let item = this.form_detail

                let snac = { isOpen: true, color: "error", msg: "[Error]" }
                if (!this.form_transfer_date || Object.keys(this.form_cabang).length == 0 || Object.keys(this.form_divisi).length == 0) {
                    snac.msg = "[Error] Masih terdapat form yang kosong"
                    this.$store.commit("p_data/update_snackbar", snac, { root: true })
                    return
                }

                
                if (item.length <= 0) {
                    snac.msg = "[Error] Detail Item masih kosong"
                    this.$store.commit("p_data/update_snackbar", snac, { root: true })
                    return
                }

                item.forEach(element => {
                    if (parseInt(element.PurchaseRequestFlagQtyRest) > parseInt(element.StockGudang)) {
                        error_id.push(element.PurchaseRequestFlagID)
                    }
                });

                if (error_id.length > 0) {
                    this.empty_id = error_id
                    return
                }

                if (this.is_verif == 'Draft') {
                    this.is_verif = 'Pending'
                }

                if (act == 'BARU' && error_id.length == 0) {
                    this.empty_id = error_id
                    this.$store.dispatch("np_form/createTFReq")
                } else if (act == 'EDIT' && error_id.length == 0) {
                    this.empty_id = error_id
                    this.$store.dispatch("np_form/updateTFReq")
                }
            },
            submitTF(type) {
                let error_id = [];
                let act = this.type_act;
                let item = this.form_detail;
                let approvlevel = this.approve_level;
                let currentTF = this.selected_tf

                let snac = { isOpen: true, color: "error", msg: "[Error]" };

                if (!this.form_transfer_date || Object.keys(this.form_cabang).length == 0 || Object.keys(this.form_divisi).length == 0) {
                    snac.msg = "[Error] Masih terdapat form yang kosong";
                    this.$store.commit("p_data/update_snackbar", snac, { root: true });
                    return;
                }

                if (item.length <= 0) {
                    snac.msg = "[Error] Detail Item masih kosong";
                    this.$store.commit("p_data/update_snackbar", snac, { root: true });
                    return;
                }

                item.forEach(element => {
                    if (parseInt(element.PurchaseRequestFlagQtyRest) > parseInt(element.StockGudang)) {
                        error_id.push(element.PurchaseRequestFlagID);
                    }
                });

                if (error_id.length > 0) {
                    this.empty_id = error_id;
                    return;
                }

                if (type == 'V' && approvlevel.M_UserM_ApproveLevelID == '1') {
                    if (currentTF.T_GoodsTransferVerifiedBy != '0') {
                        snac.msg = "[INFO] Request sudah diverifikasi";
                        snac.color = 'warning';
                        this.$store.commit("p_data/update_snackbar", snac, { root: true });
                        return;
                    }

                    this.is_verif = 'Verified';
                    this.act_verif = type
                    if (act == 'EDIT' && error_id.length == 0) {
                        this.empty_id = error_id;
                        this.$store.dispatch("np_form/updateTFReq");
                    }
                } else if (type == 'A' && approvlevel.M_UserM_ApproveLevelID == '2') {
                    if (currentTF.T_GoodsTransferApprovedBy != '0') {
                        snac.msg = "[INFO] Request sudah diapprove";
                        snac.color = 'warning';
                        this.$store.commit("p_data/update_snackbar", snac, { root: true });
                        return;
                    }

                    this.is_verif = 'Approved';
                    if (act == 'EDIT' && error_id.length == 0) {
                        this.empty_id = error_id;
                        this.$store.dispatch("np_form/updateTFReq");
                    }
                }
            }
        },
    }
</script>