import Vue from 'vue'
import Main from '../pagesPre/Main'
import router from '../routerPre'
import store from '../vuexPre'
import ElementUI from 'element-ui'
import axios from 'axios'
// import moment from 'moment'
import VueI18n from 'vue-i18n'
import RongIM from '../RongIM'
Vue.use(RongIM)

import '../elementVariables.scss'
import 'normalize.css/normalize.css'
// import 'element-ui/lib/theme-chalk/index.css'
import '../mainPre.less'
import { format } from 'date-fns'

import distanceInWordsToNow from 'date-fns/distance_in_words_to_now'
import zh from 'date-fns/locale/zh_cn'
var scale = (window.screen.width / 375).toFixed(2)
var meta = document.createElement('meta')
meta.name = 'viewport'
meta.content = 'width=375,initial-scale=' + scale + ',user-scalable=no'
document.head.appendChild(meta)



Vue.config.productionTip = false;
Vue.use(ElementUI);
Vue.use(VueI18n);
const baseUrl = process.env.NODE_ENV === 'production' ? '../' : `http://${location.hostname}:8080`;
Vue.prototype.$baseUrl = baseUrl;
axios.defaults.withCredentials = true;
axios.defaults.baseURL = baseUrl;
// axios.post('/auth/loginGuest').then(res => {
//     if (res.data.success) {
//         axios.defaults.headers.common['token'] = res.data.data

//         if (store.state.serviceType.length == 0) {
//             axios.get('/serviceType/home').then(res => {
//                 if (res.data.success) {
//                     store.commit('updateServiceType', res.data.data)
//                 }
//             }).catch(e => {
//                 console.log(e)
//             })

//         }
//     }
// })
Vue.prototype.$http = {
    get(params) {
        return new Promise((resolve, reject) => {
            if (params instanceof String) {
                params = { url: params };
            } else if (!params instanceof Object) {
                reject('params error');
                return;
            }
            if (!params.url) {
                reject('url error');
                return;
            } else if (!params.url instanceof String) {
                reject('url error');
                return;
            } else if (params.url.length === 0) {
                reject('url error');
                return;
            }
            // if (!/^(http:\/\/)|(https:\/\/)/.test(params.url)) {
            //     params.url = baseUrl + params.url;
            // }
            store.commit('updateFetchingData', true);
            axios.get(params.url, {
                params: params.data
            }, { withCredentials: true }).then(res => {
                store.commit('updateFetchingData', false);
                if (res.status === 200) {
                    resolve(res.data);
                } else {
                    reject(res);
                }
                try {
                    if (res.data.code === 10001) {
                        axios({
                            method: 'post',
                            url: '/auth/logout'
                        });
                        store.commit('updateUserInfo', null);
                        router.replace('/login');
                    }
                } catch (e) {

                }
            }).catch(e => {
                store.commit('updateFetchingData', false);
                reject(e);
            });
        });
    },
    post(params) {
        if (params instanceof String) {
            params = { url: params };
        } else if (!params instanceof Object) {
            reject('params error');
            return;
        }
        if (!params.url) {
            reject('url error');
            return;
        } else if (!params.url instanceof String) {
            reject('url error');
            return;
        } else if (params.url.length === 0) {
            reject('url error');
            return;
        }
        // if (!/^(http:\/\/)|(https:\/\/)/.test(params.url)) {
        //     params.url = baseUrl + params.url;
        // }
        let data = new FormData();
        if (params.data) {
            for (let key in params.data) {
                if (params.data.hasOwnProperty(key)) {
                    if (params.data[key] instanceof Array) {
                        let hasObject = false;
                        params.data[key].forEach(i => {
                            if (i instanceof Object) {
                                hasObject = true;
                            }
                        });
                        if (!hasObject) {
                            data.append(key, params.data[key].join());
                        }
                    } else if (!(params.data[key] instanceof Object)) {
                        data.append(key, params.data[key]);
                    }
                }
            }
        }
        return new Promise((resolve, reject) => {
            store.commit('updateFetchingData', true);
            axios.post(params.url, data, { withCredentials: true }).then(res => {
                store.commit('updateFetchingData', false);
                if (res.status === 200) {
                    resolve(res.data);
                } else {
                    reject(res);
                }
                try {
                    if (res.data.code === 10001) {
                        axios({
                            method: 'post',
                            url: '/auth/logout'
                        });
                        store.commit('updateUserInfo', null);
                        router.replace('/login');
                    }
                } catch (e) {

                }
            }).catch(e => {
                store.commit('updateFetchingData', false);
                reject(e);
            });
        });
    }
};





Vue.prototype.getTime = function(str) {
    if (str) {
        // return moment(str).format('YYYY-MM-DD HH:mm')
        return format(new Date(str), 'YYYY-MM-DD HH:mm', { locale: zh })
    } else {
        return ''
    }
}

Vue.prototype.getPhone = function(phone) {
    if (phone) {
        if (phone.length == 11) {
            var str = phone.substr(0, 3)
            str += '****'
            str += phone.substr(phone.length - 4, 4)
            return str
        } else {
            return ''
        }
    } else {
        return ''
    }


}
Vue.prototype.getMail = function(mail) {
    if (mail) {
        var list = mail.split('@')
        var str = list[0].substr(0, 3)
        str += '****'
        str += list[0].substr(list[0].length - 2, 2)
        str += '@' + list[1]
        return str
    } else {
        return ''
    }

}


Vue.prototype.sendMeg = function(phone, code) {
    return new Promise((resolve, reject) => {
        this.$http.get({
            url: '/aliapi/sendCode',
            data: {
                phone: phone,
                templateCode: code
            }
        }).then(res => {
            if (res.success) {
                resolve(res)
            } else {
                resolve(res)
            }
        }).catch(e => {
            resolve(e)

        })
    })

}

//检查是否存在
Vue.prototype.checkHas = function(data) {
    return new Promise((resolve, reject) => {
        this.$http.get({
            url: '/userInfo/getOne',
            data: data
        }).then(res => {
            if (res.success) {
                if (res.data) {
                    resolve(true)
                } else {
                    resolve(false)
                }

            } else {
                resolve(res.data)
            }
        }).catch(e => {
            resolve(e)

        })
    })


}


//获取距离现在时间
Vue.prototype.forNow = function(str) {
    var time = ''
    if (str) {
        // time = moment(str).fromNow()
        time = distanceInWordsToNow(new Date(str), { locale: zh, addSuffix: true })
    }
    return time
}



Vue.mixin({
    methods: {
        timeFormatter(row, column, cellValue, index) {
            return format(new Date(cellValue), 'HH:mm', { locale: zh })
        },
        datetimeFormatter(row, column, cellValue, index) {
            if (!cellValue) return ''
            return format(new Date(cellValue), 'YYYY/MM/DD HH:mm', { locale: zh })
        }
    }
});

const updateTableHeight = () => {
    try {
        const total = document.getElementsByTagName('main')[0].clientHeight;
        const filter = document.getElementsByClassName('filters-container')[0].clientHeight;
        const page = document.getElementsByClassName('pagination-wrapper')[0].clientHeight;
        store.commit('updateTableHeight', total - filter - page - 44);
    } catch (e) {
        // console.error(e)
    }
};



//校验手机号是否正确
Vue.prototype.checkPhone = function(phone) {
    var result = false
    if ((/^1[3|4|5|8|7|6|9][0-9]\d{8}$/.test(phone))) {
        result = true
    }
    return result
}


window.onload = updateTableHeight;
window.onresize = updateTableHeight;
setInterval(updateTableHeight, 500);

var app = new Vue({
    el: '#app',
    router,
    store,
    components: { Main },
    template: '<Main/>'
});