import axios from 'axios'
import store from '@/store'
import storage from "@/framework/utils/storage";
import lStorage from '@/utils/localStorage';
import {
  message
} from '@/api/scan/config.js'

var CancelToken = axios.CancelToken
var cancel

// 创建axios实例
const axiosservice = axios.create({
  timeout: 3000000, // 请求超时时间
  retry: 4, //重新请求次数
  retryDelay: 1000, //重新请求的间隔
  credentials: true, // 接口每次请求会跨域携带cookie
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c
  })
})

axiosservice.interceptors.request.use(
  config => {
    config.cancelToken = new axios.CancelToken(cancel => {
      if (config.url !== `${message}/message/update-state` || config.url !== '/image-service/common/multipart_upload') {
        store.commit('setAxiosArr', {
          cancel
        })
      }
    })
    // config.withCredentials = true // 允许携带token ,这个是解决跨域产生的相关问题
    // let token = store.getters['ssoToken']
    // if (token) {
    //     config.headers = {
    //         'sso-token': token
    //     }
    // }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

axiosservice.interceptors.response.use(
  function (res) {
    //在这里对返回的数据进行处理
    let resp = res.data
    // if (resp.result === 'unauthc') {
    //     store.commit('logined', false)
    //     MessageBox.confirm('未登录或登录信息已失效, 是否重新登录?', '提示', {
    //         confirmButtonText: '确定',
    //         cancelButtonText: '取消',
    //         type: 'error'
    //     })
    //         .then(resp => {
    //             const ssoServer = process.env.SSO_SERVER
    //             const redirectUrl = window.location.protocol + '//' + window.location.host + '/adm/auth'
    //             window.location.href = `${ssoServer}?redirectUrl=${redirectUrl}`
    //         })
    //         .catch(error => {
    //             console.log('')
    //         })
    // }
    return res
  },
  function (err) {
    console.log('axios interceptors err = ', err)
    return Promise.reject(err)
  }
)

export default {
  //获取cookie
  getCookie(name) {
    var arr,
      reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
    if ((arr = document.cookie.match(reg))) {
      return unescape(arr[2])
    } else {
      /* 如果没有参数，那么就获取本域下的所有cookie */
      return document.cookie
    }
  },

  async getJson(url, params) {
    let ssoToken = store.state.ssoToken ?
      store.state.ssoToken :
      lStorage.get("ssoToken");
    let ProjectId = store.state.layout.projectId ?
      store.state.layout.projectId :
      lStorage.get("projectId");
    let userName = store.state.layout.userInfo.userName ?
      store.state.layout.userInfo.userName :
      storage.get("user_name");
    let group_code = store.state.layout.group_code ?
      store.state.layout.group_code :
      lStorage.get("group_code");
    try {
      let response = await axiosservice({
        url,
        headers: {
          projectId: ProjectId,
          token: ssoToken,
          appId: "adm",
          userId: userName,
          groupCode: group_code
        },
        params,
        method: 'get'
      })
      return response.data
    } catch (err) {
      throw err
    }
  },
  async postJson(url, data) {
    let ssoToken = store.state.ssoToken ?
      store.state.ssoToken :
      lStorage.get("ssoToken");
    let ProjectId = store.state.layout.projectId ?
      store.state.layout.projectId :
      lStorage.get("projectId");
    let userName = store.state.layout.userInfo.userName ?
      store.state.layout.userInfo.userName :
      storage.get("user_name");
    let group_code = store.state.layout.group_code ?
      store.state.layout.group_code :
      lStorage.get("group_code");
    try {
      let response = await axiosservice({
        url,
        headers: {
          projectId: ProjectId,
          token: ssoToken,
          appId: "adm",
          userId: userName,
          groupCode: group_code
        },
        data,
        method: 'post'
      })
      return response.data
    } catch (err) {
      throw err
    }
  },
  /**
 * 根据用户ID获取用户信息：基本信息、菜单、项目
 * nh 2021.10.25
 */
  getUserInfoByUserId(param) { 
    return new Promise(function (resolve, reject) {
      axios({
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        method: "post",
        url: "/getUserById",
        data: "jsonString=" + JSON.stringify(param),
      }).then(res => { 
        resolve(res.data);
      }).catch(err => { 
        reject(err);
      });
    });
  },
  axios: axiosservice
}
