package com.njcn.prepare.harmonic.utils;

import cn.hutool.core.util.StrUtil;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.EnumUtils;
import com.njcn.prepare.harmonic.enums.PrepareResponseEnum;

import javax.validation.constraints.NotNull;
import java.util.Objects;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年05月26日 17:17
 */
public class PrepareEnumUtil {

    /**
     * 获取PrepareResponseEnum实例
     */
    public static PrepareResponseEnum getPrepareResponseEnumByMessage(@NotNull Object value) {
        PrepareResponseEnum prepareResponseEnum;
        try {
            String message = value.toString();
            if(message.indexOf(StrUtil.C_COMMA)>0){
                value = message.substring(message.indexOf(StrUtil.C_COMMA)+1);
            }
            prepareResponseEnum = EnumUtils.valueOf(PrepareResponseEnum.class, value, PrepareResponseEnum.class.getMethod(BusinessException.GET_MESSAGE_METHOD));
            return Objects.isNull(prepareResponseEnum) ? PrepareResponseEnum.PREPARE_INNER_ERROR : prepareResponseEnum;
        } catch (NoSuchMethodException e) {
            throw new BusinessException(CommonResponseEnum.INTERNAL_ERROR);
        }
    }


    public static Enum<?> getExceptionEnum(HttpResult<Object> result){
        //如果返回错误，且为内部错误，则直接抛出异常
        CommonResponseEnum commonResponseEnum = EnumUtils.getCommonResponseEnumByCode(result.getCode());
        if (commonResponseEnum == CommonResponseEnum.PREPARE_RESPONSE_ENUM) {
            return getPrepareResponseEnumByMessage(result.getMessage());
        }
        return commonResponseEnum;
    }
}
