<template>
    <v-dialog v-model="dialogDetail" persistent max-width="500px">
        <v-card>
            <v-card-title class="headline grey lighten-2" primary-title>
                FORM REQUEST DETAIL
            </v-card-title>

            <v-card-text>
                <v-form ref="form_detail" v-model="form_detail_valid" lazy-validation>
                    <v-layout column>
                        <v-flex>
                            <v-autocomplete
                                v-model="selected_category" return-object label="Kategori" 
                                :items="category_direct" item-text="PurchaseDirectCategoryName" 
                                item-key="PurchaseDirectCategoryCode" :rules="autocomp_rules" 
                                @input="resetCalc()"
                            ></v-autocomplete>
                        </v-flex>
                        <v-flex>
                            <v-text-field
                                v-model="xDescriptionDetail" required 
                                :rules="freetext_rules" label="Deskripsi" 
                                :disabled="isCategorySelected()" 
                            ></v-text-field>
                        </v-flex>
                        <v-flex>
                            <v-text-field
                                v-model="formatted_amount" required
                                :min="1" :rules="freetext_rules" label="Jumlah"
                                :disabled="isCategorySelected()" @blur="viewBlurAmount"
                                :readonly="this.selected_category.PurchaseDirectCategoryName == 'BBM'"
                            ></v-text-field>
                        </v-flex>
                        <v-flex>
                            <v-autocomplete
                                label="Unit Item" v-model="selected_item_unit"
                                :items="item_units" item-text="ItemUnitName" 
                                :rules="autocomp_rules" return-object
                                :disabled="isCategorySelected()" 
                            ></v-autocomplete>
                        </v-flex>
                        <v-flex>
                            <v-text-field 
                                prefix="Rp." required label="Harga"
                                v-model="formatted_estimate_price"
                                :disabled="isCategorySelected()"
                                @blur="viewBlurMoney" @focus="viewFokusNumber"
                            ></v-text-field>
                        </v-flex>
                        <v-flex>
                            <v-text-field
                                prefix="Rp." v-model="formatted_total_price" 
                                :disabled="isCategorySelected()" label="Total Harga"
                                :readonly="this.selected_category.PurchaseDirectCategoryName != 'BBM'"
                                @blur="viewBlurMoney" @focus="viewFokusNumber"
                            ></v-text-field>
                        </v-flex>
                    </v-layout>
                </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="error" flat @click="closeForm()">Tutup</v-btn>
                <v-btn v-if="this.act === 'new'" color="primary" dark @click="simpanForm()">Simpan</v-btn>
                <v-btn v-else color="primary" dark @click="updateForm()">Simpan</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script>
module.exports = {
    data() {
        return {
            form_detail_valid: true,
            amount_input: 0,
            price_input: 0,
            total_input: 0,
            freetext_rules: [v => !!v || "Tidak boleh kosong"],
            autocomp_rules: [v => (v && Object.keys(v).length > 0) || 'Tidak boleh kosong'],
            amount_rules: [v => (v && v >= 0) || "Jumlah tidak sesuai"]
        }
    },
    computed: {
        dialogDetail: {
            get() {
                return this.$store.state.requester.dialogDetail
            },
            set(val) {
                this.$store.commit("requester/updateDialogDetail", val)
            }
        },
        selected_category: {
            get() {
                return this.$store.state.requester.selected_category;
            },
            set(val) {
                this.$store.commit("requester/update_selected_category", val)
            }
        },
        xDescriptionDetail: {
            get() {
                return this.$store.state.requester.xDescriptionDetail;
            },
            set(val) {
                this.$store.commit("requester/updateXDescriptionDetail", val);
            },
        },
        xAmountRequest: {
            get() {
                return this.$store.state.requester.xAmountRequest;
            },
            set(val) {
                this.$store.commit("requester/updateXAmountRequest", Number(val));
            },
        },
        formatted_amount: {
            get() {
                return this.amount_input;
            },
            set(value) {
                let raw = value.replace(/\./g, '').replace(',', '.');
                this.xAmountRequest = parseFloat(raw) || 0;
            }
        },
        selected_item_unit: {
            get() {
                return this.$store.state.requester.selected_item_unit;
            },
            set(val) {
                this.$store.commit("requester/updateSelectedItemUnit", val);
            },
        },
        xEstimationPrice: {
            get() {
                return this.$store.state.requester.xEstimationPrice;
            },
            set(val) {
                this.$store.commit("requester/updateXEstimationPrice", val);
            },
        },
        formatted_estimate_price: {
            get() {
                return this.price_input;
            },
            set(value) {
                let raw = value.replace(/\./g, '').replace(',', '.');
                this.xEstimationPrice = parseFloat(raw) || 0;
            }
        },
        total_price: {
            get() {
                return this.$store.state.requester.total_price;
            },
            set(val) {
                this.$store.commit("requester/updateTotalPrice", val)
            }
        },
        formatted_total_price: {
            get() {
                return this.total_input;
            },
            set(value) {
                // Hilangkan titik dan koma, ubah jadi number
                let raw = value.replace(/\./g, '').replace(',', '.');
                this.total_price = parseFloat(raw) || 0;
            }
        },
        category_direct() {
            return this.$store.state.requester.category_direct;
        },
        item_units() {
            return this.$store.state.requester.item_units;
        },
        selectedMainTable() {
            return this.$store.state.requester.selectedMainTable;
        },
        selectedDetailTable() {
            return this.$store.state.requester.selectedDetailTable;
        },
        act() {
            return this.$store.state.requester.act;
        },
    },
    methods: {
        roundToThreeSignificantDigits(digit) {
            // if (num === 0) return 0;
            
            // const absNum = Math.abs(num);
            // const magnitude = Math.floor(Math.log10(absNum)) + 1;
            // if (magnitude <= 3) return num;
            // const factor = Math.pow(10, magnitude - 3);
            // return Math.round(num / factor) * factor;

            const num = parseInt(digit, 10)
            if (isNaN(num) || num <= 0) {
                return 0;
            }

            const scale = 10 ** digit.length;
            const decimal = num / scale
            return Math.round(decimal * 100);
        },
        oneMoney(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, ".");
            }
        },
        viewBlurMoney() {
            let category = this.selected_category
            if (category.PurchaseDirectCategoryName == 'BBM') {
                let total = this.total_price
                if (total % 1 === 0) {
                    total = this.oneMoney(total) + ",00"
                    this.total_input = total
                } else {
                    this.total_input = this.oneMoney(this.total_price)
                }

                let price = this.xEstimationPrice
                if (price % 1 === 0) {
                    price = this.oneMoney(price) + ",00"
                    this.price_input = price
                } else {
                    this.price_input = this.oneMoney(this.xEstimationPrice)
                }

            } else {
                this.price_input = this.oneMoney(this.xEstimationPrice)
                this.total_input = this.oneMoney(this.total_price)
            }
        },
        viewFokusNumber() {
            let price = this.xEstimationPrice ?? 0;
            let total = this.total_price ?? 0;

            this.price_input = price.toString().replace('.', ',');
            this.total_input = total.toString().replace('.', ',');
        },
        viewBlurAmount() {
            let category = this.selected_category
            if (category.PurchaseDirectCategoryName == 'BBM') {
                let amount = this.xAmountRequest
                if (amount % 1 === 0) {
                    this.amount_input = amount
                } else {
                    this.amount_input = this.oneMoney(amount)
                }
            } else {
                this.amount_input = this.xAmountRequest
            }
        },
        calculateTotalPrice() {
            let category = this.selected_category
            let jumlah = this.xAmountRequest
            let total = this.total_price
            let price = this.xEstimationPrice

            if (category.PurchaseDirectCategoryName === 'BBM') {
                if (total > 0 && price > 0) {
                    let a = total / price
                    this.xAmountRequest = a
                    this.amount_input = this.oneMoney(a)
                    return
                }
                this.xAmountRequest = 0
                this.amount_input = this.oneMoney(0)
                
            } else {
                if (jumlah > 0 && price > 0) {
                    let a = jumlah * price
                    this.total_price = a
                    return
                }
                this.total_price = 0
            }
        },
        isCategorySelected() {
            let category = this.selected_category
            if (Object.keys(category).length > 0) {
                return false
            }
            return true
        },
        resetCalc() {
            this.xDescriptionDetail = ''
            this.xAmountRequest = 0
            this.amount_input = 0
            this.selected_item_unit = {}

            this.xEstimationPrice = 0
            this.price_input = 0
            this.total_price = 0
            this.total_input = 0

            this.$refs.form_detail.resetValidation()
        },
        resetForm() {
            this.selected_category = {}
            this.selected_item_unit = {}
            this.xDescriptionDetail = ''
            this.xAmountRequest = 0
            this.xEstimationPrice = 0
            this.total_price = 0
            
            this.amount_input = 0
            this.price_input = 0
            this.total_input = 0

            this.$refs.form_detail.resetValidation()
        },
        closeForm() {
            this.resetForm()
            this.dialogDetail = false
        },
        simpanForm() {
            if (this.$refs.form_detail.validate()) {
                this.$store.dispatch("requester/saveDetail", {
                    PRID: this.selectedMainTable.PurchaseRequestDirectID,
                    PRDDescriptionDetail: this.xDescriptionDetail,
                    PRDAmountRequest: this.xAmountRequest,
                    PRDEstimationPrice: this.xEstimationPrice,
                    PRDItemUnitID: this.selected_item_unit.ItemUnitID,
                    PRDCategoryID: this.selected_category.PurchaseDirectCategoryID,
                    PRDTotalPrice: this.total_price
                });
            }
        },
        updateForm() {
            if (this.$refs.form_detail.validate()) {
                this.$store.dispatch("requester/updateDetail", {
                    PRID: this.selectedMainTable.PurchaseRequestDirectID,
                    PRDID: this.selectedDetailTable.PurchaseRequestDirectDetailID,
                    PRDDescriptionDetail: this.xDescriptionDetail,
                    PRDAmountRequest: this.xAmountRequest,
                    PRDEstimationPrice: this.xEstimationPrice,
                    PRDItemUnitID: this.selected_item_unit.ItemUnitID,
                    PRDCategoryID: this.selected_category.PurchaseDirectCategoryID,
                    PRDTotalPrice: this.total_price
                });
            }
        }
    },
    watch: {
        dialogDetail(val) {
            if (val) {
                this.$nextTick(() => {
                    this.$refs.form_detail?.resetValidation()
                    if (this.act == 'new') {
                        this.resetForm()
                    } else {
                        this.price_input = this.oneMoney(this.xEstimationPrice)
                        this.total_input = this.oneMoney(this.total_price)
                        this.amount_input = this.oneMoney(this.xAmountRequest)
                    }
                })
            }
        },
        xAmountRequest(val, old) {
            this.calculateTotalPrice()
        },
        xEstimationPrice(val, old) {
            this.calculateTotalPrice()
        },
        total_price(val, old) {
            this.calculateTotalPrice()
        }
    }
}
</script>