package com.testor.common.translation.handler;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.testor.common.annotation.Translation;
import com.testor.common.core.utils.poi.ExcelUtil;
import com.testor.common.core.utils.reflect.ReflectUtils;
import com.testor.common.translation.TranslationInterface;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 翻译处理器
 *
 * @author Lion Li
 */
@Slf4j
public class TranslationHandler extends JsonSerializer<Object> implements ContextualSerializer {

    /**
     * 全局翻译实现类映射器
     */
    public static final Map<String, TranslationInterface<?>> TRANSLATION_MAPPER = new ConcurrentHashMap<>();

    private Translation translation;

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        // 获取翻译器
        TranslationInterface<?> trans = TRANSLATION_MAPPER.get(translation.type());
        // 如果映射字段不为空，则取映射字段的值
        if (StringUtils.isNotBlank(translation.mapper())) {
            value = ReflectUtils.invokeGetter(gen.getCurrentValue(), translation.mapper());
        }
        // 如果值为 null，直接写出 null
        if (ObjectUtil.isNull(value)) {
            gen.writeNull();
            return;
        }
        Object result = value;
        if (ObjectUtil.isNotNull(trans)) {
            // 使用翻译器进行翻译
            result = trans.translation(value, translation.other());
        } else {
            // 根据 other 字段的格式进行转换
            if (translation.other().contains(",")) {
                result = ExcelUtil.convertByExp(String.valueOf(value), translation.other(), ",");
            }
        }
        // 写出结果
        gen.writeObject(result);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        Translation translation = property.getAnnotation(Translation.class);
        if (Objects.nonNull(translation)) {
            this.translation = translation;
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
