package com.ai.da.common.config.exception;

import com.ai.da.common.context.UserContext;
import com.ai.da.common.response.ResultEnum;
import com.ai.da.model.enums.Language;
import com.ai.da.model.vo.AuthPrincipalVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Objects;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * @author: dangweijian
 * @description: 业务异常
 * @create: 2020-01-01 17:24
 **/
@Data
@Slf4j
public class BusinessException extends RuntimeException {

    private Integer code;
    private String msg;

    public BusinessException(ResultEnum resultEnum) {
        this.code = resultEnum.getCode();
        this.msg = getMessageFromResource(resultEnum.getMsg(), getUserLocale());
    }

    public BusinessException(String msg) {
        this.code = ResultEnum.FAIL.getCode();
        this.msg = getMessageFromResource(msg, getUserLocale());
    }

    public BusinessException(String msg, Integer code) {
        this.code = code;
        this.msg = getMessageFromResource(msg, getUserLocale());
    }

    public BusinessException(Throwable cause) {
        this.code = ResultEnum.FAIL.getCode();
        this.msg = getMessageFromResource(cause.getMessage(), getUserLocale());
    }

    private static Locale getUserLocale() {
        AuthPrincipalVo userInfo = UserContext.getUserHolder();
        if (Objects.isNull(userInfo)) {
            return new Locale("en");
        }
        return new Locale(Language.valueOf(userInfo.getLanguage()).getValue());
    }

    public static String getMessageFromResource(String msg) {
        return getMessageFromResource(msg, getUserLocale());
    }

    public static String getMessageFromResource(String msg, Locale userLocale) {
        try (InputStream inputStream = BusinessException.class.getClassLoader().getResourceAsStream("messages_" + userLocale.getLanguage() + ".properties")) {
            if (inputStream != null) {
                ResourceBundle bundle = new PropertyResourceBundle(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                if (bundle.containsKey(msg)) {
                    return bundle.getString(msg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg; // 如果找不到对应的资源文件，返回原始的消息
    }
}