import axios from 'axios'
import qs from 'qs'
import router from '../../router'
import { Message } from 'element-ui'
import saveAs from './../lib/filesaver'
import NProgress from 'nprogress'
import './../../../static/css/nprogress.css'

var http = require('./httpurl')
function getUserToken () {
  var data = window.localStorage.getItem('etorcurrentuser')
  if (data) { return JSON.parse(data).Token }
  return ''
}

var bmsAxios = axios.create({
  // timeout: 120000,
  // withCredentials: true,
  baseURL: http.baseURL,
  headers: {
    post: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
  }
})

bmsAxios.interceptors.request.use(
  config => {
    var data = ''
    if (window.localStorage.getItem('etorcurrentuser')) {
      data = window.localStorage.getItem('etorcurrentuser')
    }

    if (data == '') {
      config.headers.token = ''
      // eslint-disable-next-line no-use-before-define
      config.headers.sid = sid || 0
    } else {
      config.headers.token = JSON.parse(data).Token
      // var TenantId = JSON.parse(data).Manager.TenantId;
      // var OperaterID = JSON.parse(data).Manager.ID;
    }
    var sid = window.localStorage.getItem('sid')
    config.headers.sid = sid || 0
    removeNullAndUndefinedProperty(config.data)// 没用的参数不要传
    removeNullAndUndefinedProperty(config.params)// 没用的参数不要传
    if (config.url != 'Permission/AgainGetToken') {
      window.localStorage.setItem(
        'lastrequesttime',
        JSON.stringify(Date.now())
      ) // 记录用户最后请求时间
    }
    // debugger
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回状态
let onceMessage = false
bmsAxios.interceptors.response.use(
  res => {
    return res
  },
  error => {
    // 有异常
    if (error.response) {
      switch (error.response.status) {
        case 401:
          if (onceMessage) return
          onceMessage = true
          // Message.error("信息过期，请重新登陆");
          router.replace({
            path: '/login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
          break
        case 204:
          Message.error('暂无数据')
          break
      }
    }

    return Promise.reject(error)
  }
)

export function get (url, config) {
  return new Promise((resolve, reject) => {
    bmsAxios.get(url, {
      params: config,
      paramsSerializer: function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }).then(
      response => {
        if (response.data.Code == 10000) {
          return resolve(response.data)
        } else {
          Message.error(response.data.Message || '数据异常')
        }
      },
      err => {
        reject(err)
      }
    )
      .catch(error => {
        reject(error)
      })
  })
}

export function post (url, params) {
  return new Promise((resolve, reject) => {
    bmsAxios.post(url, params).then(
      response => {
        if (response.data.Code === 20000) {
          return
        }
        if (response.data.Code === 30000) {
          return resolve(response.data)
        }
        if (response.data.Code === 10000) {
          Message.success('操作成功')
          return resolve(response.data)
        } else {
          Message.error(response.data.Message)
        }
      },
      err => {
        Message.error('操作失败')
        reject(err)
      }
    )
      .catch(error => {
        Message.error('操作异常')
        reject(error)
      })
  })
}

export function put (url, params) {
  return new Promise((resolve, reject) => {
    bmsAxios.put(url, params).then(
      response => {
        resolve(response.data)
      },
      err => {
        reject(err)
      }
    )
      .catch(error => {
        reject(error)
      })
  })
}
export function del (url, config) {
  return new Promise((resolve, reject) => {
    bmsAxios.delete(url, { params: config }).then(
      response => {
        resolve(response.data)
      },
      err => {
        reject(err)
      }
    )
      .catch(error => {
        reject(error)
      })
  })
}
/** 使用 get HTTP Method 下载文件 */
export function getDownloadFile (url, params, name) {
  NProgress.start()
  return new Promise((resolve, reject) => {
    bmsAxios
      .get(url, {
        params: {
          ...params,
          params: params
        },
        responseType: 'blob'
      })
      .then(response => {
        // 确定最终文件名
        const fileNameHeader = 'x-suggested-filename'
        let suggestedFileName = response.headers[fileNameHeader] || name
        if (suggestedFileName) { suggestedFileName = decodeURIComponent(suggestedFileName) }
        const effectiveFileName =
                    suggestedFileName === undefined ? 'untitled' : suggestedFileName

        // 长度为零给出提示，扔出错误
        // eslint-disable-next-line eqeqeq
        if (response.data.size == 0) throw new Error('文件长度为0')

        // 返回json，进行解析，获取Message，扔出错误
        // eslint-disable-next-line eqeqeq
        if (response.data.type == 'application/json') {
          let reader = new FileReader()
          reader.onload = function (event) {
            var message = JSON.parse(event.target.result)
            reject(new Error(message.Message)) // 拒绝
          }
          reader.readAsText(response.data)
        } else {
          saveAs(response.data, effectiveFileName)
          resolve() // 解决
        }
      })
      .catch(e => reject(e)).finally(function () {
        NProgress.done()
      }) // 拒绝
  })
}
export function all (urlArr) { // 并发请求
  if (urlArr.length > 6) {
    // eslint-disable-next-line no-throw-literal
    throw '当前不支持数量大于6个的并发请求'
  }
  return new Promise((resolve, reject) => {
    axios.all(urlArr).then(
      axios.spread((v0, v1, v2, v3, v4, v5) => {
        let ret = {}
        arguments.forEach((item, idx) => {
          if (item) { ret[`ret${idx}`] = item }
        })
        // eslint-disable-next-line no-undef
        resolve(item)
      }),
      err => {
        reject(err)
      }
    )
      .catch(error => {
        reject(error)
      })
  })
}

export function axiosHttp (url, params, type = 'get') {
  return new Promise((resolve, reject) => {
    axios[type](url, { params: params }).then(
      response => {
        resolve(response.data)
      },
      err => {
        reject(err)
      }
    ).catch(error => {
      reject(error)
    })
  })
}
function removeNullAndUndefinedProperty (model) { // 移除对象中值为null、undefined的属性
  if (model) {
    for (let key in model) {
      if (model[key] === null || typeof (model[key]) === 'undefined') {
        delete model[key]
      }
    }
  }
}

function createFileInput (accept, onSelect) {
  var lastFileInput = document.getElementById('f1_id')
  if (lastFileInput != null) {
    document.body.removeChild(lastFileInput)
  }
  lastFileInput = document.createElement('input')
  lastFileInput.type = 'file'
  lastFileInput.name = 'f1'
  lastFileInput.id = 'f1_id'
  accept && (lastFileInput.accept = accept)
  lastFileInput.setAttribute('style', 'display:none;')
  document.body.appendChild(lastFileInput)
  lastFileInput.onchange = function (e) {
    var f = lastFileInput.files[0]
    onSelect && onSelect(f)
  }
  return lastFileInput
}
export function getUuid (length) {
  return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36)
}

// 通过axios上传文件
export function upload (url, uconfig) {
  // eslint-disable-next-line no-redeclare
  var uconfig = uconfig || {}
  var params = uconfig.params || {}
  var accept = uconfig.accept || 'image/gif, image/jpeg,image/jpg,image/png,image/*'
  var onProgress = uconfig.onProgress || function () { }
  var onStart = uconfig.onStart || function () { }
  var uuid = uconfig.uuid || getUuid(10)
  let config = {
    headers: {
      'Content-Type': 'multipart/form-data',
      'token': getUserToken(),
      'sid': 0
    },
    transformRequest: [function (data) {
      return data
    }],
    onUploadProgress: e => {
      var completeProgress = ((e.loaded / e.total * 100) | 0)
      onProgress && onProgress(uuid, completeProgress)
      console.log('onUploadProgress:' + completeProgress)
    }
  }
  let formData = new FormData()
  for (let key of Object.keys(params)) {
    formData.append(key, params[key] !== null ? params[key] : '')
  }
  
  return new Promise((resolve, reject) => {
      var uploadAxios = axios.create({
        // withCredentials: true,
        baseURL: http.baseURL
      })
      uploadAxios.post(url, formData, config).then(
        response => { resolve(response.data) },
        err => { reject(err) }
      ).catch(error => { reject(error) })
  })
}
export default {
  baseURL: http.baseURL,
  phpURL: http.phpURL,
  get,
  post,
  del,
  put,
  upload, // :httpfile.upload,
  getDownloadFile,
  all (urlArr) { // 并发请求
    return all(urlArr)
  }
}
