<template>
    <v-layout row justify-center>
        <v-dialog v-model="dialogVoucherPay" persistent max-width="50vw">
            <v-card>
                <v-card-title class="headline grey lighten-2" primary-title>
                    FORM PEMBAYARAN
                </v-card-title>
                <v-card-text class="pt-2 pb-0">
                    <v-layout pt-2>
                        <v-flex xs12 pa-2>
                            <span class="font-weight-bold">NOMOR REQUEST:</span>
                        </v-flex>
                    </v-layout>
                    <v-layout row>
                        <v-flex xs12 pa-2>
                            <v-chip label
                                v-for="(item, index) in numberRequest"
                                :key="index"
                                class="ma-1"
                            >
                                {{ item }}
                            </v-chip label>
                        </v-flex>
                    </v-layout>
                    <v-layout row>
                        <v-flex xs12 pa-2>
                            <v-textarea
                                filled
                                outline
                                hide-details
                                label="Catatan*"
                                rows="3"
                                v-model="xnotepay"
                            ></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>
                        <v-flex xs12 pa-2>
                            <v-textarea
                                filled
                                outline
                                hide-details
                                label="Deskripsi Request"
                                rows="3"
                                readonly
                                v-model="requestDescription"
                            ></v-textarea>
                        </v-flex>
                    </v-layout>
                    <v-layout>
                        <v-flex xs12 pa-2>
                            <v-text-field 
                                v-model="this.$store.state.cashier.selected_cashier.user_request"
                                readonly
                                hide-details
                                outline
                                label="Nama Request">
                            </v-text-field>
                        </v-flex>
                    </v-layout>
                    <v-layout>
                        <v-flex xs12 pa-2>
                            <v-autocomplete
                                v-model="selected_userReceive"
                                menu-icon="mdi-chevron-down"
                                :items="userReceive"
                                item-text="M_UserUsername"
                                item-value="M_UserID"
                                label="Penerima Uang*"
                                outline
                                hide-details
                            ></v-autocomplete>
                            <p v-if="checkErrorForm('requireUserReceive')" class="error pl-2 pr-2" style="color:#fff">Penerima uang belum di pilih</p>
                        </v-flex>
                    </v-layout>
                    <v-layout>
                        <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 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="imagePayPreviews.length > 0 && !show_progrees_upload" align-center row wrap>
                        <v-flex
                            v-for="(imgUrl, index) in imagePayPreviews"
                            :key="index"
                            xs6
                            class="pa-2">
                                <v-img :src="imgUrl">
                                    <div class="fill-height bottom-gradient"></div>
                                </v-img>
                        </v-flex>
                    </v-layout>

                    <v-divider></v-divider>
                    <v-layout v-if="imagePreviews.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="imagePreviews.length > 0" align-center row wrap>
                        <v-flex
                            v-for="(img, index) in imagePreviews"
                            :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="updatePay()">Bayar & 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);
        },
        dialogVoucherPay: {
            get() {
                return this.$store.state.cashier.dialog_cashier_pay;
            },
            set(val) {
                this.$store.commit("cashier/update_dialog_cashier_pay", 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)
            }
        },
        xnotepay: {
            get() {
                return this.$store.state.cashier.notepay
            },
            set(val) {
                this.$store.commit("cashier/update_notepay", val)
            }
        },
        imagePreviews: {
            get() {
                return this.$store.state.cashier.imagePreviews
            },
            set(val) {
                this.$store.commit("cashier/update_imagePreviews", val)
            }
        },
        numberRequest: {
            get() {
                return this.$store.state.cashier.numberRequest;
            },
            set(val) {
                this.$store.commit("cashier/update_numberRequest", val);
            },
        },
        requestDescription: {
            get() {
                return this.$store.state.cashier.requestDescription;
            },
            set(val) {
                this.$store.commit("cashier/update_requestDescription", val);
            },
        },
        imagePayPreviews: {
            get() {
                return this.$store.state.cashier.imagePayPreviews;
            },
            set(val) {
                this.$store.commit("cashier/update_imagePayPreviews", val);
            },
        },
        imagePayFiles: {
            get() {
                return this.$store.state.cashier.imagePayFiles;
            },
            set(val) {
                this.$store.commit("cashier/update_imagePayFiles", val);
            },
        },
        selected_userReceive: {
            get() {
                return this.$store.state.cashier.selected_userReceive;
            },
            set(val) {
                this.$store.commit("cashier/update_selected_userReceive", val);
            },
        },
        userReceive() {
            return this.$store.state.cashier.userReceive;
        },
    },
    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, ".");
            }
        },
        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.imagePayPreviews = [];
            this.imagePayFiles = [];
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const url = URL.createObjectURL(file);
                this.imagePayPreviews.push(url);
                this.imagePayFiles.push(file);
            }
        },
        onFilePickedold(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.dialogVoucherPay = false;
            this.xnotepay = ""
            this.url = ""
            this.filesToUpload = []
            this.imageName = ''
            this.imageFile = ''
            this.imageUrl = ''
            this.$store.commit("cashier/update_errors", []);
            this.$store.commit("cashier/update_selected_userReceive",);
        },
        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.xnotepay = ""
            this.imageName = ''
            this.imageFile = ''
            this.imageUrl = ''
        },
        updatePay() {
            this.$store.commit("cashier/update_errors", []);
            var errors = this.$store.state.cashier.errors;
            if (_.isEmpty(this.xnotepay)) {
                errors.push("requireNote");
            }
            if (_.isEmpty(this.selected_userReceive)) {
                errors.push("requireUserReceive");
            }
            if (errors.length === 0) {
                var formData = new FormData()
                console.log("formData",this.imagePayFiles.length)
                for( var i = 0; i < this.imagePayFiles.length; i++ ){
                    let file = this.imagePayFiles[i]
                    
                    formData.append('files[' + i + ']', file)
                    console.log("formData",formData)
                }

                formData.append("token", one_token())
                formData.append("note", this.xnotepay)
                formData.append("ID", this.$store.state.cashier.selected_cashier.PaymentVoucherID)
                formData.append("userReceiveID", this.$store.state.cashier.selected_userReceive)

                // let prm = {
                //     "img": this.imageUrl + '/' + this.imageName + '/' + this.imageFile,
                //     "note": this.xnotepay,
                //     "ID": this.$store.state.cashier.selected_cashier.PaymentVoucherID
                // }

                this.$store.dispatch("cashier/updatepaid", formData);
            }
        },
    },
    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();
        },
    },
}
</script>