fwq
2024-09-27 4034fdffb309c5636c2f7430b8f52bc2b0f2b514
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
package com.hx.phip.his.task;
 
import com.alibaba.fastjson.JSONObject;
import com.hx.common.service.CommonService;
import com.hx.exception.TipsException;
import com.hx.mp.util.MD5Util;
import com.hx.mybatisTool.SqlSentence;
import com.hx.phiappt.model.BaseEntity;
import com.hx.phiappt.model.ComparePhotoRecordPictures;
import com.hx.phip.his.config.BaseConfig;
import com.hx.phip.his.config.SystemConfig;
import com.hx.phiappt.dao.mapper.ComparePhotoRecordPicturesMapper;
import com.hx.resultTool.Result;
import com.hx.util.DateUtil;
import com.hx.util.StringUtils;
import com.hz.his.feign.service.phis.SFileService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
 
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
 
/**
 * @Author
 */
@Component
public class HisUserPicturesTask {
 
    // log4g
    private static final Logger logger = LoggerFactory.getLogger(HisUserPicturesTask.class);
 
    @Resource
    private BaseConfig baseConfig;
    @Resource
    private CommonService commonService;
    @Resource
    private SFileService sFileService;
    @Resource
    private SystemConfig systemConfig;
 
    //@Scheduled(cron="0 0/5 * * * ?")
    public void syncPictureTask() {
        this.handlerSyncPicture(null);
    }
 
    /**
     * 处理上传用户对比照图片
     * @param userId 用户id
     */
    public void handlerSyncPicture(String userId) {
        logger.info("开始执行his图片转换成本地服务器图片定时器");
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
        map.put("isDel", BaseEntity.NO);
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT * FROM compare_photo_record_pictures WHERE isDel=#{m.isDel} ");
        if (!StringUtils.isEmpty(userId)) {
            sql.append(" AND comparePhotoRecordId IN (SELECT id FROM compare_photo_record WHERE userId=#{m.userId} AND isDel=#{m.isDel}) ");
            map.put("userId", userId);
        }
        sql.append(" AND imgUrl IS NULL AND hisImgUrl IS NOT NULL ORDER BY createTime ASC LIMIT #{m.pageNum},#{m.pageSize}");
        sqlSentence.sqlSentence(sql.toString(), map);
        List<ComparePhotoRecordPictures> list;
        // 翻页查询数据
        int pageNum = 0;
        int pageSize = 200;
        // 数据处理
        while (true) {
            map.put("pageNum", pageNum);
            map.put("pageSize", pageSize);
            list = commonService.selectList(ComparePhotoRecordPicturesMapper.class, sqlSentence);
            for (ComparePhotoRecordPictures comparePhotoRecordPictures : list) {
                try {
                    // 处理上传图片转换
                    String imgUrl = this.downloadImg(comparePhotoRecordPictures.getHisImgUrl(), comparePhotoRecordPictures.getId(), comparePhotoRecordPictures.getCreateTime());
                    if (!StringUtils.isEmpty(imgUrl)) {
                        comparePhotoRecordPictures.setImgUrl(imgUrl);
                        commonService.updateAll(ComparePhotoRecordPicturesMapper.class, comparePhotoRecordPictures);
                    }
                } catch (Exception e) {
                    logger.error("数据id: {} 执行his图片转换成本地服务器图片出现异常:", comparePhotoRecordPictures.getId(), e);
                }
            }
            if (list.size() < pageSize) {
                break;
            }
            pageNum = pageNum + pageSize;
        }
        logger.info("完成执行his图片转换成本地服务器图片定时器");
    }
 
    /**
     * 上传图片方法
     * @param url url
     * @param imgName 文件名称
     * @param createTime 文件创建时间
     * @return 返回
     */
    public synchronized String downloadImg(String url, String imgName, Date createTime) {
     /*   URL urlfile = new URL(url);
        InputStream inStream = urlfile.openStream();
 
        File file = File.createTempFile("temp", ".JPG");
        System.out.println(file.getPath());
        File targetFile = new File(file.getPath());
        org.apache.commons.io.FileUtils.copyInputStreamToFile(inStream, targetFile);*/
 
        /*URL urlfile = new URL(url);
        InputStream inStream = urlfile.openStream();*/
 
        // 创建文件名称 小写
        String fileName = MD5Util.MD5Encode(imgName + DateUtil.formatDate_1(createTime), "UTF-8").toLowerCase().replace("-", "").replace(" ", "");
        // 获取文件
        MultipartFile file = createFileItem(url, imgName);
        Result result = sFileService.upload(file, "phi_appt/synchro_picture", systemConfig.getCosBucketName(), fileName + ".jpg");
        if (!result.checkCode()) {
            logger.error("上传图片失败:" + JSONObject.toJSONString(result));
            throw new TipsException("上传图片失败!");
        }
 
        JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(result.getData()));
        String fileUrl = "";
        if (object != null) {
            fileUrl = object.getString("fileUrl");
 
        }
        return fileUrl;
 
     /*   StringBuffer filePath = new StringBuffer();
        filePath.append("phi_appt/synchro_his/"+imgName);
        try {     synchro_contrast
            String imgUrl = OSSUtil.uploadImg(filePath.toString(), file, baseConfig.getOssKeyId(), baseConfig.getOssKeySecret(), baseConfig.getOssEndPoint(), baseConfig.getOssBucket());
            return imgUrl;
        } catch (Exception e) {
            logger.info("上传图片失败:"+e.getMessage());
            e.printStackTrace();
        }*/
    }
 
    /**
     * 创建文件
     * @param url url
     * @param imgName 图片名称
     * @return 返回
     */
    private static MultipartFile createFileItem(String url,String imgName) {
        FileItem item = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setReadTimeout(60000);
            conn.setConnectTimeout(60000);
            //设置应用程序要从网络连接读取数据
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                // 创建工厂对象
                FileItemFactory factory = new DiskFileItemFactory(16, null);
                // 通过工厂对象创建 item 对象
                item = factory.createItem(imgName + ".jpg", ContentType.IMAGE_JPEG.toString(), false, imgName + ".jpg");
                OutputStream os = item.getOutputStream();
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        }
 
        return new CommonsMultipartFile(item);
    }
}