package com.njcn.common.pojo.exception;

import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年04月20日 14:48
 */
@Data
@Slf4j
@NoArgsConstructor
public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = -1;

    public static final String GET_CODE_METHOD = "getCode";

    public static final String GET_MESSAGE_METHOD = "getMessage";

    /**
     * 异常码
     */
    private String code;

    /**
     * 异常提示信息
     */
    private String message;

    /**
     * 构造器内的枚举
     */
    private Enum<?> anEnum;

    /**
     * openfeign请求，返回的非常规结果集
     */
    private HttpResult result;

    public BusinessException(Enum<?> eEnum) {
        anEnum = eEnum;
        try {
            Method codeMethod = eEnum.getClass().getMethod(GET_CODE_METHOD);
            Method messageMethod = eEnum.getClass().getMethod(GET_MESSAGE_METHOD);
            this.code = (String) codeMethod.invoke(eEnum);
            this.message = (String) messageMethod.invoke(eEnum);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 针对批量操作的业务返回
     *
     * @author cdf
     * @date 2021/7/7
     */
    public BusinessException(Enum<?> eEnum, String msg) {
        anEnum = eEnum;
        try {
            Method codeMethod = eEnum.getClass().getMethod(GET_CODE_METHOD);
            Method messageMethod = eEnum.getClass().getMethod(GET_MESSAGE_METHOD);
            this.code = (String) codeMethod.invoke(eEnum);
            this.message = (String) messageMethod.invoke(eEnum);
            this.message = this.message.concat(": " + msg);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    public BusinessException(HttpResult result) {
        this.result = result;
    }

    public BusinessException(String message) {
        super(message);
        this.message = message;
        this.code = CommonResponseEnum.FAIL.getCode();
    }
}
