// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import Modal from './components/Modal'
import Alert from './components/Alert'
import ShowPicture from './components/ShowPicture'
import LoadData from './components/LoadData'
import axios from 'axios'
import YDUI from 'vue-ydui'; /* 相当于import YDUI from 'vue-ydui/ydui.rem.js' */
import 'vue-ydui/dist/ydui.px.css';
/* 使用px：import 'vue-ydui/dist/ydui.px.css'; */

Vue.use(YDUI);

Vue.config.productionTip = false
Vue.prototype.$modal = Modal
Vue.prototype.$alert = Alert
Vue.prototype.$loadData = LoadData
Vue.prototype.$showPicture = ShowPicture
    /* eslint-disable no-new */
var scale = (window.screen.width / 375).toFixed(2)
var css = document.createElement('style')
var fontSize = scale * 50
css.innerHTML = `html{font-size: ${fontSize}px}`
document.head.appendChild(css)
var iNoBounce = require('./inobounce.min.js')
var isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
const baseUrl = process.env.NODE_ENV === 'production' ? '../' : 'http://www.xiangjuwu.com/';
// const baseUrl = 'http://www.xiangjuwu.com'
store.commit('updateBaseUrl', baseUrl)
axios.defaults.withCredentials = true;
axios.defaults.baseURL = baseUrl;

let houseId = getQueryString('houseId')
if (houseId) {
    store.commit('updateRedirect', {
        name: 'houseDetail',
        query: {
            id: houseId
        }
    })
}



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: '/userInfo/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) {
                        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: '/userInfo/logout'
                        });
                        store.commit('updateUserInfo', null);
                        router.replace('/login');
                    }
                } catch (e) {

                }
            }).catch(e => {
                store.commit('updateFetchingData', false);
                reject(e);
            });
        });
    }
};
//更新用户信息
Vue.prototype.updateUser = function(type, value) {

    return new Promise((resolve, reject) => {
        store.commit('updateLoading', true);
        var data = {
            id: store.state.userInfo.id
        }
        data[type] = value
        console.log(data)
        this.$http.post({
            url: '/userInfo/update',
            data: data
        }).then(res => {
            store.commit('updateLoading', false);
            if (res.success) {
                this.$modal.success({ msg: '修改成功', duration: 1500 })
                resolve()
            } else {
                this.$modal.info({ msg: res.error, duration: 1500 })
            }
        });
    })
}

//校验手机号是否正确
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
}

Vue.prototype.userHasPhone = function() {
    if (store.state.userInfo.phone) {
        return true
    } else {
        this.$alert({ title: '提示', content: '该功能需要先绑定手机号，才能开发', showCancel: true, }, () => {
            this.$router.push({
                name: 'login',
                query: {
                    bindType: 1
                },
                params: {
                    isNext: 1
                }
            })
        })

        return false
    }
}
new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App),
    mounted() {
        if (isiOS) {
            iNoBounce.enable()
        } else {
            iNoBounce.disable()
        }
    }
})


function getQueryString(name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    let r = window.location.search.substr(1).match(reg)
    if (r != null) return unescape(r[2])
    return null
}