package com.gitee.sop.admin.service.jackson.convert.serde;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.gitee.sop.admin.common.context.SpringContext;
import com.gitee.sop.admin.common.resp.UserVO;
import com.gitee.sop.admin.common.user.User;
import com.gitee.sop.admin.common.util.CopyUtil;
import com.gitee.sop.admin.service.sys.UserCacheService;
import lombok.extern.slf4j.Slf4j;

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

/**
 * @author 六如
 */
@Slf4j
public class UserFormatSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }
        Long userId = (Long) value;
        if (Objects.equals(userId, 0L)) {
            gen.writeNumber(userId);
            return;
        }
        Optional<User> userOpt = SpringContext.getBean(UserCacheService.class).getUser(userId);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            UserVO userVO = CopyUtil.copyBean(user, UserVO::new);
            gen.writeObject(userVO);
        } else {
            gen.writeObject(value);
        }
    }
}
