package com.njcn.rdms.module.system.service.user;

import com.njcn.rdms.framework.common.enums.CommonStatusEnum;
import com.njcn.rdms.module.system.dal.dataobject.file.FileDO;
import com.njcn.rdms.module.system.dal.dataobject.user.UserSignatureDO;
import com.njcn.rdms.module.system.dal.mysql.user.UserSignatureMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import static com.njcn.rdms.framework.common.util.collection.CollectionUtils.singleton;

@Service
public class UserSignatureServiceImpl implements UserSignatureService {

    @Resource
    private UserSignatureMapper userSignatureMapper;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private com.njcn.rdms.module.system.service.file.FileService fileService;

    @Override
    public UserSignatureDO getByUserId(Long userId) {
        if (userId == null) {
            return null;
        }
        return userSignatureMapper.selectByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Long userId, Long fileId, String fileName, Integer status, String remark) {
        adminUserService.validateUserList(singleton(userId));
        FileDO file = fileService.getFile(fileId);

        UserSignatureDO existing = userSignatureMapper.selectByUserId(userId);
        UserSignatureDO target = new UserSignatureDO();
        if (existing != null) {
            target.setId(existing.getId());
        }
        target.setUserId(userId);
        target.setFileId(fileId);
        target.setFileName(StringUtils.hasText(fileName) ? fileName.trim() : file.getName());
        target.setStatus(status == null ? CommonStatusEnum.ENABLE.getStatus() : status);
        target.setRemark(StringUtils.hasText(remark) ? remark.trim() : null);
        if (existing == null) {
            userSignatureMapper.insert(target);
        } else {
            userSignatureMapper.updateById(target);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByUserId(Long userId) {
        if (userId == null) {
            return;
        }
        userSignatureMapper.deleteByUserId(userId);
    }
}
