xinyb
2024-09-20 562e208f397b70d27c519f225d821298ab04c5cf
提交 | 用户 | age
95fe95 1 package com.yc.crm.mail.service;
X 2
3 import com.yc.action.grid.GridUtils;
4 import com.yc.crm.mail.entity.MailFileEntity;
5 import com.yc.entity.DataSourceEntity;
6 import com.yc.entity.attachment.AttachmentEntity;
7 import com.yc.multiData.MultiDataSource;
8 import com.yc.sdk.shopping.entity.ImageEntity;
9 import com.yc.sdk.shopping.entity.ShoppingImageEntity;
10 import com.yc.sdk.shopping.util.BlobToFile;
11 import com.yc.sdk.shopping.util.SettingKey;
12 import com.yc.service.BaseService;
13 import com.yc.utils.ImageUtils;
14 import org.apache.commons.lang3.StringUtils;
15 import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.dao.DataAccessException;
17 import org.springframework.dao.EmptyResultDataAccessException;
18 import org.springframework.jdbc.LobRetrievalFailureException;
19 import org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor;
20 import org.springframework.jdbc.support.lob.DefaultLobHandler;
21 import org.springframework.stereotype.Service;
22 import org.springframework.transaction.annotation.Transactional;
23
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpSession;
26 import java.io.File;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.sql.ResultSet;
30 import java.sql.SQLException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37
38 /**
39  * @BelongsProject: eCoWorksV3
40  * @BelongsPackage: com.yc.crm.mail.service
41  * @author: xinyb
42  * @CreateTime: 2024-09-19  10:19
43  * @Description:邮件附件或图片处理
44  */
45 @Service("MailFileImpl")
46 public class MailFileImpl extends BaseService implements MailFileIfc {
47     private final ShoppingImageEntity shoppingImage =  new ShoppingImageEntity() ;
48     @Autowired
49     private DefaultLobHandler defaultLobHandler;
50     @Override
51     public void saveAttachment(List<MailFileEntity> mailFile) {
52         try {
53
54         } catch (Exception e) {
55             throw e;
56         }
57     }
58
59
60     @Override
61     public List<AttachmentEntity> getAttachmentEntityList(String unIdSeq) {
62         String unId = null;
63         if (StringUtils.isBlank(unIdSeq)) {
64             return null;
65         }
66         String[] array = unIdSeq.split(";");
67         unId = array[0];//在有值时候第一个必定是unId
68         ArrayList<String> fieldId = new ArrayList<>(Arrays.asList(array));
69         fieldId.remove(0);//去掉第一个元素(UNID)
70         String sql = " set nocount on \n"
71                 + " declare @unid varchar(50) = " + GridUtils.prossSqlParm(unId) +
72                 ",@fieldid varchar(1000) = " + GridUtils.prossSqlParm(StringUtils.join(fieldId, ",")) + " \n";
73
74         sql += " select UNID,seq,DocCode,RowId,FieldId,FormId, \n"
75                 + " PhysicalPath,PhysicalFile,OriginalFileName,FileSize,FileType, \n"
76                 + " AuthorCode,AuthorName,SmallPicPath,UploadTime,OriginalPicture \n"
77                 + " from _sys_Attachment \n"
78                 + " where unid = @unid ";
79         if (fieldId.size() > 0) {
80             if (isNumeric(fieldId.get(0))) {
81                 sql += " and seq in(select list from GetInStr(@fieldid)) \n";
82             } else {
83                 sql += " and fieldid in(select list from GetInStr(@fieldid)) \n";
84             }
85         }
86         List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql);
87         List<AttachmentEntity> attachmentList = new ArrayList<AttachmentEntity>();
88         for (int i = 0; list != null && i < list.size(); i++) {
89             AttachmentEntity attachment = new AttachmentEntity();
90             attachment.setUnid(unId);
91             attachment.setPhysicalFile(list.get(i).get("PhysicalFile") == null ? null : (String) list.get(i).get("PhysicalFile"));
92             attachment.setOriginalFileName(list.get(i).get("OriginalFileName") == null ? null : (String) list.get(i).get("OriginalFileName"));
93             attachment.setOriginalPicture(list.get(i).get("OriginalPicture") == null ? null : (byte[]) list.get(i).get("OriginalPicture"));  //附件处理
94             attachmentList.add(attachment);
95         }
96         return attachmentList;
97     }
98
99
100
101     @Transactional(rollbackFor = Exception.class)
102     @Override
103     public Integer deleteAttachment(List<String> unId) {
104         try {
105             if (unId == null || unId.size() == 0) {
106                 return 0;
107             }
108             String sql = " set nocount on \n"
109                     + " declare @unid varchar(4000) = '" + StringUtils.join(unId, ",") + "'  \n";
110             sql += "delete _sys_Attachment where unid in (select list from GetInStr(@unid)) \n";
111             sql += "select @@ROWCOUNT";
112             return jdbcTemplate.queryForObject(sql, Integer.class);
113         } catch (Exception e) {
114             throw e;
115         }
116     }
117
118     @Override
119     public ImageEntity getImageFile(String unid, Integer width, Integer height, boolean isShowOrgImage, HttpServletRequest request, String attachmentPath, String formidPath) throws Exception {
120         HttpSession session = request.getSession();
121         if (unid == null || "".equals(unid)) {
122             // this.print(response, "获取图片时,必须传递参数 " + SettingKey.UNID);
123             return null;
124         }
125         if (isShowOrgImage) {
126             width = null;
127             height = null;
128         }
129         ShoppingImageEntity shoppingImageEntity = null ;
130         DataSourceEntity dataSourceEntity = null;
131         try {
132             dataSourceEntity = MultiDataSource.getDataSourceMap( request) ;
133             if (dataSourceEntity == null) {
134                 throw new Exception("没有找到数据源,获取图片文件失败!" ) ;
135             }
136
137             String rootPath = session.getServletContext().getRealPath("/");
138             //String uuid = UUID.randomUUID().toString().toUpperCase();
139
140             shoppingImageEntity = getImage( unid,rootPath ,dataSourceEntity.getDbId(),attachmentPath,formidPath);
141
142             if (shoppingImageEntity == null || shoppingImageEntity.getImage() == null) {
143                 return null;
144             }
145
146             //取原图路径
147             String shoppingImageFileName = SettingKey.getShoppingImageFileName(rootPath,unid, width,height, isShowOrgImage, dataSourceEntity.getDbId()+"", shoppingImageEntity.getFileType(),attachmentPath,formidPath);
148             File file = shoppingImageEntity.getImage();
149
150             if (file != null) {
151
152                 if (width != null && height != null && shoppingImageEntity.getFileType()!=null
153                         //图片文件才缩放,否则会报错
154                         && StringUtils.containsAny(shoppingImageEntity.getFileType().toLowerCase(),"jpg","png","gif","jpeg","tiff","bmp","raw","tga","fpx","webp")) {
155                     // 缩放图片
156                     ImageUtils.scale(file.getPath(), shoppingImageFileName, width, height);
157                 } else {
158                     shoppingImageFileName = file.getPath(); // 不缩放
159                 }
160                 ImageEntity image = new ImageEntity();
161                 image.setFile(new File(shoppingImageFileName));
162                 image.setFileType(shoppingImageEntity.getFileType());
163                 image.setOriginalFileName(shoppingImageEntity.getOriginalFileName());
164                 return image;
165             }
166         } catch (IOException e) {
167             System.out.println("输出缩略图时出错,出错文件名:" + (shoppingImageEntity!=null?shoppingImageEntity.getPhysicalFile():"") +  (dataSourceEntity!=null?"dbid:["+dataSourceEntity.getDbId() + "],系统名称:["+ dataSourceEntity.getSystemDescribe()+"]":"") );
168             throw e;
169         }catch (Exception e) {
170             throw e ;
171         } finally {
172             //if (width != null && height != null && file != null && file.exists())
173             //    file.delete();
174         }
175         return null;
176     }
177
178     private ShoppingImageEntity getImage(String unids, String rootPath, int dbId, String attachmentPath, String formidPath) {
179         if  (unids == null || "".equals(unids))  return null ;
180         String unid = "" ,mailSeq = "" ;
181         String unidStr[] = unids.split(SettingKey.NAVSPLIT) ;   //
182         unid = unidStr[0] ;
183         if (unidStr.length > 1 ) {
184             String seqs[] = unidStr[1].split(";") ;
185             mailSeq = seqs[seqs.length-1];   //只取最后一个 seq , 因为有时候传过来的值是:  7394;7382 ,如果不处理会导致语法错误
186         }
187
188         String sql = " set nocount on ; \n"
189                 + " declare @myrowcount int,@myerror int \n"
190                 + " declare @unid varchar(50) = "+ GridUtils.prossSqlParm(unid)+" \n"
191                 + " declare @FormId int,@DocCode varchar(50),@FieldId varchar(50),@RowId varchar(50) \n"
192                 + " declare @OriginalFileName varchar(200),@PhysicalFile varchar(50),@FileType varchar(50),@FileSize bigint \n"
193                 + " declare @AuthorCode varchar(50),@AuthorName varchar(50),@OriginalPicture varbinary(max) \n"
194
195                 + " select top 1 @FormId = a.FormId,@DocCode = a.DocCode,@FieldId = a.FieldId,@RowId = a.RowId, \n"
196                 + "    @OriginalFileName = a.OriginalFileName ,@PhysicalFile = a.PhysicalFile,@FileType = a.FileType,\n"
197                 + "    @FileSize = isnull(a.FileSize,0),@AuthorCode = a.AuthorCode,@AuthorName = a.AuthorName,\n"
198                 + "    @OriginalPicture = a.OriginalPicture \n"
199                 + " from " + (formidPath!=null&&"9747".equals(formidPath)?"_sys_AttachmentLog":"_sys_Attachment9") + " a \n"
200                 + " where a.UNID = @unid  \n"
201                 + (mailSeq !=null && !"".equals(mailSeq)?" and a.fieldid = '" + mailSeq + "' \n":"")
202                 + " select @myrowcount  = @@rowcount,@myerror = @@error \n"
203
204                 + " if isnull(@myrowcount,0) = 0 \n"
205                 + " begin \n"
206                 + "    select top 1 @FormId = a.FormId,@DocCode = a.DocCode,@FieldId = a.FieldId,@RowId = a.RowId, \n"
207                 + "       @OriginalFileName = a.OriginalFileName ,@PhysicalFile = a.PhysicalFile,@FileType = a.FileType,\n"
208                 + "       @FileSize = isnull(a.FileSize,0),@AuthorCode = a.AuthorCode,@AuthorName = a.AuthorName,\n"
209                 + "       @OriginalPicture = a.OriginalPicture \n"
210                 + "    from "+ (formidPath!=null&&"9747".equals(formidPath)?"_sys_AttachmentLog":"_sys_Attachment") +" a \n"
211                 + "    where a.UNID = @unid  \n"
212                 + (mailSeq !=null && !"".equals(mailSeq)?"    and a.fieldid = '" + mailSeq + "' \n":"")
213                 + " end \n "
214                 + " select @FormId as FormId,@DocCode as DocCode,@FieldId as FieldId,@RowId as RowId, \n" +
215                 "       @OriginalFileName as OriginalFileName ,@PhysicalFile as PhysicalFile,@FileType as FileType,\n" +
216                 "       isnull(@FileSize,0) as FileSize,@AuthorCode as AuthorCode,@AuthorName as AuthorName,\n" +
217                 "       @OriginalPicture as OriginalPicture \n";
218         try {
219             this.jdbcTemplate.query(sql,new AbstractLobStreamingResultSetExtractor(){
220                 protected void handleNoRowFound() throws LobRetrievalFailureException {
221                     System.out.println("在数据库id为:" + dbId + "中,导购管理  ShoppingImageImpl 未找到 unid=" + unids + " 的图片文件(或附件)!");
222                     shoppingImage.setFormId(-1);
223                     shoppingImage.setDocCode("");
224                     shoppingImage.setFieldId("");
225                     shoppingImage.setRowId("");
226
227                     shoppingImage.setOriginalFileName("");
228                     shoppingImage.setPhysicalFile(null);
229                     shoppingImage.setFileType("");
230                     shoppingImage.setFileSize(0L);
231                     shoppingImage.setAuthorCode("");
232                     shoppingImage.setAuthorName("");
233                     shoppingImage.setImage(null) ;
234                 }
235
236                 @Override
237                 protected void streamData(ResultSet rs) throws SQLException, IOException, DataAccessException {
238                     shoppingImage.setFormId(rs.getString("FormId") == null?0:rs.getInt("FormId"));
239                     shoppingImage.setDocCode(rs.getString("DocCode") == null?"":rs.getString("DocCode"));
240                     shoppingImage.setFieldId(rs.getString("FieldId") == null?"":rs.getString("FieldId"));
241                     shoppingImage.setRowId(rs.getString("RowId") == null?"":rs.getString("RowId"));
242
243                     shoppingImage.setOriginalFileName(rs.getString("OriginalFileName") == null?null:rs.getString("OriginalFileName"));
244                     shoppingImage.setPhysicalFile(rs.getString("PhysicalFile") == null?null:rs.getString("PhysicalFile"));
245                     shoppingImage.setFileType(rs.getString("FileType") == null?null:rs.getString("FileType"));
246                     shoppingImage.setFileSize(rs.getLong("FileSize"));
247                     shoppingImage.setAuthorCode(rs.getString("AuthorCode") == null?null:rs.getString("AuthorName"));
248                     shoppingImage.setAuthorName(rs.getString("AuthorName") == null?null:rs.getString("AuthorName"));
249
250
251                     //取原图路径
252                     String shoppingImageFileName = SettingKey.getShoppingImageFileName(rootPath,unids, null, null, true, dbId+"", shoppingImage.getFileType(),attachmentPath,formidPath);
253                     InputStream is = null ;
254                     byte[] bytes = null ;
255                     try {
256                         is = defaultLobHandler.getBlobAsBinaryStream(rs, "OriginalPicture");
257                         if (is != null) {
258                             bytes = ShoppingImageEntity.InputStreamToByte( is); //取二进制图片
259
260                             File file = BlobToFile.writeBytesToFile(bytes,shoppingImageFileName);  //
261                             if (file != null) {
262                                 shoppingImage.setImage(file);
263                             }
264                         }
265                     } catch (IOException e) {
266                         e.printStackTrace();
267                         throw e ;
268                     } finally {
269                         bytes = null ;
270                         if (is != null) is.close();
271                     }
272
273                 }   // end function
274             });
275
276             return shoppingImage ;
277
278         }catch(DataAccessException e ) {
279             if (e instanceof EmptyResultDataAccessException){
280                 return null ;
281             }else {
282                 System.out.println("dbid:" + dbId + ",error:" + (e.getCause() != null ?e.getCause().getMessage():e.getMessage())) ;
283                 e.printStackTrace();
284                 throw e;
285             }
286         }catch(Exception e){
287             System.out.println("dbid:" + dbId + ",error:" + (e.getCause() != null ?e.getCause().getMessage():e.getMessage())) ;
288             e.printStackTrace();
289             throw e;
290         }
291
292     }
293     /**
294      * 判断是否为数字
295      *
296      * @param str
297      * @return
298      */
299     private static boolean isNumeric(String str) {
300         Pattern pattern = Pattern.compile("\\d+");
301         Matcher matcher = pattern.matcher(str);
302         return matcher.matches();
303     }
304 }