<template>
    <v-layout>

        <!-- alert -->
        <v-dialog v-model="dialogdeletealert" max-width="30%">
            <v-card>
                <v-card-title class="headline grey lighten-2 pt-2 pb-2" primary-title>
                    Peringatan !
                </v-card-title>
                <v-card-text class="pt-2 pb-2">
                    <v-layout row>
                        <v-flex xs12 d-flex>
                            <v-layout row>
                                <v-flex pb-1 xs12>
                                    <v-layout row>
                                        <v-flex pt-2 pr-2 xs12>
                                            {{ msgalert }}
                                        </v-flex>
                                    </v-layout>
                                </v-flex>
                            </v-layout>
                        </v-flex>
                    </v-layout>
                </v-card-text>
                <v-divider></v-divider>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="error" flat @click="dialogdeletealert = false">
                        Tutup
                    </v-btn>
                    <v-btn v-if="action_delete" color="primary" @click="closeDeleteAlert()">
                        Yakin lah
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <!-- alert -->

        <!-- form -->
        <v-dialog v-model="dialogdivision" persistent max-width="600px">
            <v-card>
                <v-card-title>
                    <span class="title">Form Divisi</span></v-card-title>
                <v-card-text class="pt-0 pb-0">
                    <v-form ref="formdivision" v-model="valid" lazy-validation>
                        <v-layout wrap>
                            <v-flex xs12>
                                <v-text-field v-model="xname" label="Nama*" :rules="xnameRules" required></v-text-field>
                            </v-flex>
         
                            <v-flex xs12>
                                <v-text-field v-model="xlettercode" label="Code Surat"></v-text-field>
                            </v-flex>
                                            
                            <v-flex>
                                <p v-for="(xerror, idx) in xerrors" class="error pl-2 pr-2" style="color:#fff">
                                    {{ xerror.msg }}</p>
                            </v-flex>
                        </v-layout>
                    </v-form>
                </v-card-text>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="error" flat @click="updateDialogForm()">Tutup</v-btn>
                    <v-btn v-if="xact === 'new'" color="primary" @click="saveForm()">Simpan</v-btn>
                    <v-btn v-if="xact === 'edit'" color="primary" @click="updateForm()">Simpan Perubahan</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <!-- form -->

        <v-flex xs12>
            <v-card>
                <!-- Toolbar -->
                <v-toolbar color="blue lighten-3" dark scroll-off-screen scroll-target="#scrolling-techniques">

                    <v-toolbar-title class="headline font-weight-bold">Master Data Divisi</v-toolbar-title>
                    <v-spacer></v-spacer>
                    <v-btn class="text-xs-right" @click="openFormDivision(0)" icon><v-icon>library_add</v-icon></v-btn>
                </v-toolbar>
                <!-- End Toolbar -->

                <div id="scrolling-techniques" class="scroll-y">

                    <!-- search -->
                    <v-card elevation="0">
                        <v-card-text>
                            <v-layout row>
                                <v-flex xs3>
                                    <v-text-field v-model="xsearch" label="Search"
                                        placeholder="Cari kode atau nama divisi" outline hide-details></v-text-field>
                                </v-flex>
                            </v-layout>
                        </v-card-text>
                    </v-card>
                    <!-- search -->
                    <v-divider></v-divider>

                    <v-data-table :headers="headers" :items="divisions" :loading="isLoading" hide-actions>
                        <template v-slot:headers="props">
                            <tr>
                                <th 
                                    v-for="header in props.headers" :key="header.text"
                                    @click="changeSort(header.value, pagination.descending, header)"
                                    :width="header.width" :align="header.align" :class="header.class"
                                >
                                    <!-- <v-icon v-if="pagination.descending === 'asc'" small>arrow_upward</v-icon>
                                    <v-icon v-if="pagination.descending === 'desc'" small>arrow_downward</v-icon> -->

                                    <v-icon 
                                        color="grey lighten-2" small 
                                        v-if=" pagination.sortBy === header.value && header.sort && pagination.descending === 'asc'"
                                    >arrow_downward</v-icon>
                                    
                                    <v-icon  
                                        color="grey lighten-2" small 
                                        v-if="pagination.sortBy === header.value && header.sort && pagination.descending === 'desc'"
                                    >arrow_upward</v-icon>

                                    <v-icon 
                                        color="grey lighten-2" small 
                                        v-if="pagination.sortBy !== header.value && header.sort"
                                    >arrow_upward</v-icon>

                                    {{ header.text }}
                                </th>
                            </tr>
                        </template>
                        <v-progress-linear v-slot:progress color="blue" indeterminate></v-progress-linear>
                        <template v-slot:items="props">
                            <td class="text-xs-center pa-2" v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                @click="selectMe(props.item)">{{ props.item.code }}
                            </td>
                            <td class="text-xs-left pa-2" v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                @click="selectMe(props.item)">{{ props.item.DivisionKodeSurat }}
                            </td>
                            <td class="text-xs-left pa-2" v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                @click="selectMe(props.item)">{{ props.item.name }}
                            </td>
                            <td 
                                class="text-xs-center pa-2" @click="selectMe(props.item)"
                                v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                            >
                                <v-tooltip bottom>
                                        <template v-slot:activator="{ on, attrs }">
                                            <v-icon v-bind="attrs" v-on="on" small class="ml-3" @click="editDivision(props.item)">edit</v-icon>
                                        </template>
                                        <span>Edit</span>
                                </v-tooltip>
                                <v-tooltip bottom>
                                        <template v-slot:activator="{ on, attrs }">
                                            <v-icon v-bind="attrs" v-on="on" small class="ml-3" @click="deleteDivision(props.item)">delete</v-icon>
                                        </template>
                                        <span>Delete</span>
                                </v-tooltip>
          
                            </td>
                        </template>
                        <template v-slot:no-results>
                            <v-alert :value="true" color="error" icon="warning">
                                Pencarian "{{ xsearch }}" tiada hasil.
                            </v-alert>
                        </template>
                    </v-data-table>
                </div>
                <v-divider></v-divider>
                <v-flex xs12 class="text-xs-left pt-3 pb-3">
                    <v-pagination v-model="curr_page" :length="xtotal_page"></v-pagination>
                </v-flex>
            </v-card>
        </v-flex>

    </v-layout>
</template>

<style scoped>


.searchbox .v-input.v-text-field .v-input__slot {
    min-height: 60px;
}

.searchbox .v-btn {
    min-height: 60px;
}

table.v-table tbody td,
table.v-table tbody th {
    height: 40px;
}

table.v-table thead tr {
    height: 40px;
}

.textinput {
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
    background-color: white;
    background-position: 10px 10px;
    background-repeat: no-repeat;
    padding-left: 40px;
    width: 100%;
    padding: 8px 10px;
    margin-bottom: 5px;
    box-sizing: border-box;
    border: 1px solid #607d8b;

}

.textinput:focus {
    width: 100%;
}

.textinput:focus::-webkit-input-placeholder {
    color: transparent;
}

.textinput:focus::-moz-placeholder {
    color: transparent;
}

.textinput:-moz-placeholder {
    color: transparent;
}

.boxoutline {
    color: red;
    border: 1px solid red;
    justify-content: center;
    height: 45px;
    line-height: 45px;
    padding-left: 10px;
    background: #ffffff;
    font-size: 14px;
    font-weight: 500;
    border-radius: 1px
}

.boxoutline:hover {
    background: rgba(0, 0, 0, 0.07) !important;
    font-size: 15px;
    font-weight: 700;
}

.boxsolid {
    color: #ffffff;
    border: 1px solid #ffffff;
    justify-content: center;
    height: 45px;
    line-height: 45px;
    padding-left: 10px;
    background: #f44336;
    font-size: 14px;
    font-weight: 500;
    border-radius: 1px
}

.boxsolid:hover {
    background: #f44336de;
    font-size: 15px;
    font-weight: 700;
}

.scroll-container {
    scroll-padding: 50px 0 0 50px;
}

::-webkit-scrollbar {
    width: 7px;
}

/* this targets the default scrollbar (compulsory) */

::-webkit-scrollbar-track {
    background-color: #f8efd0;
}

/* the new scrollbar will have a flat appearance with the set background color */

::-webkit-scrollbar-thumb {
    background-color: #e9b91b;
}

/* this will style the thumb, ignoring the track */

::-webkit-scrollbar-button {
    background-color: #7b8e1b;
}

/* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

::-webkit-scrollbar-corner {
    background-color: black;
}

/* if both the vertical and the horizontal bars appear, then perhaps the right bottom corner also needs to be styled */
</style>


<script>


module.exports = {

    data() {
        return {
            harga: '',
            jumlah: '',
            total: '',
            windowHeight: window.innerHeight - 300 + 'px',
            page: 1,
            xname: '',
            xlettercode: '',
            valid: false,
            xid: 0,
            isDefault: false,
            xnameRules: [
                v => !!v || 'Nama harus diisi'
            ],
            headers: [{
                text: "KODE",
                align: "left",
                sortable: false,
                sort: true,
                value: "DivisionCode",
                width: "10%",
                class: "pa-2 blue lighten-3 white--text"
            },
            {
                text: "KODE NASKAH",
                align: "left",
                sortable: false,
                sort: true,
                value: "DivisionName",
                width: "10%",
                class: "pa-2 blue lighten-3 white--text"
            },
            {
                text: "NAMA",
                align: "left",
                sortable: false,
                sort: true,
                value: "DivisionName",
                width: "70%",
                class: "pa-2 blue lighten-3 white--text"
            },
            {
                text: "AKSI",
                align: "center",
                sortable: false,
                value: "mr",
                width: "10%",
                class: "pa-2 blue lighten-3 white--text"
            }
            ],

        };
    },
    mounted() {
        // ambil data
        this.$store.commit("divisi/update_last_id", -1)
        this.$store.dispatch("divisi/lookupbyname")
    },
    computed: {
        action_delete: {
            get() {
                return this.$store.state.divisi.action_delete
            },
            set(val) {
                this.$store.commit("divisi/update_action_delete", val)
            }
        },
        msgalert: {
            get() {
                return this.$store.state.divisi.save_error_message
            },
            set(val) {
                this.$store.commit("divisi/update_save_error_message", val)
            }
        },
        dialogdeletealert: {
            get() {
                return this.$store.state.divisi.dialogdeletealert
            },
            set(val) {
                this.$store.commit("divisi/update_dialogdeletealert", val)
            }
        },
        divisions: {
            get() {
                return this.$store.state.divisi.divisions
            },
            set(val) {
                this.$store.commit("divisi/update_divisions", val)
            }
        },

        // paging
        pagination: {
            get() {
                return this.$store.state.divisi.pagination
            },
            set(val) {
                this.$store.commit("divisi/update_pagination", val)
            }
        },
        // current page
        curr_page: {
            get() {
                return this.$store.state.divisi.current_page
            },
            set(val) {
                this.$store.commit("divisi/update_current_page", val)
                this.$store.commit("divisi/update_last_id", -1)
                this.$store.dispatch("divisi/lookupbyname")
            }
        },

        // wkt search
        xsearch: {
            get() {
                return this.$store.state.divisi.x_search
            },
            set(val) {
                this.$store.commit("divisi/update_x_search", val)
            }
        },

        xtotal_page: {
            get() {
                return this.$store.state.divisi.total_divisions
            },
            set(val) {
                this.$store.commit("divisi/update_total_divisions", val)
            }
        },

        xact() {
            return this.$store.state.divisi.act
        },

        // handle error
        xerrors() {
            return this.$store.state.divisi.errors
        },

        dialogdivision: {
            get() {
                return this.$store.state.divisi.dialog_form_division
            },
            set(val) {
                this.$store.commit("divisi/update_dialog_form_division", val)
            }
        },

        isLoading() {
            return this.$store.state.divisi.search_status == 1
        },

        // filter
        xtotalunits() {
            return this.$store.state.divisi.total_units
        },
        xtotalfilterunits() {
            return this.$store.state.divisi.total_filter_units
        },
        formattedValue() {
            return formatNumber(this.total);
        }
    },
    methods: {
       
        // click sort order by
        changeSort(value, sort, header) {
            if (header.sort) {
                var newVal = value
                var newSort = sort == 'asc' ? 'desc' : 'asc'
                if (newVal !== this.pagination.sortBy)
                    newSort = 'asc'
                this.pagination = { descending: newSort, sortBy: newVal }
                // console.log(this.pagination)
                this.$store.commit("divisi/update_last_id", -1)
                this.$store.dispatch("divisi/lookupbyname")
            }
        },

        // tutup dialog
        updateDialogForm() {
            this.$store.commit("divisi/update_dialog_form_division", false)
        },

        // open form
        openFormDivision() {
            console.log('open dialog');
            this.xname = ""
            this.isdefault = "N"
            this.$refs.formdivision.reset()
            this.$refs.formdivision.resetValidation()
            this.$store.commit("divisi/update_act", 'new')
            this.$store.commit("divisi/update_dialog_form_division", true)
        },

        // save form
        saveForm() {
            if (this.$refs.formdivision.validate()) {
                this.$store.dispatch("divisi/add", {
                    name: this.xname,
                    lettercode: this.xlettercode
                })

            }
        },

        // hapus
        deleteDivision(data) {
            this.xid = data.DivisiID
            console.log(data);
            var xdata = {
                id: data.id,
                name: data.name,
            }
            this.$store.commit("divisi/update_selected_division", xdata)
            this.msgalert = "Yakin, mau hapus divisi " + data.name + " ?"
            this.dialogdeletealert = true
            this.action_delete = true
        },

        closeDeleteAlert() {
            this.$store.commit("divisi/update_last_id", -1);
            this.$store.dispatch("divisi/delete", {
                id: this.$store.state.divisi.selected_division.id,
                name: this.$store.state.divisi.selected_division.name,
            })
            this.dialogdeletealert = false
        },

        // hover biru2
        isSelected(p) {
            return p.id == this.$store.state.divisi.selected_division.id
        },
        selectMe(selected) {
            this.$store.commit("divisi/update_selected_division", selected)
            this.$store.commit("divisi/update_last_id", selected.ItemUnitID)
        },
        // edit
        editDivision(data) {
            this.selectMe(data)

            this.xid = data.id
            // this.xcode = data.code
            this.xname = data.name
            this.xlettercode = data.DivisionKodeSurat

            // this.isdefault = data.T_SpecialistIsDefault === 'N' ? false : true
            this.$store.commit("divisi/update_act", 'edit')
            this.$store.commit("divisi/update_dialog_form_division", true)
        },

        // proses edit
        updateForm() {
            if (this.$refs.formdivision.validate()) {
                this.$store.dispatch("divisi/edit", {
                    id: this.xid,
                    name: this.xname,
                    lettercode: this.xlettercode
                })
            }
        },

        // alert
        updateAlert_success(val) {
            this.$store.commit("divisi/update_alert_success", val)
        },

        // search
        thr_search: _.debounce(function () {
            this.$store.commit("divisi/update_last_id", -1)
            this.$store.dispatch("divisi/lookupbyname")

        }, 1000),
       
        // Fungsi format hanya untuk tampilan
        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;
            }
        }
    },
    watch: {
    
        xsearch(val, old) {
            // console.log(val)
            this.xsearch = val
            this.thr_search()

        }
    }
}
</script>