cuikaidong
2025-08-27 1e514802d4ea60245c6d8adf42dba73c154274a6
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
package org.jeecg.modules.iot.service.impl;
 
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.iot.entity.Equipment;
import org.jeecg.modules.iot.entity.ParameterGroup;
import org.jeecg.modules.iot.entity.RealParameter;
import org.jeecg.modules.iot.entity.xmlEntity.Parameter;
import org.jeecg.modules.iot.mapper.RealParameterMapper;
import org.jeecg.modules.iot.mqtt.config.MqttCustomerClient;
import org.jeecg.modules.iot.service.IEquipmentService;
import org.jeecg.modules.iot.service.IParameterGroupService;
import org.jeecg.modules.iot.service.IRealParameterService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
 
/**
 * @Description: 实设备参数
 * @Author: cuikaidong
 * @Date: 2025-1-2
 * @Version: V1.0
 */
@Slf4j
@Service
public class RealParameterServiceImpl extends ServiceImpl<RealParameterMapper, RealParameter> implements IRealParameterService {
    @Lazy
    @Autowired
    private IEquipmentService equipmentService;
    @Lazy
    @Autowired
    private MqttCustomerClient mqttCustomerClient;
    @Lazy
    @Autowired
    private IParameterGroupService parameterGroupService;
 
    @Override
    public RealParameter findByParameterCode(String parameterCode) {
        return new LambdaQueryChainWrapper<>(baseMapper)
                .eq(RealParameter::getParameterCode, parameterCode)
                .one();
    }
 
    @Override
    public List<RealParameter> findRealParameterByIds(Set<String> ids) {
        return new LambdaQueryChainWrapper<>(baseMapper).in(RealParameter::getParameterGroupId, ids).list();
    }
 
    @Override
    public IPage<RealParameter> findRealParameterPage(Page<RealParameter> pages, Map<String, Object> params) {
        return baseMapper.findRealParameterPage(pages, params);
    }
 
    @Override
    public Boolean findRealParameterByName(RealParameter realParameter) {
        List<RealParameter> realParameters = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(RealParameter::getParameterGroupId, realParameter.getParameterGroupId())
                .eq(RealParameter::getParameterName, realParameter.getParameterName())
                .list();
        return realParameters.size() > 0;
    }
 
    @Override
    public Boolean findRealParameterByCode(RealParameter realParameter) {
        List<RealParameter> realParameters = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(RealParameter::getParameterGroupId, realParameter.getParameterGroupId())
                .eq(RealParameter::getParameterCode, realParameter.getParameterCode())
                .list();
        return realParameters.size() > 0;
    }
 
    @Override
    public Result<?> parameterWriting(RealParameter realParameter) {
        ParameterGroup parameterGroup = parameterGroupService.getById(realParameter.getParameterGroupId());
        Equipment equipment = equipmentService.getById(parameterGroup.getEquipmentId());
        if (realParameter.getWritingValue().isEmpty()) {
            return Result.error("参数写入失败: 值为空");
        }
        // 创建顶层 Map
        Map<String, Object> map = new HashMap<>();
        // 设置 GroupID 和 GroupName
        map.put("GroupID", parameterGroup.getCode() + "");
        map.put("GroupName", parameterGroup.getName());
        // 创建 Tags 列表
        List<Map<String, Object>> tagsList = new ArrayList<>();
        // 创建并填充第一个 Tag 对象
        Map<String, Object> tag1 = new HashMap<>();
        tag1.put("TagID", realParameter.getParameterCode() + "");
        tag1.put("TagName", realParameter.getParameterName());
        tag1.put("Value", realParameter.getWritingValue());
        // 将 Tag 添加到 Tags 列表
        tagsList.add(tag1);
        // 将 Tags 列表添加到顶层 Map
        map.put("Tags", tagsList);
        mqttCustomerClient.pushlishWriting(2, false, equipment.getWriteTopic(), map);
        return Result.ok("参数写入成功");
    }
 
    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        String parameterGroupId = request.getParameter("param1");
        if (parameterGroupId.isEmpty()) {
            return Result.error("文件导入失败: 查询不到参数组信息");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<RealParameter> realList = ExcelImportUtil.importExcel(file.getInputStream(), RealParameter.class, params);
                // 查询最新编号
                AtomicReference<Integer> parameterCode = new AtomicReference<>(this.findRealParameterGroupId(parameterGroupId));
                parameterCode.set(parameterCode.get() - 1);
                for (int i = 0; i < realList.size(); i++) {
                    Integer line = i + 2;
                    RealParameter real = realList.get(i);
                    if (StringUtils.isEmpty(real.getParameterName())) {
                        return Result.error("文件导入失败:" + line + "行,参数名称未填写");
                    }
                    // 参数名称去除空格
                    real.setParameterName(real.getParameterName().replace(" ", ""));
                    if (StringUtils.isEmpty(real.getParameterType())) {
                        return Result.error("文件导入失败:" + line + "行,数据类型未填写");
                    }
                    if (StringUtils.isEmpty(real.getAddress())) {
                        return Result.error("文件导入失败:" + line + "行,地址未填写");
                    }
                    if (StringUtils.isEmpty(real.getReadWriteType())) {
                        return Result.error("文件导入失败:" + line + "行,读写类型未填写");
                    }
                    List<Parameter> parameterList = equipmentService.findDataTypeById(parameterGroupId);
                    parameterList.forEach(p -> {
                        String replaceWithX = replaceWithX(real.getParameterType());
                        if (replaceWithX.equals(p.getName())) {
                            real.setSystemDataType(p.getSystemDataType());
                        }
                    });
//                    if (real.getSystemDataType().isEmpty()){
//                        return Result.error("文件导入失败:" + line + "行,数据类型不匹配");
//
//                    }
                    // 填充参数
                    parameterCode.set(parameterCode.get() + 1);
                    real.setParameterGroupId(parameterGroupId);
                    real.setParameterCode(parameterCode.get());
                    // 验证参数名称是否重复
                    if (this.findRealParameterByName(real)) {
                        return Result.error("文件导入失败:" + line + "行," + real.getParameterName() + "参数名称已重复");
                    }
                    // 如果是string必须填写字符串长度
                    if (real.getReadWriteType().equals("String")) {
                        if (real.getDataLength() == null) {
                            return Result.error("文件导入失败:" + line + "行,字符串长度未填写");
                        }
                    }
                }
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                saveBatch(realList);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功!数据行数:" + realList.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败!");
    }
 
    /**
     * 将字符串中括号内的内容替换为x
     *
     * @param input 输入字符串(如"Float16(16)")
     * @return 替换后的字符串(如"Float16(x)")
     */
    public static String replaceWithX(String input) {
        if (input == null || input.isEmpty() || !input.contains("(") || !input.contains(")")) {
            return input; // 无括号或格式不完整时直接返回
        }
        return input.replaceFirst("\\(.*?\\)", "(x)");
    }
 
    @Override
    public ModelAndView exportXls(HttpServletRequest request, RealParameter realParameter, String title) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // Step.2 获取导出数据
        List<RealParameter> pageList = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(RealParameter::getParameterGroupId, realParameter.getParameterGroupId())
                .list();
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, RealParameter.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }
 
    @Override
    public Integer findRealParameterGroupId(String groupCode) {
        List<RealParameter> list = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(RealParameter::getParameterGroupId, groupCode)
                .orderByDesc(RealParameter::getParameterCode)
                .list();
        if (list.size() == 0) {
            return 1;
        }
        return list.get(0).getParameterCode() + 1;
    }
 
    @Override
    public Result<?> canonicalParameter(String id) {
        int list = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(RealParameter::getParameterGroupId, id)
                .list().size();
        if (list > 1) {
            return Result.error("参数为空才可导入标准参数");
        }
        // 查询最新编号
        Integer parameterCode = findRealParameterGroupId(id) - 1;
        List<Parameter> parameters = equipmentService.findParameterById(id);
        if (parameters == null) {
            return Result.error("暂无标准参数");
        }
        List<RealParameter> realParameter = new ArrayList<>();
        for (Parameter parameter : parameters) {
            RealParameter real = new RealParameter();
            real.setParameterName(parameter.getName());
            real.setParameterType(parameter.getDataType());
            real.setAddress(parameter.getDefault1());
            real.setParameterDescribe(parameter.getDescribe());
            real.setReadWriteType("只读");
            List<Parameter> parameterList = equipmentService.findDataTypeById(id);
            parameterList.forEach(p -> {
                String replaceWithX = replaceWithX(real.getParameterType());
                if (replaceWithX.equals(p.getName())) {
                    real.setSystemDataType(p.getSystemDataType());
                }
            });
            real.setDataLength(1);
            // 填充参数
            parameterCode = parameterCode + 1;
            real.setParameterGroupId(id);
            real.setParameterCode(parameterCode);
            realParameter.add(real);
        }
        this.saveBatch(realParameter);
        return Result.ok("导入成功");
    }
 
}