package com.ssm.manage.service.impl;

import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmUploadFilesDao;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.entity.UploadFiles;
import com.ssm.manage.query.UploadFilesRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmUploadFilesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class SsmUploadFilesServiceImpl extends BaseServiceImpl<UploadFiles> implements SsmUploadFilesService {
    @Autowired
    private SsmUploadFilesDao dao;

    @Override
    public SsmUploadFilesDao getDao() {
        return dao;
    }

    @Override
    public List<UploadFiles> selectList(UploadFilesRequest filesRequest) {
        UploadFiles uploadFiles = new UploadFiles();
        BeanUtils.copyProperties(filesRequest, uploadFiles);
        List<UploadFiles> list = dao.select(uploadFiles);
        return list;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int add(UploadFiles files) throws SmsException {
        int i = 0;

        files.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        try {
            i = dao.saveNotNull(files);
        }catch (Exception e){
            log.error("SsmUploadFilesServiceImpl.add:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return 0;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int del(UploadFiles files) throws SmsException {
        int i = 0;
        try {
            i = dao.deleteByPrimaryKey(files.getId());
        }catch (Exception e){
            log.error("SsmUploadFilesServiceImpl.delete:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    public int deleteByDocId(Long id) {
        return dao.deleteByDocId(id);
    }
}
