import axios from 'axios'
import cache from '../plugins/cache'
import {  Message  } from 'element-ui'
const door = sessionStorage.getItem('AI-INTELLIGENT-TOOLS_BASE_URL');
import { decrypt } from './aes-utils';
import constants from '../utils/constants';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: door || constants.publicPath,
  // 超时
  timeout: 80000
})

service.interceptors.request.use(config => {
  if (cache.session.getJSON('SRKJ_TOKEN_CACHE')) {
    // config.headers["X-Id-Token"] = cache.session.getJSON('SRKJ_TOKEN_CACHE');
    if (!config.params) config.params = {};
    config.params.token = cache.session.getJSON('SRKJ_TOKEN_CACHE');
  }
  // 是否需要防止数据重复提交
  const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
  if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
    const requestObj = {
      url: config.url,
      data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
      time: new Date().getTime()
    }
    const sessionObj = cache.session.getJSON('sessionObj')
    if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
      cache.session.setJSON('sessionObj', requestObj)
    } else {
      const s_url = sessionObj.url;                  // 请求地址
      const s_data = sessionObj.data;                // 请求数据
      const s_time = sessionObj.time;                // 请求时间
      const interval = 100;                         // 间隔时间(ms)，小于此时间视为重复提交
      if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
      } else {
        cache.session.setJSON('sessionObj', requestObj)
      }
    }
  }
  return config
}, error => {
  Promise.reject(error)
})

service.interceptors.response.use(res => {
  // 二进制数据则直接返回
  if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
    return res.data
  }
  let srkjData = res.data;
  // if (srkjData) {
  //   const respData = decrypt(srkjData);
  //   try {
  //     srkjData = JSON.parse(respData);
  //   } catch (e) {}
  // }
  cache.session.remove('ERROR_SR_CODE');
  if (res.status === 401) {
    Message.warning(srkjData.message.description);
    return;
  }
  if (!srkjData.resultCode.endsWith('0000')) {
    cache.session.setJSON('ERROR_SR_CODE', srkjData.message.description);
    // Message.warning(srkjData.message.description)
  }
  return srkjData.queryData || srkjData.data || srkjData.token;
})

export default service
