package com.jd.lightapplication.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jd.lightapplication.mapper.UploadRecordMapper;
import com.jd.lightapplication.model.UploadRecord;
import com.jd.lightapplication.model.dto.UploadDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


@Service
public class UploadRecordService extends ServiceImpl<UploadRecordMapper, UploadRecord> {

    // 文件保存的目录路径
    @Value("${file.path}")
    private String filePath;

    // 文件访问地址
    @Value("${http.addr}")
    private String addr;

    public UploadRecord upload(MultipartFile file, UploadDto uploadDto) {
        //拿到文件的名称
        String fileName = file.getOriginalFilename();
        String fileId = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        //拿到年月日的路径(2021/9/22/)
        String path = handleFilePath();
        File newFile = new File(filePath + path + fileId);
        try {
            if (!newFile.exists()) {
                newFile.mkdirs();
                newFile.createNewFile();
            }
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("写入文件出错！！");
            throw new RuntimeException("文件上传异常！");
        }
        UploadRecord fileInfo = new UploadRecord()
                .setSourceName(fileName)
                .setFilePath(addr + path + fileId)
                .setInspectionResultId(uploadDto.getInspectionResultId())
                .setFileType(uploadDto.getFileType() == null ? 10 : uploadDto.getFileType())
                .setUploadUserId(null)
                .setCreateTime(DateUtil.now());
        boolean bl = baseMapper.insert(fileInfo) > 0;
        if (!bl) {
            throw new RuntimeException("文件上传异常！");
        }
        return fileInfo;
    }

    //处理文件路径
    public String handleFilePath() {
        Calendar rightNow = Calendar.getInstance();
        return "showfile/" + rightNow.get(Calendar.YEAR) + "/" + (rightNow.get(Calendar.MONTH) + 1) + "/" + rightNow.get(Calendar.DAY_OF_MONTH) + "/";
    }

    public Boolean updateBatch(List<Integer> fileIds, Long inspectionResultId) {
        String fileIdsStr = fileIds.stream().map(t -> {
            return t.toString();
        }).collect(Collectors.joining(","));
        return baseMapper.updateBatch(fileIdsStr, inspectionResultId);
    }
}