zhubaomin
2025-04-02 bf1b78168478f802a7413d438b16ab64b27b7f4a
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package com.dy.pipIrrWechat.command;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.dy.common.multiDataSource.DataSourceContext;
import com.dy.common.mw.protocol.Command;
import com.dy.common.mw.protocol.p206V1.CodeV1;
import com.dy.common.mw.protocol.p206V1.ProtocolConstantV206V1;
import com.dy.common.mw.protocol.p206V1.downVos.ComA1Vo;
import com.dy.common.mw.protocol.p206V2.ProtocolConstantV206V2;
import com.dy.common.mw.protocol.p206V202404.ProtocolConstantV206V202404;
import com.dy.common.util.IDLongGenerator;
import com.dy.common.webUtil.BaseResponse;
import com.dy.common.webUtil.QueryResultVo;
import com.dy.pipIrrGlobal.command.ComSupport;
import com.dy.pipIrrGlobal.command.dto.Param;
import com.dy.pipIrrGlobal.daoIr.IrIntakeOperateMapper;
import com.dy.pipIrrGlobal.daoPr.PrIntakeMapper;
import com.dy.pipIrrGlobal.daoPr.PrIntakeVcMapper;
import com.dy.pipIrrGlobal.daoPr.PrWaterPriceMapper;
import com.dy.pipIrrGlobal.daoRm.RmCommandHistoryMapper;
import com.dy.pipIrrGlobal.daoRm.RmIrrigateProfileMapper;
import com.dy.pipIrrGlobal.daoRm.RmOpenCloseValveLastMapper;
import com.dy.pipIrrGlobal.daoSe.SeClientCardMapper;
import com.dy.pipIrrGlobal.daoSe.SeVirtualCardMapper;
import com.dy.pipIrrGlobal.pojoIr.IrIntakeOperate;
import com.dy.pipIrrGlobal.pojoRm.RmCommandHistory;
import com.dy.pipIrrGlobal.pojoSe.SeClientCard;
import com.dy.pipIrrGlobal.voRm.VoIrrigaterProfile;
import com.dy.pipIrrGlobal.voRm.VoRtuAndVc;
import com.dy.pipIrrGlobal.voRm.VoUnclosedValve;
import com.dy.pipIrrGlobal.voSe.VoVirtualCard;
import com.dy.pipIrrWechat.command.dto.AutomaticClose;
import com.dy.pipIrrWechat.result.WechatResultCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
 
import java.util.*;
 
/**
 * @author ZhuBaoMin
 * @date 2024-05-30 16:13
 * @LastEditTime 2024-05-30 16:13
 * @Description
 */
 
@Slf4j
@Service
@RequiredArgsConstructor
public class CommandSv extends ComSupport {
    private final RmCommandHistoryMapper rmCommandHistoryMapper;
    private final SeVirtualCardMapper seVirtualCardMapper;
    private final PrIntakeMapper prIntakeMapper;
    private final PrWaterPriceMapper prWaterPriceMapper;
    private final PrIntakeVcMapper prIntakeVcMapper;
    private final SeClientCardMapper seClientCardMapper;
    private final RmIrrigateProfileMapper rmIrrigateProfileMapper;
    private final RmOpenCloseValveLastMapper rmOpenCloseValveLastMapper;
    //private final PrCommonIntakesMapper prCommonIntakesMapper;
    private final IrIntakeOperateMapper irIntakeOperateMapper;
 
    @Value("${mw.rtuCallbackUrl_wx}")
    private String rtuCallbackUrl_wx;
 
    /**
     * pro_mw:属性
     * tag从控制器中获取
     * key_mw:url的key
     */
    private Environment env = null;
    private String pro_mw = "mw";
    private String key_mw = "comSendUrl";
    @Autowired
    public CommandSv(RmCommandHistoryMapper rmCommandHistoryMapper,RmOpenCloseValveLastMapper rmOpenCloseValveLastMapper, SeVirtualCardMapper seVirtualCardMapper, PrIntakeMapper prIntakeMapper, PrWaterPriceMapper prWaterPriceMapper, PrIntakeVcMapper prIntakeVcMapper, SeClientCardMapper seClientCardMapper, RmIrrigateProfileMapper rmIrrigateProfileMapper, Environment env, IrIntakeOperateMapper irIntakeOperateMapper) {
        this.rmCommandHistoryMapper = rmCommandHistoryMapper;
        this.rmOpenCloseValveLastMapper = rmOpenCloseValveLastMapper;
        //this.prCommonIntakesMapper = prCommonIntakesMapper;
        this.seVirtualCardMapper = seVirtualCardMapper;
        this.prIntakeMapper = prIntakeMapper;
        this.prWaterPriceMapper = prWaterPriceMapper;
        this.prIntakeVcMapper = prIntakeVcMapper;
        this.seClientCardMapper = seClientCardMapper;
        this.rmIrrigateProfileMapper = rmIrrigateProfileMapper;
        this.env = env;
        this.irIntakeOperateMapper = irIntakeOperateMapper;
    }
    /**
     * 虚拟卡ID换虚拟卡对象
     * @param vcId
     * @return
     */
    public VoVirtualCard getVcById(Long vcId) {
        return seVirtualCardMapper.getVcById(vcId);
    }
 
    /**
     * 获取水价
     * @return
     */
    public Double getPrice() {
        return prWaterPriceMapper.getPrice();
    }
 
    /**
     * 根据操作员ID获取未关阀记录(包含在线情况)
     * @param operator
     * @return
     */
    public List<VoUnclosedValve> getUnclosedValves(Long operator) {
        Command com = new Command() ;
        com.id = Command.defaultId;
        com.code = "LCD0001";
        com.type = "innerCommand";
        comSendUrl = env.getProperty(pro_mw + "." + DataSourceContext.get() + "." + key_mw);
        JSONObject response = (JSONObject) JSON.toJSON(sendCom2Mw(com));
 
        JSONArray jsonArray = new JSONArray();
        if(response != null && response.getString("code").equals("0001")) {
            JSONObject attachment = response.getJSONObject("content").getJSONObject("attachment");
            if(attachment != null) {
                attachment.forEach((key, value) -> {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("rtuAddr", key);
                    jsonObject.put("isOnLine", value);
                    jsonArray.add(jsonObject);
                });
            }
            //System.out.println(jsonArray.toJSONString());
        }
 
        /**
         * 获取未关阀的RTU地址和虚拟卡编号对数组
         * 遍历数组获取最后命令日志ID集合
         */
        List<VoRtuAndVc> rtus = rmCommandHistoryMapper.getUnclosedRtus(operator);
        String comIds = "";
        if(rtus != null && rtus.size() > 0) {
            for (int i = 0; i < rtus.size(); i++) {
                Long comId = rmCommandHistoryMapper.getLastComId(rtus.get(i).getRtuAddr(), rtus.get(i).getVcNum());
                if(comId > 0) {
                    comIds = comIds + "\"" + comId + "\",";
                }
            }
        }
 
        if(comIds.length() > 0) {
            comIds = comIds.substring(0, comIds.length()-1);
            List<VoUnclosedValve> res = rmCommandHistoryMapper.getUnclosedValves(jsonArray.toJSONString(), comIds);
            if(res != null) {
                return res;
            }
        }
        return new ArrayList<>();
    }
 
    /**
     * 为指定(阀控器地址、水卡编号、无关阀记录)开关阀最新记录添加关阀时间,使之不在未关阀记录中显示
     * @param rtuAddr
     * @param icCardNo
     * @return
     */
    public Integer addClostTime(String rtuAddr, String icCardNo) {
        return rmOpenCloseValveLastMapper.addCloseTime(rtuAddr, icCardNo);
    }
 
    /**
     * 根据取水口ID获取与之绑定虚拟卡ID
     * @param intakeId
     * @return
     */
    public Long getVcIdByIntakeId(Long intakeId) {
        return prIntakeVcMapper.getVcIdByIntakeId(intakeId);
    }
 
    /**
     * 根据水卡编号获取水卡对象,远程充值使用
     * @param cardId
     * @return
     */
    public SeClientCard geClientCardByCardId(Long cardId) {
        return seClientCardMapper.selectByPrimaryKey(cardId);
    }
 
    /**
     * 添加命令日志
     * @param po 命令日志对象
     * @return 字符串类型的主键
     */
    public Long insert(RmCommandHistory po) {
        rmCommandHistoryMapper.insert(po);
        return po.getComId();
    }
 
    /**
     * 修改命令日志信息
     * @param po 命令日志对象
     * @return 影响记录数量
     */
    public Integer update(RmCommandHistory po) {
        return rmCommandHistoryMapper.updateByPrimaryKeySelective(po);
    }
 
    /**
     * 取水口名称换取水口ID,扫码开阀使用
     * @param intakeName
     * @return
     */
    public Long getIntakeIdByName(String intakeName) {
        return prIntakeMapper.getIntakeIdByName(intakeName);
    }
 
    /**
     * 根据配置类型获取配置值
     * @param type
     * @return
     */
    QueryResultVo<List<VoIrrigaterProfile>> getIrrPro(Integer type) {
        QueryResultVo<List<VoIrrigaterProfile>> rsVo = new QueryResultVo<>() ;
        rsVo.obj = rmIrrigateProfileMapper.getIrrPro(type);
        return rsVo ;
    }
 
    /**
     * 添加取水口操作记录,轮灌过程命令下发时使用
     * @param po
     * @return
     */
    public Long addIntakeOperate(IrIntakeOperate po) {
        irIntakeOperateMapper.insert(po);
        return po.getId();
    }
 
    ///**
    // * 根据命令ID更新取水口操作记录
    // * @param commandId
    // * @param commandResult
    // * @return
    // */
    //public Integer updateByCommandId(Long commandId, Byte commandResult) {
    //    return irIntakeOperateMapper.updateByCommandId(commandId, commandResult);
    //}
 
    /**
     * 定时关阀式计划开阀
     * @param automaticClose
     * @return
     */
    public Map planedOpenTimedClose(AutomaticClose automaticClose, Long planId, Date startTime, Integer duration) {
        Long intakeId = automaticClose.getIntakeId();
        Long vcId = automaticClose.getVcId();
        Date plannedOpenTime = automaticClose.getPlannedOpenTime();
        Integer minutes = automaticClose.getMinutes();
        Long operator = automaticClose.getOperator();
        Byte openType = automaticClose.getOpenType();
        Long comId = new IDLongGenerator().generate();
 
        if(openType != null && openType == 1) {
            IrIntakeOperate irIntakeOperate = new IrIntakeOperate();
            irIntakeOperate.setPlanId(planId);
            irIntakeOperate.setOperateType((byte)1);
            irIntakeOperate.setCommandId(comId);
            irIntakeOperate.setIntakeId(intakeId);
            irIntakeOperate.setStartTime(startTime);
            irIntakeOperate.setDuration(duration);
 
            Long id = addIntakeOperate(irIntakeOperate);
            if(id == null) {
                Map map = new HashMap<>();
                map.put("success", false);
                map.put("msg", "添加取水口操作记录失败");
                map.put("content", null);
                return map;
            }
        }
 
        Integer year = Integer.parseInt(String.format("%tY", plannedOpenTime));
        Integer month = Integer.parseInt(String.format("%tm", plannedOpenTime));
        Integer day = Integer.parseInt(String.format("%td", plannedOpenTime));
        Integer hour = Integer.parseInt(String.format("%tH", plannedOpenTime));
        Integer minute = Integer.parseInt(String.format("%tM", plannedOpenTime));
 
        /**
         * 如果农户选择了虚拟卡,则使用该虚拟卡
         * 如果农户未选择虚拟卡,则根据取水口ID获取与之绑定的虚拟卡
         * 如果取水口没有与之绑定的虚拟卡,则提示农户选择一张虚拟卡
         */
        if(vcId == null) {
            vcId = getVcIdByIntakeId(intakeId);
            if(vcId == null) {
                irIntakeOperateMapper.updateByCommandId(comId, (byte)2, WechatResultCode.PLEASE_SELECT_A_VC.getMessage() + "(" + intakeId + ")");
 
                Map map = new HashMap<>();
                map.put("success", false);
                map.put("msg", WechatResultCode.PLEASE_SELECT_A_VC.getMessage() + "(" + intakeId + ")");
                map.put("content", null);
                return map;
            }
        }
 
        // 虚拟卡ID换虚拟卡对象
        VoVirtualCard vc = getVcById(vcId);
        if(vc == null) {
            irIntakeOperateMapper.updateByCommandId(comId, (byte)2, WechatResultCode.PLEASE_SELECT_A_VC.getMessage() + "(" + intakeId + ")");
 
            Map map = new HashMap<>();
            map.put("success", false);
            map.put("msg", WechatResultCode.PLEASE_SELECT_A_VC.getMessage() + "(" + intakeId + ")");
            map.put("content", null);
            return map;
        }
        String vcNum = vc.getVcNum().toString();
        Double moneyRemain = vc.getMoney();
 
        // 获取水价
        Double waterPrice = getPrice();
        if(waterPrice == null) {
            Map map = new HashMap<>();
            map.put("success", false);
            map.put("msg", WechatResultCode.NO_WATER_PRICE.getMessage());
            map.put("content", null);
            return map;
        }
 
        // 取水口ID换阀控器地址及通讯协议
        JSONObject job_rtu = getRtu(intakeId, null);
        if(job_rtu == null) {
            irIntakeOperateMapper.updateByCommandId(comId, (byte)2, WechatResultCode.RTU_NOT_EXIST.getMessage() + "(" + intakeId + ")");
 
            Map map = new HashMap<>();
            map.put("success", false);
            map.put("msg", WechatResultCode.RTU_NOT_EXIST.getMessage());
            map.put("content", null);
            return map;
        }
        String rtuAddr = job_rtu.getString("rtuAddr");
        String protocol = job_rtu.getString("protocol");
 
        comSendUrl = env.getProperty(pro_mw + "." + DataSourceContext.get() + "." + key_mw);
 
        // 生成订单号
        String orderNo = generateOrderNo();
        if(orderNo == null) {
            irIntakeOperateMapper.updateByCommandId(comId, (byte)2, WechatResultCode.NO_ORDER_NUMBER.getMessage() + "(" + intakeId + ")");
 
            Map map = new HashMap<>();
            map.put("success", false);
            map.put("msg", WechatResultCode.NO_ORDER_NUMBER.getMessage());
            map.put("content", null);
            return map;
        }
 
        String commandCode = null;
        if(protocol.equals(ProtocolConstantV206V202404.protocolName)) {
            Map map = new HashMap<>();
            map.put("success", true);
            map.put("msg", "开阀成功");
            map.put("content", null);
            return map;
        } else if(protocol.equals(ProtocolConstantV206V1.protocolName) || protocol.equals(ProtocolConstantV206V2.protocolName)) {
            // 获取功能码
            commandCode = CodeV1.cd_A1;
 
            // 创建视图
            ComA1Vo param = new ComA1Vo();
            param.setIcCardNo(vcNum);
            param.setMoneyRemain(moneyRemain);
            param.setWaterPrice(waterPrice);
            param.setMinutes(minutes);
            param.setYear(year);
            param.setMonth(month);
            param.setDay(day);
            param.setHour(hour);
            param.setMinute(minute);
            param.setOrderNo(orderNo);
 
            /**
             * 构造命令、发送命令并处理请求结果及执行结果
             * 1 准备参数
             * 2 调用公共方法
             */
            Param myParam = new Param();
            myParam.setComId(comId);
            myParam.setComType((byte)1);
            myParam.setCommandCode(commandCode);
            myParam.setCommandName(CodeV1.getCodeName(commandCode));
            myParam.setIntakeId(intakeId);
            myParam.setRtuAddr(rtuAddr);
            myParam.setProtocol(protocol);
            myParam.setVcId(vcId);
            myParam.setParam(param);
            myParam.setRtuResultSendWebUrl(rtuCallbackUrl_wx);
            myParam.setOperator(operator);
            myParam.setOpenType(openType);
 
            BaseResponse<Boolean> result = dealWithCommandResult(myParam);
 
            Map map = new HashMap<>();
            map.put("success", result.isSuccess());
            map.put("msg", result.getMsg());
            map.put("content", result.getContent());
            return map;
        } else {
            irIntakeOperateMapper.updateByCommandId(comId, (byte)2, "系统暂不支持该协议" + "(" + intakeId + ")");
 
            Map map = new HashMap<>();
            map.put("success", false);
            map.put("msg", "系统暂不支持该协议");
            map.put("content", null);
            return map;
        }
    }
}