package com.zcxk.rmcp.web.service.impl;

import com.zcxk.core.common.util.FileUtil;
import com.zcxk.rmcp.web.service.FileLogService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.zcxk.rmcp.core.dao.FileLogMapper;
import com.zcxk.rmcp.core.entity.FileLog;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 
 * @author linqingwei
 * @date 2021-07-29 17:54
 */
@Service
public class FileLogServiceImpl implements FileLogService {

    @Resource
    private FileLogMapper fileLogMapper;
    @Value("${files.path}")
    private String filesPath;

    @Override
    public int insertSelective(FileLog record) {
        return fileLogMapper.insertSelective(record);
    }

    @Override
    public int updateByPrimaryKeySelective(FileLog record) {
        return fileLogMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public String uploadFile(MultipartFile file) {
        String fileOrigName = file.getOriginalFilename();
        if (fileOrigName!=null&&!fileOrigName.contains(".")) {
            throw new IllegalArgumentException("缺少后缀名");
        }

        String md5 = null;
        try {
            md5 = FileUtil.fileMd5(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileLog fileInfo = fileLogMapper.getById(md5);
        if (fileInfo != null) {
            return fileInfo.getUrl();
        }
        if(fileOrigName!=null){
            fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
        }
        String pathname = FileUtil.getPath() + md5 + fileOrigName;
        String fullPath = filesPath + pathname;
        System.out.println(fullPath);
        FileUtil.saveFile(file, fullPath);

        long size = file.getSize();
        String contentType = file.getContentType();

        fileInfo = new FileLog();
        fileInfo.setId(md5);
        fileInfo.setFileType(contentType);
        fileInfo.setName(file.getName());
        fileInfo.setSize(size);
        fileInfo.setPath(fullPath);
        fileInfo.setUrl(pathname);
        if(contentType!=null){
            fileInfo.setType(contentType.startsWith("image/") ? 1 : 0);
        }
        fileInfo.setStatus(1);
        fileInfo.setCreateBy("system");
        fileInfo.setCreateDate(LocalDateTime.now());
        fileLogMapper.insertSelective(fileInfo);
        return fileInfo.getUrl();
    }
}
