package com.ssyf.common.web.result;

import cn.hutool.json.JSONUtil;
import com.ssyf.common.core.util.AssertUtil;
import com.ssyf.common.web.apicode.ApiCode;
import com.ssyf.common.web.apicode.ApiCodeServer;
import com.ssyf.common.web.error.ServiceRuntimeException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应结果帮助类
 * @author huwei
 * @date 2022/7/8 17:13
 */
public class ResultHelper {

    /**
     * 是否为成功返回
     * @param result
     * @return
     */
    public static boolean isSuccess(Result result){
        return ApiCode.Ok.getCode().equals(result.getCode());
    }

    /**
     * 断言业务成功
     * @param result
     */
    public static void assertSuccess(Result result){
        assertSuccess(result ,"业务错误");
    }

    /**
     * 断言业务成功
     * @param result
     * @param message
     */
    public static void assertSuccess(Result result ,String message){
        assertSuccess(result ,new ServiceRuntimeException(ApiCodeServer.ERROR.getCode() ,message));
    }

    /**
     * 断言业务成功
     * @param result
     * @param runtimeException
     */
    public static void assertSuccess(Result result ,RuntimeException runtimeException){
        AssertUtil.isTrue(isSuccess(result) ,runtimeException);
    }


    /**
     * 响应json数据
     * @param result
     * @param response
     */
    public static void responseJson(Result result , HttpServletResponse response) throws IOException {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(JSONUtil.toJsonStr(result));
            out.flush();
        } catch (IOException e) {
            throw e;
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
