// 此脚本暂时废弃
import Vue from 'vue';
import App from './App';
import Router from 'vue-router';
import routes from './router';
import 'es6-promise/auto';
import './public-path';

import axios from 'axios';

// 主应用已经引入了babel-polyfill，子应用重复引入会报错
if (!window.__POWERED_BY_QIANKUN__) {
    require('babel-polyfill')
}

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 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') {
        router.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=";

window.addEventListener('message', e => {
    console.log("收到了跨域通信！");
    if (e.data && e.data.token === 'sasp_form_vue_token') {
        console.log(e);
        let url = e.data.url;
        if (!url || url.indexOf("/formResourceView/") === -1) {
            return;
        }
        let routerPath = url.substring(url.indexOf("/formResourceView/"));
        router.push({path: routerPath});
    }
}, false);


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; // 各服务对应名称的全局变量

window.__POWERED_BY_QIANKUN__ && (window.Vue = null);

Vue.use(Router);


const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
};

let instance;
let router;

function render(props = {}) {
    let {container, type, params} = props;

    router = new Router({
        mode: (type === "component") ? 'abstract' : 'hash',
        routes: routes
    });

    // 导航守卫
    // 使用 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');

    (type === "component") && router.push({
        path: params.routerPath
    });
}

(!window.__POWERED_BY_QIANKUN__) && render();

/**
 * bootstrap 只会在微应用初始化的时候调用一次，下次微应用重新进入时会直接调用 mount 钩子，不会再重复触发 bootstrap。
 * 通常我们可以在这里做一些全局变量的初始化，比如不会在 unmount 阶段被销毁的应用级别的缓存等。
 */
export async function bootstrap() {
}

/**
 * 应用每次进入都会调用 mount 方法，通常我们在这里触发应用的渲染方法
 */
export async function mount(props) {
    render(props)
}

/**
 * 应用每次 切出/卸载 会调用的方法，通常在这里我们会卸载微应用的应用实例
 */
export async function unmount() {
    instance.$destroy();
    instance.$el.innerHTML = '';
    instance = null;
    router = null;
}

/**
 * 可选生命周期钩子，仅使用 loadMicroApp 方式加载微应用时生效
 */
export async function update(props) {
    console.log('update props', props);
}
