package cn.qinys.platform.upms.api.service.impl;


import cn.qinys.platform.base.constants.BaseConstants;
import cn.qinys.platform.base.dto.AttachmentDTO;
import cn.qinys.platform.base.exceptions.BizException;
import cn.qinys.platform.base.utils.SnowflakeIdWorker;
import cn.qinys.platform.entity.upms.UpmsFile;
import cn.qinys.platform.upms.api.mapper.UpmsFileMapper;
import cn.qinys.platform.upms.api.service.IAttachmentService;
import cn.qinys.platform.upms.properties.SystemProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * code is far away from bug with the animal protecting
 *
 * @author v-lishiquan.gx@chinatelecom.cn
 * @description
 * @date 2020-04-29
 */
@Service
@AllArgsConstructor
@Slf4j
public class AttachmentServiceImpl implements IAttachmentService {

    private final SystemProperties systemProperties;
    private final SnowflakeIdWorker snowflakeIdWorker;
    private final UpmsFileMapper fileMapper;


    @Override
    public AttachmentDTO uploadFileAttachment(MultipartFile file) {
        return this.uploadAttach(file, systemProperties.getBaseUrl());
    }



    /**
     * 上传文件并返回数据
     *
     * @param multipartFile 上传的文件
     * @param urlPrefix     url的前缀
     * @return 数据
     */
    private AttachmentDTO uploadAttach(MultipartFile multipartFile, String urlPrefix) {
        // 获取时间
        String ym = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM")) + "/";
        AttachmentDTO dto = new AttachmentDTO();
        try {
            //获取文件后缀名
            String originalFileName = multipartFile.getOriginalFilename();
            if (Objects.isNull(originalFileName)) {
                return dto;
            }
            // 验证上传文件后缀
            String suffix = this.getFileSuffix(originalFileName);
            //生成文件名
            String id = snowflakeIdWorker.nextIdStr();
            String fileName = id + suffix;
            File tmpFile = new File(systemProperties.getFileDirectory() + ym + File.separator + fileName);
            //转存文件
            if (!tmpFile.getParentFile().exists()) {
                tmpFile.getParentFile().mkdirs();
            }
            multipartFile.transferTo(tmpFile.getAbsoluteFile());
            dto.setId(id);
            dto.setName(originalFileName);
            dto.setVirtualName(ym + fileName);
            dto.setUrl(urlPrefix + ym + fileName);
            dto.setSuffix(suffix);
            dto.setStorageType(BaseConstants.StorageType.LOCAL.getCode());
            UpmsFile file = new UpmsFile();
            BeanUtils.copyProperties(dto, file);
            file.setSize(multipartFile.getSize());
            file.setCreateTime(LocalDateTime.now());
            file.setUpdateTime(LocalDateTime.now());
            fileMapper.insert(file);
        } catch (IOException e) {
            log.error("上传文件异常:[{}]", e.getMessage());
            e.printStackTrace();
            throw new BizException("上传文件异常");
        }
        return dto;
    }

    /**
     * 获取文件后缀
     *
     * @param fileName 文件名
     * @return 后缀
     */
    private String getFileSuffix(String fileName) {
        int lastIndex = fileName.lastIndexOf('.');
        String suffix = "";
        if (lastIndex > -1 && lastIndex < (fileName.length() - 1)) {
            suffix = "." + fileName.substring(lastIndex + 1);
        }
        return suffix;
    }

}
