/* eslint-disable camelcase */
import axios from 'axios'
import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate, removeEmptyProperty } from '@/utils/ruoyi'
// import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'
import useUserStore from '@/store/modules/user'
import qs from 'qs'
import _ from 'lodash'

let downloadLoadingInstance: ReturnType<typeof ElLoading.service>

// 是否显示重新登录
export const isRelogin = { show: false }
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时
  timeout: 20000,
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    // 统一处理请求参数
    if (config.data) {
      // 1.删除空参数
      if (config.data.removeEmptyProperty) {
        let newData = removeEmptyProperty(_.cloneDeep(config.data))
        delete newData.removeEmptyProperty
        config.data = newData
      }
      // 2.删除接口编号参数
      if (config.data.pagevalue) {
        delete config.data.pagevalue
      }
    }

    // 设置token
    if (getToken()) config.headers['token'] = getToken()

    // .net 序列化请求数据
    if (config.headers['Content-Type'] !== 'multipart/form-data') {
      config.data = qs.stringify(config.data)
    }

    return config
  },
  (error) => {
    // console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response): any => {
    const res = response.data
    //处理登陆图片
    if (response.config.responseType === 'arraybuffer') {
      return Promise.resolve('data:image/png;base64,' + window.btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), '')))
    } else {
      // 特殊处理 - 阿里云的接口回调不一样
      if (res.Code == 'OK') {
        return Promise.resolve(res)
      }
      // 统一状态处理
      switch (res.Status) {
        case 0: // 成功
          return Promise.resolve(res)
          break
        case -2: // token失效
          if (!isRelogin.show) {
            isRelogin.show = true
            ElMessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                isRelogin.show = false
                useUserStore()
                  .logOut()
                  .then(() => {
                    location.href = '/index'
                  })
              })
              .catch(() => {
                isRelogin.show = false
              })
              return Promise.reject(res)
          }
          break
        default: // 其他错误
          ElMessage({
            message: res.Message,
            type: 'error',
          })
          return Promise.reject(res)
          break
      }
    }
  },
  (error) => {
    console.log('err：' + error)
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({
      message: message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download(url: string, params: any, filename: string, config: any = {}) {
  downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  return service
    .post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params)
        },
      ],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config,
    })
    .then(async (data: any) => {
      const isBlob = blobValidate(data)
      if (isBlob) {
        const blob = new Blob([data])
        saveAs(blob, filename)
      } else {
        const resText = await data.text()
        const rspObj = JSON.parse(resText)
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        ElMessage.error(errMsg)
      }
      downloadLoadingInstance.close()
    })
    .catch((r) => {
      console.error(r)
      ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close()
    })
}

export default service
