import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'
import { onError } from 'apollo-link-error'
import { Message } from 'element-ui';
import { getCookie, setCookie } from '@/utils/util.js';
import store from '@/store/index.js';
import vue from 'vue'

const httpLink = createHttpLink({
    uri: '/graphql',
    credentials: 'include',
    headers: {
        Authorization: `Bearer ${getCookie('accessToken_devops')}` || null
    }
})

const middlewareLink = new ApolloLink((operation, forward) => {
    // operation.setContext({
    //     headers: {
    //         'access-token': sessionStorage.getItem('access-token') || null
    //     }
    // })
    return forward(operation).map(response => {
        // 结果数据
        return response
    })
})

// 拦截错误
const errorLink = onError(({ networkError, response }) => {
    let errorMsg = '';
    console.log(networkError);
    if (networkError && networkError.statusCode === 401) {
        Message({
            message: '登录已过期，请重新登录',
            duration: 1000,
            type: 'error',
            onClose: function () {
                //  弹窗关闭时，跳转到登录
                setCookie('accessToken_devops', '', -1, '/');
                setCookie('refreshToken', '', -1, '/');
                setCookie('workDate', '', -1);
                window.top.location.href = store.getters.ctx;
            }
        });
    } else {
        if (!!response && response.errors !== undefined && response.errors.length) {
            errorMsg = !response.errors[0].message ? '服务器错误' : response.errors[0].message
        }
        if (networkError) {
            errorMsg = networkError.message
            if (networkError.result !== undefined) {
                errorMsg = networkError.result.success === false ? networkError.result.message : networkError.result.error
            }
        }
        if (errorMsg) {
            Message.error(errorMsg);
        }
    }
})

const authLink = middlewareLink.concat(httpLink)

const defaultOptions = {
    watchQuery: {
        fetchPolicy: 'network-only',
        errorPolicy: 'ignore'
    },
    query: {
        fetchPolicy: 'network-only',
        errorPolicy: 'all'
    }
}
const fragmentMatcher = new IntrospectionFragmentMatcher({
    introspectionQueryResultData: {
        __schema: {
            types: [
                {
                    kind: 'INTERFACE',
                    name: 'Document',
                    possibleTypes: [
                        { name: 'MyInterface1' },
                        { name: 'SomeInterface2' }
                    ]
                }
            ]
        }
    }
})

const apollo = new ApolloClient({
    link: errorLink.concat(authLink),
    cache: new InMemoryCache({ fragmentMatcher }),
    connectToDevTools: true,
    defaultOptions: defaultOptions
})

export default apollo
