BAOLH
2026-06-15 8dd4e69fafb374bbbf002819e552ba5cdc7d7568
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
/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.temp.service.impl;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import me.zhengjie.modules.temp.domain.WechatSendHistory;
import me.zhengjie.modules.temp.event.ChangeApprovalStatusEvent;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.temp.repository.WechatSendHistoryRepository;
import me.zhengjie.modules.temp.service.WechatSendHistoryService;
import me.zhengjie.modules.temp.service.dto.WechatSendHistoryDto;
import me.zhengjie.modules.temp.service.dto.WechatSendHistoryQueryCriteria;
import me.zhengjie.modules.temp.service.mapstruct.WechatSendHistoryMapper;
import me.zhengjie.utils.weixin.WXBizJsonMsgCrypt;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
* @website https://eladmin.vip
* @description 服务实现
* @author baolh
* @date 2025-02-19
**/
@Service
@RequiredArgsConstructor
public class WechatSendHistoryServiceImpl implements WechatSendHistoryService {
 
    private final WechatSendHistoryRepository wechatSendHistoryRepository;
    private final WechatSendHistoryMapper wechatSendHistoryMapper;
    private final ApplicationEventPublisher applicationEventPublisher;
 
    private final String CORP_ID = "wwc0fd49735bfcf0ad";
    private final String TOKEN = "KXUDtcVs1UdN7T";
    private final String ENCODING_AES_KEY = "FnqE1jnu1LkqkfZzzsgU6WgIRvj1FTo8a7LgOmHqKgM";
    private final String APPROVAL_AGENT_ID = "1000005";
 
    @Override
    public Map<String,Object> queryAll(WechatSendHistoryQueryCriteria criteria, Pageable pageable){
        Page<WechatSendHistory> page = wechatSendHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(wechatSendHistoryMapper::toDto));
    }
 
    @Override
    public List<WechatSendHistoryDto> queryAll(WechatSendHistoryQueryCriteria criteria){
        return wechatSendHistoryMapper.toDto(wechatSendHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
 
    @Override
    @Transactional
    public WechatSendHistoryDto findById(Long id) {
        WechatSendHistory wechatSendHistory = wechatSendHistoryRepository.findById(id).orElseGet(WechatSendHistory::new);
        ValidationUtil.isNull(wechatSendHistory.getId(),"WechatSendHistory","id",id);
        return wechatSendHistoryMapper.toDto(wechatSendHistory);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WechatSendHistoryDto create(WechatSendHistory resources) {
        return wechatSendHistoryMapper.toDto(wechatSendHistoryRepository.save(resources));
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(WechatSendHistory resources) {
        WechatSendHistory wechatSendHistory = wechatSendHistoryRepository.findById(resources.getId()).orElseGet(WechatSendHistory::new);
        ValidationUtil.isNull( wechatSendHistory.getId(),"WechatSendHistory","id",resources.getId());
        wechatSendHistory.copy(resources);
        wechatSendHistoryRepository.save(wechatSendHistory);
    }
 
    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            wechatSendHistoryRepository.deleteById(id);
        }
    }
 
    @Override
    public void download(List<WechatSendHistoryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (WechatSendHistoryDto wechatSendHistory : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("下发内容", wechatSendHistory.getContent());
            map.put("创建时间", wechatSendHistory.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
 
    @Override
    public void approvalBack(String msgSignature, String timestamp, String nonce, String echostr, HttpServletResponse response) {
        try {
            WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(TOKEN, ENCODING_AES_KEY, CORP_ID);
            // 设置响应内容类型为纯文本
            response.setContentType("text/plain; charset=UTF-8");
            // 获取PrintWriter对象
            PrintWriter out = response.getWriter();
            // 直接返回
            String message = wxcpt.VerifyURL(msgSignature, timestamp, nonce, echostr);
            out.print(message);
            // 刷新并关闭PrintWriter
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void handleApprovalCallback(String msgSignature, String timestamp, String nonce, HttpServletRequest request, HttpServletResponse response) {
        try {
            WXBizJsonMsgCrypt wxcpt = new WXBizJsonMsgCrypt(TOKEN, ENCODING_AES_KEY, CORP_ID);
            // 读取回调数据
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
 
            String callbackData = sb.toString();
            // 保存原始数据
            WechatSendHistory beforeHistory = new WechatSendHistory();
            beforeHistory.setContent(callbackData);
            wechatSendHistoryRepository.save(beforeHistory);
 
            // 解密前处理
            JSONObject dataJson;
            if (isJson(callbackData)) {
                dataJson = new JSONObject(callbackData);
            } else {
                JSONObject xmlJson = XML.toJSONObject(callbackData);
                // 修复 JSON 结构
                fixJsonStructure(xmlJson);
                // 保存解密前XML数据
                WechatSendHistory afterHistory1 = new WechatSendHistory();
                afterHistory1.setContent(xmlJson.toString());
                wechatSendHistoryRepository.save(afterHistory1);
 
                dataJson = xmlJson.getJSONObject("xml");
            }
            // 进行解密处理前将键值修改为小写
            JSONObject finalDataJson = new JSONObject(dataJson.keySet().stream().collect(Collectors.toMap(key -> key.toLowerCase(), val -> dataJson.get(val))));
            String decryptedMessage = wxcpt.DecryptMsg(msgSignature, timestamp, nonce, finalDataJson.toString());
            // 保存解密后原始数据
            WechatSendHistory afterHistory2 = new WechatSendHistory();
            afterHistory2.setContent(decryptedMessage);
            wechatSendHistoryRepository.save(afterHistory2);
 
            // 解密后处理
            JSONObject decryptDataJson;
            if (isJson(decryptedMessage)) {
                decryptDataJson = new JSONObject(decryptedMessage);
            } else {
                JSONObject xmlJson = XML.toJSONObject(decryptedMessage);
                // 修复 JSON 结构
                fixJsonStructure(xmlJson);
                // 保存解密后XML数据
                WechatSendHistory afterHistory3 = new WechatSendHistory();
                afterHistory3.setContent(xmlJson.toString());
                wechatSendHistoryRepository.save(afterHistory3);
 
                decryptDataJson = xmlJson.getJSONObject("xml");
            }
            // 保存最终数据
            WechatSendHistory afterHistory4 = new WechatSendHistory();
            afterHistory4.setContent(decryptDataJson.toString());
            WechatSendHistory afterHistorySaved = wechatSendHistoryRepository.save(afterHistory4);
            ChangeApprovalStatusEvent event = new ChangeApprovalStatusEvent(new Object(), afterHistorySaved.getId());
            applicationEventPublisher.publishEvent(event);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void handleWechatSendHistoryBySpNo(String spNo) {
        if (StringUtils.isNotBlank(spNo)) {
            WechatSendHistoryQueryCriteria criteria = new WechatSendHistoryQueryCriteria();
            criteria.setContentInnerLike(spNo);
            List<WechatSendHistory> historyList = wechatSendHistoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), Sort.by(Sort.Direction.DESC, "id"));
            if (historyList.size() > 0) {
                WechatSendHistory filterData = historyList.stream().filter(h -> h.getContent().startsWith("{\"ApprovalInfo\"")).findFirst().orElseGet(WechatSendHistory::new);
                if (StringUtils.isNotBlank(filterData.getContent())) {
                    ChangeApprovalStatusEvent event = new ChangeApprovalStatusEvent(new Object(), filterData.getId());
                    applicationEventPublisher.publishEvent(event);
                }
            }
        }
    }
 
    /**
     * 判断字符串是不是Json格式
     *
     * @param str 字符串对象
     */
    private static Boolean isJson(String str) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    /**
     * 修复 JSON 结构,确保指定字段始终是列表
     *
     * @param jsonObject JSON 对象
     */
    private static void fixJsonStructure(JSONObject jsonObject) {
        // 定义需要确保为列表的字段名
        String[] listFields = {"ProcessList", "NodeList", "Details", "Notifyer", "SubNodeList", "SpRecord", "Comments" };
 
        for (String fieldName : listFields) {
            if (jsonObject.has(fieldName)) {
                Object value = jsonObject.get(fieldName);
                if (!(value instanceof JSONArray)) {
                    // 如果不是列表,将其包装为列表
                    JSONArray array = new JSONArray();
                    array.put(value);
                    jsonObject.put(fieldName, array);
                }
            }
        }
 
        // 递归处理嵌套对象
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                fixJsonStructure((JSONObject) value);
            } else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                for (int i = 0; i < array.length(); i++) {
                    Object item = array.get(i);
                    if (item instanceof JSONObject) {
                        fixJsonStructure((JSONObject) item);
                    }
                }
            }
        }
    }
}