package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhentao.dto.PublishDynamicDTO;
import com.zhentao.entity.UserDynamics;
import com.zhentao.mapper.UserDynamicsMapper;
import com.zhentao.service.PublishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class PublishServiceImpl implements PublishService {

    @Autowired
    private UserDynamicsMapper userDynamicsMapper;

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer publish(PublishDynamicDTO dto) {
        UserDynamics d = new UserDynamics();
        d.setUserId(dto.getUserId() == null ? 1 : dto.getUserId());
        d.setContent(dto.getContent());
        d.setMediaType(dto.getMediaType() == null ? 1 : dto.getMediaType());
        d.setVisibility(dto.getVisibility() == null ? 1 : dto.getVisibility());
        d.setAuditStatus(1); // 简化：直接审核通过
        d.setStatus(1);
        d.setCreatedAt(LocalDateTime.now());
        d.setUpdatedAt(LocalDateTime.now());
        if (CollectionUtils.isNotEmpty(dto.getMediaList())) {
            try {
                d.setMediaUrls(mapper.writeValueAsString(dto.getMediaList()));
            } catch (JsonProcessingException ignore) {}
        }
        userDynamicsMapper.insert(d);
        return d.getDynamicId();
    }
}



