import axios from 'axios'
import router from '../../router'
import qs from 'qs'
import { Message as iviewMessage, Notice as iviewNotice } from 'view-design'
// axios.defaults.timeout = 5000;
if (process.env.NODE_ENV == 'development') {
  axios.defaults.baseURL = '/api'
  // axios.defaults.baseURL='http://localhost:3007/screening-api/'
} else {
  axios.defaults.baseURL = process.env.VUE_APP_URL
}
console.log('接口地址',axios.defaults.baseURL)
window.baseURL = axios.defaults.baseURL
//http request 拦截器
axios.create({
  withCredentials: true,
})
axios.interceptors.request.use(
  (config) => {
    config.data = config.data
    config.headers['user-cookie'] = localStorage.getItem('token')
    if (config.url === '/ewell-tumors-user/province/list') {
      //坐下判断如果是获取省市接口则不做拦截
    }
    //  else if(!localStorage.getItem("token")){
    //     toLogin()
    //   }
    return config
  },
  (error) => {
    return Promise.reject(err)
  }
)

/**
 * 跳转登录页
 * 携带当前页面路由，以期在登录页面完成登录后返回当前页面
 */
const toLogin = () => {
  router.replace({
    path: '/login',
    query: {
      redirect: router.currentRoute.fullPath,
    },
  })
}

//响应拦截器即异常处理
axios.interceptors.response.use(
  (response) => {
    if (response.data.code === 0 || response.data.code === -1) {
      if(response.config.url!='/api/gastric-cancer-user/role/getRolePerByUser')
      {
        iviewMessage.error(response.data.message)
      }
    } else if (response.data.code === -100) {
      window.location.hash = '/login'
    }
    return response
  },
  (err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          iviewMessage.error('错误请求')
          console.log('错误请求')
          break
        case 401:
          iviewMessage.error('未授权，请重新登录')
          toLogin()
          console.log('未授权，请重新登录')
          break
        case 403:
          iviewMessage.error('拒绝访问')
          console.log('拒绝访问')
          break
        case 404:
          iviewMessage.error('请求错误,未找到该资源')
          console.log('请求错误,未找到该资源')
          break
        case 405:
          iviewMessage.error('请求方法未允许')
          console.log('请求方法未允许')
          break
        case 408:
          iviewMessage.error('请求超时')
          console.log('请求超时')
          break
        case 500:
          iviewMessage.error('服务器端出错')
          console.log('服务器端出错')
          break
        case 501:
          iviewMessage.error('网络未实现')
          console.log('网络未实现')
          break
        case 502:
          iviewMessage.error('网络错误')
          console.log('网络错误')
          break
        case 503:
          iviewMessage.error('服务不可用')
          console.log('服务不可用')
          break
        case 504:
          iviewMessage.error('网络超时')
          console.log('网络超时')
          break
        case 505:
          iviewMessage.error('http版本不支持该请求')
          console.log('http版本不支持该请求')
          break
        default:
          iviewMessage.error(`连接错误${err.response.status}`)
          console.log(`连接错误${err.response.status}`)
      }
    } else {
      iviewMessage.error('连接到服务器失败')
      console.log('连接到服务器失败')
    }
    return Promise.resolve(err.response)
  }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, data).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, {
        params,
      })
      .then(
        (response) => {
          resolve(response.data)
        },
        (err) => {
          reject(err)
        }
      )
  })
}
export function postForm(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, qs.stringify(data), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
      .then(
        (response) => {
          resolve(response.data)
        },
        (err) => {
          reject(err)
        }
      )
  })
}
export function postFormJ(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, {
        headers: {
          'Content-Type': 'application/json',
        },
      })
      .then(
        (response) => {
          resolve(response.data)
        },
        (err) => {
          reject(err)
        }
      )
  })
}

//用来导出excel
export function expoertExcel(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, qs.stringify(data), {
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
      .then(
        (response) => {
          resolve(response.data)
        },
        (err) => {
          reject(err)
        }
      )
  })
}

//下载excel
export function downloadExcel(url, data = {}, title = '筛查信息导出表') {
  return axios({
    method: 'post',
    url: url,
    data: data,
    responseType: 'blob',
  })
    .then((res) => {
      if ('msSaveOrOpenBlob' in navigator) {
        //兼容ie
        let blob = new Blob([res.data], {
          type: 'application/vnd.ms-excel',
        })
        window.navigator.msSaveOrOpenBlob(blob, `${title}.xls`)
        return
      } else {
        const link = document.createElement('a')
        let blob = new Blob([res.data], {
          type: 'application/vnd.ms-excel',
        })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', `${title}.xls`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    })
    .catch((error) => {
      this.$Notice.error({
        title: '错误',
        desc: '系统数据错误',
      })
      console.log(error)
    })
}
/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function Delete(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.delete(url, data).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}
export function deleteForm(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, {	
        data: 	            // 请求参数拼接在url上
          params, 
      }
        // {
        //   headers: {
        //     'Content-Type': 'application/x-www-form-urlencoded',
        //   },
        // }
      )
      .then(
        (response) => {
          resolve(response.data)
        },
        (err) => {
          reject(err)
        }
      )
  })
}
/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(
      (response) => {
        resolve(response.data)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

export function getUrl() {
  return axios.defaults.baseURL
}
