import axios from 'axios'
// import qs from 'qs'
// import message from '@/components/public/message/src'
import router from '@/router/index'
import { getCookie, clonAllCookie } from '@/utils/cookie'
// import cookie from '@/tools/cookie.js'

axios.defaults.timeout = 60000 //响应时间
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';        //配置请求头
axios.defaults.headers.post['Content-Type'] = 'application/json'

axios.defaults.headers.post['lang'] = 'en' //配置语言请求头
axios.defaults.withCredentials = true //跨域携带cookie
import { message } from 'ant-design-vue'

let httpIp = import.meta.env.VITE_USER_NODE_ENV == 'development' ? '' : ''
// let httpIp = import.meta.env.VITE_USER_NODE_ENV == 'development' ? "https://192.168.1.8:10086" : "";

axios.defaults.baseURL = httpIp //配置接口地址
// console.log(axios.defaults.baseURL);
axios.defaults.baseURL = import.meta.env.VITE_APP_BASE_URL //配置接口地址
console.log(import.meta.env.VITE_APP_BASE_URL)

// 创建取消令牌
const CancelToken = axios.CancelToken
const source = CancelToken.source()
// console.log(import.meta.env.VITE_APP_BASE_URL);
let isLoginTime = false
//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use(
  (config) => {
    //在发送请求之前做某件事

    if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
      // config.data = qs.stringify(config.data);
    }
    config.headers.Authorization = getCookie('token')
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
const binaryToUrl = (binary, type = 'application/json', res) => {
  let blob = new Blob([binary], { 'content-type': type })
  let url = URL.createObjectURL(blob)
  return url
}
//返回状态判断(添加响应拦截器)
axios.interceptors.response.use(
  (res) => {
    // 允许透传完整响应：请求时传 config.fullData = true

    // if(res.data.data == null){
    // 	message.warning(res.data.errMsg)
    //     return Promise.reject(res.data);
    // }else
    if (res?.config?.env?.binary) {
      let url = binaryToUrl(res.data, res.config.env.binaryType, res)
      return Promise.resolve({ url, data: res.data })
    }
    if (res?.data) {
      if (res?.data?.errCode === 0) {
        // message.error(res?.data?.errMsg)
        if (res?.config?.fullData) {
          return Promise.resolve(res.data)
        }
        return Promise.resolve(res?.data?.data)
      } else if (res?.data?.errCode === 1) {
        message.warning(res?.data?.errMsg)
        return Promise.reject(res?.data)
      } else if (res?.data?.errCode === 2) {
        return Promise.reject(res?.data)
      } else if (res?.data?.errCode === -1) {
        message.error(res?.data?.errMsg)
        return Promise.reject(res?.data)
      }
    } else {
      if (res?.data?.errCode === 0) {
        message.warning(res?.data?.errMsg)
        return Promise.reject(res?.data)
      } else if (res?.data?.errCode === 1) {
        message.warning(res?.data?.errMsg)
        return Promise.reject(res?.data)
      } else if (res?.data?.errCode === 2) {
        return Promise.reject(res?.data)
      } else if (res?.data?.errCode === -1) {
        message.error(res?.data?.errMsg)
        return Promise.reject(res?.data)
      }
    }
  },
  function (error) {
    if (error?.response?.status === 401 && router.currentRoute._value.name != 'setIdentification') {
      //如果是记录浏览器页面就不跳转login
      clonAllCookie()
      if (!isLoginTime) {
        isLoginTime = true
        let isSystemUserRouteList = ['/Square'] //如果是这两个页面就无需跳转未登录页
        let sSystemUser = false
        for (let index = 0; index < isSystemUserRouteList.length; index++) {
          if (router.currentRoute.value.path.indexOf(isSystemUserRouteList[index]) > -1) {
            sSystemUser = true
            break
          }
        }
        if (!sSystemUser) {
          router.replace('/')
        }
        message.warning('Please login and try again~')
        setTimeout(() => [(isLoginTime = false)], 2000)
      }
      // source.cancel('取消后续接口调用');
      return Promise.reject()
    }
    let data_new = error?.response?.data
    // message.error(data_new?.errMsg || 'Error: server exception')
    return Promise.reject(data_new)
  }
)
export const Https = {
  httpUrls: {
    // award页面
    checkEmail: '/api/global-award/checkEmail', // 检查邮箱是否存在
    checkOTP: '/api/global-award/checkCode', // 检查验证码是否正确
    initPdfUpload: '/api/global-award/uploads/pdf/init', // 初始化pdf上传
    initVideoUpload: '/api/global-award/uploads/video/init', // 初始化video上传
    uploadPDF: '/api/global-award/uploads/pdf/chunk', // 上传pdf
    uploadVideo: '/api/global-award/uploads/video/chunk', // 上传video
    uploadPDFComplete: '/api/global-award/uploads/pdf/complete', // 上传pdf完成
    uploadVideoComplete: '/api/global-award/uploads/video/complete', // 上传video完成
    submitForm: '/api/global-award/contestants/save', // 提交表单
    getContestantByID: '/api/global-award/contestants/' // 获取表单
  },

  axiosGet(url, config) {
    return new Promise((resolve, reject) => {
      if (isLoginTime && url != '/api/portfolio/page') {
        resolve('')
        return
      }
      axios
        .get(url, config)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  axiosPut(url, data) {
    return new Promise((resolve, reject) => {
      if (isLoginTime && url != '/api/portfolio/page') {
        resolve('')
        return
      }
      axios
        .put(url, data)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  axiosPost(url, data, config) {
    return new Promise((resolve, reject) => {
      if (isLoginTime && url != '/api/portfolio/page') {
        resolve('')
        return
      }
      axios
        .post(url, data, config)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  axiosDelete(url, newData) {
    return new Promise((resolve, reject) => {
      if (isLoginTime && url != '/api/portfolio/page') {
        resolve('')
        return
      }
      axios
        .delete(url, { data: newData })
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
}
