import globalConfig from './global';

const NEED_RELOGIN_TOPIC = 'NEED_RELOGIN_TOPIC';
/**
 * http 状态
 */
const HTTP_STATUS = {
  SUCCESS: 200,
  /** 未包含认证信息,如：未携带 token 信息 */
  NO_AUTH: 401,
  /** 认证已重置，如：其它地点登录 */
  RESET_AUTH: 409
};

function validReLogin(data){
  return data && [HTTP_STATUS.RESET_AUTH, HTTP_STATUS.NO_AUTH].includes(data.status);
}

export default function(data){
  return new Promise((resolve, reject) => {
    // 兼容老版系统框架返回值
    if ('dataList' in data) {
      if (data.result && data.result.toLocaleLowerCase() === 'success') {
        resolve(data.dataList);
      } else {
        reject(data.message);
      }
    }
    if (data.state) {
      resolve(data);
    } else {
      if (data && data.status === HTTP_STATUS.SUCCESS) {
        resolve(data.result);
      }
      if (data && data.code === HTTP_STATUS.SUCCESS) {
        resolve(data.data);
      }
      // 处理用户被挤掉问题
      else if (validReLogin(data)) {
        if (globalConfig.pubSub && globalConfig.pubSub.publish) {
          globalConfig.pubSub.publish(NEED_RELOGIN_TOPIC, data.message);
        }
        reject(data.message);
      } else {
        if (data && data.message) {
          reject(data.message);
        } else if (data && data.devMessage){
          reject(data.devMessage);
        } else {
          reject(data);
        }
      }
    }
  });
}
