package com.mosty.common.magic.api.config;

import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;

/**
 *	magic 全局结果包装
 * @author kevin
 * @date 2022/5/29 6:06 下午
 * @since 1.0.0
 * @see ResponseResult
 * @see com.mosty.common.base.exception.MostyExceptionHandler
 */
@Slf4j
@Component
@Qualifier("globalResultHandler")
public class CustomJsonValueProvider implements ResultProvider {
    /**
    *   定义返回结果，默认返回JsonBean
    */
	@Override
	public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
        // 如果对分页格式有要求的话，可以对data的类型进行判断，进而返回不同的格式
		return new ResponseResult(code, message, data);
	}

	@Override
	public Object buildException(RequestEntity requestEntity, Throwable throwable) {
		throwable.printStackTrace();
		log.warn("业务异常：message={}", throwable.getMessage());
		Throwable cause = throwable.getCause();
		if (cause instanceof BusinessException) {
			BusinessException businessException = (BusinessException) cause;
			return businessException.getCode() != null ?
					ResponseResult.fail(businessException.getCode(), businessException.getMessage()) :
					ResponseResult.fail(businessException.getMessage());
		}

		return ResponseResult.fail(500, "系统异常，请稍后重试");
	}

	/**
	 *   定义分页返回结果，该项会被封装在Json结果内，
	 *   此方法可以不覆盖，默认返回PageResult
	 */
//	@Override
//	public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List<Map<String, Object>> data) {
//		return new HashMap<String,Object>(){
//			{
//				put("total", total);
//				put("list", data);
//			}
//		};
//	}
}