import { fetch } from '@ttk/utils';
import { Message as message } from '@ttk/component';
import { mockXHR } from '../mock'
import { targetDomId, startAppName, appId } from '../constant'

// fetch配置
function configFetch() {
    fetch.config({
        // mock: false,
        appId,
        after: (response, url, data, header) => {
            const resultHead = response.head;
            const resultBody = response.body;
            const body = header.body ? JSON.parse(header.body) : null;

            // 如果请求参数带有interceptConfigAll属性，并值为true时，不做拦截
            if (body && body.interceptConfigAll) {
                return response
            }
            // 有head没有body
            if (resultHead && !resultBody) {
                if (resultHead.errorCode === '0' || resultHead.errorCode === "-1") {
                    return resultHead;
                } else if (resultHead.errorCode === '00000214' || resultHead.errorCode === '010121' || resultHead.errorCode === '100100000018') {
                    //登录超时，直接跳转到登录页
                    message.error(resultHead.errorMsg)
                    // window.location.href = '/app-root/app-login' // gotoLogin()
                    // window.location.href = '/'
                } else {
                    message.error(resultHead.errorMsg)
                }
                return resultHead
            } else if (resultHead && resultBody) {
                if (body && body.interceptConfig) {
                    return resultHead;
                }
                return resultBody;
            }
        }
    })
}

let _options = {}
function config(options) {
    // 使用mock数据静态化
    if (process.env.NODE_ENV !== 'production') {
        mockXHR()
    }
    
    configFetch();

    Object.assign(_options, options)
    _options.targetDomId = targetDomId //react render到目标dom
    _options.startAppName = startAppName //启动app名，需要根据实际情况配置
    return _options
}

config.current = _options
export default config