package com.chushang.common.dict.jackson;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.chushang.common.dict.annotation.DictFormat;
import com.chushang.common.dict.utils.DictUtils;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Slf4j
public class DictJsonSerializer extends JsonSerializer<Object> implements ContextualSerializer {

    private String dictType;
    private boolean rewrite;
    private boolean labelGetValue;

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        DictFormat anno = property.getAnnotation(DictFormat.class);
        if (Objects.nonNull(anno) && StrUtil.isNotBlank(anno.dictType())) {
            this.dictType = anno.dictType();
            this.rewrite = anno.rewrite();
            this.labelGetValue = anno.labelGetValue();
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        try {
            if (null != value){
                String dict = labelGetValue ? DictUtils.getDictValue(dictType, Convert.toStr(value)) :
                        DictUtils.getDictLabel(dictType, Convert.toStr(value));
                if (rewrite) {
                    // 重写了 原先的 code
                    gen.writeString(dict);
                }else {
                    // value == code
                    gen.writeObject(value);
                    gen.writeFieldName(gen.getOutputContext().getCurrentName() + "Name");
                    gen.writeString(dict);
                }
            }else {
                gen.writeObject(value);
            }

        } catch (BeansException e) {
            log.error("字典数据未查到, 采用默认处理【{}】", e.getMessage());
            gen.writeObject(value);
        }
    }
}
