import httpConfig from './httpConfig.js';
import Aes from './Aes.js';
import Cache from '../utils/cache.js';

var noSessionCode = '03100014^03100149^03100150^1001^1011^03100013^01040043^03100143^03100112^03100102^03100102^03100102^01010013^03100099^01020008^08010034^12100046^';

// 当前页面是否在 pages/staticPages 目录下（该目录下的静态页面不跳转登录）
function isStaticPage() {
  try {
    const href = location.href;
    return href.indexOf('pages/staticPages') > -1;
  } catch (e) {
    return false;
  }
}

export const $http = {
  post: (type, Nothis, Objson, callBack) => {
    let fetchUrl = httpConfig.urlAddress;
    let formData = Object.assign({}, Objson.data);
    formData.code = Objson.code;
    if(Objson.namespace) {
      formData.HISFlag = Objson.namespace || "";
      formData.UPPFlag = Objson.namespace || "";
    }
    if(Objson.wechatCode) {
      formData.wechatCode = Objson.wechatCode || "";
    }
    let userData = Cache.get('userData');
    let isLogin = !!(userData && userData.userID);
    let session = [];
    if (isLogin) {
      session.push(userData);
    } else {
      session.push({});
    }
    if (noSessionCode.indexOf(formData.code) < 0 && !isLogin && !isStaticPage()) {
      // 单点登录进行中时，不跳登录页，等待 SSO 完成后页面会自动刷新
      let ssoPending = false;
      try {
        let appRef = getApp();
        ssoPending = !!(appRef && appRef.globalData && appRef.globalData.ssoPending);
      } catch (e) {}
      if (ssoPending) {
        return;
      }
      let object = {};
      object.index = 1;
      object.text = '';
      uni.setTabBarBadge(object);
      uni.showToast({
        title: '请先登录',
        icon: 'none',
        success: function () {
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/tabBar/login/login'
            });
          }, 1500);
        }
      });
      return;
    }
    formData.session = session;
    let bodyData = JSON.stringify(formData);
    if (fetchUrl.indexOf('Encrypt') > -1) {
      bodyData = Aes.Encrypt(JSON.stringify(formData));
    }
    uni.request({
      url: fetchUrl,
      data: bodyData,
      method: 'post',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': httpConfig.authorizationToken
      },
      success: function (res) {
        Objson.callback && Objson.callback.call(Nothis, bodyData);
        if (+res.statusCode === 200) {
          let data = res.data;
          if (fetchUrl.indexOf('Encrypt') > -1) {
            data = JSON.parse(Aes.Decrypt(data));
          }
          if (data.errorCode == '0') {
            Objson.success.call(Nothis, data);
          } else {
            if ((data.errorCode == '01040053' || data.errorCode == '01040054' || data.errorCode == '01040055') && !isStaticPage()) {
              Cache.remove('userData');
              let object = {};
              object.index = 1;
              object.text = '';
              uni.setTabBarBadge(object);
              uni.showToast({
                title: '请先登录',
                icon: 'none',
                success: function () {
                  setTimeout(() => {
                    uni.switchTab({
                      url: '/pages/tabBar/login/login'
                    });
                  }, 1500);
                }
              });
            } else {
              if (data.errorCode != '01040052') {
                if (Objson.fail) {
                  Objson.fail.call(Nothis, data);
                }
                if (callBack && callBack.error === 'Y') {
                  Objson.success.call(Nothis, data);
                  return;
                }
                uni.showToast({
                  title: data.errorMessage,
                  icon: 'none'
                });
              }
            }
          }
        } else {
          uni.showModal({
            title: '异常提示',
            content: '接口访问异常，请在【我的-帮助和反馈】或【我的-"点击"问号图标】中进行反馈,谢谢！',
            showCancel: false,
            confirmText: '知道了',
            success: function (res) {
              if (res.confirm) {
                if (callBack && callBack.error === 'Y') {
                  let data = {};
                  data.errorCode = '-1';
                  data.errorMessage = '接口异常';
                  Objson.success.call(Nothis, data);
                }
              }
            }
          });
        }
      },
      fail: function (error) {
        console.log(error);
        let data = {};
        data.errorCode = '-1';
        data.errorMessage = '网络异常，请检查网络';
        Objson.success.call(Nothis, data);
        uni.showToast({
          title: '网络异常，请检查网络',
          icon: 'none'
        });
      },
      complete: function (data) {
        typeof Objson.complete == 'function' && Objson.complete.call(Nothis, data);
      }
    });
  }
};

export default $http;
