import axios from 'axios'
import qs from 'qs'
import * as types from '../store/mutations-types'
import store from '../store/store'
import {appSecret, apiBaseUrl} from './config'
import apiErrorHandler from '../api/error'
import {md5} from 'vux'

axios.defaults.baseURL = apiBaseUrl //基础路径
axios.defaults.timeout = 10 * 1000  //默认10秒超时
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' //设置默认头信息

//请求拦截器
axios.interceptors.request.use((config) => {
  //开发环境时输出调试
  if (process.env.NODE_ENV === 'development') {
    if (config.method === 'get') {
      console.log({
        url: config.url,
        params: config.params,
      })
    } else if (config.method === 'post') {
      console.log({
        url: config.url,
        params: config.data,
      })
    }
  }

  //post时，参数序列化处理
  if (config.method === 'post') {
    if (config.headers.post['Content-Type'] == 'multipart/form-data') {
      let data = new FormData();
      _.forIn(config.data, (v, k) => {
        data.append(k, v);
      })

      config.data = data
    } else {
      config.data = qs.stringify(config.data, {arrayFormat: 'brackets'})
    }
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

//响应拦截器
axios.interceptors.response.use((response) => {
  //开发环境时输出访问接口数据
  if (process.env.NODE_ENV === 'development') {
    console.log(response.data)
  }

  //图片类型的直接返回
  if (response.headers["content-type"] === 'image/jpeg') {
    return response.data
  }

  if (response.data) {
    if (response.data.error_code !== 0) {
      //返回服务器错误
      return Promise.reject({
        'error_code': response.data.error_code,
        'error_message': response.data.message,
        'data': response.data.data
      })
    }

    //只返回接口data 对象
    return response.data.data
  }

  //无返回值时，输出错误
  return Promise.reject()

}, function (error) {
  return Promise.reject(error);
})

/**
 * 生成签名
 * @param param
 * @returns {string}
 */
const sign = (param) => {
  let sign = '', key = [], p = Object.assign({}, param)

  //参数排序
  p.key = appSecret
  _.forIn(p, (v, k) => {
    key.push(k)
  })
  key.sort()

  //生成签名字符串
  key.map((v, k) => {
    p[v] = (p[v] != null && p[v] != undefined) ? p[v] : ''
    sign += `&${v}=${p[v]}`
  })
  sign = sign.substr(1)
  sign = md5(sign)
  sign = sign.toLowerCase()

  return sign
}

/**
 * 错误处理
 * @param error
 * @param reject
 */
const errorHandler = (error, reject) => {
  // if (process.env.NODE_ENV === 'development') {
  //   console.log(error)
  // }

  apiErrorHandler(error, reject)
}

export default (url = '', params = {}, options = {}) => {
  let config = {}
  options = Object.assign({method: 'get', loading: false, errorHandle: true}, options)
  options.method = options.method.trim().toUpperCase();

  if (url) {

    //获取签名
    const signStr = sign(params)

    //修改：sign都使用post传参,get方法改为拼接url
    if (options.method === 'GET') {
      let getParams = '';
      _.forIn(params, (v, k) => {
        getParams += `&${k}=${v != null && v != undefined ? v : ''}`
      })
      getParams = getParams.substr(1)
      if (getParams.length > 0)
        url = url.indexOf('?') > -1 ? url + '&' + getParams : url + '?' + getParams

      //清除可能post过去的数据
      // params = {}
    }

    params.sign = signStr

    //处理返回值是原生图片类型
    if (options.requestType === 'image') {
      config.responseType = 'arraybuffer'
    }

    //处理文件上传信息
    if (options.requestType == 'file') {
      config.headers = {}
      config.headers.post = {}
      config.headers.post['Content-Type'] = 'multipart/form-data' //文件上传头信息
    }

    return new Promise((resolve, reject) => {
      if (options.loading) {
        store.dispatch(types.SHOW_LOADING)
      }
      axios.post(url, params, config)
        .then(res => {
          resolve(res)
        })
        .catch(error => {
          if (options.errorHandle) {
            errorHandler(error, reject)
          }
          reject(error)
        })
        .finally(() => {
          if (options.loading) {
            store.dispatch(types.HIDE_LOADING)
          }
        })
    })
    // }
  }

}
