import { notification, message as amessage, Button } from 'antd';
import isUndefined from 'lodash/isUndefined';
import React from 'react';
import { BASENAME } from '../constants';

// 1. 业务重定向
const bizRedirectHandler = response => {
  const { status, data } = response;
  if (status === 302 && data && data.redirectUrl) {
    window.location.assign(data.redirectUrl);
  } else if (status === 401) {
    const key = 'authrizeFail';
    const btn = (
      <Button
        type="primary"
        size="small"
        onClick={() => {
          notification.close(key);
          window.location.href = `/${BASENAME}/user/login`;
        }}
      >
        确定
      </Button>
    );
    if (!/\/user\/login$/.test(window.location.pathname)) {
      notification.warning({
        key,
        title: '提示',
        message: '授权失败，即将跳转到登录页',
        duration: 4,
        btn,
      });
      setTimeout(() => {
        window.location.href = `/${BASENAME}/user/login`;
      }, 4000);
    }
  }
};

// 2. 开发级错误信息转换
const bizDevErrorAdapter = response => {
  const { status, success, message, description } = response;
  const opCode = Number(status);
  if (success === false && opCode >= 300 && opCode !== 302) {
    return {
      message: message || `${status}`,
      description: description || message,
    };
  }
  return null;
};

// 3. 用户级错误信息转换
const bizErrorMessageAdapter = response => {
  const { status, success, message } = response;
  const opCode = Number(status);
  if (success === false && (opCode < 300 || opCode === 302)) {
    return message;
  }
  return null;
};

// 4. 成功信息转换
const bizSuccessMessageAdapter = (response, successMessage) => {
  const { success, message } = response;
  if (successMessage === false) {
    return null;
  }
  if (success !== false) {
    if (successMessage === true) {
      return message;
    }
    return successMessage;
  }
  return null;
};

// 5. 消息通知
const bizNotifyHandler = notifyMessages => {
  const { successMessage, errorMessage, errorDesc } = notifyMessages;
  if (successMessage) {
    amessage.success(successMessage);
  } else if (errorMessage) {
    amessage.error(errorMessage);
  } else if (errorDesc) {
    notification.error({
      message: errorDesc.message,
      description: errorDesc.description,
    });
  }
};

// 6. 业务数据转换
const bizDataAdapter = response => {
  if (response && !isUndefined(response.data)) {
    return response.data;
  }
  return response;
};

// 7. 请求超时
const bizTimeoutHandler = response => {
  const { status } = response;
  if (status === 500) {
    notification.warning({
      title: '提示',
      message: '请求超时',
      duration: 4,
    });
  }
};

export default {
  bizDataAdapter,
  bizDevErrorAdapter,
  bizErrorMessageAdapter,
  bizSuccessMessageAdapter,
  bizNotifyHandler,
  bizRedirectHandler,
  bizTimeoutHandler,
};
