import axios from 'axios'
import { baseUrl } from '@/utils/env.js'
import router from '@/router'
import { removeToken,getToken } from '@/utils/auth'

let sessionId = ''

// 添加请求头
const instance = axios.create({
  withCredentials: true,
  baseURL: baseUrl, // 请求地址的基础路径
  timeout: 20000 // 请求超时时间
})

axios.defaults.withCredentials = true;

// 通过拦截器格式化参数
instance.interceptors.request.use(config => {
  // post请求就格式化数据
  if (config.method === 'post') {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  }
  if(sessionId){
    config.headers['Cookie'] = `sessionid=${sessionId}`;
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// // 响应拦截器，获取 Set-Cookie 中的 sessionid
// instance.interceptors.response.use(response => {
//   // 检查响应头是否有 Set-Cookie，并提取 sessionid
//   const setCookieHeader = response.headers['Set-Cookie'];
//   console.log(response,setCookieHeader,'setCookieHeader')
//   if (setCookieHeader) {
//     const sessionMatch = setCookieHeader.match(/sessionid=([^;]+)/);
//     if (sessionMatch) {
//       sessionId = sessionMatch[1]; // 存储 sessionId 以便后续请求使用
//     }
//   }
//   else{
//     this.$message.error('登录失效，请重新登录!!!!!!!!!!!!')
//   }
//   return response;
// }, error => {
//   return Promise.reject(error);
// })

export default (url = '', data = {}, type = 'POST', responseType = 'json', headers = {}) => {
  return new Promise((resolve, reject) => {
    let httpPromise = null

    if (type.toUpperCase() === 'GET') {
      httpPromise = instance({
        method: type,
        url: url,
        params: data,
        headers,
        responseType,
      })
    } else {
      httpPromise = instance({
        method: type,
        url: url,
        data: data,
        headers,
        responseType,
      })
    }
    httpPromise.then(res => {
      // 处理返回的文件流
      // 通过a标签实现文件的下载
      if (responseType === 'blob') {
        const content = res.data
        const elink = document.createElement('a') // 创建a标签
        // 获取文件名,根据后端返回不同获取的字段不同
        elink.download = decodeURI(escape(res.headers['content-disposition'].split('=')[1]))
        elink.style.display = 'none'
        const blob = new Blob([content], { type: 'application/vnd.ms-excel;charset=UTF-8' })
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click() // 触发点击a标签事件
        document.body.removeChild(elink)
        resolve()
      } else {
        if (res.data.code == 101 || res.data.message == "用户未登录") {
          // 没有登录清空code
          removeToken()
          router.push({
            path: '/login'
          });
          return
        } else if (res.data.code == 201) {
          resolve(res.data)
          return ''
        }
        resolve(res.data)
      }
    }).catch(err => {
      let errMsg = '请求失败'
      if (err.response && err.response.status === 500) {
        errMsg = '服务器开小差了~'
      } else if (err.code === 'ECONNABORTED') {
        errMsg = '请求超时'
      }
      reject(new Error(errMsg))
    })
  })
}
