/**
 * 网络请求
 */
const _getHeaderUrl = Symbol('_getHeaderUrl')
// const signatureUtil = require('./HSSignatureUtil.js')
// import { Loading } from 'element-ui'
import axios from 'axios'
import store from '../../store/storeAll'
import NProgress from 'nprogress' // 引入nprogress插件
import 'nprogress/nprogress.css'  // 这个nprogress样式必须引入
axios.defaults.timeout = 600000 // 超时时间
// 生成一个时间戳
const time = new Date()
const timeSing = `${time.getFullYear()}.${time.getMonth() + 1}.${time.getDate()}.${time.getHours()}.${time.getMinutes()}`
let file_name_down = timeSing + '.xlsx' // 默认文件名
let fullLoading
// function showLoading() {
//   fullLoading = Loading.service({
//     lock: true,
//     text: '加载中...',
//     spinner: 'el-icon-loading',
//     background: '#eceaea12'
//   })
//   setTimeout(_ => {
//     fullLoading.close()
//   }, 1000)
// }
function closeLoading() {
  fullLoading && fullLoading.close()
}
let loading_request_count = 0
function show_full_screen_loading() {
  if (loading_request_count === 0) {
    // showLoading()
  }
  loading_request_count++
}
function hide_full_screen_loading() {
  if (loading_request_count <= 0) return
  loading_request_count--
  if (loading_request_count === 0) {
    closeLoading()
  }
}

axios.interceptors.request.use(
  config => {
    if (config.url.indexOf('no_loading') !== -1) {
      console.log('no_loading')
      // 123
    } else {
      if (config.url.startsWith('http:') || config.url.startsWith('https:')) {
        // 俺啥都不干
      } else {
        config.url = config.url.replace('//', '/')
      }
      NProgress.start()
      show_full_screen_loading()
    }
    return config
  },
  err => {
    hide_full_screen_loading()
    return Promise.reject(err)
  }
)
function response_success_del(response) {
  const { url, method, data } = response.config
  const debug_sql = response.headers.debug_sql
  const { status, statusText } = response
  let responseText = ''
  try {
    responseText = typeof response.request.response === 'object' ? '' : response.request.responseText
  } catch (e) {
    responseText = ''
  }
  if (debug_sql) {
    const debug_sql_c = decodeURIComponent(debug_sql)
      .replace(/\*{3}/g, '\n')
      .replace(/\|{5}/g, '\n\n')
    store.commit('set_dug_sql_error_info', {
      url,
      debug_sql: debug_sql_c,
      status,
      statusText,
      method,
      responseText,
      data
    })
  }
}

function response_error_del(error) {
  const { response, code } = error
  const { status, statusText, data } = response || {}
  let error_title = '错误信息'
  let error_detail = ''
  if (!response && !code) {
    // 没网的情况
    error_title = '网络连接失败，请检查网络！'
    error_detail = '尝试关闭网站重新登陆！'
  } else if (code === 'ECONNABORTED') {
    error_title = '请求超时ECONNABORTED'
    error_detail = 'Uncaught (in promise) Error: timeout of 60000ms exceeded'
  } else if (status === 504) {
    error_title = '请求超时504'
    error_detail = data
  } else if (status === 404) {
    error_title = '404资源请求路径找不到'
    error_detail = response.request.responseURL
  } else if (status === 401 && statusText === 'UNAUTHORIZED') {
    if (self !== top) parent.postMessage('login', '*')
    sessionStorage.removeItem('header')
    error_detail = 'UNAUTHORIZED-未授权401'
    error_title = '身份验证失败，请重新登录!'
  } else {
    if (data.message) {
      error_title = data.message
    } else if (data instanceof Blob) {
      // 这条判断是解决 下载文件返回流的情况 要把流转成json
      const reader = new FileReader()
      reader.readAsText(data)
      const dealFileReader = async function() {
        const result = await new Promise(function(resolve, reject) {
          reader.onload = e => {
            resolve(JSON.parse(e.target.result))
          }
        })
        error_title = result.error_title ? result.error_title : '服务器异常'
        error_detail = result.error_detail
        store.commit('set_error_info', { error_title, error_detail })
      }
      dealFileReader()
      return // 这里一定要加一个return 避免两次触发 store.commit('set_error_info')
    } else if (Object.keys(data).length === 4) {
      error_title = data.error_title ? data.error_title : '服务器异常'
      error_detail = data.error_detail
    } else {
      error_title = '服务器内部错误'
      error_detail = data
    }
  }
  store.commit('set_error_info', { error_title, error_detail })
}

// 增加一个response拦截器
axios.interceptors.response.use(
  function(response) {
    hide_full_screen_loading()
    response_success_del(response)
    // 处理下载文件获取文件名
    if (response.data instanceof Blob) {
      const disposition = response.headers['content-disposition']
      if (disposition) {
        if (disposition.split('=').length > 1) {
          file_name_down = decodeURIComponent(disposition.split('=')[1])
        }
      }
    }
    NProgress.done() // 设置加载进度条(结束..)
    return response
  },
  function(error) {
    hide_full_screen_loading()
    response_error_del(error)
    if (error.response) {
      response_success_del(error.response)
    }
    return Promise.reject(error)
  }
)

class HSHttpClient {
  // parm1:路由参数 parm2问号参数 parm3：body参数
  constructor(url, parm1 = {}, parm2 = {}, parm3 = '') {
    this.urlParams = new Map()
    this.realUrl = url
    this[_getHeaderUrl](parm1) // 处理路由参数
    this.newUrl = this.getSignRequestUrl(parm2, parm3) // 处理问号参数和body参数
  }
  [_getHeaderUrl](params) {
    for (const key in params.data) {
      params.routerUrl = params.routerUrl.replace(
        key,
        encodeURIComponent(params.data[key])
      )
      this.urlParams.set(key, params.data[key])
    }
    if (params.routerUrl) {
      this.realUrl = this.realUrl + params.routerUrl + '/'
    }
  }
  getSignRequestUrl(paramsObj, body = '') {
    let returnUrl = ''
    let tempParamsUrl = ''
    if (paramsObj) {
      for (var key in paramsObj) {
        const val = encodeURIComponent(paramsObj[key])
        if (val !== '') {
          tempParamsUrl += `&${key}=${val}`
          this.urlParams.set(key, paramsObj[key])
        }
      }
    }
    // const timestamp = signatureUtil.getTimeStamp()
    // const nonce = signatureUtil.getRandom(5)
    // const signaPlain = signatureUtil.makeSignPlain(
    //   this.urlParams,
    //   body,
    //   timestamp,
    //   nonce
    // )
    if (this.realUrl.includes('/ref')) {
      returnUrl = this.realUrl
    } else {
      returnUrl = `${
        this.realUrl
      }?${tempParamsUrl}`
    }
    return returnUrl
  }
}
const API = {
  /**
   * get // routerParms:路由参数；interrogationParms：问号参数
   * @param {*} urls
   * @param {*} routerParms
   * @param {*} interrogationParms
   */
  get(urlOld, routerParms = {}, interrogationParms = {}) {
    const Single = new HSHttpClient(urlOld, routerParms, interrogationParms)
      .newUrl
    return axios.get(Single)
  },
  get_singe_url(urlOld, routerParms = {}, interrogationParms = {}) {
    const Single = new HSHttpClient(urlOld, routerParms, interrogationParms)
      .newUrl
    return Single
  },
  get_file_blob(urlOld, routerParms = {}, interrogationParms = {}) {
    const Single = new HSHttpClient(urlOld, routerParms, interrogationParms)
      .newUrl
    return axios({
      method: 'get',
      responseType: 'blob',
      url: Single
    })
  },
  get_file_blob_down(
    urlOld,
    routerParms = {},
    interrogationParms = {},
    filename = '下载的excle'
  ) {
    const Single = new HSHttpClient(urlOld, routerParms, interrogationParms)
      .newUrl
    axios({
      method: 'get',
      responseType: 'blob',
      url: Single
    }).then(data => {
      const url = window.URL.createObjectURL(new Blob([data.data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', filename)
      link.click()
    })
  },
  down_Template(file_name) {
    this.get_file_blob('mesAPI/file/demo/', {}, { file_name }).then(data => {
      const url = window.URL.createObjectURL(new Blob([data.data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', file_name)
      // document.body.appendChild(link)
      link.click()
    })
  },

  down_Excel_sysInit_old(export_type) {
    const routerParms = {
      routerUrl: 'export_type',
      data: {
        export_type
      }
    }
    this.get_file_blob('mesAPI/system_init/export_excel/', routerParms).then(data => {
      const url = window.URL.createObjectURL(new Blob([data.data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', file_name_down)
      link.click()
    })
  },
  isJson(obj) {
    // 判定是否是json
    const isjson =
      typeof obj === 'object' &&
      Object.prototype.toString.call(obj).toLowerCase() === '[object object]' &&
      !obj.length
    return isjson
  },
  down_Excel_sysInit(export_type, ids = []) {
    const bodyParm = {
      export_type: export_type,
      ids: ids
    }
    this.postFiles('mesAPI/system_init/export_excel/', {}, {}, bodyParm).then(data => {
      const url = window.URL.createObjectURL(new Blob([data.data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', file_name_down)
      link.click()
    })
  },
  postFiles(urlOld, routerParms = {}, interrogationParms = {}, bodyParms = {}) {
    const Single = new HSHttpClient(urlOld, routerParms)
    const urlNew = Single.getSignRequestUrl(interrogationParms, bodyParms)
    return axios({
      method: 'post',
      responseType: 'blob',
      url: urlNew,
      data: bodyParms
    })
  },
  /**
   * post routerParms:路由参数；interrogationParms：问号参数，data：body参数
   * @param {*} urls
   * @param {*} routerParms
   * @param {*} interrogationParms
   * @param {*} bodyParms
   */
  post(urlOld, routerParms = {}, interrogationParms = {}, bodyParms = {}) {
    const Single = new HSHttpClient(urlOld, routerParms)
    const urlNew = Single.getSignRequestUrl(interrogationParms, bodyParms)
    return axios.post(urlNew, bodyParms)
  },
  delete(urlOld, routerParms = {}, interrogationParms = {}, bodyParms = {}) {
    const Single = new HSHttpClient(urlOld, routerParms)
    const urlNew = Single.getSignRequestUrl(interrogationParms, bodyParms)
    return axios.delete(urlNew, { data: bodyParms })
  },
  put(urlOld, routerParms = {}, interrogationParms = {}, bodyParms = {}) {
    const Single = new HSHttpClient(urlOld, routerParms)
    const urlNew = Single.getSignRequestUrl(interrogationParms, bodyParms)
    return axios.put(urlNew, bodyParms)
  },
  post_file(urlOld, data = {}, routerParms = {}, interrogationParms = {}) {
    const url = this.get_singe_url(urlOld, routerParms, interrogationParms)
    return axios.post(url, data)
  },
  win_open_down_file(type) {
    window.open(`/mesAPI/system_init/export_excel/${type}/`)
  }
}

export default API
