<template>
    <v-layout class="fill-height" column>
        <v-toolbar color="blue lighten-3" dark>
            <v-toolbar-title class="white--text">PERSENTASE BIAYA</v-toolbar-title>
            <v-spacer></v-spacer>
                <v-btn flat icon @click="openAddPresentase()" :disabled="Object.keys(selected_precab).length === 0">
                    <v-icon medium>add_box</v-icon>
                </v-btn>
        </v-toolbar>
        <v-card class="pa-2">
            <v-layout row wrap class="scroll-container" style="max-height: 600px; overflow: auto;">
                <v-flex xs12>
                    <v-data-table
                        :headers="detail_headers"
                        :loading="loading_detail"
                        :items="tabel_detail.records"
                        class="elevation-1"
                        hide-actions
                        xs12
                    >
                        <template v-slot:items="props">
                            <tr>
                                <td>{{ props.index + 1 }}</td>
                                <td class="text-xs-center pa-2">{{ props.item.S_RegionalName }}</td>
                                <td class="text-xs-center pa-2">{{ props.item.DetailCabang }}</td>
                                <td class="text-xs-center pa-2">
                                    <v-icon
                                        small
                                        class="mr-2"
                                        @click="openEditPresentase(props.item)"
                                    >edit</v-icon>
                                    <v-icon
                                        small
                                        @click="openDelPresentase(props.item)"
                                    >delete</v-icon>
                                </td>
                            </tr>
                        </template>
                    </v-data-table>
                    <div class="text-xs-center pt-2">
                        <v-pagination v-model="pagination_detail" :length="det_pages" :total-visible="5"></v-pagination>
                    </div>
                </v-flex>
            </v-layout>
        </v-card>
        <v-dialog persistent width="500" v-model="dialogFormDet">
            <v-card>
                <v-card-title class="headline grey lighten-2" primary-title>
                    {{ crud_state ==  "delete" ?  'DELETE DETAIL PRESENTASE BIAYA CABANG' : 'FORM PRESENTASE BIAYA CABANG'}}
                </v-card-title>
                <v-card-text>
                    <v-subheader v-if="crud_state == 'delete'">Apa anda yakin akan menghapus detail presentase cabang berikut: </v-subheader>
                    <v-autocomplete
                        outline
                        v-model="selected_input_reg"
                        :items="regional_list.records"
                        label="Regional"
                        item-text="S_RegionalName"
                        return-object
                        :disabled="crud_state != 'add'"
                        @input="changeRegional"
                    ></v-autocomplete>
                    <v-layout row wrap v-for="item in regional_branches.records" :key="item.M_BranchID">
                        <v-flex xs6 pr-1>
                            <v-text-field
                                :label="item.M_BranchName"
                                outline
                                suffix="%"
                                type="number"
                                v-model.number="item.branchValue"
                                :disabled="crud_state == 'delete'"
                            ></v-text-field>
                        </v-flex>
                        <v-flex xs6 pl-1>
                            <v-autocomplete
                                outline
                                v-model="item.accountNumber"
                                :items="item.listCoa"
                                label="Account Number"
                                item-text="display"
                                item-value="number"
                                no-filter
                                :search-input.sync="selected_coa[item.M_BranchCode]"
                                :disabled="crud_state == 'delete'"
                            ></v-autocomplete>
                        </v-flex>
                    </v-layout>
                </v-card-text>
                <v-divider></v-divider>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                        color="error"
                        flat
                        @click="dialogFormDet = false"
                    >Batal</v-btn>
                    <v-btn
                        color="primary"
                        @click="crudDetail()"
                    >{{ crud_state == "delete" ? "Yakin" : "Simpan"  }}</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-layout>
</template>

<style scoped></style>

<script>
    module.exports = {
        mounted() {
            
        },
        data() {
            return {
                detail_headers: [
                    {
                        text: "NO",
                        align: "left",
                        sortable: false,
                        value: "no",
                        width: "10%",
                        class: "blue lighten-3 white--text",
                    },
                    {
                        text: "REGIONAL",
                        align: "center",
                        sortable: false,
                        value: "type",
                        width: "20%",
                        class: "blue lighten-3 white--text",
                    },
                    {
                        text: "PRESENTASE",
                        align: "center",
                        sortable: false,
                        value: "type",
                        width: "50%",
                        class: "blue lighten-3 white--text",
                    },
                    {
                        text: "AKSI",
                        align: "center",
                        sortable: false,
                        value: "type",
                        width: "20%",
                        class: "blue lighten-3 white--text",
                    }
                ],
                crud_state: "add",
                delete_ids: "",
                check_msg: ""
            }
        },
        computed: {
            tabel_detail() {
                return this.$store.state.presentase.tabel_detail;
            },
            loading_detail() {
                return this.$store.state.presentase.loading_detail;
            },
            selected_precab() {
                return this.$store.state.presentase.selected_precab;
            },
            list_coa() {
                return this.$store.state.presentase.list_coa;
            },
            pagination_detail: {
                get() {
                    return this.$store.state.presentase.pagination_detail
                },
                set(data) {
                    this.$store.commit("presentase/update_pagination_detail", data)
                    this.$store.dispatch("presentase/get_listing_reg", {currpages: data, presentasecostid: this.selected_precab.BranchCostPercentID})
                }
            },
            det_pages() {
                let total_data = this.tabel_detail.total;
                if (total_data == undefined) {
                    return 1
                } 

                return Math.ceil(total_data / 10);
            },
            selected_coa: {
                get() {
                    return this.$store.state.presentase.selected_coa
                },
                set(data) {
                    this.$store.commit("presentase/update_selected_coa", data)
                }
            },
            dialogFormDet: {
                get() {
                    return this.$store.state.presentase.dialogFormDet
                },
                set(data) {
                    this.$store.commit("presentase/update_dialog_form_det", data)
                }
            },
            regional_list: {
                get() {
                    return this.$store.state.presentase.list_regional
                },
                set(data) {
                    this.$store.commit("presentase/update_list_regional", data)
                }
            },
            selected_input_reg: {
                get() {
                    return this.$store.state.presentase.selected_input_reg
                },
                set(data) {
                    this.$store.commit("presentase/update_selected_input_reg", data)
                }
            },
            regional_branches: {
                get() {
                    return this.$store.state.presentase.regional_branches
                },
                set(data) {
                    this.$store.commit("presentase/update_regional_branches", data)
                }
            },
            snackbar: {
                get() {
                    return this.$store.state.presentase.snackbar
                },
                set(data) {
                    this.$store.commit("presentase/update_snackbar", data)
                }
            },
        },
        methods: {
            openAddPresentase() {
                this.selected_input_reg = {};
                this.regional_branches = {};
                this.selected_coa = {};
                this.crud_state = "add";
                this.$store.dispatch("presentase/get_regional_input");
                this.dialogFormDet = true;
            },
            async openEditPresentase(data) {
                console.log('data',data)
                this.crud_state = "edit";

                this.selected_coa = {};
                // this.$store.commit("presentase/update_selected_coa", data)
                this.selected_input_reg = { S_RegionalID: data.S_RegionalID, S_RegionalName: data.S_RegionalName }
                await this.$store.dispatch("presentase/get_current_value_detail", { regionalid: data.S_RegionalID, branchcostpercentid: this.selected_precab.BranchCostPercentID })
                let sel = {
                    records: [{ S_RegionalID: data.S_RegionalID, S_RegionalName: data.S_RegionalName }],
                    total: 1
                }
                this.regional_list = sel

                this.setCoaStates("edit")
                this.setupCoaWatcher()

                this.dialogFormDet = true
            },
            async openDelPresentase(data) {
                this.crud_state = "delete";

                this.selected_coa = {};
                this.selected_input_reg = { S_RegionalID: data.S_RegionalID, S_RegionalName: data.S_RegionalName }
                await this.$store.dispatch("presentase/get_current_value_detail", { regionalid: data.S_RegionalID, branchcostpercentid: this.selected_precab.BranchCostPercentID })
                let sel = {
                    records: [{ S_RegionalID: data.S_RegionalID, S_RegionalName: data.S_RegionalName }],
                    total: 1
                }
                this.regional_list = sel
                this.delete_ids = data.ListBranchPercentDetailID

                this.setCoaStates("delete")
                this.setupCoaWatcher()

                this.dialogFormDet = true;
            },
            async changeRegional(selectedItem) {
                this.selected_coa = {};
                let params = {
                    regionalid: selectedItem.S_RegionalID
                }
                await this.$store.dispatch("presentase/get_regional_branches", params)
                // this.$store.dispatch("presentase/get_list_coa", { keyword: "" })
                this.setCoaStates("")
                this.setupCoaWatcher()
            },
            crudDetail() {
                if (this.loading_api) {
                    let snac = {
                        isOpen: true,
                        color: "warning",
                        msg: "Loading proses lain ...."
                    };
                    this.snackbar = snac;
                    return;
                }

                if (! this.checkTotal()) {
                    console.log("msg", this.check_msg)
                    let snac = {
                        isOpen: true,
                        color: "warning",
                        msg: this.check_msg
                    };
                    this.snackbar = snac;
                    return;
                }

                if (this.crud_state == "add") {
                    console.log('add')
                    this.$store.dispatch("presentase/insert_detail_precab");
                } else if (this.crud_state == "edit") {
                    this.$store.dispatch("presentase/edit_detail_precab");
                } else if (this.crud_state == "delete") {
                    let del_id = this.delete_ids
                    console.log("delete_id", del_id)
                    this.$store.dispatch("presentase/delete_detail_precab", { precabdetailid: del_id });
                }
            },
            setCoaStates(data) {
                // if (Object.keys(this.regional_branches).length == 0) return;
                let regional = this.regional_branches.records
                regional.forEach( item => {
                    // console.log("created: ", item.M_BranchCode)
                    this.$set(this.selected_coa, item.M_BranchCode, "")
                })

                if (data == "edit" || data == "delete") {
                    regional.forEach( item => {
                        this.$store.dispatch("presentase/get_list_coa", {keyword: "", code: item.M_BranchCode});
                    })
                }
            },
            setupCoaWatcher() {
                // if (Object.keys(this.regional_branches).length == 0) return;
                // let regional = this.regional_branches.records
                // regional.forEach(item => {
                //     this.$watch(() => this.selected_coa[item.M_BranchCode], _.debounce((newVal, oldVal) => {
                //         console.log("val", newVal)
                //         if (newVal == oldVal) return;
                //         if (!newVal) return;
                //         if (newVal.length < 1) return;
                //         this.$store.dispatch("presentase/get_list_coa", {keyword: newVal, code: item.M_BranchCode});
                //     }, 1000), {deep: true, immediate: true})
                // })
                let regional = this.regional_branches.records
                regional.forEach(item => {
                    this.$watch(
                        () => this.selected_coa[item.M_BranchCode], 
                        _.debounce((newVal, oldVal) => {
                            // Gunakan item.accountNumber atau item.listCoa[0].number sebagai default keyword
                            const defaultKeyword = item.accountNumber || (item.listCoa[0] ? item.listCoa[0].number : '')
                            
                            const keyword = newVal || defaultKeyword
                            
                            // console.log("val", keyword)
                            
                            if (!keyword || keyword.length < 1) return;
                            
                            this.$store.dispatch("presentase/get_list_coa", {
                                keyword: keyword, 
                                code: item.M_BranchCode
                            });
                        }, 1000), 
                        {deep: true, immediate: true}
                    )
                })
            },
            checkTotal() {
                let total = 0
                let acc_msg = 0
                let regional = this.regional_branches.records
                regional.forEach( item => {
                    if (item.branchValue != '') {
                        total += item.branchValue
                    }

                    if (item.accountNumber == '') {
                        acc_msg = 1
                    }
                });

                let totall= 0
                totall = Math.round(total)

                if (totall > 100) {
                    this.check_msg = "Total presentase cabang lebih dari 100%"
                    return false
                }

                if (acc_msg > 0) {
                    this.check_msg = "Nomor akun belum terisi"
                    return false
                }

                return true
            }
        },
        watch: {

        }
    }
</script>

