<template>
    <div style="width: 100%;">
        <!-- SNACKBAR -->
        <v-snackbar v-model="snackbar" :timeout="5000" :multi-line="false" :vertical="false" :top="true">
            {{ msgSnackbar }}
            <v-btn flat @click="updateAlertSuccess(false)"> Tutup </v-btn>
        </v-snackbar>

        <!-- ERROR DIALOG -->
        <v-dialog v-model="dialog_error" max-width="500px">
            <v-card>
                <v-card-title>
                    <span>ERROR !</span>
                    <v-spacer></v-spacer>
                </v-card-title>
                <v-divider></v-divider>
                <div class="ma-3 red--text">{{ msgError }}</div>
                <v-divider></v-divider>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="primary" flat @click="dialog_error = false">Tutup</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <!-- END ERROR DIALOG -->
        <v-layout row wrap>
            <v-flex xs12 fill-height>
                <v-toolbar color="primary" dark>
                    <v-toolbar-title class="white--text">SUPPLIER</v-toolbar-title>
                    <v-spacer></v-spacer>
                    <v-btn icon @click="openDialogSupplier()">
                        <v-icon>add_box</v-icon>
                    </v-btn>
                </v-toolbar>
                <v-card class="pa-2">
                    <v-layout>
                        <v-flex xs3 pl-2>
                            <v-text-field label="Cari..." placeholder="Supplier" outline v-model="xsearch"
                                hide-details></v-text-field>
                        </v-flex>
                        <v-flex pl-2 pr-2>
                            <v-btn dark color="primary" style="min-width: 50px; height: 50px; margin: 0"
                                @click="mainTableSearch()">
                                <v-icon>search</v-icon>
                            </v-btn>
                        </v-flex>
                    </v-layout>
                </v-card>
                <v-card class="pa-2 mt-2">
                    <v-layout row style="max-height: 600px; overflow: auto">
                        <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                            <v-data-table :items="suppliers" :headers="headers" :loading="isLoading" hide-actions
                                class="elevation-1">
                                <template slot="items" slot-scope="props">
                                    <td class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)">{{ props.item.SupplierCode }}</td>
                                    <td class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)">{{ props.item.SupplierName }}</td>
                                    <!-- <td
                                        class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)"
                                    >{{ props.item.SupplierPpnPct }}</td>
                                    <td
                                        class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)"
                                    >{{ props.item.SupplierPphPct }}</td> -->
                                    <td class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)">{{
                                            props.item.SupplierAddress ? props.item.SupplierAddress : "-" }}</td>
                                    <td class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)">{{
                                            props.item.SupplierPhone ? props.item.SupplierPhone : "-" }}</td>
                                    <td class="text-xs-left pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)">{{ props.item.SupplierPIC ? props.item.SupplierPIC
                                            :
                                            "-" }}</td>
                                    <td class="text-xs-center pa-2"
                                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                                        @click="selectMe(props.item)">
                                        <v-icon small @click="openUpdateSupplier(props.item)">edit</v-icon>
                                        <v-icon small @click="deleteSupplier(props.item)">delete</v-icon>
                                    </td>
                                </template>
                            </v-data-table>
                        </v-flex>
                    </v-layout>
                    <v-divider></v-divider>
                    <v-pagination style="margin-top: 10px; margin-bottom: 10px" v-model="curr_page"
                        :length="xtotal_page"></v-pagination>
                </v-card>
            </v-flex>
        </v-layout>

        <!-- form -->
        <template>
            <v-layout row justify-center>
                <v-dialog v-model="dialogForm" persistent max-width="40vw">
                    <v-card>
                        <v-card-title class="headline grey lighten-2" primary-title>
                            FORM SUPPLIER
                        </v-card-title>
                        <v-card-text class="pt-2 pb-0">
                            <v-layout wrap>
                                <v-flex xs12 pa-2>
                                    <v-text-field label="Nama Supplier*" v-model="nameSupplier"
                                        hide-details></v-text-field>
                                    <p v-if="checkErrorForm('requireSupplierName')" class="error pl-2 pr-2"
                                        style="color:#fff">Nama harus diisi</p>
                                </v-flex>
                                <v-flex xs12 pa-2>
                                    <v-layout row>
                                        <v-flex>
                                            <v-textarea label="Alamat Supplier" v-model="supplierAddress" outline
                                                hide-details></v-textarea>
                                        </v-flex>
                                    </v-layout>
                                </v-flex>
                                <v-flex xs12 pa-2>
                                    <v-layout row>
                                        <v-flex>
                                            <v-text-field 
                                                label="Term Of Payment" type="number" suffix="hari"
                                                v-model="termofpay" outline hide-details 
                                            ></v-text-field>
                                            <p v-if="toperror" class="error pl-2 pr-2" style="color:#fff">
                                                Jumlah tidak boleh negatif
                                            </p>
                                        </v-flex>
                                    </v-layout>
                                </v-flex>
                                <v-flex xs12 pa-2>
                                    <v-layout row>
                                        <v-flex>
                                            <v-text-field label="Supplier Phone" type="" v-model="supplierPhone" outline
                                                hide-details @keypress="onlyNumber($event)"
                                                @input="filterNumber('supplierPhone')"></v-text-field>
                                        </v-flex>
                                    </v-layout>
                                </v-flex>
                                <v-flex xs12 pa-2>
                                    <v-layout row>
                                        <v-flex>
                                            <v-text-field label="PIC" v-model="supplierPIC" outline
                                                hide-details></v-text-field>
                                        </v-flex>
                                    </v-layout>
                                </v-flex>
                                <v-flex xs12 pa-2>
                                    <v-layout row>
                                        <v-flex>
                                            <v-text-field label="PIC Email" v-model="supplierPICEmail" outline
                                                type="email" @input="validateEmail" hide-details></v-text-field>
                                            <p v-if="emailError && supplierPICEmail" class="error pl-2 pr-2" style="color:#fff">
                                                Format Email Tidak Sesuai
                                            </p>
                                        </v-flex>
                                    </v-layout>
                                </v-flex>
                                <v-flex xs12 pa-2>
                                    <v-layout row>
                                        <v-flex>
                                            <v-text-field label="PIC Phone" v-model="supplierPICPhone" outline
                                                hide-details @keypress="onlyNumber($event)"
                                                @input="filterNumber('supplierPICPhone')"></v-text-field>
                                        </v-flex>
                                    </v-layout>
                                </v-flex>
                                <v-flex xs12 pa-2>
                                    <v-layout row>
                                        <v-flex>
                                            <v-text-field label="PIC Hp" v-model="supplierPICHp" outline hide-details
                                                @keypress="onlyNumber($event)"
                                                @input="filterNumber('supplierPICHp')"></v-text-field>
                                        </v-flex>
                                    </v-layout>
                                </v-flex>
                            </v-layout>
                        </v-card-text>
                        <v-card-actions>
                            <v-spacer></v-spacer>
                            <v-btn color="error" flat @click="closeDialogForm()">
                                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>
            </v-layout>
        </template>
        <!-- end form -->

        <template>
            <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>
                                                Yakin, mau hapus Item : <span class="font-weight-bold">{{ msgalertname
                                                }}</span> ?
                                            </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 color="primary" @click="closeDeleteAlert()">
                            Yakin lah
                        </v-btn>
                    </v-card-actions>
                </v-card>
            </v-dialog>
        </template>

    </div>
</template>

<style scoped>
.date-type-table {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

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

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

.scroll-container {
    scroll-padding: 50px 0 0 50px;
}
</style>

<script>
module.exports = {
    components: {
        "dialog-form-voucher": httpVueLoader("./dialogFormVoucher.vue"),
        "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
        "one-dialog-error": httpVueLoader("../../common/oneDialogError.vue")
    },
    data() {
        return {
            termofpay: 0,
            toperror: false,
            nameSupplier: "",
            supplierAddress: "",
            supplierPhone: "",
            supplierPIC: "",
            supplierPICEmail: "",
            supplierPICPhone: "",
            supplierPICHp: "",
            emailError: false,
            IsPpn: false,
            IsPph: false,
            PpnPercent: 0,
            PphPercent: 0,
            xid: 0,
            dialogdeletealert: false,
            msgalertname: "",
            codeSupplier: "",
            headers: [
                {
                    text: "KODE",
                    align: "left",
                    sortable: false,
                    value: "no",
                    width: "10%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "NAMA",
                    align: "left",
                    sortable: false,
                    value: "date",
                    width: "20%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "ALAMAT",
                    align: "left",
                    sortable: false,
                    value: "total",
                    width: "50%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "PHONE",
                    align: "left",
                    sortable: false,
                    value: "status",
                    width: "10%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "PIC",
                    align: "left",
                    sortable: false,
                    value: "status",
                    width: "10%",
                    class: "blue lighten-3 white--text",
                },
                {
                    text: "AKSI",
                    align: "left",
                    sortable: false,
                    value: "status",
                    width: "10%",
                    class: "blue lighten-3 white--text",
                },
            ],
        }
    },
    mounted() {
        this.$store.dispatch("supplier/search")
    },
    computed: {
        suppliers() {
            return this.$store.state.supplier.suppliers
        },
        isLoading() {
            return this.$store.state.supplier.search_status == 1
        },
        xsearch: {
            get() {
                return this.$store.state.supplier.xsearch
            },
            set(val) {
                this.$store.commit("supplier/update_xsearch", val)
            }
        },
        curr_page: {
            get() {
                return this.$store.state.supplier.current_page
            },
            set(val) {
                this.$store.commit("supplier/update_current_page", val)
                this.$store.commit("supplier/update_last_id", -1)
                this.$store.dispatch("supplier/search")
            }
        },
        xtotal_page: {
            get() {
                return this.$store.state.supplier.total_page
            },
            set(val) {
                this.$store.commit("supplier/update_total_page", val)
            }
        },
        dialogForm: {
            get() {
                return this.$store.state.supplier.dialog_form
            },
            set(val) {
                this.$store.commit("supplier/update_dialog_form", val)
            }
        },
        xact: {
            get() {
                return this.$store.state.supplier.act
            },
            set(val) {
                this.$store.commit("supplier/update_act", val)
            }
        },
        snackbar: {
            get() {
                return this.$store.state.supplier.alert_success
            },
            set(val) {
                this.$store.commit("supplier/update_alert_success", val)
            }
        },
        msgSnackbar() {
            return this.$store.state.supplier.msg_success;
        },
        dialog_error: {
            get() {
                return this.$store.state.supplier.alert_error
            },
            set(val) {
                this.$store.commit("supplier/update_alert_error", val)
            },
        },
        msgError() {
            return this.$store.state.supplier.save_error_message
        },
    },
    methods: {
        validateEmail() {
            const email = this.supplierPICEmail;
            this.emailError = !!email && !/^[^@]+@[^@]+$/.test(email);
        },
        onlyNumber(e) {
            // hanya izinkan angka (0-9)
            const char = String.fromCharCode(e.keyCode);
            if (!/[0-9]/.test(char)) {
                e.preventDefault();
            }
        },
        filterNumber(field) {
            // filter agar hanya angka yang boleh diinput (untuk copy-paste)
            this[field] = this[field].replace(/\D/g, '');
        },
        isSelected(p) {
            return p.SupplierID == this.$store.state.supplier.selected_supplier.SupplierID
        },
        selectMe(sc) {
            this.$store.commit("supplier/update_selected_supplier", sc)
            this.$store.dispatch("supplier/searchdetail")
        },
        thr_search: _.debounce(function () {
            this.$store.dispatch("supplier/search")
        }, 1000),
        mainTableSearch() {
            this.$store.dispatch("supplier/search")
            this.$store.commit("supplier/update_selected_supplier", {})
            this.$store.commit("supplier/update_supplier_prices", [])
            this.$store.commit("supplier/update_total_page_supplier_price", 0)
        },
        openDialogSupplier() {
            this.$store.commit("supplier/update_dialog_form", true)
            this.$store.commit("supplier/update_act", "new")
            this.$store.commit("supplier/update_errors", [])
            this.nameSupplier = ""
            this.supplierAddress = ""
            this.supplierPhone = ""
            this.supplierPic = ""
            this.supplierPICEmail = ""
            this.supplierPICPhone = ""
            this.supplierPICHp = ""
            this.emailError = false
            this.IsPpn = false
            this.IsPph = false
            this.PpnPercent = 0
            this.PphPercent = 0
        },
        closeDialogForm() {
            this.$store.commit("supplier/update_dialog_form", false)
        },
        // check error form
        checkErrorForm(value) {
            var errors = this.$store.state.supplier.errors
            if (errors.includes(value)) {
                return true
            } else {
                return false
            }
        },

        clearPpnPercent() {
            if (this.PpnPercent === 0) {
                this.PpnPercent = ''
            }
        },
        resetPpnPercent() {
            if (this.PpnPercent === '' || this.PpnPercent === null) {
                this.PpnPercent = 0
            }
        },

        clearPphPercent() {
            if (this.PphPercent === 0) {
                this.PphPercent = ''
            }
        },
        resetPphPercent() {
            if (this.PphPercent === '' || this.PphPercent === null) {
                this.PphPercent = 0
            }
        },

        // save
        saveForm() {
            this.$store.commit("supplier/update_errors", [])
            var errors = this.$store.state.supplier.errors

            if (_.isEmpty(this.nameSupplier)) {
                errors.push("requireSupplierName")
            }

            if (this.supplierPICEmail && !/^[^@]+@[^@]+$/.test(this.supplierPICEmail)) {
                this.emailError = true;
                return; // stop submit jika email tidak valid
            } else {
                this.emailError = false;
            }

            if (Number(this.termofpay) < 0) {
                this.toperror = true
                return;
            } else {
                this.toperror = false
            }

            if (errors.length === 0) {
                this.$store.commit("supplier/update_errors", [])

                var prm = {
                    nameSupplier: this.nameSupplier,
                    SupplierAddress: this.supplierAddress,
                    SupplierTOP: this.termofpay,
                    SupplierPhone: this.supplierPhone,
                    SupplierPIC: this.supplierPIC,
                    SupplierPICEmail: this.supplierPICEmail,
                    SupplierPICPhone: this.supplierPICPhone,
                    SupplierPICHp: this.supplierPICHp,
                    isPpn: this.IsPpn === true ? 'Y' : 'N',
                    isPph: this.IsPph === true ? 'Y' : 'N',
                    PpnPercent: this.PpnPercent,
                    PphPercent: this.PphPercent
                }
                this.$store.dispatch("supplier/save", prm)
            }
        },

        openUpdateSupplier(val) {
            this.$store.commit("supplier/update_errors", [])
            this.$store.commit("supplier/update_dialog_form", true)
            this.$store.commit("supplier/update_act", "edit")
            this.nameSupplier = val.SupplierName
            this.supplierAddress = val.SupplierAddress
            this.termofpay = val.SupplierTermOfPayment
            this.supplierPhone = val.SupplierPhone
            this.supplierPIC = val.SupplierPIC
            this.supplierPICEmail = val.SupplierPICEmail
            this.supplierPICPhone = val.SupplierPICPhone
            this.supplierPICHp = val.SupplierPICHp
            this.IsPpn = val.SupplierIsPpn === 'Y' ? true : false
            this.IsPph = val.SupplierIsPph === 'Y' ? true : false
            this.PpnPercent = val.SupplierPpnPct
            this.PphPercent = val.SupplierPphPct
            this.xid = val.SupplierID
        },

        updateForm() {
            this.$store.commit("supplier/update_errors", [])
            var errors = this.$store.state.supplier.errors

            if (_.isEmpty(this.nameSupplier)) {
                errors.push("requireSupplierName")
            }

            if (this.supplierPICEmail && !/^[^@]+@[^@]+$/.test(this.supplierPICEmail)) {
                this.emailError = true;
                return; // stop submit jika email tidak valid
            } else {
                this.emailError = false;
            }

            if (Number(this.termofpay) < 0) {
                this.toperror = true
                return;
            } else {
                this.toperror = false
            }

            if (errors.length === 0) {
                this.$store.commit("supplier/update_errors", [])

                var prm = {
                    nameSupplier: this.nameSupplier,
                    SupplierAddress: this.supplierAddress,
                    SupplierTOP: this.termofpay,
                    SupplierPhone: this.supplierPhone,
                    SupplierPIC: this.supplierPIC,
                    SupplierPICEmail: this.supplierPICEmail,
                    SupplierPICPhone: this.supplierPICPhone,
                    SupplierPICHp: this.supplierPICHp,
                    isPpn: this.IsPpn === true ? 'Y' : 'N',
                    isPph: this.IsPph === true ? 'Y' : 'N',
                    PpnPercent: this.PpnPercent,
                    PphPercent: this.PphPercent,
                    supplier_id: this.xid
                }
                this.$store.dispatch("supplier/update", prm)
            }
        },

        deleteSupplier(val) {
            this.xid = val.SupplierID
            this.msgalertname = val.SupplierCode + " " + val.SupplierName
            this.codeSupplier = val.SupplierCode
            this.dialogdeletealert = true
        },
        closeDeleteAlert() {
            this.dialogdeletealert = false
            this.$store.dispatch("supplier/deletesupplier", {
                supplier_id: this.xid,
                codeSupplier: this.codeSupplier
            })
        }
    },
    watch: {
        xsearch(val, old) {
            this.xsearch = val
            this.thr_search()
        },
    }
}
</script>