import Vue from 'vue'
import router from '../router'
import store from '../vuex'
import ElementUI from 'element-ui'
import axios from 'axios'
import MultiUpload from '../components/MultiUpload'
import SingleUpload from '../components/SingleUpload'
import RichText from '../components/RichText'
import VueI18n from 'vue-i18n'
import VueAMap from 'vue-amap'

import VueDND from 'awe-dnd';

import 'normalize.css/normalize.css'
import 'element-ui/lib/theme-chalk/index.css'
import '../main.less'
import { format } from 'date-fns'
import zh from 'date-fns/locale/zh_cn'
import vuex from '../vuex';

VueAMap.initAMapApiLoader({
    key: 'bf91055058a47a7dc387e40ab6256a5f',
    plugin: ['Autocomplete', 'PlaceSearch', 'Scale', 'OverView', 'ToolBar', 'MapType', 'PolyEditor', 'AMap.CircleEditor', 'AMap.Geolocation'],
    v: '1.4.7'
});

Vue.config.productionTip = false;
Vue.use(ElementUI);
Vue.use(VueI18n);
Vue.use(VueDND);
Vue.component('multi-upload', MultiUpload);
Vue.component('single-upload', SingleUpload);
Vue.component('rich-text', RichText);
const baseUrl = process.env.NODE_ENV === 'production' ? '../' : `http://${location.hostname}:8080`;
Vue.prototype.$baseUrl = baseUrl;
Vue.prototype.$widgetBaseUrl = 'http://116.62.160.108:8180/';
Vue.prototype.$handleDomain = 'http://121.43.171.110:8082/'
Vue.prototype.$handleUrl = 'http://121.43.171.110:8082/webService/call'

// Vue.prototype.$widgetBaseUrl = 'http://172.16.86.43:8180/';
// Vue.prototype.$handleDomain = 'http://180.169.224.24:8092/'
// Vue.prototype.$handleUrl = 'http://180.169.224.24:8092/webService/call'
//0使用信牧图标,1使用光明图标
Vue.prototype.$isGuangming = 0

axios.defaults.withCredentials = true;
axios.defaults.baseURL = baseUrl;
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,
            }).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;
        }
        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).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.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 })
        }
    }
});

//serviceName, methodName, params,返回类型:list/json,tableKey:默认牛号,日期转换格式:YYYY-MM-DD
Vue.prototype.getHaleInfo = function(serviceName, methodName, params, type, newkey, dateTypeType) {

    return new Promise((resolve, reject) => {
        var data = {
            "serviceName": serviceName,
            "methodName": methodName,
            "params": params
        }
        console.log(store.state.requireToken)
        axios.post(this.$handleUrl, data, {
            headers: {
                'token': store.state.requireToken
            }
        }).then(res => {
            if (res.data.success) {
                var jsonp = {}
                var list = []
                if (res.data.data.key) {
                    if (type == 'list') {
                        resolve([])
                    } else {
                        resolve({})
                    }
                } else if (type == 'list') {
                    //list处理

                    var useKey = '牛号'
                    if (newkey) {
                        useKey = newkey
                    }

                    var useDateType = 'YYYY-MM-DD'
                    if (dateTypeType) {
                        useDateType = dateTypeType
                    }

                    if (res.data.data[useKey]) {
                        list.push(res.data.data)
                    } else {
                        list = res.data.data
                    }
                    list.forEach(item => {
                        for (var key in item) {

                            if (key.indexOf('日期') != -1) {
                                item[key] = format(new Date(item[key]), useDateType, { locale: zh })
                            }
                            if (key.indexOf('时间') != -1) {
                                item[key] = format(new Date(item[key]), useDateType, { locale: zh })
                            }
                        }
                    })

                    resolve(list)

                } else if (type == 'json') {
                    jsonp = res.data.data
                    for (var key in jsonp) {
                        if (key.indexOf('日期') != -1) {
                            jsonp[key] = format(new Date(jsonp[key]), dateTypeType ? dateTypeType : 'YYYY-MM-DD', { locale: zh })
                        }
                        if (key.indexOf('时间') != -1) {
                            jsonp[key] = format(new Date(jsonp[key]), dateTypeType ? dateTypeType : 'YYYY-MM-DD HH:mm:ss', { locale: zh })
                        }
                    }
                    resolve(jsonp)
                }

            } else {
                this.$message({
                    message: res.data.error,
                    type: 'warning'
                });
                reject()
            }

        })
    })
}

Vue.prototype.JsonSort = function(list, jsonp, hasNot) {
        if (hasNot) {
            list.forEach(item => {
                if (!jsonp[item]) {
                    jsonp[item] = ''
                }
            })
        }
        var needList = Object.keys(jsonp).sort((a, b) => {
            if (list.indexOf(a) == -1) {
                return 1
            } else if (list.indexOf(b) == -1) {
                return -1
            } else {
                return list.indexOf(a) - list.indexOf(b)
            }
        })
        var returnJson = {}
        needList.forEach(item => {
            returnJson[item] = jsonp[item]

        })
        return returnJson

    }
    //获取牛只信息
Vue.prototype.getCowInfo = function(cowID, type, isBack, returnFalse) {

    return new Promise((resolve, reject) => {
        if (cowID.length != 8) {
            this.$message({
                message: '牛号错误',
                type: 'warning'
            });
            reject(new Error())
            return
        }
        this.getHaleInfo('wsCow', 'getCowExtendInfoByCowID', [cowID, type ? type : 99], 'json').then((data) => {
            if (Object.keys(data).length == 0) {
                if (isBack) {
                    resolve()
                } else {
                    if (!returnFalse) {
                        this.$message({
                            message: '当前牛只信息不存在',
                            type: 'warning'
                        });
                    }

                    reject(new Error())
                }

            } else {
                if (isBack) {
                    this.$message({
                        message: '该奶牛已经在系统中登记，无法为新生犊牛编号，请更换耳号',
                        type: 'warning'
                    });
                    reject(new Error())
                } else {
                    resolve(this.JsonSort(['牛号', '当前牛舍'], data))
                }

            }

        })
    })
}

Vue.prototype.getTime = function(str, useDateType) {
    return format(new Date(str), useDateType, { locale: zh })
}

Vue.prototype.getCowList = function(cow) {
        return new Promise((resolve, reject) => {
            this.getHaleInfo('wsCow', 'getLiveCows', [this.$store.state.farmName, cow], 'list').then((data) => {

                var cowList = []
                data.forEach(item => {
                    cowList.push({
                        value: item['牛号']
                    })
                })

                resolve(cowList)

            })

        })
    }
    //String转Xml
Vue.prototype.getXml = function(xmlString) {
    if (document.all) {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        xmlDom.loadXML(xmlString);
        return xmlDom;
    } else return new DOMParser().parseFromString(xmlString, "text/xml");

}

Vue.prototype.queryCow = function(queryString, cb) {
    if (queryString.length > 3) {
        this.getCowList(queryString).then(list => {
            var results = list
            cb(results)
        });

    } else {
        cb([])
    }
}


const updateTableHeight = () => {
    try {
        const total = document.getElementsByTagName('main')[0].clientHeight;
        store.commit('updateAllHeight', total);
        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)
    }
};

const debounce = function(idle, action) {
    let last;
    return function() {
        let ctx = this,
            args = arguments;
        clearTimeout(last);
        last = setTimeout(function() {
            action.apply(ctx, args)
        }, idle)
    }
};

window.onload = updateTableHeight;
window.onresize = debounce(100, () => {

    updateTableHeight();
    store.commit('updateWindowSize', {
        width: window.innerWidth,
        height: window.innerHeight
    })
});
setInterval(updateTableHeight, 500);

new Vue({
    el: '#app',
    router,
    store,
    components: {},
    template: `<keep-alive include="*">
            <router-view></router-view>
        </keep-alive>`
});