manailin
2021-06-21 26e9429512245f4b441b55c3ce59c21a5ebb570f
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
package com.panzhihua.serviceapi.biz.impl;
 
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.panzhihua.common.api.LangchaoApiConstants;
import com.panzhihua.common.constants.TokenConstant;
import com.panzhihua.common.enums.LocalEventToLangChaoEventTypeEnum;
import com.panzhihua.common.model.dtos.api.EventFile;
import com.panzhihua.common.model.dtos.api.EventInfo;
import com.panzhihua.common.model.vos.R;
import com.panzhihua.common.model.vos.grid.EventDetailsVO;
import com.panzhihua.common.model.vos.grid.EventGridDataDetailsVO;
import com.panzhihua.common.model.vos.grid.EventResourceVO;
import com.panzhihua.common.service.grid.GridService;
import com.panzhihua.serviceapi.biz.LcApiService;
import com.panzhihua.serviceapi.model.dto.LcGridData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
 
/**
 * program 攀枝花智慧社区项目
 * description 第三方浪潮市平台对接接口管理API
 *
 * @author manailin
 * Date 2021-01-22 15:30
 **/
@Slf4j
@Service
public class LcApiServiceImpl implements LcApiService {
 
    @Resource
    private GridService gridService;
 
    @Autowired
    private StringRedisTemplate redisTemplate;
 
    /**
     * 从redis获取token
     *
     * @return String 浪潮对接的token
     */
    private String getAuthToken() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        if(valueOperations.get(LangchaoApiConstants.LANG_CHAO_TOKEN) ==null){
            saveTokenFromRemoteRequest("18080799023", "123456");
        }
        return valueOperations.get(LangchaoApiConstants.LANG_CHAO_TOKEN);
    }
 
    @Override
    public String saveTokenFromRemoteRequest(String name, String password) {
        if (redisTemplate.hasKey(LangchaoApiConstants.LANG_CHAO_TOKEN)) {
            //如果redis存在token,直接返回redis存储的token
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            return valueOperations.get(LangchaoApiConstants.LANG_CHAO_TOKEN);
        } else {
            //如果第一次请求浪潮的token请求,请求完成后,保存对于的token到数据库中。便于12小时内重复调用
            HttpRequest request = HttpUtil.createPost(LangchaoApiConstants.GRID_GET_TOKEN_URL.replace("#username", name).replace("#password", password));
            HttpResponse result = request.execute();
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            valueOperations.set(LangchaoApiConstants.LANG_CHAO_TOKEN, result.body(), TokenConstant.EXPIRETIME, TimeUnit.MINUTES);
            return result.toString();
        }
    }
 
    @Override
    public String getAllEventTypeList() {
        HttpRequest request = HttpUtil.createPost(LangchaoApiConstants.GRID_EVENT_CATEGORY_URL);
        request.auth(getAuthToken());
        HttpResponse result = request.execute();
        return result.body();
    }
 
    @Override
    public String submitEventRegister(EventInfo eventInfo) {
        HttpRequest request = HttpUtil.createPost(LangchaoApiConstants.GRID_REGIST_EVENT_URL);
        request.auth(getAuthToken());
        ObjectMapper mapper = new ObjectMapper();
        try {
            //对象转map
            Map m = mapper.readValue(mapper.writeValueAsString(eventInfo), Map.class);
            request.form(m);
        } catch (JsonProcessingException e) {
            log.info("方法submitEventRegister发生错误:{}",e.getMessage());
        }
        HttpResponse result = request.execute();
        log.info(result.body());
        return result.body();
    }
 
    @Override
    public R submitEventRelationFile(EventFile eventFile) {
        HttpRequest request = HttpUtil.createPost(LangchaoApiConstants.GRID_EVENT_FILE_UPLOAD_URL);
        request.auth(getAuthToken());
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(eventFile.getFiles()).openConnection();
            httpUrl.connect();
            File file = inputStreamToFile(httpUrl.getInputStream(), eventFile.getFileName());
            request.form("files", file);
            httpUrl.disconnect();
            request.form("dataId", eventFile.getDataId());
            request.form("type", eventFile.getType());
            request.form("module", eventFile.getModule());
            HttpResponse result = request.execute();
            file.delete();
            return R.ok(result.body());
        } catch (Exception e) {
            log.info("方法submitEventRelationFile发生错误:{}",e.getMessage());
        }
        return R.fail();
    }
 
    @Override
    public String getEventInfoById(String eventId) {
        HttpRequest request = HttpUtil.createPost(LangchaoApiConstants.GRID_APP_EVENT_INFO_DETAIL_URL);
        request.auth(getAuthToken());
        request.form("eventId", eventId);
        HttpResponse result = request.execute();
        return result.body();
    }
 
    @Override
    public List<LcGridData> getGridListByAreaId(String areaId) {
        HttpRequest request = HttpUtil.createPost(LangchaoApiConstants.GRID_GET_EVENT_INFO_AREA_ID_URL);
        request.auth(getAuthToken());
        request.form("areaId", areaId);
        HttpResponse result = request.execute();
        return JSONArray.parseArray(result.body(), LcGridData.class);
    }
 
    @Override
    public String getGridMemberListByAreaIdOrName(String areaId) {
        HttpRequest request = HttpUtil.createPost(LangchaoApiConstants.GRID_GET_GETALL_SEARCH_PAGE_URL);
        request.auth(getAuthToken());
        request.form("areaId", areaId);
        HttpResponse result = request.execute();
        return result.body();
    }
 
    @Override
    public void automationUploadEventAndFile() {
        List<EventDetailsVO> unUploadEventList = gridService.getUnUploadEvent();
        unUploadEventList.forEach(eventInfoVo -> {
            log.info("定时向浪潮服务器提交网格事件登记开始");
            EventInfo eventInfo = new EventInfo();
            String lcGrid = gridService.getLcGridIdByLocal(eventInfoVo.getGridId());
            String lcGridUserId = gridService.getLcUserIdByLocalUserId(eventInfoVo.getGridMemberId().toString());
            eventInfo.setGridId(lcGrid);
            R grid = gridService.eventGridDataDetails(eventInfoVo.getGridId());
            EventGridDataDetailsVO gridData = (EventGridDataDetailsVO) grid.getData();
            eventInfo.setGridName(gridData.getGridName());
            eventInfo.setCaseTypeCode(LocalEventToLangChaoEventTypeEnum.getCodeByName(eventInfoVo.getEventType()));
            eventInfo.setCaseTypeName(LocalEventToLangChaoEventTypeEnum.getEventNameByCode(eventInfoVo.getEventType()));
            eventInfo.setHappenTime(String.valueOf(eventInfoVo.getHappenTime().getTime()));
            eventInfo.setHappenAddress(eventInfoVo.getHappenAddress());
            String[] data = eventInfoVo.getHappentLatLng().split(",");
            eventInfo.setLongitude(data[0]);
            eventInfo.setLatitude(data[1]);
            eventInfo.setCaseDescription(eventInfoVo.getEventDes());
            eventInfo.setCaseRecordTime(String.valueOf(eventInfoVo.getCreateAt().getTime()));
            eventInfo.setHandleType("REPORT");
            eventInfo.setHandleDescription(eventInfoVo.getProcessDesc());
            eventInfo.setDataId(eventInfoVo.getId().toString());
            //获取系统网格员映射的浪潮网格员对于的用户ID
            eventInfo.setUserId(lcGridUserId);
            eventInfo.setHandleTime(String.valueOf(eventInfoVo.getHappenTime().getTime()));
            eventInfo.setCaseName(eventInfoVo.getEventTitle());
            submitEventRegister(eventInfo);
            log.info("定时向浪潮服务器提交网格事件登记结束");
            log.info("开始上传附件信息");
            List<EventResourceVO> picsList = eventInfoVo.getPics();
            uploadLcApiEventFile(eventInfoVo, picsList, "png");
            List<EventResourceVO> audiosList = eventInfoVo.getAudios();
            uploadLcApiEventFile(eventInfoVo, audiosList, "mp3");
            List<EventResourceVO> videoList = eventInfoVo.getVideos();
            uploadLcApiEventFile(eventInfoVo, videoList, "mp4");
            log.info("结束上传附件信息");
            gridService.updateLcUploadFlag(eventInfoVo.getId());
        });
    }
 
    private void uploadLcApiEventFile(EventDetailsVO eventInfoVo, List<EventResourceVO> picsList, String type) {
        picsList.forEach(eventResourceVO -> {
            EventFile eventFile = new EventFile();
            eventFile.setDataId(eventInfoVo.getId().toString());
            eventFile.setFiles(eventResourceVO.getUrl());
            eventFile.setType(type);
            eventFile.setModule("event");
            eventFile.setFileName(eventResourceVO.getResourceName());
            submitEventRelationFile(eventFile);
        });
    }
 
    /**
     * 工具方法
     * inputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception {
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
        log.info(System.getProperty("java.io.tmpdir") + File.separator + name);
        if (file.exists()) {
            return file;
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }
}