import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import errorCode from '@/utils/errorCode'
import axios from 'axios'
import { Message, MessageBox, Notification } from 'element-ui'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
    mutations: {
        SET_TOKEN: (state, Authorization) => {
            state.Authorization = Authorization
        },
    },
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    //baseURL: process.env.NODE_ENV === 'development' ? 'http://10.10.9.219:9902' : process.env.VUE_APP_BASE_URL,
    baseURL:  process.env.VUE_APP_BASE_URL_change,
    // 超时
    timeout: 400000,
})
// request拦截器
service.interceptors.request.use(
    config => {
        // 是否需要设置 token请根据实际情况自行修改
        config.headers['ksbm']=location.search.slice(1).split('=')[3]==undefined?"0":location.search.slice(1).split('=')[3]==''?'0':location.search.slice(1).split('=')[3]
        const isToken = (config.headers || {}).isToken === false
        config.headers['job_number'] = localStorage.getItem('jobNumber')
          config.headers['token'] = 'outside'
        config.headers['dept_code'] = localStorage.getItem('deptCode')
        console.log(localStorage.getItem('deptCode'),'pppppppppppppp')
        if (localStorage.getItem('deptCode')=='') {
            let urlParams = new URLSearchParams(window.location.search)
            config.headers['dept_code'] = urlParams.get('dept')
            console.log( urlParams.get('dept'),'kkkkkkkkkkkkkkkkkkk')
        }
        // if (getToken() && !isToken) {
        //     config.headers['Authorization'] = getToken()
        //     // config.headers['ksbm']=location.search.slice(1).split('=')[3]==undefined?"0":location.search.slice(1).split('=')[3]==''?'0':location.search.slice(1).split('=')[3]
        //     // config.headers['token'] = getToken()
        // }
        // Warning:插件市场官方用户token,禁止修改
        if (config.url.includes('/qaapi/')) {
            config.headers['apitoken'] = Cookies.get('Api-Token')
        }
        // if (localStorage.getItem('SET_TOKEN')) {
        //     config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('SET_TOKEN')
        //     // config.headers['ksbm']=location.search.slice(1).split('=')[3]==undefined?"0":location.search.slice(1).split('=')[3]==''?'0':location.search.slice(1).split('=')[3]
        // }
        return config
    },
    error => {
        console.log(error)
        Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    res => {
        if (res.status == 204) {
            Message({ message: '操作成功！', type: 'success',duration: 5 * 1000  })
        }
        else {
            return res.data
        }
    },
    error => {
        let { message } = error
        if (error.response.status == 422) {
            var title='请求参数异常'
        } else if (error.response.status == 429) {
            var title='请求过于频繁'
        }else if (error.response.status == 404) {
            var title='未找到资源'
        }else if (error.response.status == 403) {
            var title='权限不足'
        }else if (error.response.data.code == '401') {
            MessageBox.confirm('登录状态已过期,请重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    return new Promise(resolve => {
                        localStorage.removeItem('SET_TOKEN')
                        const key = 'Admin-Token'
                        Cookies.remove(key)
                        location.reload()
                    })
                })
                .catch(() => { })
            return Promise.reject('令牌验证失败')
        }
        else if (error.response.status >= 500) {
            var title='服务异常'
            // Notification.error({
            //     title: '内部错误',
            //     message: error.response.data.message,
            //     duration: 0
            //   });
        }
        else if (error.response.status >=400) {
            var title='请求异常'
            // Notification.warning({
            //     title: '请求异常',
            //     message: error.response.data.message,
            //     duration: 0
            //   });
        }
        Notification.error({
            title: title,
            dangerouslyUseHTMLString: true,
            message: error.response.data.message +'<p>'+error.response.data.u_id+'</p>',
            duration: 0
          });
        // Message({ message: error.response.data.message, type: 'error', duration: 5 * 1000 })
        return Promise.reject(error)

    }
)

export default service
