import Vue from 'vue';
import App from './App';
import Router from 'vue-router';
import routers from './router';
import 'es6-promise/auto';
import 'babel-polyfill'
import axios from 'axios';

import WujieVue from "wujie-vue2";

Vue.use(WujieVue);

Vue.use(Router);

if (location.href.indexOf("/formPath/") > -1) {
    let href = location.href;
    window.JAVA_URL = href.substring(0, href.indexOf("/formPath/"));
}
window.Vue = Vue;
window.ADMIN_NAME = window.ADMIN_NAME || "admin";
//
Vue.prototype.api = {};

let saspFormRouter;
let loginName = "login";
axios.defaults.maxRedirects = 5;
axios.defaults.headers = axios.defaults.headers || {};
axios.defaults.headers.common = axios.defaults.headers.common || {};

axios.defaults.transformRequest = axios.defaults.transformRequest || [];
axios.defaults.headers.common["Authorization"] = (localStorage["Authorization" + (window.projectSuffix || "")] || "");
axios.defaults.transformRequest.push(
    function (data, config) {
        if (config["Is-Sasp-Qs"]) {
            delete config["Is-Sasp-Qs"];
            if (data && typeof data === "string") {
                try {
                    data = JSON.parse(data);
                } catch (e) {
                    console.error(e);
                }
            }
            return qs.stringify(data);
        } else {
            return data;
        }
    });
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // console.log(config);
    if ((config.headers["Content-Type"] != 'multipart/form-data')) {
        config = Object.assign({}, config);
        config.headers = Object.assign({}, config.headers || {}, {
            "Is-Sasp-Qs": true,
            "Content-Type": "application/x-www-form-urlencoded"
        });
        if (window.encryption) {
            config.headers['encryption'] = 'enc';
        }
    }
    return config;
});
//
// // 未登录无权限时跳转到登录页
axios.interceptors.response.use(res => {
    if (res && res.data.operateCode == '401') {
        saspFormRouter.push({path: '/'});
        return;
    }
    return res;
});

Vue.prototype.axios = axios;
Vue.prototype.USE_ADMIN_SERVE = false; // 是否使用admin服务，true为使用

import SaspBase, {isAxiosFormData} from "sasp-base";
// import SaspFlowRender from 'sasp-flow-render';
import renderIndex from "../index";
import qs from "qs";

if (!window.hasOwnProperty("SPDA_URL")) {
    window.SPDA_URL = "http://10.204.20.165:8089";
}
window.SPDA_DASH_VIEW_URL = "http://10.204.20.165:9999/spda-vue/#/dashbarodPreview?dashboardId=";
window.SPDA_REPORT_VIEW_URL = "http://10.204.20.165:9999/spda-vue/#/reportPreview?reportId=";

let modules = [
    {module: SaspBase, SERVICE_URL: JAVA_URL},
    // {module: SaspFlowRender, SERVICE_URL: FLOW_URL, ADMIN_URL: ADMIN_URL},
    {module: renderIndex, SERVICE_URL: JAVA_URL, ADMIN_URL: ADMIN_URL},
];
let serviceNameObj = {};
modules.forEach(m => {
    if (m.name) {
        let serviceName = (m.SERVICE_URL || "");
        serviceNameObj[m.name] = "/" + serviceName.substring(serviceName.lastIndexOf("/") + 1) + "/";
    }
    Vue.use(m.module, {
        // router,
        axios: axios,
        SERVICE_URL: m.SERVICE_URL || "",
        ADMIN_URL: m.ADMIN_URL || ""
    });
});

if (!window.FLOW_URL) {
    Vue.prototype.USE_SASP_FLOW = false;
}

window.SERVICE_NAME = serviceNameObj; // 各服务对应名称的全局变量

let instance;

/**
 *
 * @param props
 */
function render(props = {}) {
    let {container} = props;

    const router = new Router({
        mode: 'hash',
        routes: routers
    });

    saspFormRouter = router;

    // 导航守卫
    // 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
    router.beforeEach((to, from, next) => {
        //如果去往登录页则放行
        if (to.path === '/') {
            next();
        } else if (to.path.indexOf("/formResourceView/") > -1) {
            next();
        } else {
            // 从本地存储里获取token
            let suffix = window.projectSuffix || "";
            let token = localStorage.getItem('USERTOKEN' + suffix);
            // 判断token是否为空如果为空则跳转到登录页 如果有则放行
            if (token === null || token === '') {
                next({path: '/'});
            } else {
                next();
            }
        }
    });

    instance = new Vue({
        router,
        render: h => h(App)
    }).$mount(container ? container.querySelector('#app') : '#app');
}

if (window.__POWERED_BY_WUJIE__) {
    window.__WUJIE_MOUNT = () => {
        render();
    };

    window.__WUJIE_UNMOUNT = () => {
        instance.$destroy();
        instance.$el.innerHTML = '';
        instance = null;
    };
} else {
    render();
}