package com.xkrs.common.encapsulation;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

/**
 * 输出信息封装
 * @author tajochen
 */
@Component
public class OutputEncapsulation {

    private static final Logger logger = LoggerFactory.getLogger(OutputEncapsulation.class);

    /**
     * 读取多国语言文件
     * @return
     */
    public static MessageSource messageSource() {
        Properties properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
        // 使用properties对象加载输入流
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    /**
     * 封装输出数据
     * @param promptMessageEnum
     * @param obj
     * @return
     */
    public static String outputEncapsulationObject(PromptMessageEnum promptMessageEnum, Object obj, Locale locale) {

        EncapsulationObejct encapsulationObejct = new EncapsulationObejct();
        encapsulationObejct.setStatus(promptMessageEnum.getCode());
        encapsulationObejct.setMsg(messageSource().getMessage(promptMessageEnum.getText(),null,locale));
        encapsulationObejct.setData(obj);

        ObjectMapper objectMapper = new ObjectMapper();
        // 忽略无法转换的对象
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        // 忽略json字符串中不识别的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 解决jackson无法反序列化LocalDateTime的问题,引入jsr310标准
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        objectMapper.registerModule(javaTimeModule);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        String strByEo = "";
        try {
            strByEo = objectMapper.writeValueAsString(encapsulationObejct);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            logger.warn(e.toString());
        }
        return strByEo;
    }

    /**
     * 输出请求值检验错误信息
     * @param fieldErrors
     * @return
     */
    public static String outputEncapsulationErrorList(List<FieldError> fieldErrors, Locale locale){
        List<String> errorMsg = new ArrayList<>();
        for (FieldError fieldError : fieldErrors) {
            String errMessage = fieldError.getDefaultMessage().subSequence(1,fieldError.getDefaultMessage().length()-1).toString();
            errorMsg.add(messageSource().getMessage(errMessage,null,locale));
        }
        return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,errorMsg,locale);
    }
}
