import './../../../static/encry.min' // 接口参数加密
import util from './../../util/util'

function initData(params)
{
  var URLSearchParams = require('url-search-params');
  //360浏览器不支持URLSearchParams
  if(typeof URLSearchParams==="function")
  {
    var formMap = new URLSearchParams();
    for(var key in params){
      formMap.append(key, params[key]);
    }
    return formMap;
  }
  else
  {
    return params;
  }

}

function showTokenInvalid (val) {
  let tips = '未知token错误'
  switch (val) {
      case -1:
          tips = 'token为空'
          break;
      case -2:
          tips = 'token无效或过期'
          break;
      default:
          break;
  }

  alert(tips)
}

function showParamCheck (val) {
  let tips = '参数校验错误'
  switch (val) {
      case -2:
          tips = '参数校验失败'
          break;
      case -3:
          tips = '参数校验失败，服务器异常'
          break;
      default:
          break;
  }

  alert(tips)
}

export default async(url = '',baseUrl='',data = {},dataType = 'JSON', type = 'GET', method = 'fetch') => {
	type = type.toUpperCase();
  if(process.env.NODE_ENV === 'development'){
    baseUrl=baseUrl;
  }
  else if(process.env.NODE_ENV === 'production')
  {
     let hostConfig = process.env.hostConfig
     if(baseUrl)
     {
       switch (baseUrl) {
         case "/crm400":
           baseUrl = process.env.findAddr(hostConfig, 'crm400');
           break;
         case "/walter":
           baseUrl = process.env.findAddr(hostConfig, 'walter');
           break;
         case "/club":
           baseUrl = process.env.findAddr(hostConfig, 'club');
           break;
         case "/activity":
           baseUrl = process.env.findAddr(hostConfig, 'activity');
           break;
         case "/steward":
           baseUrl = process.env.findAddr(hostConfig, 'steward');
           break;
         case "/houserkeep":
           baseUrl = process.env.findAddr(hostConfig, 'houserkeep');
           break;
         case '/question'://调查问卷
           baseUrl = process.env.findAddr(hostConfig, 'question');
           break;
         case '/article'://调查问卷
           baseUrl = process.env.findAddr(hostConfig, 'article');
           break;
         case '/charge'://收费系统
           baseUrl = process.env.findAddr(hostConfig, 'charge');
           break;
         case '/activiti': // 用餐预定、会议室预定
           baseUrl = process.env.findAddr(hostConfig, 'activiti');
           break;
         case '/decorationManage': // 装修申请
           baseUrl = process.env.findAddr(hostConfig, 'decorationManage');
           break;
         case '/itemPassport': // 物品放行
           baseUrl = process.env.findAddr(hostConfig, 'itemPassport');
           break;
           case '/neikong': //内控
            baseUrl = process.env.findAddr(hostConfig, 'neikong');
         default:
           baseUrl = "";
           break;
       }
     }
  }
	url = baseUrl + url;

	if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr+'&_t=' + new Date().getTime();;
		}
	}

	if (window.fetch && method == 'fetch') {
    var header_content = {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
    };
    if(dataType && dataType==="XML")
    {
      header_content = {
        'Accept': 'application/xml',
        'Content-Type': 'application/x-www-form-urlencoded',
      };
    }

    header_content.sign = key_gen.encode(key_gen.handlerData(type == 'GET'?url.substring(url.indexOf("?")+1):data));
    header_content.token = localStorage.token ? localStorage.token : '';

    try {
      var useraccount = localStorage.getItem('userAccount');
      if (useraccount) {
        header_content.useraccount = encodeURI(useraccount);
      }
      var username = localStorage.getItem('fullName')
      if (username) {
        header_content.username = encodeURI(username);
      }
      var projectname = JSON.parse(localStorage.getItem("currProject")).projectName;
      if (projectname) {
        header_content.projectname = encodeURI(projectname);
      }
    }
    catch (e) {
      console.log(JSON.stringify(e));
    }

		let requestConfig = {
			credentials: 'include',
			method: type,
			headers: header_content,
			mode: "cors",
			cache: "force-cache"
		}

		if (type == 'POST') {
			Object.defineProperty(requestConfig, 'body', {
				value: initData(data)
			})
		}
    //if (type == 'POST') {
    //  Object.defineProperty(requestConfig, 'body', {
    //    value: JSON.stringify(data)
    //  })
    //}

		try {
			const response = await fetch(url, requestConfig);
      if(dataType && dataType==="XML")
      {
        const responseJson = await response.text();
        return responseJson
      }
      else
      {
        const responseJson = await response.json();

        // token_code: -1:token为空，-2:token:无效或者过期
        if (responseJson.token_code === -1 || responseJson.token_code === -2) {
            if (util.isWeixin()) {
                showTokenInvalid(responseJson.token_code)
            } else {
                EbeiPlugins.showTokenInvalidAlert()
            }
        } else if (responseJson.code === -2 || responseJson.code === -3) {
            //code: -2:参数校验失败, -3: 服务器异常
            if (util.isWeixin()) {
                showParamCheck(responseJson.token_code)
            } else {
                EbeiPlugins.showParamInvalidAlert(responseJson.code)
            }
        }

        return responseJson
      }
		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, url, true);
			requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      requestObj.setRequestHeader("token", localStorage.getItem('token') || "");
      requestObj.setRequestHeader("sign", key_gen.encode(key_gen.handlerData(type == 'GET'?url.substring(url.indexOf("?")+1):data)));

			try {
			  var useraccount = localStorage.getItem('userAccount');
        if (useraccount) {
          requestObj.setRequestHeader("useraccount", encodeURI(useraccount));
        }
        var username = localStorage.getItem('fullName')
        if (username) {
          requestObj.setRequestHeader("username", encodeURI(username));
        }
        var projectname = JSON.parse(localStorage.getItem("currProject")).projectName;
        if (projectname) {
          requestObj.setRequestHeader("projectname", encodeURI(projectname));
        }
      }
      catch (e) {
			  console.log(JSON.stringify(e));
      }
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response
						if (typeof obj !== 'object') {
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
						reject(requestObj)
					}
				}
			}
		})
	}
}
