<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 VOUCHER
                </v-card-title>
                <v-card-text class="pt-2 pb-0">
                    <v-layout wrap>
                        <v-flex xs12 mb-2>
                            <v-autocomplete label="Cabang"
                                    :items="branchList" v-model="selectedBranch"
                                    :search-input.sync="search_branch"
                                    auto-select-first no-filter item-text="M_BranchName" return-object
                                    no-data-text="Pilih Cabang"
                                    :disabled="xact === 'edit'"
                                    hide-details>
                                    <template slot="item" slot-scope="{ item }">
                                        <v-list-tile-content>
                                            <v-list-tile-title v-text="item.M_BranchName"></v-list-tile-title>
                                        </v-list-tile-content>
                                    </template>
                            </v-autocomplete>
                            <p v-if="checkErrorForm('requireBranch')" class="error pl-2 pr-2" style="color:#fff">Cabang harus diisi</p>
                        </v-flex>
                        <v-flex xs12 mb-2>
                            <v-autocomplete label="Account Sumber Dana"
                                    :items="accountDanaList" v-model="selectedAccountDana"
                                    :search-input.sync="search_accountDana"
                                    auto-select-first no-filter item-text="coaDescription" return-object
                                    no-data-text="Pilih Account Sumber Dana"
                                    hide-details>
                                    <template slot="item" slot-scope="{ item }">
                                        <v-list-tile-content>
                                            <v-list-tile-title v-text="item.coaDescription"></v-list-tile-title>
                                            <v-list-tile-sub-title
                                                v-text="item.coaAccountNo"
                                            ></v-list-tile-sub-title>
                                        </v-list-tile-content>
                                    </template>
                            </v-autocomplete>
                            <p v-if="checkErrorForm('requireAccountDana')" class="error pl-2 pr-2" style="color:#fff">Account sumber dana harus diisi</p>
                        </v-flex>

                        <!-- <v-flex xs12 mb-2>
                            <v-autocomplete label="Account Biaya"
                                    :items="accountBiayaList" v-model="selectedAccountBiaya"
                                    :search-input.sync="search_accountBiaya"
                                    auto-select-first no-filter item-text="coaDescription" return-object
                                    no-data-text="Pilih Account Biaya"
                                    hide-details>
                                    <template slot="item" slot-scope="{ item }">
                                        <v-list-tile-content>
                                            <v-list-tile-title v-text="item.coaDescription"></v-list-tile-title>
                                            <v-list-tile-sub-title
                                                v-text="item.coaAccountNo"
                                            ></v-list-tile-sub-title>
                                        </v-list-tile-content>
                                    </template>
                            </v-autocomplete>
                            <p v-if="checkErrorForm('requireAccountBiaya')" class="error pl-2 pr-2" style="color:#fff">Account biaya harus diisi</p>
                        </v-flex> -->
                        <v-flex xs12 mb-2>
                            <v-autocomplete label="Account Tampungan Sementara"
                                    :items="accountTempList" v-model="selectedAccountTemp"
                                    :search-input.sync="search_accountTemp"
                                    auto-select-first no-filter item-text="coaDescription" return-object
                                    no-data-text="Pilih Account"
                                    hide-details>
                                    <template slot="item" slot-scope="{ item }">
                                        <v-list-tile-content>
                                            <v-list-tile-title v-text="item.coaDescription"></v-list-tile-title>
                                            <v-list-tile-sub-title
                                                v-text="item.coaAccountNo"
                                            ></v-list-tile-sub-title>
                                        </v-list-tile-content>
                                    </template>
                            </v-autocomplete>
                            <p v-if="checkErrorForm('requireAccountTemp')" class="error pl-2 pr-2" style="color:#fff">Account tampungan sementara harus diisi</p>
                        </v-flex>

                        <!-- listing -->
                        <v-flex xs12 mt-2>
                            <v-layout row>
                            <v-flex xs12 pt-2 pb-2>
                                <v-card color="cyan ">
                                <v-layout align-center row>
                                    <h4 class="subheader pl-3 pt-2 pb-2">DAFTAR REQUEST</h4>
                                </v-layout>
                                <v-divider></v-divider>
                                </v-card>
                            </v-flex>
                            </v-layout>
                            <v-layout row>
                                <v-flex xs12 pt-1 pb-2>
                                    <v-data-table
                                        class="v-table elevation-1 with-vertical-lines"
                                        hide-actions
                                        :items="purchaseList"
                                        :headers="headers"
                                    >
                                        <template v-slot:items="props">
                                            <td class="table-cell text-xs-left"style="height: 42px">
                                                {{ props.item.PurchaseRequestDirectNumber }}
                                            </td>
                                            <td class="table-cell text-xs-left"
                                            style="height: 42px"
                                            >
                                            {{ props.item.user_request }}
                                            </td>
                                            <td class="table-cell text-xs-left"
                                            style="height: 42px"
                                            >
                                            {{ props.item.PurchaseRequestDirectDescription }}
                                            </td>
                                            <td class="table-cell text-xs-left"
                                            style="height: 42px"
                                            >
                                            Rp {{ props.item.PurchaseRequestDirectTotalRealitation.toString().replace(
                                                    /\B(?=(\d{3})+(?!\d))/g,
                                                    "."
                                                ) }}
                                            </td>
                                            <td class="table-cell text-xs-center" style="height: 42px">
                                                <v-btn
                                                    dark
                                                    @click="addPurchase(props.item)"
                                                    v-if="purchaseExist(props.item)"
                                                    style="min-width: 25px; height: 30px"
                                                    small
                                                    color="info"
                                                >
                                                    <v-icon style="cursor: pointer; font-size: 18px">
                                                    add_box
                                                    </v-icon>
                                                </v-btn>
                                                <v-btn
                                                    dark
                                                    v-if="!purchaseExist(props.item)"
                                                    @click="removePurchase(props.item)"
                                                    style="min-width: 25px; height: 30px"
                                                    small
                                                    color="red"
                                                >
                                                    <v-icon style="cursor: pointer; font-size: 18px">
                                                    delete
                                                    </v-icon>
                                                </v-btn>
                                            </td>
                                        </template>
                                        <template v-slot:footer>
                                        <tr>
                                            <td colspan="3" class="font-weight-bold pa-2">TOTAL</td>

                                            <td class="text-xs-right pa-2 font-weight-bold">
                                                Rp {{ resume.totalRealitation.toString().replace(
                                                    /\B(?=(\d{3})+(?!\d))/g,
                                                    "."
                                                ) }}
                                            </td>
                                        </tr>
                                        </template>
                                    </v-data-table>
                                </v-flex>
                            </v-layout>
                        </v-flex>
                        <!-- end listing -->
                    </v-layout>
                </v-card-text>
                <v-divider></v-divider>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="error" flat @click="closeDiallogVoucher()"> 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="updateVoucher()">Simpan Perubahan</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-layout>
</template>

<script>
module.exports = {
    name: "DialogFormVoucher",
    data() {
        return {
            headers: [
                {
                    text: "NO",
                    align: "left",
                    sortable: false,
                    value: "no",
                    width: "10%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "USER REQUEST",
                    align: "left",
                    sortable: false,
                    value: "user",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "DESKRIPSI",
                    align: "left",
                    sortable: false,
                    value: "date",
                    width: "35%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "TOTAL REALISASI",
                    align: "left",
                    sortable: false,
                    value: "supplier",
                    width: "25%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "AKSI",
                    align: "left",
                    sortable: false,
                    value: "status",
                    width: "15%",
                    class: "blue lighten-3 white--text",
                },
            ],
        };
    },
    mounted() {
        this.$store.dispatch("voucher/searchBranch", this.search_branch);
        this.$store.dispatch("voucher/searchAccDana", this.search_accountDana);
        this.$store.dispatch("voucher/searchAccBiaya", this.search_accountBiaya);
        this.$store.dispatch("voucher/searchAccTemp", this.search_accountTemp);
    },
    computed: {
        dialogVoucher: {
            get() {
                return this.$store.state.voucher.dialog_voucher;
            },
            set(val) {
                this.$store.commit("voucher/update_dialog_voucher", val);
            },
        },
        branchList() {
            return this.$store.state.voucher.branchList;
        },
        selectedBranch: {
            get() {
                return this.$store.state.voucher.selected_branch;
            },
            set(val) {
                this.$store.commit("voucher/update_selected_branch", val);
                this.getPurchaseReq();
            },
        },
        search_branch: {
            get() {
                return this.$store.state.voucher.search_branch;
            },
            set(val) {
                this.$store.commit("voucher/update_search_branch", val);
            },
        },
        accountDanaList() {
            return this.$store.state.voucher.accountDanaList;
        },
        selectedAccountDana: {
            get() {
                return this.$store.state.voucher.selected_accountDana;
            },
            set(val) {
                this.$store.commit("voucher/update_selected_accountDana", val);
            },
        },
        search_accountDana: {
            get() {
                return this.$store.state.voucher.search_accountDana;
            },
            set(val) {
                this.$store.commit("voucher/update_search_accountDana", val);
            },
        },
        accountBiayaList() {
            return this.$store.state.voucher.accountBiayaList;
        },
        selectedAccountBiaya: {
            get() {
                return this.$store.state.voucher.selected_accountBiaya;
            },
            set(val) {
                this.$store.commit("voucher/update_selected_accountBiaya", val);
            },
        },
        search_accountBiaya: {
            get() {
                return this.$store.state.voucher.search_accountBiaya;
            },
            set(val) {
                this.$store.commit("voucher/update_search_accountBiaya", val);
            },
        },
        accountTempList() {
            return this.$store.state.voucher.accountTempList;
        },
        selectedAccountTemp: {
            get() {
                return this.$store.state.voucher.selected_accountTemp;
            },
            set(val) {
                this.$store.commit("voucher/update_selected_accountTemp", val);
            },
        },
        search_accountTemp: {
            get() {
                return this.$store.state.voucher.search_accountTemp;
            },
            set(val) {
                this.$store.commit("voucher/update_search_accountTemp", val);
            },
        },
        purchaseList() {
            return this.$store.state.voucher.purchaseList;
        },
        selected_purchase: {
            get() {
                return this.$store.state.voucher.selected_purchase;
            },
            set(val) {
                this.$store.commit("voucher/update_selected_purchase", val);
            },
        },
        resume() {
            return this.$store.state.voucher.resume_total;
        },
        xact: {
            get() {
                return this.$store.state.voucher.act;
            },
            set(val) {
                this.$store.commit("voucher/update_act", val);
            },
        },
    },
    methods: {
        convertMoney(money){
            return one_money(money)
        },
        thr_search_branch: _.debounce(function() {
            this.$store.dispatch("voucher/searchBranch", this.search_branch);
        }, 500),
        thr_search_accountDana: _.debounce(function() {
            this.$store.dispatch("voucher/searchAccDana", this.search_accountDana);
        }, 500),
        thr_search_accountBiaya: _.debounce(function() {
            this.$store.dispatch("voucher/searchAccBiaya", this.search_accountBiaya);
        }, 500),
        thr_search_accountTemp: _.debounce(function() {
            this.$store.dispatch("voucher/searchAccTemp", this.search_accountTemp);
        }, 500),
        getPurchaseReq() {
            this.$store.dispatch("voucher/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.voucher.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("voucher/update_resume_total", xresume);
        },
        purchaseExist(item) {
            let selected_purchase = this.$store.state.voucher.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.voucher.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("voucher/update_resume_total", xresume);
        },
        checkErrorForm(val) {
            let errors = this.$store.state.voucher.errors;
            if (errors.includes(val)) {
                return true;
            } else {
                return false;
            }
        },
        closeDiallogVoucher() {
            this.dialogVoucher = false;
            this.$store.commit("voucher/update_selected_branch", {});
            this.$store.commit("voucher/update_selected_accountDana", {});
            this.$store.commit("voucher/update_selected_accountBiaya", {});
            this.$store.commit("voucher/update_selected_accountTemp", {});
            this.$store.commit("voucher/update_selected_purchase", []);
            this.$store.commit("voucher/update_purchaseList", []);
            this.$store.commit("voucher/update_resume_total", {"totalRealitation": 0});
            this.$store.commit("voucher/update_errors", []);
        },
        saveVoucher() {
            this.$store.commit("voucher/update_errors", []);
            var errors = this.$store.state.voucher.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.voucher.resume_total.totalRealitation,
                    "details": this.$store.state.voucher.selected_purchase,
                };
                this.$store.dispatch("voucher/save", prm);
            }
        },
        updateVoucher() {
            this.$store.commit("voucher/update_errors", []);
            var errors = this.$store.state.voucher.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 = {
                    "voucherID": this.$store.state.voucher.selected_voucher.PaymentVoucherID,
                    "branch": this.selectedBranch.M_BranchCode,
                    "accountDana": this.selectedAccountDana.coaID,
                    "accountBiaya": this.selectedAccountBiaya.coaID,
                    "accountTemp": this.selectedAccountTemp.coaID,
                    "total": this.$store.state.voucher.resume_total.totalRealitation,
                    "details": this.$store.state.voucher.selected_purchase,
                };
                this.$store.dispatch("voucher/update", prm);
            }
        },
    },
    watch: {
        search_branch(val, old) {
            if (val == old) return;
            if (!val) return;
            if (val.length < 1) return;
            if (this.$store.state.voucher.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.voucher.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.voucher.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.voucher.load_status_accTemp == 1) return;
            this.thr_search_accountTemp();
        },
    },
}
</script>