import _findIndex from 'lodash/findIndex'; 
var crypto = require('crypto');
import User from '../model/User';
import {
  cspAk,
  tplusHostArray,
  ciaHostArray,
  devProxyHost,
  prodProxyHost,
  noProxyHostArray
} from '../const/app';
import {env} from 'mutants-microfx';
import { url } from 'inspector';
const {constant,platform,browser,os} = env;

function getAppCloudAuthInfo(orgId) {

  const user = User.restore();
  if (!user) {
    return '';
  }
  var params = {
    appKey: atob(cspAk),
    orgId: orgId ? orgId : user.orgId,
    userUid: user.userId
  }
  var params_string = JSON.stringify(params);
  var hash = crypto.createHash('md5').update(params_string).digest("hex");
  return new Buffer(hash + ',' + params_string).toString('base64');
}

const middleware = function (axios) {
  axios.interceptors.request.use(
    function proxyRequest(cfg) {
      let user = User.restore();
      //使用在线的代理服务器 解决跨域问题
      let proxyURL = user && user.proxyserver?user.proxyserver:prodProxyHost;
      //如果调试时在启动本地代理
      //_DEV_是否启用模拟数据
      // if (__DEV__) {
      //   proxyURL = devProxyHost;
      // }else{
      //   proxyURL = prodProxyHost;
      // }
      if (cfg.url.indexOf('http') == -1) {
        cfg.url = `${cfg.baseURL}${cfg.url}`
      }
      let noProxyHostIndex = _findIndex(noProxyHostArray, (url) => {
        return cfg.url.indexOf(url) !== -1;
      });
      if (proxyURL && noProxyHostIndex === -1) {
        if(platform == constant.platform.chanjet && window.location.protocol.indexOf('file') > -1){
           // 工作圈模式下  http转为file协议  不用使用代理
        }else{
          cfg.url = `${proxyURL}/?url=${cfg.url}`;
        }
      }
      
        let tplusHostIndex = _findIndex(tplusHostArray, (url) => {
          return cfg.baseURL.indexOf(url) !== -1;
        });
        if (tplusHostIndex !== -1) {
          let authInfo = getAppCloudAuthInfo(cfg.data && cfg.data.targetOrgID ? cfg.data.targetOrgID : '');
          cfg.headers['authInfo'] = authInfo;
        }

        
        
        if (user.channel && user.channel.throughProxy) {
          cfg.headers['appkey'] = atob(cspAk);
          if (user) {
            cfg.headers['userid'] = user.userId;
            cfg.headers['orgid'] = user.orgId;
            cfg.headers['token'] = user.accessToken;
          }
        }
        if(cfg.headers['checkThroughProxy'] && cfg.headers['checkOrgId']){
          cfg.headers['appkey'] = atob(cspAk);
          if (user) {
            cfg.headers['userid'] = user.userId;
            cfg.headers['orgid'] = cfg.headers['checkOrgId'];
            cfg.headers['token'] = user.accessToken;
          }
        }
       
        //支持saas版本
        if (user && user.sid && !cfg.headers['checkThroughProxy']) {
          cfg.headers['tplussid'] = user.sid;
        }

        if(cfg.url.indexOf('/api/v2/')>0){
          cfg.headers['openToken'] = getAppCloudAuthInfo('');
          cfg.headers['appkey'] = atob(cspAk);
        }

        delete cfg.headers['checkThroughProxy'];
        delete cfg.headers['checkOrgId'];
        
        let ciaHostIndex = _findIndex(ciaHostArray, (url) => {
          return cfg.baseURL.indexOf(url) !== -1;
        });
        if (ciaHostIndex === -1 && user && user.tplusToken) {
          if(!!cfg.headers['Authorization']){
            //Authorization如果有值  用调用方的值  不覆盖
          }else{
            cfg.headers['Authorization'] = `token ${user.tplusToken}`;
          }
        }
      return cfg;
    },

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

export default middleware;
