<template>
    <v-layout row justify-center>
        <v-dialog v-model="dialogVoucher" persistent max-width="50vw">
            <v-card>
                <v-card-title class="headline grey lighten-2" primary-title>
                    FORM REALISASI
                </v-card-title>
                <v-card-text class="pt-2 pb-0">
                    <v-layout row>
                        <v-flex xs12 pa-2>
                            <v-textarea
                                filled
                                outline
                                hide-details
                                label="Catatan*"
                                rows="3"
                                v-model="xnote"
                            ></v-textarea>
                            <p v-if="checkErrorForm('requireNote')" class="error pl-2 pr-2" style="color:#fff">Catatan harus diisi</p>
                        </v-flex>
                    </v-layout>
                    <v-layout mr-2 ml-2 style="border:1px solid black" align-center row pa-2 mb-2>
                        <v-flex xs9>
                            <!-- <input type="file" ref="image" accept="image/*" @change="onFilePicked"> -->
                            <input type="file" id="files" ref="files" accept="image/*" multiple v-on:change="onFilePicked()"/>
                        </v-flex>
                    </v-layout>
                    <v-layout v-if="show_progrees_upload" row align-center mr-2 ml-2>
                        <v-flex xs12>
                        
                        <v-progress-linear :indeterminate="true"></v-progress-linear>

                        </v-flex>
                    </v-layout>
                    <v-layout  v-if="imageRelationPreviews.length > 0 && !show_progrees_upload" align-center row wrap>
                        <v-flex
                            v-for="(imgUrl, index) in imageRelationPreviews"
                            :key="index"
                            xs6
                            class="pa-2">
                                <v-img :src="imgUrl">
                                    <div class="fill-height bottom-gradient"></div>
                                </v-img>
                        </v-flex>                    
                    </v-layout>
                    <v-layout row>
                        <v-flex xs12 pa-2>
                            <v-text-field 
                                prefix="Rp"
                                v-model="formatted_total_price"
                                readonly
                                hide-details
                                outline
                                label="Total Bayar">
                            </v-text-field>
                        </v-flex>
                    </v-layout>
                    <v-layout row>
                        <v-flex xs11 pl-2>
                            <v-text-field 
                                prefix="Rp"
                                v-model="formattedRestPrice" 
                                @blur="resetRestPrice"
                                @focus="clearRestPrice"
                                outline readonly
                                hide-details
                                label="Harga">
                            </v-text-field>
                        </v-flex>
                        <v-flex xs>
                            <v-btn
                                outline color="blue lighten-2"
                                @click="openRealisedItem()"
                            >
                                <v-icon small color="blue">edit</v-icon>
                            </v-btn>
                        </v-flex>
                    </v-layout>
                    <v-layout row>
                        <v-flex xs12 pa-2>
                            <v-text-field 
                                prefix="Rp"
                                v-model="formattedTotalAkhir"
                                readonly
                                hide-details
                                outline
                                label="Sisa">
                            </v-text-field>
                        </v-flex>
                    </v-layout>

                    <v-divider></v-divider>
                    <v-layout v-if="imagePrevPaid.length > 0" pt-2>
                        <v-flex xs12 pa-2>
                            <span class="font-weight-bold">BUKTI PEMBAYARAN :</span>
                        </v-flex>
                    </v-layout>
                    <v-layout v-if="imagePrevPaid.length > 0" align-center row wrap>
                        <v-flex
                            v-for="(img, index) in imagePrevPaid"
                            :key="index"
                            xs6
                            class="pa-2"
                        >
                            <v-img :src="img">
                            <div class="fill-height bottom-gradient"></div>
                            </v-img>
                        </v-flex>
                    </v-layout>
                </v-card-text>
                <v-divider></v-divider>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="error" flat @click="closeDiallogCashier()"> Tutup </v-btn>
                    <v-btn v-if="xact === 'new'" color="primary" dark @click="saveVoucher()">Simpan</v-btn>
                    <v-btn v-if="xact === 'edit'" color="primary" dark @click="updateChasier()">Realisasi & Simpan</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-layout>
</template>

<script>
module.exports = {
    name: "DialogFormVoucher",
    data() {
        return {
            url: "",
            filesToUpload: [],
            fileName: "", // Untuk menyimpan nama file
            imageName: "",
            imageFile: "",
            imageUrl: "",
            headers: [
                {
                    text: "NO",
                    align: "left",
                    sortable: false,
                    value: "no",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "DESKRIPSI",
                    align: "left",
                    sortable: false,
                    value: "date",
                    width: "40%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "TOTAL REALISASI",
                    align: "left",
                    sortable: false,
                    value: "supplier",
                    width: "30%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "AKSI",
                    align: "left",
                    sortable: false,
                    value: "status",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
            ],
        };
    },
    mounted() {

    },
    computed: {
        formatted_total_price() {
            var val = Object.keys(this.$store.state.cashier.selected_cashier).length > 0 ? this.$store.state.cashier.selected_cashier.PaymentVoucherTotal : 0;
            return this.oneMoney(val);
        },
        formattedRestPrice: {
            get() {
                return this.oneMoney(this.restPrice);
            },
            set(value) {
                // Hilangkan titik dan koma, ubah jadi number
                let raw = value.replace(/\./g, '').replace(',', '.');
                this.restPrice = parseFloat(raw) || 0;
            }
        },
        total_akhir() {
            return this.$store.state.cashier.total_akhir;
        },
        formattedTotalAkhir: {
            get() {
                return this.oneMoney(this.total_akhir);
            },
            set(value) {
                // Hilangkan titik dan koma, ubah jadi number
                let raw = value.replace(/\./g, '').replace(',', '.');
                this.total_akhir = parseFloat(raw) || 0;
            }
        },
        dialogVoucher: {
            get() {
                return this.$store.state.cashier.dialog_cashier;
            },
            set(val) {
                this.$store.commit("cashier/update_dialog_cashier", val);
            },
        },
        branchList() {
            return this.$store.state.cashier.branchList;
        },
        selectedBranch: {
            get() {
                return this.$store.state.cashier.selected_branch;
            },
            set(val) {
                this.$store.commit("cashier/update_selected_branch", val);
                this.getPurchaseReq();
            },
        },
        search_branch: {
            get() {
                return this.$store.state.cashier.search_branch;
            },
            set(val) {
                this.$store.commit("cashier/update_search_branch", val);
            },
        },
        accountDanaList() {
            return this.$store.state.cashier.accountDanaList;
        },
        selectedAccountDana: {
            get() {
                return this.$store.state.cashier.selected_accountDana;
            },
            set(val) {
                this.$store.commit("cashier/update_selected_accountDana", val);
            },
        },
        search_accountDana: {
            get() {
                return this.$store.state.cashier.search_accountDana;
            },
            set(val) {
                this.$store.commit("cashier/update_search_accountDana", val);
            },
        },
        accountBiayaList() {
            return this.$store.state.cashier.accountBiayaList;
        },
        selectedAccountBiaya: {
            get() {
                return this.$store.state.cashier.selected_accountBiaya;
            },
            set(val) {
                this.$store.commit("cashier/update_selected_accountBiaya", val);
            },
        },
        search_accountBiaya: {
            get() {
                return this.$store.state.cashier.search_accountBiaya;
            },
            set(val) {
                this.$store.commit("cashier/update_search_accountBiaya", val);
            },
        },
        accountTempList() {
            return this.$store.state.cashier.accountTempList;
        },
        selectedAccountTemp: {
            get() {
                return this.$store.state.cashier.selected_accountTemp;
            },
            set(val) {
                this.$store.commit("cashier/update_selected_accountTemp", val);
            },
        },
        search_accountTemp: {
            get() {
                return this.$store.state.cashier.search_accountTemp;
            },
            set(val) {
                this.$store.commit("cashier/update_search_accountTemp", val);
            },
        },
        purchaseList() {
            return this.$store.state.cashier.purchaseList;
        },
        selected_purchase: {
            get() {
                return this.$store.state.cashier.selected_purchase;
            },
            set(val) {
                this.$store.commit("cashier/update_selected_purchase", val);
            },
        },
        resume() {
            return this.$store.state.cashier.resume_total;
        },
        xact: {
            get() {
                return this.$store.state.cashier.act;
            },
            set(val) {
                this.$store.commit("cashier/update_act", val);
            },
        },
        show_progrees_upload: {
            get() {
                return this.$store.state.cashier.show_progrees_upload
            },
            set(val) {
                this.$store.commit("cashier/update_show_progrees_upload", val)
            }
        },
        xnote: {
            get() {
                return this.$store.state.cashier.note
            },
            set(val) {
                this.$store.commit("cashier/update_note", val)
            }
        },
        restPrice: {
            get() {
                return this.$store.state.cashier.restPrice
            },
            set(val) {
                this.$store.commit("cashier/update_restPrice", val)
            }
        },
        imagePrevPaid: {
            get() {
                return this.$store.state.cashier.imagePrevPaid
            },
            set(val) {
                this.$store.commit("cashier/update_imagePrevPaid", val)
            }
        },
        imageRelationPreviews: {
            get() {
                return this.$store.state.cashier.imageRelationPreviews;
            },
            set(val) {
                this.$store.commit("cashier/update_imageRelationPreviews", val);
            },
        },
        imageRelationFiles: {
            get() {
                return this.$store.state.cashier.imageRelationFiles;
            },
            set(val) {
                this.$store.commit("cashier/update_imageRelationFiles", val);
            },
        },
    },
    methods: {
        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, ".");
            }
        },
        convertMoney(money){
            return one_money(money)
        },
        formatAngka(nilai) {
            // Jika tidak ada nilai
            if (!nilai) return '';
            
            try {
                // Ubah ke string
                let strNilai = String(nilai);
                
                // Jika berisi titik desimal
                if (strNilai.includes('.')) {
                    // Split bagian utama dan desimal
                    let bagian = strNilai.split('.');
                    let utama = bagian[0];
                    let desimal = bagian[1];
                    
                    // Format bagian utama
                    utama = utama.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
                    
                    // Kembalikan gabungan
                    return utama + ',' + desimal;
                } else {
                    // Tidak ada desimal, hanya format bagian utama
                    return strNilai.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
                }
            } catch (error) {
                console.error("Error formatting:", error);
                return nilai;
            }
        },
        resetRestPrice() {
            if (this.restPrice === '' || this.restPrice === null) {
                this.restPrice = 0
            }
        },
        clearRestPrice() {
            if (this.restPrice === 0) {
                this.restPrice = ''
            }
        },
        handleFileUploadsbkp(){
            // this.files = this.$refs.files.files

            const files = this.$refs.files.files;
            this.urls = [];
            this.filesToUpload = [];
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const url = URL.createObjectURL(file);
                this.urls.push(url);
                this.filesToUpload.push(file);
            }
            // console.log('urls', this.urls)
             console.log('filesToUpload', this.filesToUpload)
        },
        handleFileUploads(){
            const file = this.$refs.files.files[0];
            if (file) {
                this.fileName = file.name; // Simpan nama file
                this.filesToUpload = [file]; // Masukkan ke array untuk konsistensi
                this.url = URL.createObjectURL(file); // Preview jika diperlukan
            }

        },
        onFilePicked(){
            // this.files = this.$refs.files.files

            const files = this.$refs.files.files;
            this.imageRelationPreviews = [];
            this.imageRelationFiles = [];
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const url = URL.createObjectURL(file);
                this.imageRelationPreviews.push(url);
                this.imageRelationFiles.push(file);
            }
        },
        onFilePicked_old(e) {
            const files = e.target.files
            console.log('cek files',files[0]);
            if (files[0] !== undefined) {
                this.imageName = files[0].name
                if (this.imageName.lastIndexOf('.') <= 0) {
                    return
                }
                const fr = new FileReader()
                fr.readAsDataURL(files[0])
                fr.addEventListener('load', () => {
                    this.imageUrl = fr.result
                    this.imageFile = files[0] // this is an image file that can be sent to server...
                })

                // console.log('imageName', this.imageName)
                // console.log('imageFile', this.imageFile)
                // console.log('imageUrl', this.imageUrl)

            } else {
                this.imageName = ''
                this.imageFile = ''
                this.imageUrl = ''
            }
        },
        thr_search_branch: _.debounce(function() {
            this.$store.dispatch("cashier/searchBranch", this.search_branch);
        }, 500),
        thr_search_accountDana: _.debounce(function() {
            this.$store.dispatch("cashier/searchAccDana", this.search_accountDana);
        }, 500),
        thr_search_accountBiaya: _.debounce(function() {
            this.$store.dispatch("cashier/searchAccBiaya", this.search_accountBiaya);
        }, 500),
        thr_search_accountTemp: _.debounce(function() {
            this.$store.dispatch("cashier/searchAccTemp", this.search_accountTemp);
        }, 500),
        getPurchaseReq() {
            this.$store.dispatch("cashier/getPurchase", this.selectedBranch === undefined ? "" : this.selectedBranch.M_BranchCode);
        },
        formatCurrency(val) {
          // Format the price above to USD using the locale, style, and currency.
          let price = parseFloat(val);
          let USDollar = new Intl.NumberFormat("id-ID", {
            style: "currency",
            currency: "IDR",
          });
  
          // console.log(
          //   `The formated version of ${price} is ${USDollar.format(price)}`
          // );
          return `${USDollar.format(price)}`;
        },
        addPurchase(item) {
            let selected_purchase = this.$store.state.cashier.selected_purchase;
            selected_purchase.push(item);

            let totalRealitation = 0;
            for (let i = 0; i < selected_purchase.length; i++) {
                const e = selected_purchase[i];
                totalRealitation += parseFloat(e.PurchaseRequestDirectTotalRealitation);
            }
            let xresume = {
                "totalRealitation": totalRealitation,
            };
            this.$store.commit("cashier/update_resume_total", xresume);
        },
        purchaseExist(item) {
            let selected_purchase = this.$store.state.cashier.selected_purchase;
            let found = selected_purchase.find((el) => el.PurchaseRequestDirectID === item.PurchaseRequestDirectID);
            if (found) {
                return false;
            }
            return true;
        },
        removePurchase(item) {
            let selected_purchase = this.$store.state.cashier.selected_purchase;
            let found = selected_purchase.find((el) => el.PurchaseRequestDirectID === item.PurchaseRequestDirectID);
            if (found) {
                let index = selected_purchase.indexOf(found);
                selected_purchase.splice(index, 1);
            }

            let totalRealitation = 0;
            for (let i = 0; i < selected_purchase.length; i++) {
                const e = selected_purchase[i];
                totalRealitation += parseFloat(e.PurchaseRequestDirectTotalRealitation);
            }
            let xresume = {
                "totalRealitation": totalRealitation,
            };
            this.$store.commit("cashier/update_resume_total", xresume);
        },
        checkErrorForm(val) {
            let errors = this.$store.state.cashier.errors;
            if (errors.includes(val)) {
                return true;
            } else {
                return false;
            }
        },
        closeDiallogCashier() {
            this.dialogVoucher = false;
            this.xnote = ""
            this.url = ""
            this.filesToUpload = []
            this.imageName = ''
            this.imageFile = ''
            this.imageUrl = ''
            this.restPrice = 0
            this.$store.commit("cashier/update_total_akhir", 0);
            this.$store.commit("cashier/update_errors", []);
        },
        saveVoucher() {
            this.$store.commit("cashier/update_errors", []);
            var errors = this.$store.state.cashier.errors;
            if (_.isEmpty(this.selectedBranch)) {
                errors.push("requireBranch");
            }
            if (_.isEmpty(this.selectedAccountDana)) {
                errors.push("requireAccountDana");
            }
            if (_.isEmpty(this.selectedAccountBiaya)) {
                errors.push("requireAccountBiaya");
            }
            if (_.isEmpty(this.selectedAccountTemp)) {
                errors.push("requireAccountTemp");
            }
            if (errors.length === 0) {
                let prm = {
                    "branch": this.selectedBranch.M_BranchCode,
                    "accountDana": this.selectedAccountDana.coaID,
                    "accountBiaya": this.selectedAccountBiaya.coaID,
                    "accountTemp": this.selectedAccountTemp.coaID,
                    "total": this.$store.state.cashier.resume_total.totalRealitation,
                    "details": this.$store.state.cashier.selected_purchase,
                };
                // this.$store.dispatch("cashier/save", prm);
            }
        },
        resetAllInput() {
            this.xnote = ""
            this.restPrice = 0
            this.$store.commit("cashier/update_total_akhir", 0);
            this.$store.commit("cashier/update_imageRelationPreviews", []);
            this.$store.commit("cashier/update_imageRelationFiles", []);
        },
        updateChasier() {
            this.$store.commit("cashier/update_errors", []);
            var errors = this.$store.state.cashier.errors;
            if (_.isEmpty(this.xnote)) {
                errors.push("requireNote");
            }
            if (errors.length === 0) {
                var formData = new FormData()

                for( var i = 0; i < this.imageRelationFiles.length; i++ ){
                    let file = this.imageRelationFiles[i]
                    
                    formData.append('files[' + i + ']', file)
                }      

                formData.append("token", one_token())
                formData.append("note", this.xnote)
                formData.append("restPrice", this.restPrice)
                formData.append("ID", this.$store.state.cashier.selected_cashier.PaymentVoucherID)

                this.$store.dispatch("cashier/update", formData);
            }
        },
        calculateTotalPrice() {
            var totalHarga = Object.keys(this.$store.state.cashier.selected_cashier).length > 0 ? this.$store.state.cashier.selected_cashier.PaymentVoucherTotal : 0;
            if (this.restPrice > 0) {
                let total = totalHarga - this.restPrice;
                this.$store.commit("cashier/update_total_akhir", total);
            }
        },
        openRealisedItem() {
            this.$store.dispatch("cashier/getVoucherDetail")
            this.$store.commit("cashier/update_dialog_realise_item", true)
        }
    },
    watch: {
        search_branch(val, old) {
            if (val == old) return;
            if (!val) return;
            if (val.length < 1) return;
            if (this.$store.state.cashier.load_status_branch == 1) return;
            this.thr_search_branch();
        },
        search_accountDana(val, old) {
            if (val == old) return;
            if (!val) return;
            if (val.length < 1) return;
            if (this.$store.state.cashier.load_status_accDana == 1) return;
            this.thr_search_accountDana();
        },
        search_accountBiaya(val, old) {
            if (val == old) return;
            if (!val) return;
            if (val.length < 1) return;
            if (this.$store.state.cashier.load_status_accBiaya == 1) return;
            this.thr_search_accountBiaya();
        },
        search_accountTemp(val, old) {
            if (val == old) return;
            if (!val) return;
            if (val.length < 1) return;
            if (this.$store.state.cashier.load_status_accTemp == 1) return;
            this.thr_search_accountTemp();
        },
        restPrice(val, old) {
            if (val < 0) {
                this.$store.commit("cashier/update_restPrice",0);
            }
            this.calculateTotalPrice();
        }
    },
}
</script>