lxw
2022-08-03 9e2ee26a25c6ac42963e374afb01b788831bb52f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package com.whyc.service;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whyc.constant.UserOperation;
import com.whyc.dto.FileDirPath;
import com.whyc.dto.Response;
import com.whyc.dto.ZipUtils;
import com.whyc.mapper.ProductBomMapper;
import com.whyc.pojo.DocUser;
import com.whyc.pojo.ProductBom;
import com.whyc.pojo.ProductBomApproving;
import com.whyc.pojo.ProductBomHistory;
import com.whyc.util.ActionUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
 
@Service
public class ProductBomService {
 
    @Autowired(required = false)
    private ProductBomMapper mapper;
 
    @Autowired
    private DocLogService logService;
    //图纸分类检索
    public Response searchCadDrawer(ProductBom productBom,int pageCurr,int pageSize) {
        PageHelper.startPage(pageCurr,pageSize);
        List list=mapper.searchCadDrawer(productBom);
        PageInfo pageInfo=new PageInfo(list);
        return  new Response().setII(1,list.size()>0?true:false,pageInfo,"数据返回");
    }
    //图纸文件下载
    public void downloadCadDrawer(HttpServletRequest req, HttpServletResponse resp, ArrayList<String> pictureUrls) {
        String fileDirName = FileDirPath.getFileDirName();
        String rootFace=fileDirName+ File.separator+"downLoad";
        String pictureName="";
        //将选中的文件存入指定目录下打包下载
        if(pictureUrls!=null&&pictureUrls.size()>0){
            for (String picUrl:pictureUrls) {
                pictureName+=picUrl.substring(picUrl.lastIndexOf("\\")+1)+",";
                File sourceFile=new File(fileDirName+ File.separator+picUrl);
                copyFile(sourceFile,rootFace);
            }
        }
        String timeStr= ActionUtil.sdfwithFTP.format(new Date());
        try {
            File file=new File(rootFace+".zip");
            FileOutputStream forootFace = new FileOutputStream(file);
            ZipUtils.toZip(rootFace, forootFace,true);
            // 转码防止乱码
            resp.addHeader("Content-Disposition", "attachment;filename="
                    + new String(timeStr.getBytes("UTF-8"), "ISO8859-1")
                    + ".zip");
            OutputStream out = resp.getOutputStream();
            FileInputStream in = new FileInputStream(rootFace+".zip");
            int len=0;
            byte[] buffer =new byte[1024];
            //7. 将缓冲区中的数据输出
            while ((len=in.read(buffer))>0){
                out.write(buffer,0,len);
            }
            in.close();
            out.close();
            file.delete();
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //记录日志
        DocUser docUser= ActionUtil.getUser();
        String operationDetail="具体图纸为:"+pictureName.substring(0,pictureName.lastIndexOf(","));
        String opreationMsg="执行了文件打包下载操作";
        String terminalIp=req.getRemoteAddr();
        logService.recordOperationLog(docUser.getId(),docUser.getName(), UserOperation.TYPE_DOWNLOAD.getType(),new Date(),terminalIp,opreationMsg,operationDetail);
 
    }
    //根据子件code获取最终的信息
    public Response getBomBySubcode(String scode) {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("sub_code",scode);
        wrapper.last("limit 1");
        ProductBom productBom=mapper.selectOne(wrapper);
        return new Response().setII(1,productBom!=null?true:false,productBom,"返回数据");
    }
 
    /**获取产品的信息(不包含子料)*/
    public ProductBom getProduct(String parentModel){
        QueryWrapper<ProductBom> query = Wrappers.query();
        query.eq("parent_model",parentModel).last(" limit 1");
        return mapper.selectOne(query);
    }
 
    /** 删除旧的bom,增加新的bom*/
    @Transactional
    public void updateNewBom(List<ProductBomHistory> newBomHistoryList) {
        UpdateWrapper<ProductBom> update = Wrappers.update();
        update.eq("parent_model",newBomHistoryList.get(0).getParentModel());
        mapper.delete(update);
 
        List<ProductBom> newBomList = new LinkedList<>();
        newBomHistoryList.forEach(newBomHis->{
            ProductBom newBom = new ProductBom();
            newBom.setCategory(newBomHis.getCategory());
            newBom.setCreateDate(new Date());
            newBom.setDwgUrl(newBomHis.getDwgUrl());
            newBom.setFileUrl(newBomHis.getFileUrl());
            newBom.setMaterial(newBomHis.getMaterial());
            newBom.setNotes(newBomHis.getNotes());
            newBom.setParentCode(newBomHis.getParentCode());
            newBom.setParentModel(newBomHis.getParentModel());
            newBom.setParentName(newBomHis.getParentName());
            newBom.setParentVersion(newBomHis.getParentVersion());
            newBom.setPictureUrl(newBomHis.getPictureUrl());
            newBom.setProducer(newBomHis.getProducer());
            newBom.setQuantity(newBomHis.getQuantity());
            newBom.setSubCode(newBomHis.getSubCode());
            newBom.setSubModel(newBomHis.getSubModel());
            newBom.setSubName(newBomHis.getSubName());
            newBom.setSurfaceDetail(newBomHis.getSurfaceDetail());
            newBom.setThickness(newBomHis.getThickness());
            newBom.setType(newBomHis.getType());
            newBom.setUnit(newBomHis.getUnit());
            newBom.setUpUserId(newBomHis.getUpUserId());
            newBom.setVersion(newBomHis.getEVersion());
 
            newBomList.add(newBom);
        });
        mapper.insertBatchSomeColumn(newBomList);
    }
 
    //将选中的文件存入指定目录下
    public void copyFile(File source,String dest ){
        //创建目的地文件夹
        File destfile = new File(dest);
        if(!destfile.exists()) {
            destfile.mkdir();
        }
        //source是文件,则用字节输入输出流复制文件
        try {
            if(source.isFile()){
                FileInputStream fis = new FileInputStream(source);
                //创建新的文件,保存复制内容,文件名称与源文件名称一致
                File dfile = new File(dest+File.separator+source.getName());
                if(!dfile.exists()){
                    dfile.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(dfile);
                // 读写数据
                // 定义数组
                byte[] b = new byte[1024];
                // 定义长度
                int len;
                // 循环读取
                while ((len = fis.read(b))!=-1) {
                    // 写出数据
                    fos.write(b, 0 , len);
                }
                //关闭资源
                fos.close();
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public void updateUrl(List<ProductBomApproving> fileBomApprovingList) {
        mapper.updateUrl(fileBomApprovingList);
    }
    /**
     * 获取所有产品信息*/
    public Response getAllBom() {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.select("distinct parent_code","parent_name","parent_model","version").orderByAsc("id");
        List list=mapper.selectList(wrapper);
        return new Response().setII(1,list!=null?true:false,list,"返回数据");
    }
    //产品打包下载
    public  Response downloadBom(HttpServletRequest req, HttpServletResponse resp, String parentModel) {
        HSSFWorkbook wb = new HSSFWorkbook();
        //字体格式-加粗
        HSSFCellStyle cellStyle = wb.createCellStyle();
        HSSFFont font = wb.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        cellStyle.setFont(font);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("parent_model",parentModel);
        List<ProductBom> list=mapper.selectList(wrapper);
        //生成excel并将dwg文件放在同一报下压缩
        creatBomExcel(req,resp,list,wb);
        return  new Response().setII(1,true,"","");
    }
    //根据产品信息创建excel表格并存放在指定目录
    public void creatBomExcel(HttpServletRequest req, HttpServletResponse resp,List<ProductBom> list, HSSFWorkbook wb){
        String fileDirName = FileDirPath.getFileDirName();
        String rootFace=fileDirName+ File.separator+"downLoad";
        String pictureName="";
        String excelName="";
        //创建单个sheet
        HSSFSheet sheet = wb.createSheet("bom信息");
        sheet.setColumnWidth(16,6000);
        //图片元素
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        int rownum = 1;
        sheet.createRow(rownum);
        sheet.getRow(rownum).createCell(1).setCellValue("序列");
        sheet.getRow(rownum).createCell(2).setCellValue("母物料编码");
        sheet.getRow(rownum).createCell(3).setCellValue("母物料名称");
        sheet.getRow(rownum).createCell(4).setCellValue("母物料型号");
        sheet.getRow(rownum).createCell(5).setCellValue("类别");
        sheet.getRow(rownum).createCell(6).setCellValue("子件编码");
        sheet.getRow(rownum).createCell(7).setCellValue("子件名称");
        sheet.getRow(rownum).createCell(8).setCellValue("子件型号");
        sheet.getRow(rownum).createCell(9).setCellValue("基本单位");
        sheet.getRow(rownum).createCell(10).setCellValue("子件数量");
        sheet.getRow(rownum).createCell(11).setCellValue("生产商");
        sheet.getRow(rownum).createCell(12).setCellValue("封装类型/材质");
        sheet.getRow(rownum).createCell(13).setCellValue("元件编号/料厚");
        sheet.getRow(rownum).createCell(14).setCellValue("表面处理/物料详情");
        sheet.getRow(rownum).createCell(15).setCellValue("备注");
        sheet.getRow(rownum).createCell(16).setCellValue("图片");
        //将选中的文件存入指定目录下打包下载
        if(list!=null&&list.size()>0){
            for (int i=0;i<list.size();i++) {
                ProductBom bom=list.get(i);
                String dwgUrl=bom.getDwgUrl();
                excelName=bom.getParentCode();
                if((dwgUrl!=null)&&(!dwgUrl.isEmpty())){
                    pictureName+=dwgUrl.substring(dwgUrl.lastIndexOf("\\")+1)+",";
                    File sourceFile=new File(fileDirName+ File.separator+dwgUrl);
                    copyFile(sourceFile,rootFace);
                }
                Row row=sheet.createRow(rownum+i+1);
                row.setHeight((short)(1500));
                sheet.getRow(rownum+i+1).createCell(1).setCellValue(i+1);
                sheet.getRow(rownum+i+1).createCell(2).setCellValue(bom.getParentCode());
                sheet.getRow(rownum+i+1).createCell(3).setCellValue(bom.getParentName());
                sheet.getRow(rownum+i+1).createCell(4).setCellValue(bom.getParentModel());
                sheet.getRow(rownum+i+1).createCell(5).setCellValue(bom.getCategory());
                sheet.getRow(rownum+i+1).createCell(6).setCellValue(bom.getSubCode());
                sheet.getRow(rownum+i+1).createCell(7).setCellValue(bom.getSubName());
                sheet.getRow(rownum+i+1).createCell(8).setCellValue(bom.getSubModel());
                sheet.getRow(rownum+i+1).createCell(9).setCellValue(bom.getUnit()==null?"":bom.getUnit());
                sheet.getRow(rownum+i+1).createCell(10).setCellValue(bom.getQuantity());
                sheet.getRow(rownum+i+1).createCell(11).setCellValue(bom.getProducer()==null?"":bom.getProducer());
                sheet.getRow(rownum+i+1).createCell(12).setCellValue(bom.getMaterial());
                sheet.getRow(rownum+i+1).createCell(13).setCellValue(bom.getThickness());
                sheet.getRow(rownum+i+1).createCell(14).setCellValue(bom.getSurfaceDetail());
                sheet.getRow(rownum+i+1).createCell(15).setCellValue(bom.getNotes());
                if((bom.getPictureUrl()!=null)&&(!bom.getPictureUrl().isEmpty())){
                    ByteArrayOutputStream byteArrayOut = null;
                    try {
                        byteArrayOut = new ByteArrayOutputStream();
                        BufferedImage bufferImg = ImageIO.read(new FileInputStream(new File(fileDirName+File.separator+bom.getPictureUrl())));
                        ImageIO.write(bufferImg, "png", byteArrayOut);
                        //anchor主要用于设置图片的属性
                        HSSFClientAnchor anchor = new HSSFClientAnchor(50, 20, 1000, 230,(short) 16, rownum+i+1, (short) 16, rownum+i+1);
                        anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE);
                        //插入图片
                        patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (byteArrayOut != null) {
                            try {
                                byteArrayOut.close();
                            } catch (IOException e) {
                                System.out.println("关闭ByteArrayOutputStream失败");
                            }
                        }
                    }
                }
                FileOutputStream fileOut =null;
                try {
                    fileOut = new FileOutputStream(rootFace+File.separator+excelName+".xls");
                    // 写入excel文件
                    wb.write(fileOut);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(fileOut != null){
                        try {
                            fileOut.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        try {
            File file=new File(rootFace+".zip");
            FileOutputStream forootFace = new FileOutputStream(file);
            ZipUtils.toZip(rootFace, forootFace,true);
            // 转码防止乱码
            resp.addHeader("Content-Disposition", "attachment;filename="
                    + new String(excelName.getBytes("UTF-8"), "ISO8859-1")
                    + ".zip");
            OutputStream out = resp.getOutputStream();
            FileInputStream in = new FileInputStream(rootFace+".zip");
            int len=0;
            byte[] buffer =new byte[1024];
            //7. 将缓冲区中的数据输出
            while ((len=in.read(buffer))>0){
                out.write(buffer,0,len);
            }
            in.close();
            out.close();
            file.delete();
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
}