<template>
    <v-dialog v-model="dialogDetail" persistent max-width="500px">
        <v-card>
            <v-card-title class="headline grey lighten-2" primary-title>
                FORM EDIT REQUEST DETAIL
            </v-card-title>
            <v-card-text>
                <v-form ref="formDetail" v-model="validationDetail" lazy-validation>
                    <v-text-field
                        v-model="formattedAmount" label="Jumlah" outline
                        :min="0" required class="mb-2" hide-details 
                        :readonly="selectedDetailTable.PurchaseDirectCategoryName == 'BBM'"
                        @blur="onBlurInput()" @focus="onFokusInput()"
                    ></v-text-field>
                    <v-text-field
                        v-model="formattedPrice" label="Harga Satuan" class="mb-2"
                        prefix="Rp. " required hide-details outline 
                        @blur="onBlurInput()" @focus="onFokusInput()"
                    ></v-text-field>
                    <v-text-field
                        v-model="formattedTotal" label="Harga Total" class="mb-2"
                        prefix="Rp. " required hide-details outline
                        :readonly="selectedDetailTable.PurchaseDirectCategoryName != 'BBM'"
                        @blur="onBlurInput()" @focus="onFokusInput()"
                    ></v-text-field>
                </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="error" flat @click="closeDialogDetail()">Tutup</v-btn>
                <v-btn color="primary" dark @click="updateDialogDetail()">Simpan</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script>
module.exports = {
    data() {
        return {
            validationDetail: false,
            amount_input: 0,
            price_input: 0,
            total_input: 0,
            amountRules: [v => !!v || "Tidak boleh kosong"]
        }
    },
    computed: {
        dialogDetail: {
            get() {
                return this.$store.state.manager.dialogDetail;
            },
            set(val) {
                this.$store.commit("manager/updateDialogDetail", val);
            },
        },
        formattedAmount: {
            get() {
                return this.amount_input
            },
            set(val) {
                let raw = val.replace(/\./g, '').replace(',', '.');
                this.xAmount = parseFloat(raw)
            }
        },
        formattedPrice: {
            get() {
                return this.price_input
            },
            set(val) {
                let raw = val.replace(/\./g, '').replace(',', '.');
                this.xPrice = parseFloat(raw)
            }
        },
        formattedTotal: {
            get() {
                return this.total_input
            },
            set(val) {
                let raw = val.replace(/\./g, '').replace(',', '.');
                this.xTotal = parseFloat(raw)
            }
        },
        selectedDetailTable: {
            get() {
                return this.$store.state.manager.selectedDetailTable
            },
            set(val) {
                this.$store.commit("manager/updateSelectedDetailTable", val)
            }
        },
        xAmount: {
            get() {
                return this.$store.state.manager.xAmount;
            },
            set(val) {
                this.$store.commit("manager/updateXAmount", val);
            },
        },
        xPrice: {
            get() {
                return this.$store.state.manager.xPrice;
            },
            set(val) {
                this.$store.commit("manager/updatexPrice", val);
            },
        },
        xTotal: {
            get() {
                return this.$store.state.manager.xTotal;
            },
            set(val) {
                this.$store.commit("manager/updatexTotal", val);
            },
        }
    },
    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 '00';
            }

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

                let price = this.xPrice;
                if (price % 1 === 0) {
                    price = this.oneMoney(price) + ",000";
                    this.price_input = price
                } else {
                    this.price_input = this.oneMoney(price);
                }

                let amount = this.xAmount
                if (amount % 1 === 0) {
                    this.amount_input = amount
                } else {
                    this.amount_input = this.oneMoney(amount)
                }
            } else {
                this.price_input = this.oneMoney(this.xPrice);
                this.total_input = this.oneMoney(this.xTotal);
            }
        },
        onFokusInput() {
            let amount = this.xAmount ?? 0;
            let price = this.xPrice ?? 0;
            let total = this.xTotal ?? 0;

            this.amount_input = amount.toString().replace('.', ',');
            this.price_input = price.toString().replace('.', ',');
            this.total_input = total.toString().replace('.', ',');
        },
        closeDialogDetail() {
            this.amount_input = 0;
            this.price_input = 0;
            this.total_input = 0;

            this.xAmount = 0;
            this.xPrice = 0;
            this.xTotal = 0;
            this.$refs.formDetail.resetValidation();
            this.dialogDetail = false;
        },
        updateDialogDetail() {
            if (this.$refs.formDetail.validate()) {
                this.$store.dispatch("manager/updateDetail", {
                    PRID: this.selectedDetailTable.PurchaseRequestDirectDetailPurchaseRequestDirectID,
                    PRDID: this.selectedDetailTable.PurchaseRequestDirectDetailID,
                    PRDDescription: this.selectedDetailTable.PurchaseRequestDirectDescription,
                    PRDAmount: this.xAmount,
                    PRDPrice: this.xPrice,
                    PRDTotal: this.xTotal
                });
            }
        }
    },
    watch: {
        dialogDetail(val) {
            if (val) {
                this.$nextTick(() => {
                    this.$refs.formDetail?.resetValidation();
                    let detail = this.selectedDetailTable;
                    this.amount_input = this.oneMoney(detail.PurchaseRequestDirectDetailAmountRequest);
                    this.price_input = this.oneMoney(detail.PurchaseRequestDirectDetailEstimationPrice);
                    this.total_input = this.oneMoney(detail.PurchaseRequestDirectDetailTotalEstimationPrice);

                    if (detail.PurchaseDirectCategoryName == 'BBM') {
                        this.xAmount = parseFloat(detail.PurchaseRequestDirectDetailAmountRequest)
                        this.xPrice = parseFloat(detail.PurchaseRequestDirectDetailEstimationPrice)
                        this.xTotal = parseFloat(detail.PurchaseRequestDirectDetailTotalEstimationPrice)
                    } else {
                        this.xAmount = detail.PurchaseRequestDirectDetailAmountRequest
                        this.xPrice = detail.PurchaseRequestDirectDetailEstimationPrice
                        this.xTotal = detail.PurchaseRequestDirectDetailTotalEstimationPrice
                    }
                })
            }
        }
    },
}
</script>