package com.gz.service.system.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.gz.common.DataGlobalVariable;
import com.gz.core.exception.BusinessException;
import com.gz.core.exception.CustomExceptionEnum;
import com.gz.dto.system.FileDTO;
import com.gz.mapper.system.FileMapper;
import com.gz.rvo.system.FileUploadRVO;
import com.gz.service.system.FileService;
import com.gz.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author LiuchangLan
 * @date 2020/9/9 11:24
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Resource
    private FileMapper fileMapper;

    @Override
    @Transactional
    public FileUploadRVO upload(MultipartFile file, String fileId) throws BusinessException, IOException {

            if (file.isEmpty()) {
                throw new BusinessException(CustomExceptionEnum.File_NOT_EXISTS);
            }
            String fileName = file.getOriginalFilename();
            // 上传路径
            String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/upload/" + DateUtil.format(new Date(), "yyyyMMdd") + "/";
            File file1 = new File(filePath);
            // 判断上传是否存在
            if (!file1.exists()) {
                file1.mkdirs();
            }
            if ("null".equals(fileId) || fileId == null || "".equals(fileId)) {
                fileId = IdUtil.simpleUUID();
            }
        // 现文件名
            String fn = IdUtil.simpleUUID() + fileName.substring(fileName.indexOf("."));
            File dest = new File(filePath + fn);
            // 上传
            file.transferTo(dest);
            // 数据库插入
            FileDTO fileDTO = new FileDTO();
            fileDTO.setFileId(fileId);
            fileDTO.setOriginalFileName(fileName);
            fileDTO.setDownloadPath("upload/" + DateUtil.format(new Date(), "yyyyMMdd") + "/" + fn);
            fileDTO.setCreated(JwtUtils.getCurrentUserJwtPayload().getId());
            fileMapper.insertSelective(fileDTO);

            FileUploadRVO fileUploadRVO = new FileUploadRVO(fileId,fileName, fn, "upload/" + DateUtil.format(new Date(), "yyyyMMdd") + "/" + fn);
            return fileUploadRVO;

    }

    @Override
    public List<FileDTO> selectByFileId(String fileId) {
        FileDTO fileDTO = new FileDTO();
        fileDTO.setFileId(fileId);
        List<FileDTO> select = fileMapper.select(fileDTO);
        return select;
    }

    @Override
    public Integer delete(Integer id) {
        return fileMapper.deleteByPrimaryKey(id);
    }


}
