src/main/java/com/whyc/service/MaterialService.java
@@ -5,27 +5,28 @@
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whyc.dto.FileDirPath;
import com.whyc.dto.MaterialCheckDTO;
import com.whyc.dto.Response;
import com.whyc.mapper.MaterialMapper;
import com.whyc.pojo.DocUser;
import com.whyc.pojo.Material;
import com.whyc.pojo.MaterialHistory;
import com.whyc.pojo.ProductBom;
import com.whyc.util.ActionUtil;
import com.whyc.util.CommonUtil;
import com.whyc.util.DateUtil;
import com.whyc.util.FileUtil;
import com.whyc.util.Zip4jUtil;
import com.whyc.util.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@@ -34,6 +35,10 @@
public class MaterialService {
    @Autowired(required = false)
    private MaterialMapper mapper;
    @Autowired
    private MaterialHistoryService mhService;
    //查询所有的散装件信息加设置了替换关系的子件信息
    /*public Response getAllMaterial(String category,String subCode,String subName,String subModel,int pageCurr,int pageSize) {
        PageHelper.startPage(pageCurr,pageSize);
@@ -75,6 +80,27 @@
    public Response getMaterialLimit(String subCode, String subName, String subModel, int pageCurr, int pageSize) {
        PageHelper.startPage(pageCurr,pageSize);
        List<Material> list=mapper.getMaterialLimit(subCode,subName,subModel);
        String fileDirName = FileDirPath.getFileDirName();
        int flag=0;
        // 需要统计附件状态 存在未锁定的附件:1 无附件或者附件全部锁定:0
        if(list!=null&&list.size()>0){
            for (Material m:list) {
                if(m.getFileUrl()!=null&&!m.getFileUrl().isEmpty()){
                    File file = new File(fileDirName+File.separator+m.getFileUrl());
                    if(!file.exists()) {
                        flag=0;
                    }else{
                        String[] fileNames = file.list();//获取该文件夹下的所有文件以及目录的名字
                        if(fileNames.length==m.getAttachLocks().size()){
                            flag=0;
                        }else{
                            flag=1;
                        }
                    }
                }
                m.setAttachFlag(flag);
            }
        }
        PageInfo pageInfo=new PageInfo(list);
        return new Response().setII(1,list.size()>0,pageInfo,"查询所有物料(分页,模糊查询)");
    }
@@ -269,15 +295,15 @@
                        cellValue = cell.getStringCellValue();
                        switch (m){
                            case 2:{material.setCategory(cellValue);}break;
                            //case 2:{material.setCategory(cellValue);}break;
                            case 3:{material.setSubCode(cellValue);}break;
                            case 4:{material.setSubName(cellValue);}break;
                            case 5:{material.setSubModel(cellValue);}break;
                            case 6:{material.setMaterial(cellValue);}break;
                            case 7:{material.setThickness(cellValue);}break;
                            //case 6:{material.setMaterial(cellValue);}break;
                            //case 7:{material.setThickness(cellValue);}break;
                            //case 8:{material.setProducer(cellValue);}break;
                            case 9:{material.setSurfaceDetail(cellValue);}break;
                            case 10:{material.setNotes(cellValue);}break;
                            //case 9:{material.setSurfaceDetail(cellValue);}break;
                            //case 10:{material.setNotes(cellValue);}break;
                            case 11:{
                                //图片从1开始,0是yc logo
                                PictureData pictureData = allPictures.get(l - 7);
@@ -303,6 +329,19 @@
                return response.set(1,false,"拒绝解析,excel文件中记录包含名称为空的记录");
            }
        }
        //追加物料规范校验 暂时去除校验
        /*List<MaterialCheckDTO> checkList = list.stream().map(material -> {
            MaterialCheckDTO dto = new MaterialCheckDTO();
            dto.setNum(material.getId());
            dto.setSubCode(material.getSubCode());
            dto.setSubName(material.getSubName());
            dto.setSubModel(material.getSubModel());
            return dto;
        }).collect(Collectors.toList());
        List<MaterialCheckDTO> irregularList = CommonUtil.checkFormat(checkList);
        if(irregularList.size()>0){
            return new Response().setII(1,false,irregularList,"名称或型号命名不规范");
        }*/
        return response.setII(1,true,list,filePath);
    }
    //根据物料id查询返回附件文件夹下所有的文件列表
@@ -356,66 +395,228 @@
    }
    /**
     * @param multipartFile 被追加的附件,zip内只能的附件都必须是文件
     * @param multipartFileList 被追加的附件,zip集合
     * @param material
     * @return 返回被追加文件的文件夹路径
     */
    @Transactional
    public Response addAttachment(MultipartFile multipartFile, Material material) throws IOException {
    public Response addAttachment(List<MultipartFile> multipartFileList, Material material) throws IOException {
        List<String> currentFileList = new LinkedList<>();
        List<String> uploadingFileList = new LinkedList<>();
        //String dirPath = "doc_file" + File.separator + "material" + File.separator + material.getId() + material.getSubCode() + material.getSubModel();
        String dirPath = CommonUtil.getRootFile() + "material" + File.separator + material.getId() + material.getSubCode() + material.getSubModel();
        String dirPathDB = "doc_file" + File.separator + "material" + File.separator + material.getId() + "-"+ material.getSubCode() + "-" + material.getSubModel();
        String dirPath = CommonUtil.getRootFile() + "material" + File.separator + material.getId() + "-"+ material.getSubCode() + "-" + material.getSubModel();
        File dirFile = new File(dirPath);
        String originalFilename = multipartFile.getOriginalFilename();
        Date now = new Date();
        long timestamp = now.getTime();
        //long timestamp = now.getTime();
        String formattedTimestamp = DateUtil.YYYY_MM_DD_HH_MM_SS_UNION.format(now);
        //压缩包文件夹校验
        File zipFile = new File(dirPath + File.separator + originalFilename);
        multipartFile.transferTo(zipFile);
        //解压文件夹,删除原zip文件
        boolean dirFileExist = true;
        if(!dirFile.exists()){
            dirFile.mkdirs();
            dirFileExist = false;
        }
        for (int i = 0; i < multipartFileList.size(); i++) {
            MultipartFile multipartFile = multipartFileList.get(i);
            String originalFilename = multipartFile.getOriginalFilename();
            File zipFile = new File(dirPath + File.separator + originalFilename.substring(0,originalFilename.lastIndexOf(".")) + "_" + formattedTimestamp + originalFilename.substring(originalFilename.lastIndexOf(".")));
            multipartFile.transferTo(zipFile);
        }
        /*//解压文件夹,删除原zip文件
        String unPackageDir = dirPath + File.separator + timestamp;
        Zip4jUtil.unPackZip(zipFile, null, unPackageDir);
        File unPackageFile = new File(unPackageDir);
        File[] unPackageFileList = unPackageFile.listFiles();
        zipFile.delete();
        for (int i = 0; i < unPackageFileList.length; i++) {
            File tempFile = unPackageFileList[i];
            if(tempFile.isDirectory()){
                FileUtil.deleteFile(unPackageFile);
                if(!dirFileExist){
                    FileUtil.deleteFile(dirFile);
                }
                return new Response().set(1,false,"拒绝上传:上传的压缩包存在文件夹");
            }
        }
        zipFile.delete();
        }*/
        if(!dirFile.exists()){
            dirFile.mkdirs();
        if(!dirFileExist){
            //路径不存在,说明是首次上传,设置物料对应的fileUrl
            Material temp = new Material();
            temp.setId(material.getId());
            temp.setFileUrl(dirPath);
            temp.setFileUrl(dirPathDB);
            mapper.updateById(temp);
        }else{
        }/*else{
            //查询路径下现有的所有文件
            String[] fileArr = dirFile.list();
            currentFileList = Arrays.asList(fileArr);
        }
        }*/
        //查询新上传的文件路径
        /*//查询新上传的文件路径
        String[] unPackageFileArr = unPackageFile.list();
        uploadingFileList = Arrays.asList(unPackageFileArr);
        for (String uploadingFile : uploadingFileList){
            if(currentFileList.contains(uploadingFile)){
                new File(unPackageDir + File.separator + uploadingFile)
                        .renameTo(new File(unPackageDir + File.separator + formattedTimestamp + uploadingFile));
                        .renameTo(new File(unPackageDir + File.separator  + uploadingFile.substring(0,uploadingFile.lastIndexOf(".")) + "_" + formattedTimestamp + uploadingFile.substring(uploadingFile.lastIndexOf("."))));
            }
        }
        //上传的文件夹转移到正式路径
        org.aspectj.util.FileUtil.copyDir(unPackageFile,dirFile);
        FileUtil.deleteFile(unPackageFile);*/
        return new Response().set(1,true,"上传完成");
    }
    /**
     * @param multipartFile 更新的图纸或图片
     * @param material
     */
    @Transactional
    public Response updatePicOrDwg(MultipartFile multipartFile, Material material) throws IOException {
        List<String> currentFileList = new LinkedList<>();
        List<String> uploadingFileList = new LinkedList<>();
        String dirPathDB = "doc_file" + File.separator + "material" + File.separator + material.getSubCode() + "-" + material.getSubModel();
        String dirPath = CommonUtil.getRootFile() + "material" + File.separator + material.getSubCode() + "-" + material.getSubModel();
        File dirFile = new File(dirPath);
        Date now = new Date();
        //long timestamp = now.getTime();
        String formattedTimestamp = DateUtil.YYYY_MM_DD_HH_MM_SS_UNION.format(now);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileFullName = File.separator + originalFilename.substring(0, originalFilename.lastIndexOf(".")) + "_" + formattedTimestamp + originalFilename.substring(originalFilename.lastIndexOf("."));
        File zipFile = new File(dirPath + fileFullName);
        multipartFile.transferTo(zipFile);
        //路径不存在,说明是首次上传,设置物料对应的fileUrl
        //同时在物料历史里面添加记录
        Material temp = new Material();
        MaterialHistory mh = new MaterialHistory();
        temp.setId(material.getId());
        mh.setProductId(-1);
        mh.setMaterialId(material.getId());
        int userId = ActionUtil.getUser().getId().intValue();
        mh.setUpUserId(userId);
        mh.setCreateTime(now);
        if(fileSuffix.equals("dwg")){
            temp.setDwgUrl(dirPathDB + fileFullName);
            mh.setDwgUrl(dirPathDB + fileFullName);
        }else {
            temp.setPictureUrl(dirPathDB + fileFullName);
            mh.setPictureUrl(dirPathDB + fileFullName);
        }
        mapper.updateById(temp);
        mhService.insert(mh);
        return new Response().set(1, true, "上传完成");
    }
    public Response dwgCompare(int materialId, int materialId2) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        //获取各自物料的图纸
        String dwgUrl = mapper.selectById(materialId).getDwgUrl();
        String dwgUrl2 = mapper.selectById(materialId2).getDwgUrl();
        if(dwgUrl == null || dwgUrl2 == null){
            return new Response().set(1,false,"无法对比,所选物料至少有1个不存在图纸");
        }
        String dwgFileStr = CommonUtil.getProjectDir() + File.separator + dwgUrl;
        String dwgFileStr2 = CommonUtil.getProjectDir() + File.separator + dwgUrl2;
        String absoluteDwgPngPath = dwgFileStr.substring(0,dwgFileStr.lastIndexOf("."))+"-dwg.png";
        String absoluteDwgPngPath2 = dwgFileStr2.substring(0,dwgFileStr2.lastIndexOf("."))+"-dwg.png";
        if(!new File(absoluteDwgPngPath).exists()){
            DwgToPngUtil.dwg2png(new File(dwgFileStr));
        }
        if(!new File(absoluteDwgPngPath2).exists()) {
            DwgToPngUtil.dwg2png(new File(dwgFileStr2));
        }
        ByteArrayOutputStream stream = ImageDiff.compareImages(absoluteDwgPngPath, absoluteDwgPngPath2);
        return new Response().setII(1,true, Base64.encodeBase64String(stream.toByteArray()),null);
        //String fileName = "name.png";
        //OutputStream toClient = null;
        //try {
        //    response.setContentType("application/octet-stream");
        //    response.setHeader("Content-Disposition","attachment;filename=" + fileName);
        //    response.addHeader("Pragma", "no-cache");
        //    response.addHeader("Cache-Control", "no-cache");
        //    toClient = response.getOutputStream();
        //    stream.writeTo(toClient);
        //    //toClient.write(stream.toByteArray());
        //    toClient.flush();
        //    toClient.close();
        //} catch (IOException e) {
        //    e.printStackTrace();
        //}
        //
        //
        //return null;
    }
    public void updateDwgUrlAndPicUrl(List<Material> materialUpdateList) {
        mapper.updateDwgUrlAndPicUrl(materialUpdateList);
    }
    public List<Material> getSameSubCodeAndModel(List<ProductBom> bomList) {
        return mapper.getSameSubCodeAndModel(bomList);
    }
    public void checkNaming(InputStream inputStream, HttpServletResponse response) throws IOException, InvalidFormatException {
        List<MaterialCheckDTO> checkList = new LinkedList<>();
        Workbook workbook = null;
        workbook = WorkbookFactory.create(inputStream);
        inputStream.close();
        //取第一个sheet表
        Sheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            System.out.println(i);
            //从第二行开始
            Row row = sheet.getRow(i);
            Cell cell = row.getCell(0);
            cell.setCellType(CellType.STRING);
            String code = cell.getStringCellValue();
            String name = row.getCell(1).getStringCellValue();
            Cell cell2 = row.getCell(2);
            cell2.setCellType(CellType.STRING);
            String model = cell2.getStringCellValue();
            MaterialCheckDTO dto = new MaterialCheckDTO();
            dto.setNum(i);
            dto.setSubName(name);
            dto.setSubCode(code);
            dto.setSubModel(model);
            checkList.add(dto);
        }
        List<MaterialCheckDTO> materialCheckDTOS = CommonUtil.checkFormat(checkList);
        int size = materialCheckDTOS.size();
        //ECR编号,申请日期,申请人,变更描述,变更料号,变更型号,变更所属型号,处理方式,创建时间
        String[] title = new String[]{"序号","物料编码","物料名称","规格型号","不规范原因"};
        String[][] values = new String[size][]; //size行
        for (int i = 0; i < size; i++) {
            values[i] = new String[5];
            MaterialCheckDTO dto = materialCheckDTOS.get(i);
            values[i][0] = dto.getNum().toString();
            values[i][1] = dto.getSubCode();
            values[i][2] = dto.getSubName();
            values[i][3] = dto.getSubModel();
            values[i][4] = dto.getIrregularDesc();
        }
        ExcelUtil.exportExcel("清单","物料",title,values,null,response);
    }
    public Material getLastByCode(String code) {
        QueryWrapper<Material> query = Wrappers.query();
        query.eq("sub_code",code).orderByDesc("id").last(" limit 1");
        return mapper.selectOne(query);
    }
}