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 tokenCheck(status) {
  if (status === 401) {
    // store.commit('logout', this);
    // store.commit('clearOpenedSubmenu');
    // store.commit('clearAllTags');
    // router.push({
    //     name: 'login',
    //     props: {
    //         timeout: true
    //     },
    //     query: {
    //         isTokenInValid: true
    //     }
    // });
  }
  return false;
}

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', requestType = 'JSON', pathArr = [], method = 'fetch') => {
  type = type.toUpperCase();
  // 拼接userid
  // data.userId = localStorage.userId;
  // 清除空参数
  data = util.filter_param(data);
  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 '/itemHouse': // 物品放行
          baseUrl = process.env.findAddr(hostConfig, 'itemHouse');
          break;
        case '/datashow': //深交所 - 管理视图
          baseUrl = process.env.findAddr(hostConfig, 'datashow');
          break;
        case '/warning': //深交所 - 预警
          baseUrl = process.env.findAddr(hostConfig, 'warning');
          break;
        case '/groupcontrol': //深交所 - 会议管理
          baseUrl = process.env.findAddr(hostConfig, 'groupcontrol');
          break;
        case '/energy-charging': //深交所 - 水电气表查询
          baseUrl = process.env.findAddr(hostConfig, 'energyCharging');
          break;
        case '/wuyecrm': //深交所 - 水电气表查询
          baseUrl = process.env.findAddr(hostConfig, 'wuyecrm');
          break;
        case '/qpi': //内控
          baseUrl = process.env.findAddr(hostConfig, 'qpi');
          break;
        case '/leasing': //内控
          baseUrl = process.env.findAddr(hostConfig, 'leasing');
          break;
        case '/neikong': //内控
          baseUrl = process.env.findAddr(hostConfig, 'neikong');
          break;
        case '/device': //设备预警
          baseUrl = process.env.findAddr(hostConfig, 'device');
          break;
        default:
          baseUrl = "";
      }
    }
  }
  url = baseUrl + url;
  if (pathArr && pathArr.length > 0) {
    url += "/" + pathArr.join("/");
  }
  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();
    } else {
      url = url + '?_t=' + new Date().getTime();
    }
  }

  if (window.fetch && method === 'fetch') {
    var header_content = {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
      'x-user-header': localStorage.user_account ? localStorage.user_account : '',
      'x-userId-header': localStorage.user_id ? localStorage.user_id : '',
      'x-userAccount-header': localStorage.userAccount ? encodeURI(localStorage.userAccount) : '',
      'x-userName-header': localStorage.userName ? encodeURI(localStorage.userName) : '',
      'x-companyId-header': localStorage.companyId ? localStorage.companyId : '',
    };

    if (dataType && dataType === "XML") {
      header_content = {
        'Accept': 'application/xml',
        'Content-Type': 'application/x-www-form-urlencoded',
        'x-user-header': localStorage.user_account ? localStorage.user_account : '',
        'x-userId-header': localStorage.user_id ? localStorage.user_id : '',
        'x-userAccount-header': localStorage.userAccount ? encodeURI(localStorage.userAccount) : '',
        'x-userName-header': localStorage.userName ? encodeURI(localStorage.userName) : '',
        'x-companyId-header': localStorage.companyId ? localStorage.companyId : '',
      };
    } else if (requestType === "JSON") {
      if (type === 'POST') {
        header_content = {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'x-user-header': localStorage.user_account ? localStorage.user_account : '',
          'x-userId-header': localStorage.user_id ? localStorage.user_id : '',
          'x-userAccount-header': localStorage.userAccount ? encodeURI(localStorage.userAccount) : '',
          'x-userName-header': localStorage.userName ? encodeURI(localStorage.userName) : '',
          'x-companyId-header': localStorage.companyId ? localStorage.companyId : '',
        };
      }
    } else if (requestType === "FORMDATA") {
      header_content = {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': "Basic ZWJlaTplYmVp",
        'x-user-header': localStorage.user_account ? localStorage.user_account : '',
        'x-userId-header': localStorage.user_id ? localStorage.user_id : '',
        'x-userAccount-header': localStorage.userAccount ? encodeURI(localStorage.userAccount) : '',
        'x-userName-header': localStorage.userName ? encodeURI(localStorage.userName) : '',
        'x-companyId-header': localStorage.companyId ? localStorage.companyId : '',
      };
    }

    if (localStorage.token && requestType === "JSON") {
      header_content.Authorization = (localStorage.tokenType === "bearer" ? "Bearer " : "") + localStorage.token;
    } else {
      tokenCheck(402);
    }
    header_content.token = localStorage.getItem('token') || ""
    header_content.sign = key_gen.encode(key_gen.handlerData(type === 'GET' ? url.substring(url.indexOf("?") + 1) : data));

    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: "no-cache"
    };

    if (type === 'POST') {
      if (requestType === "FORMDATA") {
        Object.defineProperty(requestConfig, 'body', {
          value: initData(data)
        })
      } else if (requestType === "JSON") {
        Object.defineProperty(requestConfig, 'body', {
          value: JSON.stringify(data)
        })
      }
    }
    try {
      const response = await fetch(url, requestConfig);
      if (dataType && dataType === "XML") {
        const responseJson = await response.text();
        // responseJson.interfacePath = process.env.NODE_ENV === 'development' ? url : '';
        // tokenCheck(responseJson.status);
        return responseJson
      } else {
        const responseJson = await response.json();
        responseJson.errCode = 200;
        responseJson.interfacePath = process.env.NODE_ENV === 'development' ? url : '';

        // 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) {
      const responseJson = {
        errCode: 500,
        msg: "系统异常"
      };
      return responseJson;
    }
  } else {
    return new Promise((resolve, reject) => {
      let requestObj;
      if (window.XMLHttpRequest) {
        requestObj = new XMLHttpRequest();
      } else {
        requestObj = new ActiveXObject;
      }

      let sendData = '';
      if (type === 'POST') {
        if (requestType === "FORMDATA") {
          sendData = initData(data);
        } else if (requestType === "JSON") {
          sendData = JSON.stringify(data);
        }
      }

      requestObj.open(type, url, true);
      if (requestType === "JSON") {
        if (type === 'GET') {
          requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        } else if (type === 'POST') {
          requestObj.setRequestHeader("Content-type", "application/json");
        }
      } else {
        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.indexOf("<?xml") == -1) {
              obj = JSON.parse(obj);
            }
            obj.interfacePath = process.env.NODE_ENV === 'development' ? url : '';
            // token_code: -1:token为空，-2:token:无效或者过期
            if (obj.token_code === -1 || obj.token_code === -2) {
              if (util.isWeixin()) {
                showTokenInvalid(obj.token_code)
              } else {
                EbeiPlugins.showTokenInvalidAlert()
              }
            } else if (obj.code === -2 || obj.code === -3) {
              //code: -2:参数校验失败, -3: 服务器异常
              if (util.isWeixin()) {
                showParamCheck(obj.code)
              } else {
                EbeiPlugins.showParamInvalidAlert(obj.code)
              }
            }
            // tokenCheck(obj.status);
            resolve(obj)
          } else {
            reject(requestObj)
          }
        }
      }
    })
  }
}
