<template>
    <v-layout row justify-center>
        <v-dialog v-model="dialogUnit" persistent max-width="25%">
            <v-card>
                <v-card-title class="title grey lighten-2" primary-title>
                    Ganti Satuan {{ selectedItem.itemDesc ? selectedItem.itemDesc : "" }}
                </v-card-title>
                <v-card-text>
                    <v-layout row>
                        <v-flex xs12>
                            <v-select :loading="loadingUnit" v-model="selectedUnit" return-object :items="unitOptions"
                                label="Pilih Satuan" item-text="unitName"></v-select>
                        </v-flex>
                    </v-layout>
                </v-card-text>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="error" flat @click="dialogUnit = false">
                        Tutup
                    </v-btn>
                    <v-btn color="primary" flat @click="saveUnit()">Ganti</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>

        <v-dialog v-model="dialogRequest" persistent max-width="75%">
            <v-card>
                <v-card-title class="headline grey lighten-2" primary-title>
                    FORM STOCK REQUEST
                </v-card-title>
                <v-card-text class="pt-0 pb-0">
                    <v-layout row>
                        <v-flex pa-2 xs6>
                            <v-menu v-model="menuDateUse" :close-on-content-click="false" transition="scale-transition"
                                :nudge-right="40" lazy :disabled="act == 'preview'" offset-y full-width
                                max-width="290px" min-width="290px">
                                <template v-slot:activator="{ on }">
                                    <v-text-field :value="dateUseFormatted" label="Tanggal Permintaan" readonly
                                        v-on="on" @blur="dDateUse = deFormatedDate(dateUseFormatted)"></v-text-field>
                                </template>
                                <v-date-picker no-title v-model="xDateUse" @input="menuDateUse = false"></v-date-picker>
                            </v-menu>
                        </v-flex>
                        <v-flex pa-2 xs6>
                            <v-autocomplete v-model="xRegional" label="Regional*" menu-icon="mdi-chevron-down"
                                :items="regionalOptions" item-text="S_RegionalName" :disabled="act == 'preview'"
                                item-value="S_RegionalID" return-object readonly :error="errors.regional"
                                :error-messages="errors.regional ? 'Regional harus diisi' : ''"></v-autocomplete>
                        </v-flex>
                        <v-flex pa-2 xs6>
                            <v-autocomplete v-model="xBranch" :label="user.M_BranchID != '0' ? 'Cabang*' : 'Cabang'"
                                menu-icon="mdi-chevron-down" :items="branchOptions" item-text="M_BranchName"
                                item-value="M_BranchCode" placeholder="Pilih Cabang" :disabled="act == 'preview'"
                                return-object :error="errors.branch"
                                :error-messages="errors.branch ? 'Cabang harus diisi' : ''"></v-autocomplete>
                        </v-flex>
                        <v-flex pa-2 xs6>
                            <v-select v-model="selectedItemCategory" label="Kategori Item*" :items="itemCategoryOptions"
                                item-text="itemCategoryName" item-value="itemCategoryID" return-object
                                menu-icon="mdi-chevron-down" hide-details :error="errors.itemCategory"
                                :error-messages="errors.itemCategory ? 'Kategori Item harus dipilih' : ''"></v-select>

                        </v-flex>
                    </v-layout>
                    <v-layout row>
                        <v-flex pa-2 pl-0 xs12>
                            <v-text-field v-model="xDescription" label="Keterangan*" :disabled="act == 'preview'"
                                :error="errors.description" required
                                :error-messages="errors.description ? 'Keterangan harus diisi' : ''"></v-text-field>
                        </v-flex>
                    </v-layout>
                    <v-layout row>
                        <v-flex pa-2 pl-0 xs12>
                            <!-- <v-btn v-if="dialogItem == false && act != 'preview'" color="primary" @click="dialogItem = true">Pilih Item</v-btn> -->
                            <v-btn v-if="dialogItem == false && act != 'preview'" color="primary"
                                @click="validateAndOpenItemDialog">Pilih
                                Item</v-btn>
                            <v-btn v-if="dialogItem == true && act != 'preview'" color="primary"
                                @click="dialogItem = false">Tutup Pilih
                                Item</v-btn>
                        </v-flex>
                    </v-layout>
                    <v-layout v-if="errors.details" row>
                        <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                            <v-alert :value="true" type="error" dismissible v-html="msgErrDetails">
                            </v-alert>
                        </v-flex>
                    </v-layout>
                    <div v-if="dialogItem == true && act != 'preview'">
                        <v-divider></v-divider>
                        <v-card elevation="10" class=" mt-2">
                            <v-layout row>
                                <v-flex class="mt-2" pa-2 pb-0 xs3>
                                    <v-text-field v-model="searchItem" label="Cari..." placeholder="Ketikkan item"
                                        style="max-width: 250px" hide-details></v-text-field>
                                </v-flex>
                                <v-flex class="mt-2" pa-2 pb-0 xs3>
                                    <v-autocomplete v-model="selectedDivision" :items="divisionOptions" label="Divisi"
                                        return-object menu-icon="mdi-chevron-down" item-text="DivisionName" hide-details
                                        item-value="DivisionID"></v-autocomplete>

                                </v-flex>
                                <v-flex class="mt-2" pa-2 pb-0 xs3>
                                    <v-autocomplete v-model="selectedItemGroup" :items="itemGroupOptions" hide-details
                                        label="Grup" return-object menu-icon="mdi-chevron-down"
                                        item-text="Nat_GroupName" item-value="Nat_GroupID"></v-autocomplete>

                                </v-flex>
                                <v-flex class="mt-2" pa-2 pb-0 xs3>
                                    <v-autocomplete v-model="selectedItemSubGroup" :items="itemSubGroupOptions"
                                        return-object hide-details label="Sub Grup" menu-icon="mdi-chevron-down"
                                        item-text="Nat_SubGroupName" item-value="Nat_SubGroupID"></v-autocomplete>

                                </v-flex>
                                <v-flex class="mt-2" pa-2 pb-0 xs2>
                                    <v-btn dark color="success" style="min-width: 40px; height: 40px; margin: 0"
                                        @click="itemSearch()">
                                        <v-icon>search</v-icon>
                                    </v-btn>
                                </v-flex>
                            </v-layout>

                            <v-layout row>
                                <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                                    <v-data-table :headers="headers" :items="items" :loading="loadingItem" hide-actions
                                        class="elevation-1">
                                        <template slot="items" slot-scope="props">
                                            <td class="text-xs-left pa-2"
                                                v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                                @click="selectMe(props.item)">
                                                <div style="display: flex;flex-direction: column; align-items: center;">
                                                    {{ props.item.itemCode }}
                                                    <v-chip small style="border-radius: 5px; flex-grow: 0">
                                                        {{ props.item.itemDesc }}
                                                    </v-chip>
                                                </div>
                                            </td>
                                            <td class="text-xs-center pa-2"
                                                v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                                @click="selectMe(props.item)">
                                                {{ props.item.remaining_stock }}
                                            </td>
                                            <td class="text-xs-center pa-2"
                                                v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                                @click="selectMe(props.item)">
                                                {{ props.item.unitName }}
                                            </td>
                                            <td class="text-xs-center pa-2"
                                                v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                                @click="selectMe(props.item)">
                                                <v-btn v-if="checkSelected(props.item) == false"
                                                    style="min-width: 35px; height: 35px; margin: 0" small
                                                    color="success" @click="addItem(props.item)"><v-icon
                                                        small>check</v-icon></v-btn>

                                                <v-btn style="min-width: 35px; height: 35px; margin: 0;" small
                                                    color="info" @click="get_riwayat(props.item.itemId)">
                                                    <v-icon small>history</v-icon>
                                                </v-btn>
                                            </td>
                                        </template>
                                    </v-data-table>
                                </v-flex>
                            </v-layout>
                            <v-divider></v-divider>
                            <v-layout row>
                                <v-flex xs6>
                                    <v-pagination style="margin-top: 10px; margin-bottom: 10px"
                                        v-model="itemCurrentPage" :length="itemTotalPage"
                                        :total-visible="7"></v-pagination>
                                </v-flex>
                                <v-flex class="pt-2 text-xs-right" xs6>
                                    <v-btn color="primary" @click="dialogItem = false">Tutup Pilih Item</v-btn>
                                </v-flex>
                            </v-layout>
                        </v-card>
                        <v-divider></v-divider>
                    </div>
                    <v-card elevation="0" flat class=" mt-2">
                        <v-layout row style="max-height: 600px; overflow: auto">
                            <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                                <v-data-table :headers="headersItems" :items="selectedItems" hide-actions
                                    :loading="loadingDetailRequest" class="elevation-1">
                                    <template slot="items" slot-scope="props">
                                        <td class="text-xs-left pa-2"
                                            v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                            @click="selectMe(props.item)">
                                            <div style="
                              display: flex;
                              flex-direction: column;
                              align-items: center;
                            ">
                                                {{ props.item.itemCode }}
                                                <v-chip small style="border-radius: 5px; flex-grow: 0">
                                                    {{ props.item.itemDesc }}
                                                </v-chip>
                                            </div>
                                        </td>
                                        <td class="text-xs-center pa-2"
                                            v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                            @click="selectMe(props.item)">
                                            <v-btn depressed v-if="act != 'preview'" small color="primary"
                                                @click="openDialogUnit(props.item)">{{ props.item.unitName }}</v-btn>
                                            <span v-else>{{ props.item.unitName }}</span>
                                        </td>
                                        <td class="text-xs-center pa-2"
                                            v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                            @click="selectMe(props.item)">
                                            <v-text-field v-if="act != 'preview'" v-model="props.item.qty"
                                                @change="updateQuantity(props.item)"></v-text-field>
                                            <span v-else>{{ props.item.qty }}</span>

                                        </td>
                                        <td class="text-xs-center pa-2"
                                            v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                            @click="selectMe(props.item)">
                                            <v-text-field prefix="Rp" v-if="props.item.isEditingPrice == 'Y'"
                                                v-model="props.item.price" outlined @blur="updatePrice(props.item)"
                                                @click.stop></v-text-field>
                                            <v-text-field prefix="Rp" v-else :value="oneMoney(props.item.price)"
                                                outlined readonly @click.stop="changePrice(props.item)"></v-text-field>
                                        </td>
                                        <td class="text-xs-right pa-2"
                                            v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                            @click="selectMe(props.item)">
                                            <span>Rp {{ oneMoney(props.item.price * props.item.qty) }}</span>
                                        </td>
                                        <td class="text-xs-center pa-2"
                                            v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                            @click="selectMe(props.item)">
                                            <v-btn v-if="act != 'preview'"
                                                style="min-width: 35px; height: 35px; margin: 0" small color="error"
                                                dark @click="deleteItem(props.item)"><v-icon
                                                    small>close</v-icon></v-btn>

                                            <v-btn style="min-width: 35px; height: 35px; margin: 0;" small color="info"
                                                @click="get_riwayat(props.item.itemId)">
                                                <v-icon small>history</v-icon>
                                            </v-btn>

                                        </td>
                                    </template>
                                </v-data-table>
                            </v-flex>
                        </v-layout>
                    </v-card>
                </v-card-text>

                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn v-if="act === 'new'" color="info" :disabled="loadingSave" dark
                        @click="saveAndRequestPurchase()">Save &
                        Request Purchase</v-btn>
                    <v-btn v-if="act === 'edit'" color="info" :disabled="loadingSave" dark
                        @click="requestPending()">Request
                        Purchase</v-btn>
                    <v-btn color="error" flat @click="closeDialogRequest()">Tutup</v-btn>
                    <v-btn v-if="act === 'new'" color="primary" :disabled="loadingSave" dark
                        @click="savePurchaseRequest()">Simpan</v-btn>
                    <v-btn v-if="act === 'edit'" color="primary" :disabled="loadingSave" dark
                        @click="updatePurchaseRequest()">Simpan
                        Perubahan</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>

        <one-dialog-alert :status="dialogConfirmRequest"
            :msg="'Yakin mau melakukan Purchase Request? Tidak bisa diedit setelah melakukan Request'"
            @forget-dialog-alert="dialogConfirmRequest = false" @close-dialog-alert="confirmAndRequestPurchase()"
            confirmLabel="Yakin" cancelLabel="Batal"></one-dialog-alert>
    </v-layout>
</template>

<script>
module.exports = {
    name: "AddPurchaseRequestDialog",
    components: {
        "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue")
    },
    data() {
        return {
            errors: { regional: false, branch: false, description: false, details: false },
            msgErrDetails: "<p>Data item belum ada. Silahkan masukkan data item terlebih dahulu.</p>",
            itemUnitChange: {},
            dialogItem: false,
            regionalRules: [(v) => !!v || "Regional harus diisi"],
            branchRules: [(v) => !!v || "Cabang harus diisi"],
            descRules: [(v) => !!v || "Keterangan harus diisi"],
            validationForm: true,
            dialogConfirmRequest: false,
            headers: [
                {
                    text: "ITEM PERSEDIAAN",
                    align: "center",
                    sortable: false,
                    value: "itemName",
                    width: "15%",
                    class: "success lighten-3 white--text",
                },
                {
                    text: "SISA STOCK",
                    align: "center",
                    sortable: false,
                    value: "qty",
                    width: "10%",
                    class: "success lighten-3 white--text",
                },
                {
                    text: "SATUAN",
                    align: "center",
                    sortable: false,
                    value: "unitName",
                    width: "15%",
                    class: "success lighten-3 white--text",
                },
                {
                    text: "AKSI",
                    align: "center",
                    sortable: false,
                    value: "action",
                    width: "10%",
                    class: "success lighten-3 white--text",
                },
            ],
            headersItems: [
                {
                    text: "ITEM PERSEDIAAN",
                    align: "center",
                    sortable: false,
                    value: "itemName",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "SATUAN",
                    align: "center",
                    sortable: false,
                    value: "unitName",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "JUMLAH",
                    align: "center",
                    sortable: false,
                    value: "qty",
                    width: "5%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "HARGA",
                    align: "center",
                    sortable: false,
                    value: "price",
                    width: "12%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "TOTAL",
                    align: "center",
                    sortable: false,
                    value: "total",
                    width: "10%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "AKSI",
                    align: "center",
                    sortable: false,
                    value: "action",
                    width: "10%",
                    class: "blue lighten-3 white--text",
                },
            ]
        };
    },
    computed: {
        itemCategoryOptions() {
            return this.$store.state.requester.itemCategoryOptions;
        },
        selectedItemCategory: {
            get() {
                return this.$store.state.requester.selectedItemCategory;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedItemCategory", val);
            },
        },
        loadingDetailRequest() {
            return this.$store.state.requester.loadingDetailRequest;
        },
        loadingUnit() {
            return this.$store.state.requester.loadingUnit;
        },
        dialogUnit: {
            get() {
                return this.$store.state.requester.dialogUnit;
            },
            set(val) {
                this.$store.commit("requester/updateDialogUnit", val);
            },
        },
        selectedUnit: {
            get() {
                return this.$store.state.requester.selectedUnit;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedUnit", val);
            },
        },
        unitOptions: {
            get() {
                return this.$store.state.requester.unitOptions;
            },
            set(val) {
                this.$store.commit("requester/updateUnitOptions", val);
            },
        },
        dialogRequest: {
            get() {
                return this.$store.state.requester.dialogRequest;
            },
            set(val) {
                this.$store.commit("requester/updateDialogRequest", val);
            },
        },
        menuDateUse: {
            get() {
                return this.$store.state.requester.menuDateUse;
            },
            set(val) {
                this.$store.commit("requester/updateMenuDateUse", val);
            },
        },
        dateUseFormatted() {
            return this.formatDate(this.xDateUse);
        },
        dDateUse: {
            get() {
                return this.$store.state.requester.dDateUse;
            },
            set(val) {
                this.$store.commit("requester/updateDDateUse", val);
            },
        },
        xDateUse: {
            get() {
                return this.$store.state.requester.xDateUse;
            },
            set(val) {
                this.$store.commit("requester/updateXDateUse", val);
            },
        },
        xBranch: {
            get() {
                return this.$store.state.requester.xBranch;
            },
            set(val) {
                this.$store.commit("requester/updateXBranch", val);
            },
        },
        branchOptions() {
            return this.$store.state.requester.branchOptions;
        },
        regionalOptions() {
            return this.$store.state.requester.regionalOptions;
        },
        xRegional: {
            get() {
                return this.$store.state.requester.xRegional;
            },
            set(val) {
                this.$store.commit("requester/updateXRegional", val);
            },
        },
        xDescription: {
            get() {
                return this.$store.state.requester.xDescription;
            },
            set(val) {
                this.$store.commit("requester/updateXDescription", val);
            },
        },
        xPRID() {
            return this.$store.state.requester.xPRID;
        },
        act() {
            return this.$store.state.requester.act;
        },
        itemCurrentPage: {
            get() {
                return this.$store.state.requester.itemCurrentPage;
            },
            set(val) {
                this.$store.commit("requester/updateItemCurrentPage", val);
                this.$store.dispatch("requester/getItems", {
                    search: this.searchItem,
                    division: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : "",
                    itemGroup: this.selectedItemGroup.Nat_GroupID ? this.selectedItemGroup.Nat_GroupID : "",
                    itemSubGroup: this.selectedItemSubGroup.Nat_SubGroupID ? this.selectedItemSubGroup.Nat_SubGroupID : "",
                    itemCategory: this.selectedItemCategory.itemCategoryID ? this.selectedItemCategory.itemCategoryID : "",
                });
            },
        },
        itemTotalPage: {
            get() {
                return this.$store.state.requester.itemTotalPage;
            },
        },
        items: {
            get() {
                return this.$store.state.requester.items;
            },
            set(val) {
                this.$store.commit("requester/updateItems", val);
            }
        },
        selectedItem: {
            get() {
                return this.$store.state.requester.selectedItem;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedItem", val);
            }
        },
        searchItem: {
            get() {
                return this.$store.state.requester.searchItem;
            },
            set(val) {
                this.$store.commit("requester/updateSearchItem", val);
            }
        },
        loadingItem: {
            get() {
                return this.$store.state.requester.loadingItem;
            },
            set(val) {
                this.$store.commit("requester/updateLoadingItem", val);
            }
        },
        itemGroupOptions: {
            get() {
                return this.$store.state.requester.itemGroupOptions;
            },
            set(val) {
                this.$store.commit("requester/updateItemGroupOptions", val);
            }
        },
        selectedItemGroup: {
            get() {
                return this.$store.state.requester.selectedItemGroup;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedItemGroup", val);
                console.log("Selected Item Group", val);
                this.$store.commit("requester/updateItemSubGroupOptions", val.subGroups);
                this.$store.commit("requester/updateSelectedItemSubGroup", val.subGroups[0]);
            }
        },
        itemSubGroupOptions: {
            get() {
                return this.$store.state.requester.itemSubGroupOptions;
            },
            set(val) {
                this.$store.commit("requester/updateItemSubGroupOptions", val);
            }
        },
        selectedItemSubGroup: {
            get() {
                return this.$store.state.requester.selectedItemSubGroup;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedItemSubGroup", val);

            }
        },
        loadingItemSubGroup: {
            get() {
                return this.$store.state.requester.loadingItemSubGroup;
            },
            set(val) {
                this.$store.commit("requester/updateLoadingItemSubGroup", val);
            }
        },
        loadingItemGroup: {
            get() {
                return this.$store.state.requester.loadingItemGroup;
            },
            set(val) {
                this.$store.commit("requester/updateLoadingItemGroup", val);
            }
        },
        divisionOptions: {
            get() {
                return this.$store.state.requester.divisionOptions;
            },
            set(val) {
                this.$store.commit("requester/updateDivisionOptions", val);
            }
        },
        selectedDivision: {
            get() {
                return this.$store.state.requester.selectedDivision;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedDivision", val);
                this.$store.dispatch("requester/getItemGroupSubGroup");
            }
        },
        loadingSave: {
            get() {
                return this.$store.state.requester.loadingSave;
            },
            set(val) {
                this.$store.commit("requester/updateLoadingSave", val);
            }
        },
        selectedItem: {
            get() {
                return this.$store.state.requester.selectedItem;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedItem", val);
            }
        },
        selectedItems: {
            get() {
                return this.$store.state.requester.selectedItems;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedItems", val);
            }
        },
        dialog_riwayat: {
            get() {
                return this.$store.state.requester.dialog_riwayat
            },
            set(val) {
                this.$store.commit("requester/update_dialog_riwayat", val)
            }
        },
        user: {
            get() {
                return this.$store.state.requester.user
            },
            set(val) {
                this.$store.commit("requester/updateUser", val)
            }
        }
    },
    methods: {
        changePrice(item) {
            let items = this.selectedItems;
            let index = items.findIndex(itemloop => itemloop.itemId == item.itemId);
            items[index].isEditingPrice = 'Y';
            this.$store.commit("requester/updateSelectedItems", items);
        },
        updatePrice(item) {
            let items = this.selectedItems;
            let index = items.findIndex(itemloop => itemloop.itemId == item.itemId);
            items[index].price = item.price;
            items[index].total = item.price * item.qty;
            items[index].isEditingPrice = 'N';
            this.$store.commit("requester/updateSelectedItems", items);
        },
        roundToThreeSignificantDigits(num) {
            if (num === 0) return 0;

            // Hitung jumlah digit
            const absNum = Math.abs(num);
            const magnitude = Math.floor(Math.log10(absNum)) + 1;

            // Jika kurang dari 3 digit, tidak perlu dibulatkan
            if (magnitude <= 3) return num;

            // Hitung faktor pembulatan
            const factor = Math.pow(10, magnitude - 3);

            // Bulatkan
            return Math.round(num / factor) * factor;
        },
        oneMoney(value) {
            //return one_money(value);
            let splitValue = value.toString().split(".");
            if (splitValue.length > 1) {
                let val = splitValue[0]
                return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".") + "," + this.roundToThreeSignificantDigits(splitValue[1]);
            } else {
                return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
            }
        },

        requestPending() {
            console.log("Selected Item Category", this.selectedItemCategory);
            if (this.validateForm()) {
                this.$store.commit("requester/updateLoadingSave", true);
                this.$store.dispatch("requester/updatePurchaseRequest", {
                    act: "pending",
                    PRID: this.$store.state.requester.selectedMainTable.prId,
                    PRNumber: this.$store.state.requester.selectedMainTable.prNumber,
                    PRDateUse: this.xDateUse,
                    PRRegional: this.xRegional.S_RegionalID,
                    PRItemCategory: this.selectedItemCategory.itemCategoryID,
                    PRBranch: typeof this.xBranch === "object" && this.xBranch !== null && "M_BranchCode" in this.xBranch ? this.xBranch.M_BranchCode : "",
                    PRDescription: this.xDescription,
                    items: this.selectedItems
                });
            }
        },
        updatePurchaseRequest() {
            if (this.validateForm()) {
                this.$store.commit("requester/updateLoadingSave", true);
                this.$store.dispatch("requester/updatePurchaseRequest", {
                    act: "edit",
                    PRID: this.$store.state.requester.selectedMainTable.prId,
                    PRNumber: this.$store.state.requester.selectedMainTable.prNumber,
                    PRDateUse: this.xDateUse,
                    PRRegional: this.xRegional.S_RegionalID,
                    PRBranch: typeof this.xBranch === "object" && this.xBranch !== null && "M_BranchCode" in this.xBranch ? this.xBranch.M_BranchCode : "",
                    PRItemCategory: this.selectedItemCategory.itemCategoryID,
                    PRDescription: this.xDescription,
                    items: this.selectedItems
                });
                this.dialogItem = false;
                this.dialogItem = false;
                this.$store.commit("requester/updateSelectedItemCategory", {});
                this.$store.commit("requester/updateSelectedItems", []);
            }
        },
        checkSelected(item) {
            let selectedItems = this.selectedItems;
            let rtn = false
            if (selectedItems.length == 0) {
                rtn = false;
            }
            selectedItems.forEach(itemloop => {
                if (itemloop.itemId == item.itemId) {
                    console.log(item.itemId, "itemloop.itemId == item.itemId");
                    rtn = true;
                }
            });
            return rtn;
        },
        savePurchaseRequest() {
            if (this.validateForm()) {
                this.$store.commit("requester/updateLoadingSave", true);
                this.$store.dispatch("requester/savePurchaseRequest", {
                    PRDateUse: this.xDateUse,
                    PRRegional: this.xRegional.S_RegionalID,
                    PRBranch: typeof this.xBranch === "object" && this.xBranch !== null && "M_BranchCode" in this.xBranch ? this.xBranch.M_BranchCode : "",
                    PRItemCategory: this.selectedItemCategory.itemCategoryID,
                    PRDescription: this.xDescription,
                    items: this.selectedItems
                });
                this.dialogItem = false;
                this.$store.commit("requester/updateSelectedItemCategory", {});
                this.$store.commit("requester/updateSelectedItems", []);
            }
        },
        saveAndRequestPurchase() {
            if (this.validateForm()) {
                // Show confirmation dialog instead of proceeding directly
                this.dialogConfirmRequest = true;
            } else {
                this.errors.details = true;
                this.msgErrDetails = this.selectedItems.length == 0 ?
                    "<p>Data item belum ada. Silahkan masukkan data item terlebih dahulu.</p>" :
                    this.msgErrDetails;
            }
        },
        confirmAndRequestPurchase() {
            // Close the dialog
            this.dialogConfirmRequest = false;

            // Now proceed with the actual save and request
            this.$store.commit("requester/updateLoadingSave", true);
            this.$store.dispatch("requester/saveAndDoPurchaseRequest", {
                PRDateUse: this.xDateUse,
                PRRegional: this.xRegional.S_RegionalID,
                PRBranch: typeof this.xBranch === "object" && this.xBranch !== null && "M_BranchCode" in this.xBranch ? this.xBranch.M_BranchCode : "",
                PRItemCategory: this.selectedItemCategory.itemCategoryID,
                PRDescription: this.xDescription,
                items: this.selectedItems
            });
        },

        validateAndOpenItemDialog() {
            if (!this.selectedItemCategory || !this.selectedItemCategory.itemCategoryID) {
                this.$store.commit("requester/updateSnackbar", {
                    state: true,
                    type: "error",
                    message: "Pilih 'Kategori Item' terlebih dahulu"
                });
            } else {
                this.dialogItem = true;
                this.$store.dispatch("requester/getItems", {
                    search: "",
                    division: "",
                    itemCategory: this.selectedItemCategory.itemCategoryID ? this.selectedItemCategory.itemCategoryID : "",
                    itemGroup: "",
                    itemSubGroup: ""
                });
            }
        },

        itemSearch() {
            this.$store.dispatch("requester/getItems", {
                search: this.searchItem,
                division: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : "",
                itemGroup: this.selectedItemGroup.Nat_GroupID ? this.selectedItemGroup.Nat_GroupID : "",
                itemSubGroup: this.selectedItemSubGroup.Nat_SubGroupID ? this.selectedItemSubGroup.Nat_SubGroupID : "",
                itemCategory: this.selectedItemCategory.itemCategoryID ? this.selectedItemCategory.itemCategoryID : ""
            });
        },
        addItem(item) {
            let selectedItems = this.selectedItems;
            let index = selectedItems.findIndex(itemloop => itemloop.itemId == item.itemId);
            if (index == -1) {
                selectedItems.push(item);
            }

            this.$store.commit("requester/updateSelectedItems", selectedItems);
        },
        deleteItem(item) {
            let selectedItems = this.selectedItems;
            let index = selectedItems.findIndex(itemloop => itemloop.itemId == item.itemId);
            if (index != -1) {
                selectedItems.splice(index, 1);
            }
            this.$store.commit("requester/updateSelectedItems", selectedItems);
        },

        updateQuantity(item) {
            let items = this.selectedItems;
            let index = items.findIndex(itemloop => itemloop.itemId == item.itemId);
            items[index].qty = item.qty;
            this.$store.commit("requester/updateSelectedItems", items);
        },
        saveUnit() {
            let items = this.selectedItems;
            let index = items.findIndex(itemloop => itemloop.itemId == this.itemUnitChange.itemId);
            let selectedUnit = this.selectedUnit;
            items[index].unitCode = selectedUnit.unitCode;
            items[index].unitId = selectedUnit.unitId;
            items[index].unitName = selectedUnit.unitName;
            this.$store.commit("requester/updateSelectedItems", items);
            this.$store.commit("requester/updateDialogUnit", false);
        },
        openDialogUnit(item) {
            this.itemUnitChange = item
            this.$store.dispatch("requester/getUnitByItemId", {
                itemId: item.itemId,
                selectedUnit: { unitId: item.unitId, unitCode: item.unitCode, unitName: item.unitName }
            });
        },
        isSelected(p) {
            return (
                p.itemId ==
                this.$store.state.requester.selectedItem
                    .itemId
            );
        },
        selectMe(spr) {
            this.$store.commit("requester/updateSelectedItem", spr);
        },
        formatDate(date) {
            if (!date) return null;

            const [year, month, day] = date.split("-");
            return `${day}-${month}-${year}`;
        },
        deFormatedDate(date) {
            if (!date) return null;

            const [day, month, year] = date.split("-");
            return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
        },
        closeDialogRequest() {
            this.$store.commit(
                "requester/updateXDateUse",
                moment(new Date()).format("YYYY-MM-DD")
            );
            this.$store.commit("requester/updateXBranch", "");
            this.$store.commit("requester/updateXRegional", "");
            this.$store.commit("requester/updateXDescription", "");
            this.$store.commit("requester/updateDialogRequest", false);
            this.$store.commit("requester/updateSelectedItems", []);
            this.$store.commit("requester/updateSelectedItemCategory", {});
            this.$store.commit("requester/updateSnackbar", {
                state: false,
                type: "",
                message: ""
            });
            this.dialogItem = false;
            this.$store.commit("requester/updateItems", []);
        },
        validateForm() {
            this.errors.regional = _.isEmpty(this.xRegional) ? true : false;
            if (this.user.M_BranchID == '0') {
                this.errors.branch = false
            } else if (this.user.M_BranchID != '0') {
                this.errors.branch = _.isEmpty(this.xBranch) ? true : false;
            }
            this.errors.description = this.xDescription == "" ? true : false;
            this.errors.details = this.selectedItems.length == 0 ? true : false;
            this.errors.itemCategory = this.selectedItemCategory == "" ? true : false;
            this.msgErrDetails = this.selectedItems.length == 0 ? "<p>Data item belum ada. Silahkan masukkan data item terlebih dahulu.</p>" : "";

            let details = this.selectedItems
            details.forEach(item => {
                if (parseInt(item.qty) == 0 || item.qty == "") {
                    this.errors.details = true;
                    if (this.msgErrDetails == "") {
                        this.msgErrDetails = "<p>Qty " + item.itemDesc + " tidak boleh 0</p>";
                    } else {
                        this.msgErrDetails += "<p>Qty " + item.itemDesc + " tidak boleh 0</p>";
                    }
                }
            });
            if (this.errors.regional == false && this.errors.branch == false && this.errors.description == false && this.errors.details == false && this.errors.itemCategory == false) {
                return true;
            } else {
                return false;
            }
        },

        get_riwayat(id) {
            this.$store.dispatch("requester/getRiwayatItem", { itemid: id })
            this.dialog_riwayat = true
        }
    },
    watch: {
        selectedItemCategory: {
            handler(newVal) {
                if (newVal && newVal.itemCategoryID) {
                    if (this.dialogItem) {
                        this.$store.dispatch("requester/getItems", {
                            search: "",
                            division: "",
                            itemCategory: newVal.itemCategoryID,
                            itemGroup: "",
                            itemSubGroup: ""
                        });
                    }
                }
            },
            deep: true
        }
    },
};
</script>
