import fetch from 'dva/fetch'
import { message } from 'antd'
import MD5 from 'md5'
import queryString from 'query-string'
import config from '../config'
import { history } from './history'
import storage from './storage'

export function request(url, options, onlyData, requestKey, onException) {
  return fetch(
    config.serviceHost('api/' + url),
    options || {}
  ).then(response => {
    // 登陆过期
    if (response.status === 401) {
      window.localStorage.removeItem('accessToken')
      history.replace({ pathname: '/login' })
      throw new Error('token过期')
    }
    requestKey && window.localStorage.removeItem(requestKey)
    return response.json()
  }).then(data => {
    data.IsSuccessful !== undefined && !data.IsSuccessful && message.error(data.ErrorMessage)
    return onlyData ? data.Data : data
  }).catch(err => {
    requestKey && window.localStorage.removeItem(requestKey)
    onException instanceof Function && onException(err)
  })
}

/**
 * 获取请求 headers
 * @param {*} url 
 * @param {*} type 
 * @param {*} isIgnoreTenant 
 * @returns 
 */
export function getRequestHeaders(url, type = 'post', isIgnoreTenant) {
  // 请求参数
  const addHeader = 'Bearer ' + storage('lacal').getItem('accessToken').val
  const userId = storage('lacal').getItem('userid').val
  if (!userId) {
    history.replace({ pathname: '/login' })
  }
  const user = storage('lacal').getItem('loginUserVerify').val
  const RootOrgId = storage('lacal').getItem('RootOrgId').val
  const orgId = storage('lacal').getItem('webOrgId').val
  const depId = storage('lacal').getItem('departmentId').val
  const DataRule = storage('lacal').getItem('DataRule').val
  const headers = {
    'Content-Type': type === 'post' ? 'application/json' : 'application/x-www-form-urlencoded',
    Authorization: addHeader,
    userid: userId,
    username: user ? user.username : '',
    departmentId: depId,
    RootOrgId,
    orgId,
    DataRule
  }
  // 非 OP 路径接口，header 需要添加 Tenant
  const Tenant = storage('lacal').getItem('Tenant').val
  url.indexOf('OP') != 0 && !isIgnoreTenant && (headers.Tenant = Tenant)
  return headers
}

/**
 * post 请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} onlyData 
 * @param {*} ignoreThrottle 
 * @param {*} onException 
 * @param {*} isIgnoreTenant 
 * @returns 
 */
export function httpPost(url, data, onlyData = true, ignoreThrottle, onException, isIgnoreTenant) {
  //const DataRule = storage('lacal').getItem('DataRule').val
  const OrgRule = storage('lacal').getItem('OrgRule').val
  // 与 isIgnoreTenant 相关配套的逻辑
  const extraData = isIgnoreTenant ? { OrgId: '', IgnoreOrgRule: true } : {}
  //const dataStr = JSON.stringify(Object.assign({}, data, { DataRule, OrgRule, ...extraData }))
  const dataStr = JSON.stringify(Object.assign({}, data, { OrgRule, ...extraData }))
  // 请求节流
  const requestKey = url + '_' + MD5(dataStr) + '_requestKey'
  const loaded = storage('lacal').getItem(requestKey).val
  if (loaded && !ignoreThrottle) return null
  storage('lacal').setItem(requestKey, true)

  // 发起请求
  return request(url, {
    method: 'POST',
    headers: getRequestHeaders(url, 'post', isIgnoreTenant),
    body: dataStr,
  }, onlyData, requestKey, onException)
}

/**
 * get 请求
 * @param {*} url 
 * @param {*} data 
 * @param {*} onlyData 
 * @param {*} onException 
 * @returns 
 */
export function httpGet(url, data, onlyData = true, onException) {
  const formParams = queryString.stringify(data)
  const searchMark = url.indexOf('?') !== -1
  const formUrl = `${url}${searchMark ? '&' : '?'}${formParams}`
  url = formParams ? formUrl : url
  return request(url, {
    method: 'GET',
    headers: getRequestHeaders(url, 'get'),
  }, onlyData, null, onException)
}
