项目里的下载需求附件(需要去翻原码比对)

package com.qtong.icp.module.controller;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.exceptions.InvalidPdfException;
import com.itextpdf.text.pdf.PdfReader;
import com.mysql.jdbc.StringUtils;
import com.qtong.icp.core.aspect.LogAnno;
import com.qtong.icp.core.aspect.OperatorEnum;
import com.qtong.icp.core.common.config.CommonConfig;
import com.qtong.icp.core.common.config.UrlUtil;
import com.qtong.icp.core.constants.IntegralBehaviorEnum;
import com.qtong.icp.core.constants.ResourceTypeEnum;
import com.qtong.icp.core.domain.ResultObject;
import com.qtong.icp.core.util.CommonUtil;
import com.qtong.icp.core.util.WatermarkValidateUtil;
import com.qtong.icp.module.service.AttachmentService;
import com.qtong.icp.module.util.*;
import com.qtong.icp.pojo.admin.UserNew;
import com.qtong.icp.pojo.integral.IntegralRecord;
import com.qtong.icp.pojo.resAttAudit.ResAttAudit;
import com.qtong.icp.pojo.resAttAudit.ResAttAuditHistory;
import com.qtong.icp.pojo.resAttAudit.ResAttAuditHistorySub;
import com.qtong.icp.pojo.resAttAudit.ResAttAuditParam;
import com.qtong.icp.pojo.resource.RecourceRequest;
import com.qtong.icp.pojo.sln.slnInfo.SlnInfoRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(tags = "附件管理")
@RestController
@RequestMapping(value = "/Attachment")
public class AttachmentController {
    private static final Logger log = LoggerFactory.getLogger(AttachmentController.class);

    @Autowired
    private UrlUtil urlUtil;

    @Value("${uploadUrl.picture}")
    private String uploadUrl;

    @Value("${uploadUrl.accessUrl}")
    private String accessUrl;
    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    @Qualifier("oAuth2RestTemplate")
    private OAuth2RestTemplate oAuth2RestTemplate;

    private UserNew getUser() {
        return oAuth2RestTemplate.getForObject(urlUtil.genBaseUrl(CommonConfig.USER_OAUTH_URL), UserNew.class);
    }


    @ApiOperation(value = "需求上传", notes = "Attachment:DemandUpload")
    @PostMapping("/Demand/upload")
    @ResponseBody
    public String DemandUpload(@RequestParam("file") MultipartFile file, String DemandId) {
        UserNew user = getUser();
        String userId = user.getUserId();
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取真实文件名
            String fileRealName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileRealName);
            //获取文件的后缀
            String strArry[] = fileRealName.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String fileName = CommonUtil.generateUUID() + "." + fileSuffix;

            // 设置文件存储路径
            String filePath = urlUtil.getDefaultPath() + userId + File.separator;
            String path = filePath + fileName;

            File dest = new File(path);
            //判断文件类型 -- MP4的字节流不确定,不校验
            if (!FileTypeJudge.isMP4SuffixValid(fileName) && FileTypeJudge.isFileType(FileTypeJudge.getType(file.getInputStream()))) {
                return "不支持的文件类型";
            }
            if (!FileTypeJudge.isSuffixValid(fileName)) {
                return "不支持的文件类型";
            }

            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入

            // 写入数据库
            attachmentService.saveDemandAtt(DemandId, dest, userId, fileRealName);

            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }


    /**
     * icp_res_attachment 2
     * icp_products_attachment 7
     * icp_res_products_attachment 9
     *
     * @param file
     * @param type
     * @return
     */
    @ApiOperation(value = "文件上传", notes = "Attachment:fileUpload")
    @LogAnno(resourceType = ResourceTypeEnum.TYPE_9, operateType = OperatorEnum.UPLOAD)
    @PostMapping("/file/upload")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file, Integer type) {
        String userId = getUser().getUserId();
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileRealName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileRealName);
            //获取文件后缀和存储名称
            String strArry[] = fileRealName.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String uuid = CommonUtil.generateUUID();
            String fileName = uuid + "." + fileSuffix;

            // 处理上传pdf文件加密问题
            if (fileSuffix.equals("pdf")) {
                try {
                    PdfReader reader = new PdfReader(file.getInputStream());
                    // 判断文件是否加密
                    if (reader.isMetadataEncrypted() || reader.isEncrypted()) {
                        return "请上传未加密的pdf文件,如加密证件截图等";
                    }
                } catch (InvalidPdfException ipe) {
                    ipe.printStackTrace();
                    return "请上传合法的pdf文件";
                }
            }
            // 设置文件存储路径
            String filePath = urlUtil.getDefaultPath() + userId + File.separator;
            String path = filePath + fileName;

            File dest = new File(path);
            //判断文件类型 -- MP4的字节流不确定,不校验
            if (!FileTypeJudge.isMP4SuffixValid(fileName) && FileTypeJudge.isFileType(FileTypeJudge.getType(file.getInputStream()))) {
                return "不支持的文件类型";
            }
            if (!FileTypeJudge.isSuffixValid(fileName)) {
                return "不支持的文件类型";
            }
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            log.info("存入前置打印");
            // 写入数据库
            String resultId = attachmentService.saveAtt(dest, userId, type, fileRealName);
            log.info("存入后置打印");

            // 文件转换成功以后根据type类型 修改pdfurl
            String pdfUrl = filePath + uuid + ".pdf";
            if (fileSuffix.equalsIgnoreCase("pdf")) { // 附件是pdf 源文件地址与pdf地址是同一个
                // 上传的是pdf文件直接保存
                attachmentService.updatePdfUrlById(resultId, pdfUrl, type);
            } else if (fileSuffix.equalsIgnoreCase("jpg") || fileSuffix.equalsIgnoreCase("png") || fileSuffix.equalsIgnoreCase("jpeg")) {
                // 图片转pdf
                PdfUtil.imageToPdf(path, pdfUrl);
                attachmentService.updatePdfUrlById(resultId, pdfUrl, type);
            } else {
                // office文档转换乘pdf
                String fileType = switchFileType(fileSuffix);
                if (!fileType.equals("")) {
                    fileToPdf(resultId, fileType, path, pdfUrl, type);
                }
            }
            return resultId;
        } catch (IllegalStateException e) {
            log.info("上传附件报错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.info("上传附件报错:" + e.getMessage());
            e.printStackTrace();
        }
        return "上传失败";
    }

    // 重开线程处理 office文件转换成pdf
    private void fileToPdf(String fileId, String fileType, String fileSourceUrl, String filePdfUrl, Integer type) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                // 1:类型参数为空 ,2:路径参数为空 ,3: 类型参数错误
                String result = OfficeToPdf.fileToPDF(fileType, fileSourceUrl, filePdfUrl);
                switch (result) {
                    case "1":
                        log.error("office转换pdf:类型参数为空");
                        break;
                    case "2":
                        log.error("office转换pdf:路径参数为空");
                        break;
                    case "3":
                        log.error("验证License失败");
                        break;
                    case "4":
                        log.error("office转换pdf:类型参数错误");
                        break;
                    default:
                        attachmentService.updatePdfUrlById(fileId, filePdfUrl, type);
                }
            }
        });
        t.start();
    }

    // 根据文件后缀 选择文档类型
    private String switchFileType(String suffsix) {
        String fileType = "";
        switch (suffsix) {
            case "docx":
                fileType = "word";
                break;
            case "doc":
                fileType = "word";
                break;
            case "xls":
                fileType = "excel";
                break;
            case "xlsx":
                fileType = "excel";
                break;
            case "ppt":
                fileType = "ppt";
                break;
            case "pptx":
                fileType = "ppt";
                break;
        }
        return fileType;
    }

    /**
     * 上传视频接口
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "上传视频接口", notes = "Attachment:VideoUpload")
    @LogAnno(resourceType = ResourceTypeEnum.TYPE_9, operateType = OperatorEnum.UPLOAD)
    @PostMapping("/file/VideoUpload")
    @ResponseBody
    public String VideoUpload(@RequestParam("file") MultipartFile file) {
        String userId = getUser().getUserId();
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileRealName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileRealName);
            //获取文件后缀和存储名称
            String strArry[] = fileRealName.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String fileName = CommonUtil.generateUUID() + "." + fileSuffix;
            // 设置文件存储路径
            String filePath = urlUtil.getDefaultPath() + userId + File.separator + "video" + File.separator;

            String path = filePath + fileName;

            File dest = new File(path);

            if (!FileTypeJudge.isMP4SuffixValid(fileName)) {
                return "不支持的文件类型";
            }

            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            log.info("存入前置打印");
            //访问路径拼接
            String videoPath = urlUtil.getFileDownloadUrl() + File.separator + userId + File.separator + "video" + File.separator + fileName;
            log.info("视频访问路径--videoPath:" + videoPath);
            //拼接第一帧图片地址
            String videoCoverName = CommonUtil.generateUUID() + ".jpg";
            String coverPath = filePath + videoCoverName;
            String videoCoverUrl = urlUtil.getFileDownloadUrl() + File.separator + userId + File.separator + "video" + File.separator + videoCoverName;
            // 写入数据库
            String resultId = attachmentService.saveVideo(dest, path, coverPath, videoCoverUrl, userId, fileRealName, fileSuffix, videoPath, 7);
            log.info("存入后置打印");
            return resultId;
        } catch (IllegalStateException e) {
            log.info("上传附件报错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.info("上传附件报错:" + e.getMessage());
            e.printStackTrace();
        }
        return "上传失败";
    }

    /**
     * 上传视频接口-多类型
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "上传视频接口-多类型", notes = "Attachment:typeVideoUpload")
    @LogAnno(resourceType = ResourceTypeEnum.TYPE_9, operateType = OperatorEnum.UPLOAD)
    @PostMapping("/file/typeVideoUpload")
    @ResponseBody
    public String typeVideoUpload(@RequestParam("file") MultipartFile file, @RequestParam("type") Integer type) {
        String userId = getUser().getUserId();
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileRealName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileRealName);
            //获取文件后缀和存储名称
            String strArry[] = fileRealName.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String fileName = CommonUtil.generateUUID() + "." + fileSuffix;
            // 设置文件存储路径
            String filePath = urlUtil.getDefaultPath() + userId + File.separator + "video" + File.separator;

            String path = filePath + fileName;

            File dest = new File(path);

            if (!FileTypeJudge.isMP4SuffixValid(fileName)) {
                return "不支持的文件类型";
            }

            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            log.info("存入前置打印{}", path);
            //访问路径拼接
            String videoPath = urlUtil.getFileDownloadUrl() + File.separator + userId + File.separator + "video" + File.separator + fileName;
            log.info("视频访问路径--videoPath:" + videoPath);
            //拼接第一帧图片地址
            String videoCoverName = CommonUtil.generateUUID() + ".jpg";
            String coverPath = filePath + videoCoverName;
            String videoCoverUrl = urlUtil.getFileDownloadUrl() + File.separator + userId + File.separator + "video" + File.separator + videoCoverName;
            // 写入数据库
            String resultId = attachmentService.saveVideo(dest, path, coverPath, videoCoverUrl, userId, fileRealName, fileSuffix, videoPath, type);
            log.info("存入后置打印{}", resultId);
            return resultId;
        } catch (IllegalStateException e) {
            log.info("上传附件报错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.info("上传附件报错:" + e.getMessage());
            e.printStackTrace();
        }
        return "上传失败";
    }

    /**
     * 上传个人作品案例
     *
     * @param file
     * @param type 1 web端请求  2移动端请求
     * @return
     */
    @ApiOperation(value = "上传个人作品案例", notes = "Attachment:opusUpload")
    @PostMapping("/opus/upload")
    @ResponseBody
    public String opusUpload(@RequestParam("file") MultipartFile file, Integer type) {
        String userId = getUser().getUserId();
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileRealName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileRealName);
            //获取文件存储名称和文件后缀
            String strArry[] = fileRealName.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String fileName = CommonUtil.generateUUID() + "." + fileSuffix;
            // 设置文件存储路径
            String filePath = urlUtil.getDefaultPath() + userId + File.separator;
            String path = filePath + fileName;

            File dest = new File(path);
            //判断文件类型 -- MP4的字节流不确定,不校验
            if (!FileTypeJudge.isMP4SuffixValid(fileName) && FileTypeJudge.isFileType(FileTypeJudge.getType(file.getInputStream()))) {
                return "不支持的文件类型";
            }
            if (!FileTypeJudge.isSuffixValid(fileName)) {
                return "不支持的文件类型";
            }

            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入

            // 写入数据库
            String resultId = attachmentService.saveOpusAtt(dest, userId, type, fileRealName);

            return resultId;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @ApiOperation(value = "上传图片", notes = "Attachment:pictureUpload")
    @LogAnno(resourceType = ResourceTypeEnum.TYPE_9, operateType = OperatorEnum.UPLOAD)
    @PostMapping("/picture/upload")
    @ResponseBody
    public String pictureUpload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileRealName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileRealName);
            //获取文件存储名称和文件
            String strArry[] = fileRealName.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String fileName = CommonUtil.generateUUID() + "." + fileSuffix;
            //添加目录格式
            String datePath = DateUtil.getDateSpecyFormatStr(new Date(), DateUtil.SHORTDATEFORMAT);
            // 设置文件存储路径
            String filePath = uploadUrl + datePath + File.separator;
            String path = filePath + fileName;

            File dest = new File(path);
            //判断文件类型
            if (FileTypeJudge.isImageType(FileTypeJudge.getType(file.getInputStream()))) {
                return "不支持的文件类型";
            }
            if (!FileTypeJudge.isSuffixValid(fileName)) {
                return "不支持的文件类型";
            }

            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            return accessUrl + "/defaultFile/" + datePath + "/" + fileName;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }


    @ApiOperation(value = "上传资源", notes = "Attachment:resouceUpload")
    @LogAnno(resourceType = ResourceTypeEnum.TYPE_9, operateType = OperatorEnum.UPLOAD)
    @PostMapping("/resouce/upload")
    @ResponseBody
    public String resouceUpload(@RequestParam("file") MultipartFile file, String resId) {
        String userId = getUser().getUserId();
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileRealName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileRealName);
            //获取文件的存储名称和后缀
            String strArry[] = fileRealName.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String fileName = CommonUtil.generateUUID() + "." + fileSuffix;
            // 处理上传pdf文件加密问题
            if (fileSuffix.equals("pdf")) {
                try {
                    PdfReader reader = new PdfReader(file.getInputStream());
                    // 判断文件是否加密
                    if (reader.isMetadataEncrypted() || reader.isEncrypted()) {
                        return "请上传未加密的pdf文件,如加密证件截图等";
                    }
                } catch (InvalidPdfException ipe) {
                    ipe.printStackTrace();
                    return "请上传合法的pdf文件";
                }
            }
            // 设置文件存储路径
            String filePath = urlUtil.getDefaultPath() + userId + File.separator;
            String path = filePath + fileName;

            File dest = new File(path);
            //判断文件类型 -- MP4的字节流不确定,不校验
            if (!FileTypeJudge.isMP4SuffixValid(fileName) && FileTypeJudge.isFileType(FileTypeJudge.getType(file.getInputStream()))) {
                return "不支持的文件类型";
            }
            if (!FileTypeJudge.isSuffixValid(fileName)) {
                return "不支持的文件类型";
            }

            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入

            // 写入数据库
            attachmentService.saveResAtt(resId, dest, userId, fileRealName);
            String pdfUrl = filePath + CommonUtil.generateUUID() + ".pdf";
            if (fileSuffix.equals("pdf")) { // 附件是pdf 源文件地址与pdf地址是同一个
                // 上传的是pdf文件直接保存
                attachmentService.updatePdfUrlById(resId, pdfUrl, 2);
            } else if (fileSuffix.equals("jpg") || fileSuffix.equals("png")) {
                // 图片转pdf
                PdfUtil.imageToPdf(path, pdfUrl);
                attachmentService.updatePdfUrlById(resId, pdfUrl, 2);
            } else {
                // office文档转换乘pdf
                String fileType = switchFileType(fileSuffix);
                if (!fileType.equals("")) {
                    fileToPdf(resId, fileType, path, pdfUrl, 2);
                }
            }
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @ApiOperation(value = "下载需求附件", notes = "Attachment:downloadDemandAtt")
    @GetMapping("/Demand/download")
    @ResponseBody
    public void downloadDemandAtt(String fileId, HttpServletResponse response, Integer type,@RequestParam(required = false) String unCount) throws IOException {
        if (type == null) {
            type = 1;
        }
        Map<String, Object> fileMap = attachmentService.queryAttUrl(fileId, type,unCount);

        File file = new File(fileMap.get("url").toString());
        String fileName = java.net.URLEncoder.encode(fileMap.get("title").toString(), "UTF-8");
        BufferedInputStream bis = null;
        OutputStream os = null;
        response.reset();
        response.setContentType("application/x-download");
        response.setContentType("text/plain;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        //response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("FileName", fileName);
        response.setHeader("Access-Control-Expose-Headers", "FileName");
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] b = new byte[bis.available() + 1000];
            int i = 0;
            os = response.getOutputStream(); // 直接下载导出
            while ((i = bis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @ApiOperation(value = "下载资源附件", notes = "Attachment:downloadResAtt")
    @LogAnno(resourceType = ResourceTypeEnum.TYPE_9, operateType = OperatorEnum.DOWNLOAD)
    @GetMapping("/resouce/download")
    @ResponseBody
    public ResultObject downloadResAtt(String fileId, HttpServletResponse response, Integer type, @RequestParam(required = false) String unCount)
            throws IOException {
        Integer wordResType = 2;
        if (type == null || type == 18 || type == 19 || type == 20) {
            wordResType = type;
            type = 2;
        }
        if (type == 17 || type == 1 || type == 12) {
            wordResType = type;
        }
        UserNew user = oAuth2RestTemplate.getForObject(urlUtil.genBaseUrl(CommonConfig.USER_OAUTH_URL), UserNew.class);
        Map<String, Object> fileMap = attachmentService.queryAttUrl(fileId, type,unCount);
        File file = null;
        if (type == 2) {//资源附件下载需要校验是否有下载权限
            if (fileMap.get("auditFlag") != null && Boolean.valueOf(fileMap.get("auditFlag").toString())) {
                ResAttAudit resAttAudit = new ResAttAudit();
                resAttAudit.setApplyUserId(user.getUserId());
                resAttAudit.setAttId(fileId);
                ResAttAudit resAudit = oAuth2RestTemplate.postForObject(urlUtil.genBaseUrl(CommonConfig.ATT_DOWNLOAD_SATUS), resAttAudit, ResAttAudit.class);
                if (resAudit.getAuditStatus() == null || resAudit.getAuditStatus() != 1) {
                    return ResultObject.build(1, "未拥有该资源下载权限,请申请后再试!");
                }
            }
        }
        // 获取用户当天下载总数,超过下载数量不允许下载,没人每天最多下载50次
        Integer downloadNum = attachmentService.getUserDownloadNum(user.getUserId());
        if (null != downloadNum && downloadNum >= 50) {
            return ResultObject.build(1, "本日资源下载已达上限,请明天再来吧!");
        }
        /*
            通过附件id 获取附件挂载资源的类型
            方案库、案例库、培训库、产品库、生态库-水印内容:姓名+手机号后四位
            人员库、投标库-水印内容:仅限中移集成投标使用
            资质库-水印内容:用户申请时自行填写 当前下载接口不需要处理资质库附件下载,资质库通过/resouce/downloadPdf接口加水印
         */
        String resType = "";
        if (wordResType == 7 || wordResType == 17) // 7,17单独处理5G专区产品数据,这个数据存放在icp_res_products_attachment表中,当前sql查询不到5G专区资源类型 所以通过前端传递的type类型区分
            resType = ResourceTypeEnum.TYPE_5.getCode();
        else if (wordResType == 18) // 18单独处理5G专案例数据,案例数据存放在icp_case_info表中,当前sql查询不到5G专区资源类型 所以通过前端传递的type类型区分
            resType = ResourceTypeEnum.TYPE_4.getCode();
        else if (wordResType == 19) // 19单独处理5G专区方案数据,方案数据存放在icp_case_info表中,当前sql查询不到5G专区资源类型 所以通过前端传递的type类型区分
            resType = ResourceTypeEnum.TYPE_2.getCode();
        else if (wordResType == 20) // 20单独处理5G专区培训数据,当前sql查询不到5G专区资源类型 所以通过前端传递的type类型区分
            resType = ResourceTypeEnum.TYPE_6.getCode();
        else if (wordResType == 1) // 处理商机超市附件下载,商机超市水印规则:姓名+手机号后四位,所以resType随便指定一个用了判断水印规则
            resType = ResourceTypeEnum.TYPE_6.getCode();
        else if (wordResType == 12) // 处理商机超市-意向附件下载,商机超市水印规则:姓名+手机号后四位,所以resType随便指定一个用了判断水印规则
            resType = ResourceTypeEnum.TYPE_6.getCode();
        else
            resType = attachmentService.getReourceTypeByFileId(fileId);
        String word = "";
        if (StringUtils.isNullOrEmpty(resType)) {
            return ResultObject.build(1, "下载的资源无效");
        } else if (resType.equals(ResourceTypeEnum.TYPE_2.getCode()) ||
                resType.equals(ResourceTypeEnum.TYPE_4.getCode()) ||
                resType.equals(ResourceTypeEnum.TYPE_5.getCode()) ||
                resType.equals(ResourceTypeEnum.TYPE_6.getCode()) ||
                resType.equals(ResourceTypeEnum.TYPE_7.getCode()) ||
                resType.equals(ResourceTypeEnum.TYPE_11.getCode())) {
            //姓名+手机号后四位
            word = user.getUserName() + (user.getMobile().substring(7));
        } else if (resType.equals(ResourceTypeEnum.TYPE_3.getCode()) ||
                resType.equals(ResourceTypeEnum.TYPE_8.getCode())) {
            word = "仅限中移系统集成有限公司投标使用";
        } else {
            return ResultObject.build(1, "当前附件没有挂载资源无法区分八库类型");
        }
        response.reset();
        OutputStream os = response.getOutputStream();
        // 源文件转换成pdf的 优先下载pdf文件并加水印
        // 有pdfUrl且不为空的走pdf下载
        if (fileMap.containsKey("pdfUrl") && !StringUtils.isNullOrEmpty((String) fileMap.get("pdfUrl"))) {
            String pdfurl = (String) fileMap.get("pdfUrl");
            /*if(StringUtils.isNullOrEmpty(pdfurl)){
                return ResultObject.build(1, "附件不存在");
            }*/
            try {
                file = new File(pdfurl);
                if (!file.exists()) {
                    return ResultObject.build(1, "附件不存在!");
                }
                //获取文件名称
                String title = fileMap.get("title").toString();
                String strArry[] = title.split("\\.");
                String fileName = strArry[0] + ".pdf";
                setResponseHeader(response, fileName, "multipart/form-data");
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                // 给pdf添加水印并写回页面
                if (resType.equals(ResourceTypeEnum.TYPE_3.getCode()) ||
                        resType.equals(ResourceTypeEnum.TYPE_8.getCode())) {
                    PdfUtil.setWatermark(os, bis, word,true);
                }else {
                    PdfUtil.setWatermark(os, bis, word,false);
                }
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
                return ResultObject.build(1, "附件不存在");
            }
        } else {
            file = new File(fileMap.get("url").toString());
            if (!file.exists()) {
                return ResultObject.build(1, "附件不存在!");
            }
            BufferedInputStream bis = null;
            setResponseHeader(response, fileMap.get("title").toString(), "multipart/form-data");
            try {
                bis = new BufferedInputStream(new FileInputStream(file));
                byte[] b = new byte[bis.available() + 1000];
                int i = 0;
                while ((i = bis.read(b)) != -1) {
                    os.write(b, 0, i);
                }
                bis.close();
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
                return ResultObject.build(1, "数据异常,下载失败!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //删除审核表中审核记录
        if (type == 2) {
            ResAttAudit resAttAudit = new ResAttAudit();
            resAttAudit.setAttId(fileId);
            resAttAudit.setAuditStatus(5);
            oAuth2RestTemplate.postForObject(urlUtil.genBaseUrl(CommonConfig.UPDATE_ATT_AUDIT_STATUS), resAttAudit, Boolean.class);
        }
        // 修改下载次数
        attachmentService.updateUserDownloadNumByUId(user.getUserId());
        // 添加积分
        // 根据type判断
        if (type ==2 || type == 17){
            IntegralRecord record = new IntegralRecord();
            record.setBehaviorCode(IntegralBehaviorEnum.CODE_5001.getCode());
            record.setUserId(user.getUserId());
            record.setResId(fileId);
            String url = urlUtil.genBaseUrl(CommonConfig.ADD_INTEGRAL_URL);
            oAuth2RestTemplate.postForObject(url, record, String.class);
        }
        return null;
    }

    private void setResponseHeader(HttpServletResponse response, String title, String contentType) throws UnsupportedEncodingException {
        String fileName = java.net.URLEncoder.encode(title, "UTF-8");
        response.setContentType(contentType);
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);// 设置文件名
        response.setHeader("FileName", fileName);
        //response.setHeader("Access-Control-Expose-Headers", "FileName");
    }

    @ApiOperation(value = "删除附件", notes = "Attachment:deleteAtt")
    @LogAnno(resourceType = ResourceTypeEnum.TYPE_9, operateType = OperatorEnum.DELETE)
    @GetMapping("/file/deleteAtt")
    @ResponseBody
    public ResultObject deleteAtt(String fileId, Integer type)
            throws IOException {
        if (type == 2) {//资源附件删除
            ResAttAudit resAttAudit = new ResAttAudit();
            resAttAudit.setAttId(fileId);
            resAttAudit.setAuditStatus(4);
            oAuth2RestTemplate.postForObject(urlUtil.genBaseUrl(CommonConfig.UPDATE_ATT_AUDIT_STATUS), resAttAudit, Boolean.class);
        }

        String path = "";
        if (type ==21 || type == 22){
            path = attachmentService.queryVideoUrlAndDelete(fileId,type);
        }else {
            path = attachmentService.queryAttUrlAndDelete(fileId, type);
        }
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            file.delete();
            return ResultObject.ok();
        }
        return ResultObject.build(1,"删除失败");
    }

    @ApiOperation(value = "删除个人作品案例", notes = "Attachment:deleteOpusAtt")
    @RequestMapping(value = "/file/deleteOpusAtt", method = RequestMethod.POST)
    @ResponseBody
    public String deleteOpusAtt(String fileId) {
        String path = attachmentService.queryAttUrlAndDelete(fileId, 6);
        if (path != null && !"".equals(path)) {
            File file = new File(path);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
            return "success";
        } else {
            return "failed";
        }
    }

    @ApiOperation(value = "通过资源Id更新附件", notes = "Attachment:updateAttachmentResId")
    @RequestMapping("/updateAttachmentResId")
    @ResponseBody
    public Boolean updateAttachmentResId(@RequestBody RecourceRequest recourceRequest) {
        return attachmentService.updateAttachmentResId(recourceRequest.getAttInfoList(), recourceRequest.getResId());

    }

    @ApiOperation(value = "通过方案Id更新附件", notes = "Attachment:updateAttachmentSlnId")
    @RequestMapping("/updateAttachmentSlnId")
    @ResponseBody
    public Boolean updateAttachmentSlnId(@RequestBody SlnInfoRequest slnInfoRequest) {
        return attachmentService.updateAttachmentResId(slnInfoRequest.getAttList(), slnInfoRequest.getSlnId());
    }

    @ApiOperation(value = "查询附件URL和标题", notes = "Attachment:queryAttUrlANDTitle")
    @RequestMapping("/queryAttUrlANDTitle")
    @ResponseBody
    public Map<String, Object> queryAttUrlANDTitle(String fileId) {
        Map<String, Object> queryUrlANDTitle = attachmentService.queryUrlANDTitle(fileId);
        if (!StringUtils.isNullOrEmpty(queryUrlANDTitle.get("url").toString())) {
            queryUrlANDTitle.put("url", queryUrlANDTitle.get("url").toString().replace("/icpLocal/defaultFile", urlUtil.getFileDownloadUrl()));
        }
        return queryUrlANDTitle;
    }

    @ApiOperation(value = "pdf上传,如果上传图片将图片转换为pdf", notes = "Attachment:pdfUpload")
    @PostMapping("/resouce/pdfUpload")
    @ResponseBody
    public String pdfUpload(@RequestParam("file") MultipartFile file) {
        String userId = getUser().getUserId();
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileRealName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileRealName);
            //获取文件后缀和存储名称
            String strArry[] = fileRealName.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String s = CommonUtil.generateUUID();
            String fileName = s + "." + fileSuffix;

            // 设置文件存储路径
            String filePath = urlUtil.getDefaultPath() + userId + File.separator;
            String path = filePath + fileName;

            File dest = new File(path);
            if (!FileTypeJudge.isSuffixValid(fileName)) {
                return "不支持的文件类型";
            }
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            String resultId = "";
            //判断文件类型 jpg,png
            if (!FileTypeJudge.isImageTypeByType(FileTypeJudge.getType(file.getInputStream()))) {
                // 文件写入
                file.transferTo(dest);
                // 写入数据库
                resultId = attachmentService.saveAtt(dest, userId, 2, fileRealName);
                // 将图片转换为pdf
                String pdfPath = filePath + s + ".pdf";
                PdfUtil.imageToPdf(path, pdfPath);
                attachmentService.updatePdfUrlById(resultId, pdfPath, 2);
            }
            // 判断文件类型 pdf
            if (!FileTypeJudge.isPdfByType(FileTypeJudge.getType(file.getInputStream()))) {
                // 文件写入
                file.transferTo(dest);
                // 写入数据库
                resultId = attachmentService.saveAttPdf(dest, userId, fileRealName);
            }
            return resultId;
        } catch (IllegalStateException e) {
            log.info("上传附件报错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.info("上传附件报错:" + e.getMessage());
            e.printStackTrace();
        }
        return "上传失败";
    }

    /**
     * 下载pdf并添加水印-用户手动输入水印信息
     *
     * @param resId     资源id
     * @param fileId    附件id
     * @param purpose   用途
     * @param watermark 水印
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    @ApiOperation(value = "下载pdf并添加水印-用户手动输入水印信息", notes = "Attachment:downloadPdf")
    @LogAnno(resourceType = ResourceTypeEnum.TYPE_9, operateType = OperatorEnum.DOWNLOAD)
    @GetMapping("/resouce/downloadPdf")
    @ResponseBody
    public ResultObject downloadPdf(String resId, String fileId, String purpose, HttpServletResponse response, HttpServletRequest request, String watermark)
            throws IOException, DocumentException, NoSuchFieldException, IllegalAccessException {

        if (StringUtils.isNullOrEmpty(fileId) || StringUtils.isNullOrEmpty(purpose) || StringUtils.isNullOrEmpty(resId)) {
            return ResultObject.build(1, "请填写正确参数");
        }
        // 校验水印
        boolean b = WatermarkValidateUtil.validate(purpose);
        // false表示水印与系统水印重复,不可用
        if (!b){
            return ResultObject.build(1, "该水印为系统使用,请填写其它水印内容");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate now = LocalDate.now();
        String strNow = now.format(formatter);
        LocalDate nextMonth = now.plusMonths(1L);
        String strNextMonth = nextMonth.format(formatter);
        purpose = "仅限" + purpose + "项目投标使用," + "有效期" + strNow + "至" + strNextMonth;
        UserNew user = oAuth2RestTemplate.getForObject(urlUtil.genBaseUrl(CommonConfig.USER_OAUTH_URL), UserNew.class);
        // 获取用户当天下载总数,超过下载数量不允许下载,没人每天最多下载50次
        Integer downloadNum = attachmentService.getUserDownloadNum(user.getUserId());
        if (null != downloadNum && downloadNum >= 50) {
            return ResultObject.build(1, "本日资源下载已达上限,请明天再来吧!");
        }

        String auditId = "";
        // 查询附件
        Map<String, Object> fileMap = attachmentService.queryPdfUrl(fileId);
        if (null == fileMap.get("pdfUrl") || null == fileMap.get("title")) {
            return ResultObject.build(1, "附件不存在");
        }

        File file = new File(fileMap.get("pdfUrl").toString());
        String title = fileMap.get("title").toString();
        String[] titles = title.split("\\.");
        String fileName = java.net.URLEncoder.encode(titles[0] + ".pdf", "UTF-8");

        response.reset();

        response.setContentType("application/pdf");
        // response.setContentType("text/plain;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);// 设置文件名
        response.setHeader("FileName", fileName);
        response.setHeader("Access-Control-Expose-Headers", "FileName");
        // 流
        OutputStream os = response.getOutputStream();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        // 给pdf添加水印并写回页面
        PdfUtil.setWatermark(os, bis, purpose,false);

        // 修改下载次数
        attachmentService.updateUserDownloadNumByUId(user.getUserId());

        //添加审核表中审核记录(此从是自动下载,单纯记录下载日志,水印信息)
        ResAttAuditHistory resAttAuditHistory = new ResAttAuditHistory();
        String id = CommonUtil.generateUUID();
        resAttAuditHistory.setAuditId(id);
        resAttAuditHistory.setAttId(fileId);
        resAttAuditHistory.setAttName(titles[0] + ".pdf");
        resAttAuditHistory.setResId(resId);
        resAttAuditHistory.setAuditStatus(1);// 默认通过
        resAttAuditHistory.setDeleteFlag(0);
        resAttAuditHistory.setStartDate(new Date());
        resAttAuditHistory.setEndDate(new Date());

        ResAttAuditHistorySub resAttAuditHistorySub = new ResAttAuditHistorySub();
        resAttAuditHistorySub.setId(CommonUtil.generateUUID());
        resAttAuditHistorySub.setAuditId(id);
        resAttAuditHistorySub.setPurpose(purpose);
        resAttAuditHistorySub.setMatter(watermark);

        ResAttAuditParam resAttAuditParam = new ResAttAuditParam();
        resAttAuditParam.setResAttAuditHistory(resAttAuditHistory);
        resAttAuditParam.setResAttAuditHistorySub(resAttAuditHistorySub);
        oAuth2RestTemplate.postForObject(urlUtil.genBaseUrl(CommonConfig.ADD_AUDIT_PDF), resAttAuditParam, ResultObject.class);
        // 添加积分
        IntegralRecord record = new IntegralRecord();
        record.setBehaviorCode(IntegralBehaviorEnum.CODE_5001.getCode());
        record.setUserId(user.getUserId());
        record.setResId(fileId);
        String url = urlUtil.genBaseUrl(CommonConfig.ADD_INTEGRAL_URL);
        oAuth2RestTemplate.postForObject(url, record, String.class);
        return null;
    }

    /**
     * pdf加水印预览-用户手动输入水印信息
     *
     * @param fileId    附件id
     * @param watermark 水印内容
     * @return
     */
    @ApiOperation(value = "pdf加水印预览-用户手动输入水印信息", notes = "Attachment:pdfPreview")
    @PostMapping("/resouce/pdfPreview")
    @ResponseBody
    public ResultObject pdfPreview(String fileId, String watermark) {

        if (StringUtils.isNullOrEmpty(fileId) || StringUtils.isNullOrEmpty(watermark)) {
            return ResultObject.build(1, "请填写正确参数");
        }
        //pdf加水印预览之前查询pdfUrL
        Map<String, Object> fileMap = attachmentService.queryPdfPreviewUrl(fileId, 2);
        if (null == fileMap.get("pdfUrl") || null == fileMap.get("title")) {
            return ResultObject.build(1, "附件不存在");
        }

        // 生成预览文件路径
        String previewPath = urlUtil.getDefaultPath() + "pdfPreview";
        String fileName = File.separator + CommonUtil.generateUUID() + ".pdf";
        // 检测是否存在目录
        File dest = new File(previewPath);
        if (!dest.isDirectory()) {
            dest.mkdirs();// 新建文件夹
        }

        String preFileName = previewPath + fileName;
        File file = new File(fileMap.get("pdfUrl").toString());
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(preFileName)));
            // 给pdf添加水印并生成新的文件
            PdfUtil.setWatermark(bos, bis, watermark,false);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return ResultObject.build(1, "文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
            return ResultObject.build(1, "文件不存在");
        } catch (DocumentException e) {
            e.printStackTrace();
            return ResultObject.build(1, "添加水印失败");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        // 返回pdf路径
        return ResultObject.ok(preFileName);
    }


    /**
     * @param fileId
     * @param type   2:icp_res_attachment,7:icp_products_attachment,9:icp_res_products_attachment
     * @return
     */
    @ApiOperation(value = "移动端pdf加水印预览", notes = "Attachment:pdfPreview")
    @PostMapping("/resouce/mobildPdfPreview")
    @ResponseBody
    public ResultObject mobildPdfPreview(String fileId, Integer type) {

        if (StringUtils.isNullOrEmpty(fileId)) {
            return ResultObject.build(1, "请填写正确参数");
        }
        //pdf加水印预览之前查询pdfUrL
        Map<String, Object> fileMap = attachmentService.queryPdfPreviewUrl(fileId, type);
        if (null == fileMap || fileMap.isEmpty() || null == fileMap.get("pdfUrl")) {
            return ResultObject.build(1, "该文件不支持预览");
        }
        // 当前用户信息
        UserNew user = oAuth2RestTemplate.getForObject(urlUtil.genBaseUrl(CommonConfig.USER_OAUTH_URL), UserNew.class);
        // 水印 : 姓名+手机号后四位
        String watermark = user.getUserName() + (user.getMobile().substring(7));
        String pdfUrl = fileMap.get("pdfUrl").toString();
        return pdfToBase64(watermark, pdfUrl);
    }

    @ApiOperation(value = "发送邮件附件加水印", notes = "")
    @GetMapping("/resouce/mailFiletAddWatermark")
    @ResponseBody
    public String mailFiletAddWatermark(@RequestParam("fileId")String fileId,@RequestParam("watermark")String watermark) {

        log.info("======fileId====="+fileId);
        log.info("======watermark====="+watermark);
        //pdf加水印预览之前查询pdfUrL
        Map<String, Object> fileMap = attachmentService.queryPdfPreviewUrl(fileId, 2);
        log.info("======fileMap====="+fileMap);
        String pdfUrl = fileMap.get("pdfUrl").toString();
        try {
            File file = new File(pdfUrl);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 给pdf添加水印并写回页面
            PdfUtil.setWatermark(baos, bis, watermark,false);
            byte[] bytes = baos.toByteArray();
            return Base64.toBase64String(bytes);
        } catch (Exception e) {
            log.error("捕获文件异常",e);
        }
        // 返回pdf路径
        return null;
    }

    // pdf加水印公共方法
    private ResultObject pdfToBase64(String watermark, String pdfUrl) {
        try {
            File file = new File(pdfUrl);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 给pdf添加水印并写回页面
            PdfUtil.setWatermark(baos, bis, watermark,false);

            byte[] bytes = baos.toByteArray();
            String res = Base64.toBase64String(bytes);
            return ResultObject.build(0, res);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return ResultObject.build(1, "文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
            return ResultObject.build(1, "添加水印失败");
        } catch (DocumentException e) {
            e.printStackTrace();
            return ResultObject.build(1, "添加水印失败");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            return ResultObject.build(1, "文件不存在");
        }
        // 返回pdf路径
        return null;
    }


    @ApiOperation(value = "将数据库中所有的图片转成pdf", notes = "Attachment:refreshImagetoPdfPath")
    @PostMapping("/resouce/refreshImagetoPdfPath")
    @ResponseBody
    public ResultObject refreshImagetoPdfPath() {
        log.info("------------------------图片转pdf开始------------------");
        List<Map<String, String>> allAtt = attachmentService.selectAllImage();
        log.info("需要转换的数据共计:" + allAtt.size() + "条");
        // 设置文件存储路径
        String filePath = urlUtil.getDefaultPath() + "imageToPdf";
        File dest = new File(filePath);
        // 检测是否存在目录
        if (!dest.isDirectory()) {
            dest.mkdirs();// 新建文件夹
        }
        int totallNum = 1;
        for (Map<String, String> item : allAtt) {
            log.info("开始转换第" + totallNum + "条数据;共计:" + allAtt.size() + "条");
            log.info("id=" + item.get("id") + ";title=" + item.get("title"));
            if (StringUtils.isNullOrEmpty(item.get("url"))) {
                continue;
            }
            File file = new File(item.get("url"));
            if (file.exists()) {
                //判断文件类型 jpg,png
                String title = item.get("title");
                String[] split = title.split("\\.");
                if ("png".equals(split[split.length - 1]) || "jpg".equals(split[split.length - 1])) {
                    String pdfPath = "";
                    if (item.containsKey("pdfUrl")) {

                        String pdfurl = item.get("pdfUrl");
                        if (StringUtils.isNullOrEmpty(pdfurl)) { // 不存在创建
                            // 将图片转换为pdf
                            pdfPath = filePath + File.separator + CommonUtil.generateUUID() + ".pdf";
                        } else {                                  // 存在删除
                            File pdfFile = new File(pdfurl);
                            if (!pdfFile.exists()) {
                                if (pdfFile.delete()) {
                                    log.info("删除文件成功:deletePdfPath=" + pdfurl);
                                }
                            }
                            pdfPath = pdfurl;
                        }
                        PdfUtil.imageToPdf(item.get("url"), pdfPath);
                        attachmentService.updatePdfUrlById(item.get("id"), pdfPath, 2);
                        log.info("第" + totallNum + "条数据转换成功:pdfPath=" + pdfPath);
                    }
                }
            }
            totallNum++;
        }
        log.info("------------------------图片转pdf结束------------------");
        return ResultObject.ok();
    }

    @ApiOperation(value = "将数据库中所有的office转成pdf", notes = "Attachment:fileUpload")
    @GetMapping("/resouce/refreshOfficeToPdf")
    @ResponseBody
    public String refreshOfficeToPdf(Integer type) {

        String dirPath = urlUtil.getDefaultPath() + "officeToPdf" + File.separator;
        File dir = new File(dirPath);
        // 检测是否存在目录
        if (!dir.isDirectory()) {
            dir.mkdirs();// 新建文件夹
        }
        List<Map<String, String>> allAtt = attachmentService.selectAttByPdfurlisnull(type);
        log.info("------------------转换类型开始------------------");
        log.info("type类型:" + type + "///共查询" + allAtt.size() + "条数据");
        int tall = 0;
        for (Map<String, String> att : allAtt) {
            String title = att.get("title");
            String url = att.get("url");
            String id = att.get("id");
            tall++;
            log.info("当前第" + tall + "条资源:id=" + id + ";url=" + url + ";title=" + title);
            //获取文件后缀和存储名称
            String strArry[] = title.split("\\.");
            String fileSuffix = strArry[strArry.length - 1];
            String uuid = CommonUtil.generateUUID();

            File dest = new File(url);
            if (dest.exists()) {
                String pdfUrl = dirPath + uuid + ".pdf";
                if (fileSuffix.equalsIgnoreCase("pdf")) { // 附件是pdf 源文件地址与pdf地址是同一个
                    // 上传的是pdf文件直接保存
                    attachmentService.updatePdfUrlById(id, url, type);
                } else if (fileSuffix.equalsIgnoreCase("jpg") || fileSuffix.equalsIgnoreCase("png")) {
                    // 图片转pdf
                    PdfUtil.imageToPdf(url, pdfUrl);
                    attachmentService.updatePdfUrlById(id, pdfUrl, type);
                } else {
                    // office文档转换乘pdf
                    String fileType = switchFileType(fileSuffix);
                    if (!fileType.equals("")) {
                        // 1:类型参数为空 ,2:路径参数为空 ,3: 类型参数错误
                        String result = OfficeToPdf.fileToPDF(fileType, url, pdfUrl);
                        switch (result) {
                            case "1":
                                log.error("office转换pdf:类型参数为空");
                                break;
                            case "2":
                                log.error("office转换pdf:路径参数为空");
                                break;
                            case "3":
                                log.error("验证License失败");
                                break;
                            case "4":
                                log.error("office转换pdf:类型参数错误");
                                break;
                            default:
                                attachmentService.updatePdfUrlById(id, pdfUrl, type);
                        }
                    }
                }
            }
        }
        log.info("------------------转换类型结束------------------");
        return "转换结束";
    }


    @ApiOperation(value = "下载资源附件", notes = "Attachment:downloadResAtt")
    @GetMapping("/resouce/protalDownload")
    @ResponseBody
    public ResultObject protalDownload(String fileId, HttpServletResponse response, Integer type,
                                       @RequestParam(required = false) String unCount) throws IOException {
        if (type == null) {
            type = 2;
        }

        //业绩库web端定向审核下载添加积分
        if("unCount".equals(unCount)){
            // 当前用户信息
            UserNew user = oAuth2RestTemplate.getForObject(urlUtil.genBaseUrl(CommonConfig.USER_OAUTH_URL), UserNew.class);
            // 添加积分
            IntegralRecord record = new IntegralRecord();
            record.setBehaviorCode(IntegralBehaviorEnum.CODE_5001.getCode());
            record.setUserId(user.getUserId());
            record.setResId(fileId);
            String url = urlUtil.genBaseUrl(CommonConfig.ADD_INTEGRAL_URL);
            oAuth2RestTemplate.postForObject(url, record, String.class);
        }
        Map<String, Object> fileMap = attachmentService.queryAttUrl(fileId, type ,unCount);
        /*
            运管后台下载接口取消下载权限校验,可直接下载附件
        if (type == 2) {//资源附件下载需要校验是否有下载权限
            if (fileMap.get("auditFlag") != null && Boolean.valueOf(fileMap.get("auditFlag").toString())) {
                ResAttAudit resAttAudit = new ResAttAudit();
                resAttAudit.setApplyUserId(user.getUserId());
                resAttAudit.setAttId(fileId);
                ResAttAudit resAudit = oAuth2RestTemplate.postForObject(urlUtil.genBaseUrl(CommonConfig.ATT_DOWNLOAD_SATUS), resAttAudit, ResAttAudit.class);
                //记录审核表id  下载成功后删除审核表记录
                auditId = resAudit.getAuditId();
                if (resAudit.getAuditStatus() == null || resAudit.getAuditStatus() != 1) {
                    return ResultObject.build(1, "未拥有该资源下载权限,请申请后再试!");
                }
            }
        }*/
        response.reset();
        OutputStream os = response.getOutputStream();
        File file = new File(fileMap.get("url").toString());
        if (!file.exists()) {
            return ResultObject.build(1, "附件不存在!");
        }
        BufferedInputStream bis = null;
        setResponseHeader(response, fileMap.get("title").toString(), "application/octet-stream;charset=utf-8");
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] b = new byte[bis.available() + 1000];
            int i = 0;
            while ((i = bis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            bis.close();
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultObject.build(1, "数据异常,下载失败!");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //删除审核表中审核记录
//        if (type == 2) {
//            ResAttAudit resAttAudit = new ResAttAudit();
//            resAttAudit.setAttId(fileId);
//            resAttAudit.setAuditStatus(5);
//            oAuth2RestTemplate.postForObject(urlUtil.genBaseUrl(CommonConfig.UPDATE_ATT_AUDIT_STATUS), resAttAudit, Boolean.class);
//        }
        return null;
    }


    /**
     * @param fileId
     * @param type   2:icp_res_attachment ,17:icp_res_products_attachment
     * @return
     */
    @ApiOperation(value = "将数据库中所有的office转成pdf", notes = "Attachment:fileUpload")
    @GetMapping("/resouce/refreshOfficeToPdfById")
    @ResponseBody
    public String refreshOfficeToPdfById(String fileId, Integer type,@RequestParam(required = false) String unCount) {

        String dirPath = urlUtil.getDefaultPath() + "officeToPdf" + File.separator;
        File dir = new File(dirPath);
        // 检测是否存在目录
        if (!dir.isDirectory()) {
            dir.mkdirs();// 新建文件夹
        }
        Map<String, Object> fileMap = attachmentService.queryAttUrl(fileId, type,unCount);
        log.info("------------------转换类型开始------------------");
        String title = (String) fileMap.get("title");
        String url = (String) fileMap.get("url");
        log.info("当前资源:id=" + fileId + ";url=" + url + ";title=" + title);
        //获取文件后缀和存储名称
        String strArry[] = title.split("\\.");
        String fileSuffix = strArry[strArry.length - 1];
        String uuid = CommonUtil.generateUUID();

        File dest = new File(url);
        if (dest.exists()) {
            String pdfUrl = dirPath + uuid + ".pdf";
            if (fileSuffix.equalsIgnoreCase("pdf")) { // 附件是pdf 源文件地址与pdf地址是同一个
                // 上传的是pdf文件直接保存
                attachmentService.updatePdfUrlById(fileId, url, type);
            } else if (fileSuffix.equalsIgnoreCase("jpg") || fileSuffix.equalsIgnoreCase("png")) {
                // 图片转pdf
                PdfUtil.imageToPdf(url, pdfUrl);
                attachmentService.updatePdfUrlById(fileId, pdfUrl, type);
            } else {
                // office文档转换乘pdf
                String fileType = switchFileType(fileSuffix.toLowerCase());
                if (!fileType.equals("")) {
                    // 1:类型参数为空 ,2:路径参数为空 ,3: 类型参数错误
                    String result = OfficeToPdf.fileToPDF(fileType, url, pdfUrl);
                    switch (result) {
                        case "1":
                            log.error("office转换pdf:类型参数为空");
                            break;
                        case "2":
                            log.error("office转换pdf:路径参数为空");
                            break;
                        case "3":
                            log.error("验证License失败");
                            break;
                        case "4":
                            log.error("office转换pdf:类型参数错误");
                            break;
                        default:
                            attachmentService.updatePdfUrlById(fileId, pdfUrl, type);
                    }
                }
            }
        }
        log.info("------------------转换类型结束------------------");
        return "转换结束";
    }

    @ApiOperation(value = "下载视频", notes = "Attachment:videoDownload")
    @GetMapping("/resouce/videoDownload")
    public ResultObject videoDownload(String videoId, HttpServletResponse response)
            throws IOException {
        Map<String, Object> fileMap = attachmentService.queryVideoUrl(videoId);
        if (null == fileMap || fileMap.isEmpty()){
            return ResultObject.build(1, "视频不存在!");
        }
        response.reset();
        OutputStream os = response.getOutputStream();
        File file = new File(fileMap.get("url").toString());
        if (!file.exists()) {
            return ResultObject.build(1, "视频不存在!");
        }
        BufferedInputStream bis = null;
        setResponseHeader(response, fileMap.get("title").toString(), "application/octet-stream;charset=utf-8");
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] b = new byte[bis.available() + 1000];
            int i = 0;
            while ((i = bis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            bis.close();
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultObject.build(1, "数据异常,下载失败!");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
package com.qtong.icp.module.service;

import com.mysql.jdbc.StringUtils;
import com.qtong.icp.core.domain.Result;
import com.qtong.icp.core.util.CommonUtil;
import com.qtong.icp.module.mapper.AttachmentMapper;
import com.qtong.icp.module.mapper.QualificationsManageMapper;
import com.qtong.icp.module.util.FileUtil;
import com.qtong.icp.module.util.PeopleTypeEnum;
import com.qtong.icp.pojo.attachment.AttachmentAuditStatus;
import com.qtong.icp.pojo.attachment.QualiAttachmentResponse;
import com.qtong.icp.pojo.demandAttachment.DemandAttachment;
import com.qtong.icp.pojo.products.FileVideo;
import com.qtong.icp.pojo.qualificationsManage.ChildrenQualificationsManageResponse;
import com.qtong.icp.pojo.qualificationsManage.QualificationsManageResponse;
import com.qtong.icp.pojo.resAttachment.ResAttachment;
import com.qtong.icp.pojo.user.UserOpusAttachmend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AttachmentService {
    private static Logger log = LoggerFactory.getLogger(AttachmentService.class);

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    private QualificationsManageMapper qualificationsManageMapper;


    public int saveDemandAtt(String demandId, File file, String userId, String fileRealName) {
        if (StringUtils.isNullOrEmpty(demandId) && file.exists()) {
            return 0;
        }
        DemandAttachment da = new DemandAttachment();
        Timestamp createTime = new Timestamp((new Date()).getTime());

        da.setId(CommonUtil.generateUUID());
        da.setDemandId(demandId);
        da.setTitle(fileRealName);
        da.setUrl(file.getPath());
        da.setFileSize(file.length() / (1024));
        da.setOperatorId(userId);
        da.setOperatorTime(createTime);

        return attachmentMapper.saveDemandAtt(da);

    }

    public int saveResAtt(String resId, File file, String userId, String fileRealName) {
        if (StringUtils.isNullOrEmpty(resId) && file.exists()) {
            return 0;
        }
        ResAttachment ra = new ResAttachment();
        Timestamp createTime = new Timestamp((new Date()).getTime());

        ra.setId(CommonUtil.generateUUID());
        ra.setResId(resId);
        ra.setaTitle(fileRealName);
        ra.setUrl(file.getPath());
        ra.setSize(file.length() / (1024));
        ra.setOperatorId(userId);
        ra.setOperatorTime(createTime);

        return attachmentMapper.saveResAtt(ra);

    }

    public int createQrCode(String attid, File file, String userId, String fileRealName) {
        if (StringUtils.isNullOrEmpty(attid) && file.exists()) {
            return 0;
        }
        ResAttachment ra = new ResAttachment();
        Timestamp createTime = new Timestamp((new Date()).getTime());

        ra.setId(attid);
        ra.setaTitle(fileRealName);
        ra.setUrl(file.getPath());
        ra.setSize(file.length() / (1024));
        ra.setOperatorId(userId);
        ra.setOperatorTime(createTime);

        return attachmentMapper.saveResAtt(ra);

    }


    public String saveAtt(File file, String userId, int type, String fileRealName) {
        ResAttachment ra = new ResAttachment();
        Timestamp createTime = new Timestamp((new Date()).getTime());

        String attId = CommonUtil.generateUUID();

        ra.setId(attId);
        ra.setaTitle(fileRealName);
        ra.setUrl(file.getPath());
        ra.setSize(file.length() / (1024));
        ra.setOperatorId(userId);
        ra.setOperatorTime(createTime);
        int result = 0;
        if (type == 7 || type == 9) {
            result = attachmentMapper.saveProductsAtt(ra, type);
        } else {
            result = attachmentMapper.saveAtt(ra, type);
        }
        if (result > 0) {
            return attId;
        }
        return "";
    }

    public String saveVideo(File file, String path, String coverPath, String videoCoverUrl,String userId, String fileRealName, String videoType, String videoPath, Integer type) {
        FileVideo fileVideo = new FileVideo();
        String videoId = CommonUtil.generateUUID();
        fileVideo.setVideoId(videoId);
        fileVideo.setVideoName(fileRealName);
        fileVideo.setVideoType(videoType);
        long fileSize = file.length() / (1024);
        fileVideo.setVideoSize((int) fileSize);
        fileVideo.setVideoPath(videoPath);
        fileVideo.setCreatorId(userId);
        fileVideo.setBasePath(path);
        // 秒
        Long seconds = FileUtil.videoDuration(file);
        // 时长转换
        String exchange = exchange(seconds);
        fileVideo.setVideoMinutes(exchange);
        //将第一帧图片放到对应的路径下
        try {
            log.info("文件路径{},图片路径{}", path, coverPath);
            FileUtil.fetchFrame(path, coverPath);
        } catch (Exception e) {
            log.error(e.getMessage());
            return "上传失败";
        }
        //设置访问地址
        fileVideo.setVideoCoverUrl(videoCoverUrl);

        int result = this.attachmentMapper.saveVideo(fileVideo, type);
        if (result > 0) {
            return videoId;
        }
        return "";
    }

    private String exchange(long seconds){
        long min = seconds / 60;
        long sec = seconds % 60;
        // 视频时长小于60分钟时
        if (min < 60){
            return  new SimpleDateFormat("mm:ss").format(new Date(seconds * 1000));
        }
        String exchange = "";
        // 大于60分钟时,分钟 拼接 秒
        if (sec > 10){
            exchange = min + ":" + sec;
        }else {
            exchange = min + ":0" + sec;
        }
        return exchange;

    }

    public String saveOpusAtt(File file, String userId, Integer type, String fileRealName) {
        UserOpusAttachmend opus = new UserOpusAttachmend();
        String attId = CommonUtil.generateUUID();
        Timestamp createTime = new Timestamp((new Date()).getTime());
        opus.setId(attId);
        if (type == 2) {
            opus.setUserId(userId);
        }
        opus.setOperatorTime(createTime);
        opus.setTitle(fileRealName);
        opus.setUrl(file.getPath());
        opus.setFileSize(file.length() / (1024));
        opus.setOperatorId(userId);
        int result = this.attachmentMapper.saveOpusAtt(opus);
        if (result > 0) {
            return attId;
        }
        return "";

    }

    /***
     * 查询下载地址
     */
    public Map<String, Object> queryAttUrl(String fileId, Integer type,String unCount) {
        if (StringUtils.isNullOrEmpty(fileId)) {
            return null;
        }
        //如果是资源,要先记录下载数量
        Map<String, Object> fileMap = attachmentMapper.queryAttUrl(fileId, type);
        if(fileMap.isEmpty()){
            return null;
        }
        if (type == 2 && !StringUtils.isNullOrEmpty(fileMap.get("url").toString())) {
            // 记录资源附件表下载数量
            //业绩库,后台不添加
            if(!"unCount".equals(unCount)){
                attachmentMapper.updateDownloadNum(fileId);
            }
            // 记录解决方案资源下载数量
            attachmentMapper.updateDownloadNumBySlnId(fileId);
        }
        //记录典型案列下载数量
        if ((type == 7 || type == 17) && !StringUtils.isNullOrEmpty(fileMap.get("url").toString())) {
            attachmentMapper.updateProductsDownloadNum(fileId, type);
        }
        return fileMap;
    }

    public String queryAttUrlAndDelete(String fileId, Integer type) {
        if (StringUtils.isNullOrEmpty(fileId)) {
            return null;
        }
        String url = null;
        if (type == 2) {
            // select
            url = attachmentMapper.queryrResAttUrlAndDeleteq(fileId, type).get("url");
            // delete
            attachmentMapper.queryrResAttUrlAndDeleted(fileId, type);
        } else if (type == 8 || type == 18 || type == 19 || type == 20) {
            // select
            url = attachmentMapper.queryrVideoUrlAndDeleteq(fileId, type).get("video_path");
            // update // 删除视频
            attachmentMapper.queryrVideoUrlAndDeleted(fileId, type);

            // 将资源 视频ID 设为null
            attachmentMapper.updateVideoIdIsNull(fileId, type);
        } else if (type == 17) {
            // select
            url = attachmentMapper.queryAttUrlAndDeleteq(fileId, type).get("url");
            // delete
            attachmentMapper.queryAttUrlAndDeleted(fileId, type);
        } else {
            // select
            url = attachmentMapper.queryAttUrlAndDeleteq(fileId, type).get("url");
            // delete
            attachmentMapper.queryAttUrlAndDeleted(fileId, type);
        }
        // return
        if (url != null && !"".equals(url)) {
            return url;
        }
        return "";
    }

    public Boolean updateAttachmentResId(List<AttachmentAuditStatus> attInfoList, String resId) {
        int update = 0;
        for (AttachmentAuditStatus attInfo : attInfoList) {
            update += attachmentMapper.updateAttachmentResId(attInfo, resId);
        }
        return update == attInfoList.size();
    }

    public Map<String, Object> queryUrlANDTitle(String fileId) {

        Map<String, Object> queryAttUrl = attachmentMapper.queryAttUrl(fileId, 2);
        if (!StringUtils.isNullOrEmpty(queryAttUrl.get("url").toString())) {
            attachmentMapper.updateDownloadNum(fileId);
        }
        return queryAttUrl;
    }

    /**
     * 修改pdfurl
     * @param attId   附件id
     * @param pdfPath
     * @return
     */
    public int updatePdfUrlById(String attId, String pdfPath,Integer type) {
        return attachmentMapper.updatePdfUrlById(attId, pdfPath,type);
    }

    /**
     * 保存pdf
     *
     * @param file         文件
     * @param userId       用户id
     * @param fileRealName 文件名称
     * @return
     */
    public String saveAttPdf(File file, String userId, String fileRealName) {
        ResAttachment ra = new ResAttachment();
        Timestamp createTime = new Timestamp((new Date()).getTime());

        String attId = CommonUtil.generateUUID();

        ra.setId(attId);
        ra.setaTitle(fileRealName);
        ra.setUrl(file.getPath());
        ra.setPdfUrl(file.getPath());
        ra.setSize(file.length() / (1024));
        ra.setOperatorId(userId);
        ra.setOperatorTime(createTime);
        int result = attachmentMapper.saveAttPdf(ra);
        if (result > 0) {
            return attId;
        }
        return "";
    }


    /**
     * 查询pdf下载url
     *
     * @param fileId 附件id
     * @return
     */
    public Map<String, Object> queryPdfUrl(String fileId) {
        if (StringUtils.isNullOrEmpty(fileId)) {
            return null;
        }
        //如果是资源,要先记录下载数量
        Map<String, Object> fileMap = attachmentMapper.queryPdfUrl(fileId);
        String pdfUrl = (String) fileMap.get("pdfUrl");
        if (!StringUtils.isNullOrEmpty(pdfUrl)) {
            // 记录资源附件表下载数量
            attachmentMapper.updateDownloadNum(fileId);

            // 记录解决方案资源下载数量
            attachmentMapper.updateDownloadNumBySlnId(fileId);
        }
        return fileMap;
    }

    /**
     *  pdf 加水印预览之前查询pdfUrL
     * @param fileId
     * @return
     */
    public Map<String, Object> queryPdfPreviewUrl(String fileId,Integer type) {
        Map<String, Object> fileMap = attachmentMapper.queryPdfUrlByType(fileId,type);
        return fileMap;
    }

    public List<Map<String, String>> selectAllAtt() {
        return attachmentMapper.selectAllAtt();
    }

    public List<Map<String, String>> selectAllImage() {
        return attachmentMapper.selectAllImage();
    }

    //通过附件id 获取附件挂载资源的类型
    public String getReourceTypeByFileId(String fileId) {
        return attachmentMapper.getReourceTypeByFileId(fileId);
    }

    public Integer getUserDownloadNum(String userId) {
        return attachmentMapper.getUserDownloadNum(userId);
    }
    public Integer updateUserDownloadNumByUId(String userId) {
        return attachmentMapper.updateUserDownloadNumByUId(userId);
    }

    public List<Map<String, String>> selectAttByPdfurlisnull(Integer type) {

        return attachmentMapper.selectAttByPdfurlisnull(type);
    }

    /**
     * 上传xlsx,xls,pdf 文件
     * @param file
     * @param userId
     * @param qualiType
     * @param fileRealName
     * @return
     */
    public String saveQuali(File file, String userId, Integer qualiType, String fileRealName) {
        ResAttachment ra = new ResAttachment();
        Timestamp createTime = new Timestamp((new Date()).getTime());

        String attId = CommonUtil.generateUUID();

        ra.setId(attId);
        ra.setaTitle(fileRealName);
        ra.setUrl(file.getPath());
        ra.setSize(file.length() / (1024));
        ra.setOperatorId(userId);
        ra.setOperatorTime(createTime);
        ra.setQualiType(qualiType);
        int result = 0;
       // if (type == 7 || type == 9) {
            result = attachmentMapper.saveProductsAtt(ra,4);
//        } else {
//            result = attachmentMapper.saveAtt(ra, type);
//        }
        if (result > 0) {
            return attId;
        }
        return "";
    }

    /**
     * 上传excel 文件
     * @param file
     * @return
     */
    @Transactional
    public String excelUpload(File file,String userId,String resId,Integer qualiType,String fileRealName) {
        //查询数据    文件id resid
        if (!file.exists()) {
            return "文件为空";

        }
        if(StringUtils.isNullOrEmpty(resId)){
            return  "上传文件id为空";
        }
        //查询父节点
        List<String> resIds = qualificationsManageMapper.getParentBranchList();
        if(!resIds.contains(resId)){
            return "未查到该父节点id";
        }
        //查询附件表
        String id = attachmentMapper.queryByResId(resId, qualiType);
        if(StringUtils.isNullOrEmpty(id)){
            ResAttachment ra = new ResAttachment();
            Timestamp createTime = new Timestamp((new Date()).getTime());
            String attId = CommonUtil.generateUUID();
            ra.setId(attId);
            ra.setResId(resId);
            ra.setaTitle(fileRealName);
            ra.setUrl(file.getPath());
            ra.setSize(file.length() / (1024));
            ra.setOperatorId(userId);
            ra.setOperatorTime(createTime);
            ra.setQualiType(qualiType);
            int count = attachmentMapper.insertAtt(ra);
            if(count == 0 ){
                return "添加失败";
            }
        }else {
            ResAttachment ra = new ResAttachment();
            ra.setResId(resId);
            ra.setQualiType(qualiType);
            ra.setUrl(file.getPath());
            int count=attachmentMapper.updateUrl(ra);
            if(count == 0){
                return "修改失败";
            }
        }

        return  "操作成功";
    }


    public String pdfUpload(File file, String userId, String resId, Integer qualiType, String fileRealName) {
        //查询数据    文件id resid
        if (!file.exists()) {
            return "文件为空";

        }

        //查询最末分支
        List<String> ids = qualificationsManageMapper.getLastBranchList();
        if(!ids.contains(resId)){
            return "resId有误,不是最末菜单最末分支";
        }
        //查询附件表
        String id = attachmentMapper.queryByResId(resId, qualiType);
        if(StringUtils.isNullOrEmpty(id)){
            ResAttachment ra = new ResAttachment();
            Timestamp createTime = new Timestamp((new Date()).getTime());
            String attId = CommonUtil.generateUUID();
            ra.setId(attId);
            ra.setResId(resId);
            ra.setaTitle(fileRealName);
            ra.setUrl(file.getPath());
            ra.setPdfUrl(file.getPath());
            ra.setSize(file.length() / (1024));
            ra.setOperatorId(userId);
            ra.setOperatorTime(createTime);
            ra.setQualiType(qualiType);
            int count = attachmentMapper.insertAtt(ra);
            if(count == 0 ){
                return "添加失败";
            }
        }else {
            ResAttachment ra = new ResAttachment();
            ra.setResId(resId);
            ra.setQualiType(qualiType);
            ra.setUrl(file.getPath());
            ra.setPdfUrl(file.getPath());
            int count=attachmentMapper.updateUrl(ra);
            if(count == 0){
                return "修改失败";
            }
        }
        return "操作成功";
    }

    public File fileProcessing(MultipartFile file,String userId,String defaultPath,String fileSuffix,String fileRealName) {

        String fileName = CommonUtil.generateUUID() + "." + fileSuffix;
        log.info("上传的文件名为:" + fileRealName);
        // 设置文件存储路径
        String filePath = defaultPath + userId + File.separator;
        String path = filePath + fileName;

        File dest = new File(path);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();// 新建文件夹
        }
        try {
            file.transferTo(dest);// 文件写入
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dest;
    }

    public Map<String, Object> queryVideoUrl(String videoId) {
        if (StringUtils.isNullOrEmpty(videoId)) {
            return null;
        }
        Map<String, Object> fileMap = attachmentMapper.queryVideoUrlAndTitle(videoId);
        return fileMap;
    }

    public String queryVideoUrlAndDelete(String fileId,Integer type) {
        Map<String, Object> fileMap = attachmentMapper.queryVideoUrlAndTitle(fileId);
        if (null !=fileMap && !fileMap.isEmpty()){
            // update // 删除视频
            attachmentMapper.queryrVideoUrlAndDeleted(fileId, 18);
            // 将资源 视频ID 设为null  22展项资源视频不需要处理
            if (type != 22){
                attachmentMapper.updateVideoIdIsNull(fileId, type);
            }
            return (String) fileMap.get("url");
        }
        return "";
    }

    public String saveModelAtt(File file, String userId, int type, String fileRealName) {
        ResAttachment ra = new ResAttachment();
        Timestamp createTime = new Timestamp((new Date()).getTime());
        String attId = CommonUtil.generateUUID();
        ra.setId(attId);
        ra.setaTitle(fileRealName);
        ra.setUrl(file.getPath());
        ra.setSize(file.length() / (1024));
        ra.setOperatorId(userId);
        ra.setOperatorTime(createTime);
        ra.setQualiType(type);
        int result = attachmentMapper.saveModelAtt(ra);
        if (result > 0) {
            return attId;
        }
        return "";
    }

    /**
     * 概预算 职业技能
     * 安全员 职业技能
     * 特种作业    职业技能
     * 项目经理    职业技能
     * ITSS    职业技能
     * ITIL    职业技能
     * PMP 职业技能
     * 八大员 职业技能
     * 一级建造师   国家职业资格
     * 计算机软考   专业技术职务
     * 通信工程类   专业技术职务
     * 厂家认证    职业技能
     * 信息安全    职业技能
     * 售后服务    职业技能
     * 技术、调查   职业技能
     * 医疗器械    职业技能
     * 安防从业证   职业技能
     * 电子工程师   专业技术职务
     * 机电工程师   专业技术职务
     * 建筑工程师   专业技术职务
     * 云领域云安全  职业技能
     * 其他  职业技能
     * @param resType
     * @return
     */
    public Result getPeopleAttId(String resType) {
        String resId = "";
        Integer qualiType = 5; // 模板数据是手动导入数据库的,qualiType作为标识写死为5
        if (resType.equals(PeopleTypeEnum.TYPE_8.getCode())){
            resId = "A1"; //国家职业资格
        }else if (resType.equals(PeopleTypeEnum.TYPE_9.getCode()) ||
                resType.equals(PeopleTypeEnum.TYPE_20.getCode()) ||
                resType.equals(PeopleTypeEnum.TYPE_15.getCode()) ||
                resType.equals(PeopleTypeEnum.TYPE_16.getCode()) ||
                resType.equals(PeopleTypeEnum.TYPE_17.getCode())){
            resId = "A3"; //专业技术职务
        }else {
            resId = "A2"; //职业技能
        }
        //查询附件表
        String id = attachmentMapper.queryByResId(resId, qualiType);
        Map<String,String> map = new HashMap<>();
        map.put("modelAid",id);//模板id
      String bid = attachmentMapper.queryByResId("A4", qualiType);
        map.put("modelBid",bid);//承诺书id
        return Result.ok(map);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值