//IMPORTS AND CONFIGS
require('./bootstrap');
window.Vue = require('vue').default;
import App from './App.vue';
import Vue from 'vue';
import VueAxios from 'vue-axios';
import VueRouter from 'vue-router';
import axios from 'axios';
import { routes } from './routes';
import { modals } from './modals'; //FOR MODALS
import VueSimpleAlert from "vue-simple-alert"; //SIMPLE ALERT BOX (OK/CANCEL)
import VueLoading from 'vuejs-loading-plugin'; //LOADER
import Datepicker from 'vuejs-datepicker'; //CUSTOM DATE PICKER
import moment from 'moment'; //DATE FORMATTER
import VueSession from 'vue-session';
import VueCookies from 'vue-cookies';
import VueNotifications from 'vue-notifications';
import iziToast from 'izitoast'; // https://github.com/dolce/iziToast
import 'izitoast/dist/css/iziToast.min.css';
import Viewer from 'v-viewer';
import 'viewerjs/dist/viewer.css';
import 'vue-search-select/dist/VueSearchSelect.css';
import _, { isArray } from 'lodash';
import { ModelSelect } from 'vue-search-select';
import Paginator from './test.vue';


function toast({ title, message, type, timeout, cb }) {
    if (type === VueNotifications.types.warn) type = 'warning'
    return iziToast[type]({ title, message, timeout })
}

const options = {
    success: toast,
    error: toast,
    info: toast,
    warn: toast
}


//GLOBAL VARIABLES
Vue.prototype.$defloc = window.location.origin;
Vue.prototype.$modals = modals;
Vue.prototype.$popup_params = [];
//GLOBAL FOR REPORTS
Vue.prototype.$reportHeader = `
    <div>
        <div class="disp-center-margin-vrt" style="height: fit-content; width: fit-content; margin-bottom: 10px">
            <div class="disp-style-row">
                <img src="./images/logo.png" class="report-logo">
                <p class="reportheader-paragraph">
                    Benguet Electric Cooperative, Inc. (BENECO)<br>
                    South Drive Baguio City, 2600<br>
                    Contact No.: 092375828732/ (074)662-2845
                </p>
            </div>
        </div>
        <hr>
    </div>
`;
Vue.prototype.$reportFooter1 = `
    <div>
        <div class="disp-center-margin-vrt disp-style-row" style="justify-content: center; width: 100%">
            <div style="width: 260px">
                <p style="text-align: center; width: 200px; margin: 0 auto">Rafael, Ana Maria Paz B.</p>
                <br>
                <hr>
                <h6 style="text-align: center">General Manager</h6>
            </div>
        </div>
    </div>
    <br>
`;
Vue.prototype.$reportFooter2 = `
    <div>
        <div class="disp-center-margin-vrt" style="height: fit-content; width: fit-content;">
            <h5 style="text-align: center">Benguet Electric Cooperative, Inc. (BENECO)<br>
            South Drive Baguio City, 2600</h5>
        </div>
    </div>
    <hr>
    <br>
`;


//VUE SETUPS
Vue.use(VueNotifications, options);
Vue.use(VueCookies, { expire: '1d' });
Vue.use(VueSession);
Vue.use(VueSimpleAlert);
Vue.use(Datepicker); //USE CUSTOM DATE AND TIME PICKER
Vue.use(VueRouter);
Vue.use(VueAxios, axios);
Vue.use(VueLoading);
Vue.component('model-select', ModelSelect); //THIS IS HOW TO REGISTER CUSTOM COMPONENTS. PARAMETERS(NAME, COMPONENT)
Vue.component('datepicker', Datepicker); //THIS IS HOW TO REGISTER CUSTOM COMPONENTS. PARAMETERS(NAME, COMPONENT)
Vue.component('Paginator', Paginator); //THIS IS HOW TO REGISTER CUSTOM COMPONENTS. PARAMETERS(NAME, COMPONENT)
Vue.use(Viewer, {
    defaultOptions: {
        zIndex: 9999,
        initialViewIndex: 0
    }
})

Vue.filter('formatDate', function(value) {
    if (value) {
        return moment(String(value)).format('MM/DD/YYYY')
    }
});

Vue.filter('formatMMMMddyyyhhmmtt', function(value) {
    if (value) {
        return moment(String(value)).format('MMMM DD, YYYY h:mm A')
    }
});

Vue.filter('formatMMMMddyyy', function(value) {
    if (value) {
        return moment(String(value)).format('MMMM DD, YYYY')
    }
});

//GLOBAL FUNCTIONS
Vue.mixin({
    notifications: {
        showSuccessMsg: {
            type: VueNotifications.types.success,
            title: 'Hello there',
            message: 'That\'s the success!',
            timeout: 3500
        },
        showInfoMsg: {
            type: VueNotifications.types.info,
            title: 'Hey you',
            message: 'Here is some info for you',
            timeout: 3500
        },
        showWarnMsg: {
            type: VueNotifications.types.warn,
            title: 'Wow, man',
            message: 'That\'s the kind of warning',
            timeout: 3500
        },
        showErrorMsg: {
            type: VueNotifications.types.error,
            title: 'Wow-wow',
            message: 'That\'s the error',
            timeout: 3500
        }
    },
    methods: {
        _fileURL(data) {
            var tmp = "";
            try { tmp = window.location.origin + "/common/" + data.replace(/\\/g, ''); } catch {}
            return tmp;
        },
        _getFileExt(data) {
            var str = "";
            try {
                var tmp = data.split('.');
                str = tmp[tmp.length - 1].toUpperCase();
            } catch {}
            return str;
        },
        _arrToList(tmp) {
            var str = "";
            try {
                var list = JSON.parse(tmp);
                for (var x = 0; x < list.length; x++)
                    str += list[x] + '<br>';

                str = str.substring(0, str.length - 4);
            } catch {}

            return str;
        },
        _keypressEnter(evt, func) {
            if (evt.keyCode === 13) {
                func();
            }
        },
        _getFileName(inputFile) {
            return $('#' + inputFile).val().split('\\').pop();
        },
        _keypressDecimal: function(evt, decplaces = 2) {
            var charCode = parseInt((evt.which) ? evt.which : event.keyCode);
            var input = $(evt.target).val();

            try {
                if (input.split('.')[1].length >= decplaces)
                    evt.preventDefault();
            } catch {}
            if ((charCode < 48 && charCode !== 46) || charCode > 57 || (charCode === 46 && input.includes('.')))
                evt.preventDefault();
        },
        _formatCD(tmpval) {
            var value = parseFloat(tmpval);
            let val = (value / 1).toFixed(2).replace(',', '.')
            return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        },
        _formatToPeso(tmpval) {
            var value = parseFloat(tmpval);
            let val = (value / 1).toFixed(2).replace(',', '.')
            return "₱ " + val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        },
        _fileExists: function(urlToFile, cbtrue, cbfalse) {
            if (urlToFile !== "") {
                var tmpArr = urlToFile.split('/');
                this._vueGETfromParam(
                    'main_controller',
                    'checkFile', { filePath: tmpArr },
                    response => {
                        if (response === 1)
                            cbtrue();
                        else
                            cbfalse();
                    }
                );
            }
        },
        _uploadFile: function(file, dir, func = () => {}) {
            var finalRes = [];

            if (!Array.isArray(file)) {
                let data = new FormData();
                data.append('file', file);
                data.append('dir', dir);
                axios.post('/upload-file',
                        data, {
                            headers: {
                                'content-type': 'multipart/form-data',
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                        })
                    .then(function(res) {
                        if (res.data.output === 'success')
                            func(res.data.result.replace(/\\\\/g, '\\/'));
                        else
                            func(res.data.result);
                    })
                    .catch(function(err) {
                        func('ERROR: ' + err);
                    });
            } else {
                var done = 0;
                for (var x = 0; x < file.length; x++) {
                    let data = new FormData();
                    try {
                        if (URL.createObjectURL(file[x]).length > 0) {
                            data.append('file', file[x]);
                            data.append('dir', dir);
                            axios.post('/upload-file',
                                    data, {
                                        headers: {
                                            'content-type': 'multipart/form-data',
                                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                        }
                                    })
                                .then(function(res) {
                                    done++;
                                    if (res.data.output === 'success' && done === file.length)
                                        func(res.data.result.replace(/\\\\/g, '\\/'));
                                    else if (res.data.output !== 'success' && done === file.length)
                                        func(res.data.result);
                                })
                                .catch(function(err) {
                                    done++;
                                    if (done === file.length)
                                        func('ERROR: ' + err);
                                });
                        } else {
                            done++;
                            func(res.data.result.replace(/\\\\/g, '\\/'));
                        }
                    } catch { done++; }
                }
            }
        },
        _openImage: function(title = "", url) {
            this.$loading(true);
            this._fileExists(url,
                () => {},
                () => {
                    this.$loading(false);
                    this.showErrorMsg({
                        type: VueNotifications.types.error,
                        title: 'Ooops!',
                        message: 'Internal error has occured! Invalid Path or File does not exist!',
                        timeout: 3500
                    });
                });
        },
        _openInNewTab: function(url) {
            if (typeof url !== 'undefined' && url !== null && url !== '') {
                this.$loading(true);
                this._fileExists(url,
                    () => {
                        this.$loading(false);
                        let route = this.$router.resolve({ path: "/common/" + url });
                        window.open(route.href);
                    },
                    () => {
                        this.$loading(false);
                        this.showErrorMsg({
                            type: VueNotifications.types.error,
                            title: 'Ooops!',
                            message: 'Internal error has occured! Invalid Path or File does not exist!',
                            timeout: 3500
                        });
                    });
            } else
                this.showErrorMsg({
                    type: VueNotifications.types.error,
                    title: 'Ooops!',
                    message: 'File Path is invalid/blank!',
                    timeout: 3500
                });
        },
        _boolIFStrExists: function(input) {
            var output = false;
            try {
                if (input.trim() !== '' && input !== undefined && input !== null && typeof input !== 'undefined')
                    output = true;
            } catch {}
            return output;
        },
        _strIFStrExists: function(input) {
            var output = '';
            try {
                if (input !== undefined && input !== null && typeof input !== 'undefined')
                    output = input;
            } catch {}
            return output;
        },
        _nullIFKeyExists: function(obj, key) {
            var output = null;
            try {
                if (obj !== undefined && obj !== null && typeof obj !== 'undefined')
                    output = obj[key];
            } catch {}
            return output;
        },
        _strIFKeyExists: function(obj, key) {
            var output = '';
            try {
                if (obj !== undefined && obj !== null && typeof obj !== 'undefined')
                    output = obj[key];
            } catch {}
            return output;
        },
        _strFormat: function() {
            var args = arguments;
            return this.replace(/{(\d+)}/g, function(match, number) {
                return typeof args[number] != 'undefined' ?
                    args[number] :
                    match;
            });
        },
        _addPopup: function(name, params = {}, func = () => {}) {
            this.$popup_params.push(params);
            this.$root.$emit('addPopup', modals.find(data => data.name === name).modal, func);
        },
        _closePopup: function() {
            this.$root.$emit('closePopup');
        },
        _runCallback: function(index, params = null) {
            this.$root.$emit('runCallback', index, params);
        },
        _addImage: function(url, custID) {
            this.$root.$emit('addImage', url, custID);
        },
        _removeImage: function(id) {
            this.$root.$emit('removeImage', id);
        },
        _showImage: function(id = -1) {
            this.$root.$emit('showImage', id);
        },
        _removeImage: function(id = 0) {
            this.$root.$emit('showImage');
        },
        _clearImage: function() {
            this.$root.$emit('clearImage');
        },
        _decimalInput: function(evt, decPlaces = 2) {
            var key = parseInt(evt.keyCode);
            if (!(key >= 46 && key <= 57) || key === 47 || (key === 46 && evt.target.value.includes('.')))
                evt.preventDefault();

            if (evt.target.value.includes('.')) {
                var tmp = evt.target.value.split('.')[1];
                if (tmp.length > decPlaces - 1) {
                    evt.preventDefault();
                }
            }
        },
        _numericInput: function(evt) {
            var key = parseInt(evt.keyCode);
            if (!(key >= 48 && key <= 57))
                evt.preventDefault();
        },
        _generateParams: function(type, params) {
            return JSON.stringify({
                'type': type,
                'data': params
            });
        },
        _vuePATCH: function(ctrlname, unique = "", data = {}, func = function() {}, type = "") {
            this.axios
                .patch(this.$defloc + '/api/' + ctrlname + '/' + unique, (type !== '' ? { type: type, data: data } : data))
                .then(response => {
                    if (typeof func === 'function')
                        func(response.data);
                });
        },
        _vuePOST: function(ctrlname, data = {}, func = function() {}) {
            this.axios
                .post(this.$defloc + '/api/' + ctrlname, data)
                .then(response => {
                    if (typeof func === 'function')
                        func(response.data);
                });
        },
        _vueGETfromVar: function(ctrlname, variable = "", func = function() {}) {
            var data = [];
            this.axios
                .get(this.$defloc + '/api/' + ctrlname + '/' + variable)
                .then(response => {
                    data = response.data;
                    if (typeof func === 'function')
                        func(response.data);
                });
        },
        _vueGETfromParam: function(ctrlname, type = "", params = "", func = function() {}) {
            var data = [];
            this.axios
                .get(this.$defloc + '/api/' + ctrlname + '/' + JSON.stringify({
                    'type': type,
                    'data': params
                }))
                .then(response => {
                    data = response.data;
                    if (typeof func === 'function')
                        func(response.data);
                });
        },
        _vueGETtoArray: function(ctrlname, type = "", params = "") {
            var data = [];
            this.axios
                .get(this.$defloc + '/api/' + ctrlname + '/' + JSON.stringify({
                    'type': type,
                    'data': params
                }))
                .then(response => {
                    data = response.data;
                    return data;
                });
        },
        _vueDelete: function(ctrlname, id, func = function() {}) {
            this.axios
                .delete(this.$defloc + `/api/` + ctrlname + `/${id}`)
                .then(response => {
                    if (typeof func === 'function')
                        func(response.data);
                });
        },
        _vueObjDelete: function(ctrlname, id, func = function() {}) {
            this.axios
                .delete(this.$defloc + `/api/` + ctrlname + `/` + JSON.stringify(id))
                .then(response => {
                    if (typeof func === 'function')
                        func(response.data);
                });
        },
        _softInsert: function(jsondata, data) {
            let tmpData = jsondata.push(data);
            return tmpData;
        },
        _softDelete: function(jsondata, id) {
            let i = jsondata.map(data => data.id).indexOf(id);
            jsondata.splice(i, 1);
            return jsondata;
        },
        _pad: function(num, size) {
            num = num.toString();
            while (num.length < size) num = "0" + num;
            return num;
        },
        _validIndexpage(page = '') {
            return page === 'admin.index' ||
                page === 'bcda.index' ||
                page === 'biz.index' ||
                page === 'cecapplication.index' ||
                page === 'customs.index' ||
                page === 'eamd_cecapplication.index' ||
                page === 'event.index' ||
                page === 'finance.index' ||
                page === 'hr.index' ||
                page === 'ict.index' ||
                page === 'inspector.index' ||
                page === 'job-applicant.profile' ||
                page === 'lcp.index' ||
                page === 'locator.profile' ||
                page === 'management_vp.index' ||
                page === 'management.index' ||
                page === 'obo.index' ||
                page === 'osac.index' ||
                page === 'sezad.dashboard';
        },
        _printToPaper(contents, size = "8.5in 5.5in", margin = "10px", view = false) {
            var margin = '20px'
            var currentDate = moment().format('MMMM DD, YYYY. h:mm:ss A');
            var reportWindow = window.open('', 'PRINT', "width=" + screen.availWidth + ",height=" + screen.availHeight);
            var headerContent = '';
            var title = '';
            var footerContent = '';

            reportWindow.document.write(`
            <html>
                <head>
                    <link href="/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
                    <link href="/css/git-reporting.css" type="text/css" rel="stylesheet" />
                    <style type="text/css">
                        @page { 
                            size: ` + size + `;
                            margin: ` + margin + `; 
                        }
                        @media screen {
                            table { page-break-inside:auto }
                            tr    { page-break-inside:avoid; page-break-after:auto }
                            thead { display:table-header-group }
                            tfoot { display:table-footer-group }
                        }
                        @media print {
                            table { page-break-inside:auto }
                            tr    { page-break-inside:avoid; page-break-after:auto }
                            thead { display:table-header-group }
                            tfoot { display:table-footer-group }
                            @page {
                                size: ` + size + `;
                            }
                        }
                    </style>
                </head>
                <body style="width: 100vw; height: 100vh">
                <table>
                    <thead style="report-header-thead">
                        <tr><th>` + headerContent + `</th></tr>
                    </thead>
                    <tbody>
                    <tr><td>
                    <div class="disp-style-row" style="background-color: #E0E0E0; margin-bottom: 10px">
                        <div class="report-print-date">` + currentDate + `</div>
                        <div class="report-title">` + title + `</div>
                    </div>` +
                contents +
                `</td></tr>
                    </tbody>
                    <tfoor>
                        <tr><th style="padding-top: 20px">` + footerContent + `</th></tr>
                    </tfoot>
                </table>
                </body>
                </html>`);

            reportWindow.document.close(); // necessary for IE >= 10
            reportWindow.focus(); // necessary for IE >= 10*/

            if (!view) {
                setTimeout(() => {
                    reportWindow.print();
                    reportWindow.close();
                }, 500);
            }
        },
        _printReport(contents, reportTitle, landscape = false, shortbond = false, view = false, headerContent = this.$reportHeader, footerContent = this.$reportFooter1, margin = '20px') {
            var currentDate = moment().format('MMMM DD, YYYY. h:mm:ss A');
            var reportWindow = window.open('', 'PRINT', "width=" + screen.availWidth + ",height=" + screen.availHeight);
            reportWindow.document.write(`
            <html>
                <head>
                    <link href="/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
                    <link href="/css/git-reporting.css" type="text/css" rel="stylesheet" />
                    <style type="text/css">
                        @page { 
                            size: ` + (shortbond ? (landscape ? '11in 8.5in;' : '8.5in 11in') : (landscape ? '13in 8.5in;' : '8.5in 13in')) + `
                            margin: ` + margin + `; 
                        }
                        @media screen {
                            table { page-break-inside:auto }
                            tr    { page-break-inside:avoid; page-break-after:auto }
                            thead { display:table-header-group }
                            tfoot { display:table-footer-group }
                        }
                        @media print {
                            table { page-break-inside:auto }
                            tr    { page-break-inside:avoid; page-break-after:auto }
                            thead { display:table-header-group }
                            tfoot { display:table-footer-group }
                            @page {
                                size: ` + (shortbond ? (landscape ? '11in 8.5in;' : '8.5in 11in') : (landscape ? '13in 8.5in;' : '8.5in 13in')) + `
                            }
                        }
                    </style>
                </head>
                <body style="width: 100vw; height: 100vh">
                <table>
                    <thead style="report-header-thead">
                        <tr><th>` + headerContent + `</th></tr>
                    </thead>
                    <tbody>
                    <tr><td>
                    <div class="disp-style-row" style="background-color: #E0E0E0; margin-bottom: 10px">
                        <div class="report-print-date">` + currentDate + `</div>
                        <div class="report-title">` + reportTitle + `</div>
                    </div>` +
                contents +
                `</td></tr>
                    </tbody>
                    <tfoor>
                        <tr><th style="padding-top: 20px">` + footerContent + `</th></tr>
                    </tfoot>
                </table>
                </body>
                </html>`);

            reportWindow.document.close(); // necessary for IE >= 10
            reportWindow.focus(); // necessary for IE >= 10*/

            if (!view) {
                setTimeout(() => {
                    reportWindow.print();
                    reportWindow.close();
                }, 500);
            }
        },
        _formatThCom(input) {
            if (typeof input !== 'undefined' && input !== '')
                return input.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            else
                return "";
        },
        _checkUndefined(input) {
            if (typeof input !== 'undefined' && input !== '')
                return input;
            else
                return "";
        },
        _keyDownMobile(data, evt, id) {
            try {
                var val = parseInt(evt.keyCode);
                if (val > 47 && val < 58 && data.find(x => x.id === id).number.length < 13) {
                    var tmp = data.find(x => x.id === id).number;
                    if (tmp.length === 4 || tmp.length === 9)
                        data.find(x => x.id === id).number += '-';

                    data.find(x => x.id === id).number += evt.key;
                } else if (val === 8) {
                    var tmp = data.find(x => x.id === id).number;
                    data.find(x => x.id === id).number = tmp.substring(0, tmp.length - 1);
                }
            } catch {}
            evt.preventDefault();
        },
        _keyDownLandline(data, evt, id) {
            try {
                var val = parseInt(evt.keyCode);
                if (val > 47 && val < 58 && data.find(x => x.id === id).number.length < 12) {
                    var tmp = data.find(x => x.id === id).number;
                    if (tmp.length === 3 || tmp.length === 7)
                        data.find(x => x.id === id).number += '-';

                    data.find(x => x.id === id).number += evt.key;
                } else if (val === 8) {
                    var tmp = data.find(x => x.id === id).number;
                    data.find(x => x.id === id).number = tmp.substring(0, tmp.length - 1);
                }
            } catch {}
            evt.preventDefault();
        },
        _jsonToStrList(data) {
            var output = "";

            try {
                var tmp = [];
                if (isArray(data))
                    tmp = data;
                else
                    tmp = JSON.parse(data);

                if (tmp.length === 1)
                    return tmp[0];
                for (var i = 0; i < tmp.length; i++)
                    output += tmp[i] + '\n';
            } catch {}
            return output.trim();
        }
    }
})


//OTHER COMMANDS
const router = new VueRouter({
    mode: 'history',
    routes: routes
});

const app = new Vue({
    el: '#app',
    router: router,
    render: h => h(App),
    //CALL GLOBAL METHOD BY USING this.$root.$emit('globalmethod');
    methods: {
        exampleMethod: function(message) {
            alert(message);
        },
    },
    mounted() {
        const thisInstance = this;
        this.$root.$on('exampleMethod', function(message) {
            thisInstance.exampleMethod(message);
        });
    }
});