/* global window */
import axios from 'axios'
import qs from 'qs'
import jsonp from 'jsonp'
import lodash from 'lodash'
import pathToRegexp from 'path-to-regexp'
import { message } from 'antd'
import config from './config'
import util from './util';
import router from 'umi/router';
import permission from './permission'


const fetch = (options) => {
  let {
    method = 'post',
    data,
    fetchType,
    url,
    dataHeader
  } = options

  const cloneData = lodash.cloneDeep(data)

  try {
    let domin = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0]
      url = url.slice(domin.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domin + url
  } catch (e) {
    message.error(e.message)
  }

  if (fetchType === 'JSONP') {
    return new Promise((resolve, reject) => {
      jsonp(url, {
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000
      }, (error, result) => {
        if (error) {
          reject(error)
        }
        resolve({ statusText: 'OK', status: 200, data: result })
      })
    })
  } else if (fetchType === 'YQL') {
    url = `http://query.yahooapis.com/v1/public/yql?q=select * from json where url='${options.url}?${encodeURIComponent(qs.stringify(options.data))}'&format=json`
    data = null
  }
  console.log('am-flexbox-align-start')
  //使用axios拦截器添加sso.token请求头
  axios.interceptors.request.use(
    config => {
      var token = util.auth.getToken();
      if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers['Sso-Token'] = token;
        // config.headers['Sso-Token'] = 'eyJraWQiOiIiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhcHBsaWNhdGlvbktleSI6IndlY2hhdGNwIiwiaXNzIjoiY21zIiwidXNlck5hbWUiOiJCOTY2QkZCNC00OTNDLTQ0MUEtQkYwMi04RTM3NTA2NDRERTgiLCJncmFudFR5cGUiOiJjbGllbnRDcmVkZW50aWFscyIsImV4cCI6MTU5MzAwOTExOCwiaWF0IjoxNTkzMDAxOTE4fQ.x5X-lbwXMbkyT_ZuaCar_0bUXNto4CSkXPSrK9OFUCNIAmjkKQmv3FO5INbE73-wMmBP_gKgDLXfqZZLha2as2rZr5FnqrnGeEOS74SV1RtsNm0eF8U0sO6iOnl2YVM20Oh0AnAUkzamVp06qX-WaeoE-Ode5GyixZEkU01Fq3Q';
      }
      return config;
    }, err => {
      return Promise.reject(err);
    }
  );

  // 拦截器
  axios.interceptors.response.use(
  response => {
    if(response && response.data && response.data.messageCode){
      
      switch (response.data.messageCode) {
        
        case 105:
          util.auth.removeToken();
          permission.clear();

          //confirm('过期')
          // router.replace({
          //   path: '/login'
          // })
          // location.reload()
          //window.location.href = "/login";
          break;
      }
    }
    return response
  },
  error => {
    if (!error.response && error.request) {
      // util.auth.removeToken();
      // permission.clear();

      // confirm('接口出错或者登陆过期');
      // // router.push('/login');
      // router.replace({
      //   path: '/login'
      // })
      // location.reload()
    }
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          util.auth.removeToken();
          permission.clear();
          
          //confirm('过期')
          console.log('过期');
          // router.push('/login');
          router.replace({
            path: '/login'
          })
          location.reload()
          //window.location.href = "/login";
          break;
      }
    }
    // return Promise.reject(error.response)   // 返回接口返回的错误信息
  });

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: cloneData
      })
    case 'delete':
      return axios.delete(url, {
        data: cloneData
      })
    case 'post':
      return axios.post(url, cloneData,dataHeader) 
    case 'put':
      return axios.put(url, cloneData,dataHeader)
    case 'patch':
      return axios.patch(url, cloneData,dataHeader)
    default:
      return axios(options)
  }
}


const Asyncfetch = async (options) => {
  let {
    method = 'post',
    data,
    fetchType,
    url,
    dataHeader
  } = options

  const cloneData = lodash.cloneDeep(data)

  try {
    let domin = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0]
      url = url.slice(domin.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domin + url
  } catch (e) {
    message.error(e.message)
  }

  if (fetchType === 'JSONP') {
    return await jsonp(url, {
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000
      }, (error, result) => {
        if (error) {
          return error
        }
        return { statusText: 'OK', status: 200, data: result }
      })
  } else if (fetchType === 'YQL') {
    url = `http://query.yahooapis.com/v1/public/yql?q=select * from json where url='${options.url}?${encodeURIComponent(qs.stringify(options.data))}'&format=json`
    data = null
  }

  //使用axios拦截器添加sso.token请求头
  axios.interceptors.request.use(
    config => {
      var token = util.auth.getToken();
      console.log(token,'configs')
      if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers['Sso-Token'] = token;
        // config.headers['Sso-Token'] = 'eyJraWQiOiIiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhcHBsaWNhdGlvbktleSI6IndlY2hhdGNwIiwiaXNzIjoiY21zIiwidXNlck5hbWUiOiJCOTY2QkZCNC00OTNDLTQ0MUEtQkYwMi04RTM3NTA2NDRERTgiLCJncmFudFR5cGUiOiJjbGllbnRDcmVkZW50aWFscyIsImV4cCI6MTU5MzAwOTExOCwiaWF0IjoxNTkzMDAxOTE4fQ.x5X-lbwXMbkyT_ZuaCar_0bUXNto4CSkXPSrK9OFUCNIAmjkKQmv3FO5INbE73-wMmBP_gKgDLXfqZZLha2as2rZr5FnqrnGeEOS74SV1RtsNm0eF8U0sO6iOnl2YVM20Oh0AnAUkzamVp06qX-WaeoE-Ode5GyixZEkU01Fq3Q';
      
      }
      return config;
    }, err => {
      return Promise.reject(err);
    });

  switch (method.toLowerCase()) {
    case 'get':
      return await axios.get(url, {
        params: cloneData
      })
    case 'delete':
      return await axios.delete(url, {
        data: cloneData
      })
    case 'post':
      return await axios.post(url, cloneData,dataHeader)
    case 'put':
      return await axios.put(url, cloneData,dataHeader)
    case 'patch':
      return await axios.patch(url, cloneData,dataHeader)
    default:
      return await axios(options)
  }
}

export default function request(options) {
  //判断url前缀是否是java的，是就直接返回java的那个request
  if (options.url && options.url.indexOf("/japi") === 0) {
    options.url = options.url.replace("/japi","");
    return jrequest(options);
  }

  //TODO:后台访问地址前缀移入配置文件
  if (options.url && options.url.indexOf('//') === -1 && options.url.indexOf('api/v') > 0 && options.url.indexOf('ums/') < 0 && options.url.indexOf('web/') < 0) {
    options.url = config.apiPrefix + options.url;
  }
  if (options.url && options.url.indexOf('//') === -1 && options.url.indexOf('api/v') < 0 && options.url.indexOf('web/') > 0) {
    options.url = config.webApiPrefix + options.url;
  }
  if (options.url && options.url.indexOf('//') === -1 && options.url.indexOf('api/v') < 0 && options.url.indexOf('ums/') > 0) {
    options.url = config.authApiPrefix + options.url;
  }
  if (options.url && options.url.indexOf('//') > -1) {
    const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`

    if (window.location.origin !== origin) {
      if (config.CORS && config.CORS.indexOf(origin) > -1) {
        options.fetchType = 'CORS'
      } else if (config.YQL && config.YQL.indexOf(origin) > -1) {
        options.fetchType = 'YQL'
      } else {
        options.fetchType = 'JSONP'
      }
    }
  }

  return fetch(options).then((response) => {
    if(typeof(response)=='undefined')
      return Promise.reject({ success: false, statusCode:500 ,message: "出现未知错误，请稍后再试" });
    let data = options.fetchType === 'YQL' ? response.data.query.results.json : response.data
    if (data['httpCode'] === "200") {
      return Promise.resolve(data['result'])
    } else if (data['code'] + '' === '500') {
      return Promise.reject({ response });
    } else {
      return Promise.resolve(data);
    }
  }).catch((error) => {
    const { response } = error
    let msg
    let statusCode
    if (response && response instanceof Object) {
      const { data, statusText } = response
      statusCode = response.status
      msg = data.message || statusText
    } else {
      statusCode = 600
      msg = error.message || 'Network Error'
    }
    message.error(msg);
    return Promise.reject({ success: false, statusCode, message: msg })
  })
};
  

export let arequest = async (options) => {
  //TODO:后台访问地址前缀移入配置文件
  if (options.url && options.url.indexOf('//') === -1 && options.url.indexOf('api/v') < 0  && options.url.indexOf('ums/') < 0 && options.url.indexOf('web/') < 0) {
    options.url = config.apiPrefix + options.url;
  }
  if (options.url && options.url.indexOf('//') === -1 && options.url.indexOf('api/v') < 0 && options.url.indexOf('web/') > 0) {
    options.url = config.webApiPrefix + options.url;
  }
  if (options.url && options.url.indexOf('//') === -1 && options.url.indexOf('api/v') < 0 && options.url.indexOf('ums/') > 0) {
    options.url = config.authApiPrefix + options.url;
  }
  if (options.url && options.url.indexOf('//') > -1) {
    const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`

    if (window.location.origin !== origin) {
      if (config.CORS && config.CORS.indexOf(origin) > -1) {
        options.fetchType = 'CORS'
      } else if (config.YQL && config.YQL.indexOf(origin) > -1) {
        options.fetchType = 'YQL'
      } else {
        options.fetchType = 'JSONP'
      }
    }
  }
  try {
   let response = await Asyncfetch(options);
   
   let data = options.fetchType === 'YQL' ? response.data.query.results.json : response.data
   if (data['httpCode'] === "200") {
     return data['result']
   } else if (data['code'] + '' === '500') {
     return { response };
   } else {
     return data;
   }
  }catch(error) {
      const { response } = error
      let msg
      let statusCode
      if (response && response instanceof Object) {
        const { data, statusText } = response
        statusCode = response.status
        msg = data.message || statusText
      } else {
        statusCode = 600
        msg = error.message || 'Network Error'
      }
      message.error(msg);
      return { success: false, statusCode, message: msg }
    }
};