package com.njcn.energy.pojo.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.energy.pojo.enums.EnergyResponseEnum;

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

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2022/4/20 15:19
 */

public class EnergyEnumUtil {

    /**
     * 获取实例
     */
    public static EnergyResponseEnum getEnergyResponseEnumByMessage(@NotNull Object value) {
        EnergyResponseEnum energyResponseEnum;
        try {
            String message = value.toString();
            if(message.indexOf(StrUtil.C_COMMA)>0){
                value = message.substring(message.indexOf(StrUtil.C_COMMA)+1);
            }
            energyResponseEnum = EnumUtils.valueOf(EnergyResponseEnum.class, value, EnergyResponseEnum.class.getMethod(BusinessException.GET_MESSAGE_METHOD));
            return Objects.isNull(energyResponseEnum) ? EnergyResponseEnum.ENERGY_COMMON_ERROR : energyResponseEnum;
        } 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.USER_RESPONSE_ENUM) {
            return getEnergyResponseEnumByMessage(result.getMessage());
        }
        return commonResponseEnum;
    }
}
