EnergyPullService.java 25.6 KB
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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
package com.iot.scheduler.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class EnergyPullService {

    @Value("${energy.token.url}")
    private String energyTokenUrl;
    @Value("${energy.deviceList.url}")
    private String energyDeviceListUrl;
    @Value("${energy.detail.url}")
    private String energyDetailUrl;
    @Value("${energy.runStatus.url}")
    private String energyRunStatusUrl;

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private CorpConfigService corpConfigService;

    /**
     * 定时任务:同步能耗设备数据(遍历所有已配置公司)
     */
    @Scheduled(cron = "${scheduler.energy.cron:0 0/5 * * ?}")
    public void pullEnergyDeviceAndSave() {
        List<String> corpCodes = corpConfigService.getAllCorpCodes();
        if (corpCodes.isEmpty()) {
            log.warn("[Scheduled] energy: no corp config found, skip");
            return;
        }
        for (String corpCode : corpCodes) {
            pullEnergyDeviceAndSave(corpCode);
        }
    }

    public void pullEnergyDeviceAndSave(String corpCode) {
        if (!corpConfigService.hasValidIotCredentials(corpCode)) {
            log.warn("【能耗数据同步】IoT凭证为空, 跳过同步, corpCode={}", corpCode);
            return;
        }
        log.info("【能耗数据同步】开始同步能耗设备数据, corpCode={}", corpCode);
        try {
            String energyResult = getEnergyDeviceList(corpCode);
            if (StringUtils.isBlank(energyResult)) {
                log.error("【能耗数据同步】获取能耗设备列表失败");
                return;
            }

            Map<String, Object> energyInfos = JSON.parseObject(energyResult, new TypeReference<>() {
            });
            Integer code = (Integer) energyInfos.get("code");
            if (code == null || code != 200) {
                log.error("【能耗数据同步】获取能耗设备列表返回code不为200, code:{}, response:{}", code, energyResult);
                return;
            }

            JSONArray dataList = (JSONArray) energyInfos.get("data");
            if (CollectionUtils.isEmpty(dataList)) {
                log.warn("【能耗数据同步】能耗设备列表为空");
                return;
            }

            int successCount = 0;
            for (Object o : dataList) {
                JSONObject deviceJson = (JSONObject) o;
                String projectState = deviceJson.getString("projectState");
                String projectType = deviceJson.getString("projectType");
                String deviceName = deviceJson.getString("deviceName");
                String dtuId = deviceJson.getString("dtuId");
                String deviceId = deviceJson.getString("deviceId");
                String dtuSn = deviceJson.getString("dtuSn");
                log.info("【能耗数据处理】corpCode:{}, deviceName:{}, dtuSn:{}, projectState:{}, projectType:{}",
                        corpCode, deviceName, dtuSn, projectState, projectType);

                String todayEvalue = getTodayEnergyValue(corpCode, dtuSn);
                Map<String, String> runStatusMap = getEnergyRunStatus(corpCode, dtuSn);
                String duration = runStatusMap.get("duration");
                String runStatus = runStatusMap.get("runStatus");

                saveOrUpdateEnergyDevice(corpCode, projectState, projectType, deviceName, dtuId, deviceId, dtuSn,
                        todayEvalue, duration, runStatus);
                successCount++;
            }
            log.info("【能耗数据同步】同步完成,共处理 {} 条设备数据", successCount);
        } catch (Exception e) {
            log.error("【能耗数据同步】同步过程发生异常", e);
        }
    }

    public String getEnergyDeviceList(String corpCode) {
        String accessToken = getEnergyAccessToken(corpCode);
        Map<String, String> headerMap = new HashMap<>(1);
        headerMap.put("Authorization", "Bearer " + accessToken);
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("groupName", corpConfigService.getIotOrg(corpCode));
        String result = sendRequestGet(energyDeviceListUrl, paramsMap, headerMap);
        if (StringUtils.isBlank(result)) return null;

        Map<String, Object> resultMap = JSON.parseObject(result, new TypeReference<>() {
        });
        Integer resultCode = (Integer) resultMap.get("code");

        if (resultCode == null || resultCode != 200) {
            log.warn("【能耗设备列表】第一次请求失败,重新获取Token重试");
            accessToken = getEnergyAccessToken(corpCode);
            if (StringUtils.isEmpty(accessToken)) return null;
            headerMap.put("Authorization", "Bearer " + accessToken);
            result = sendRequestGet(energyDeviceListUrl, paramsMap, headerMap);
            if (StringUtils.isBlank(result)) return null;
            resultMap = JSON.parseObject(result, new TypeReference<>() {
            });
            resultCode = (Integer) resultMap.get("code");
            if (resultCode == null || resultCode != 200) {
                log.error("【能耗设备列表】重试后仍然失败, code:{}", resultCode);
                return null;
            }
        }
        return result;
    }

    private String getEnergyAccessToken(String corpCode) {
        String redisKey = "hnyssl_energy_token_" + corpCode;
        String cachedToken = redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isNotBlank(cachedToken) && redisTemplate.getExpire(redisKey) > 0) return cachedToken;

        // 使用公司配置中的用户名密码
        String userName = corpConfigService.getIotUsername(corpCode);
        String password = corpConfigService.getIotPassword(corpCode);
        Map<String, String> param = new HashMap<>(2);
        param.put("username", userName);
        param.put("password", password);

        HttpPost httpPost = new HttpPost(energyTokenUrl);
        String result = sendPost(httpPost, JSON.toJSONString(param));
        if (StringUtils.isBlank(result)) {
            log.error("【能耗Token】请求Token失败,响应为空");
            return "";
        }

        Map<String, Object> res = JSON.parseObject(result, new TypeReference<>() {
        });
        Integer code = (Integer) res.get("code");
        if (code == null || code != 200) {
            log.error("【能耗Token】请求Token返回异常, code:{}", code);
            return "";
        }

        JSONObject data = (JSONObject) res.get("data");
        String token = data.getString("token");
        if (StringUtils.isBlank(token)) {
            log.error("【能耗Token】响应中没有token");
            return "";
        }

        redisTemplate.opsForValue().set(redisKey, token, 3600, TimeUnit.SECONDS);
        log.info("【能耗Token】获取Token成功并缓存, corpCode={}", corpCode);
        return token;
    }

    private void saveOrUpdateEnergyDevice(String corpCode, String projectState, String projectType, String deviceName,
                                          String dtuId, String deviceId, String dtuSn,
                                          String evalue, String duration, String runStatus) {
        String energyTableName = corpConfigService.getEnergyTableName(corpCode);
        JdbcTemplate jt = corpConfigService.getJdbcTemplate(corpCode);

        List<Map<String, Object>> existList = jt.queryForList(
                "SELECT id FROM " + energyTableName + " WHERE corp_code = ? AND dtuSn = ?", corpCode, dtuSn);
        Date now = new Date();
        if (!existList.isEmpty()) {
            jt.update("UPDATE " + energyTableName +
                            " SET projectState = ?, projectType = ?, deviceName = ?, dtuId = ?, deviceId = ?, evalue = ?, duration = ?, runStatus = ?, updated_at = ?" +
                            " WHERE corp_code = ? AND dtuSn = ?",
                    projectState, projectType, deviceName, dtuId, deviceId, evalue, duration, runStatus, now, corpCode, dtuSn);
        } else {
            String id = UUID.randomUUID().toString().replace("-", "");
            jt.update("INSERT INTO " + energyTableName +
                            " (id, corp_code, created_at, created_by, updated_at, updated_by, deviceName, projectType, projectState, dtuSn, dtuId, deviceId, evalue, duration, runStatus)" +
                            " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                    id, corpCode, now, "system", now, "system",
                    deviceName, projectType, projectState, dtuSn, dtuId, deviceId, evalue, duration, runStatus);
        }
    }

    private Map<String, String> getEnergyRunStatus(String corpCode, String dtuSn) {
        Map<String, String> result = new HashMap<>();
        result.put("duration", null);
        result.put("runStatus", null);
        try {
            String accessToken = getEnergyAccessToken(corpCode);
            Map<String, String> headerMap = new HashMap<>(1);
            headerMap.put("Authorization", "Bearer " + accessToken);
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("dtuSn", dtuSn);
            paramsMap.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            String response = sendRequestGet(energyRunStatusUrl, paramsMap, headerMap);
            if (StringUtils.isBlank(response)) return result;
            Map<String, Object> resultMap = JSON.parseObject(response, new TypeReference<>() {
            });
            Integer resultCode = (Integer) resultMap.get("code");
            if (resultCode == null || resultCode != 200) {
                accessToken = getEnergyAccessToken(corpCode);
                if (StringUtils.isEmpty(accessToken)) return result;
                headerMap.put("Authorization", "Bearer " + accessToken);
                response = sendRequestGet(energyRunStatusUrl, paramsMap, headerMap);
                if (StringUtils.isBlank(response)) return result;
                resultMap = JSON.parseObject(response, new TypeReference<>() {
                });
                resultCode = (Integer) resultMap.get("code");
                if (resultCode == null || resultCode != 200) return result;
            }
            JSONArray dataList = (JSONArray) resultMap.get("data");
            String description = dataList != null ? dataList.toJSONString() : "[]";
            saveOrUpdateERunDtl(corpCode, dtuSn, description, new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));

            if (!CollectionUtils.isEmpty(dataList)) {
                JSONObject lastItem = (JSONObject) dataList.get(dataList.size() - 1);
                Long durVal = lastItem.getLong("duration");
                Integer statusVal = lastItem.getInteger("runStatus");
                result.put("duration", durVal != null ? String.valueOf(durVal) : null);
                result.put("runStatus", statusVal != null ? String.valueOf(statusVal) : null);
            }
        } catch (Exception e) {
            log.error("【能耗OEE】获取异常 - corpCode:{}, dtuSn:{}", corpCode, dtuSn, e);
        }
        return result;
    }

    private void saveOrUpdateERunDtl(String corpCode, String dtuSn, String description, String useDate) {
        String eRunDtlTableName = corpConfigService.getERunDtlTableName(corpCode);
        JdbcTemplate jt = corpConfigService.getJdbcTemplate(corpCode);
        int maxLen = 60000;
        String rs1 = "";
        String rs2 = "";
        if (description.length() > maxLen) {
            rs1 = description.substring(0, maxLen);
            rs2 = description.substring(maxLen);
        } else {
            rs1 = description;
        }

        List<Map<String, Object>> existList = jt.queryForList(
                "SELECT id FROM " + eRunDtlTableName + " WHERE corp_code = ? AND dtuSn = ? AND use_date = ?", corpCode, dtuSn, useDate);
        Date now = new Date();
        if (!existList.isEmpty()) {
            jt.update("UPDATE " + eRunDtlTableName + " SET runStatus1=?, runStatus2=?, updated_at=? WHERE corp_code=? AND dtuSn=? AND use_date=?", rs1, rs2, now, corpCode, dtuSn, useDate);
        } else {
            String id = UUID.randomUUID().toString().replace("-", "");
            jt.update("INSERT INTO " + eRunDtlTableName + " (id,corp_code,created_at,created_by,updated_at,updated_by,dtuSn,use_date,runStatus1,runStatus2)" +
                    " VALUES (?,?,?,?,?,?,?,?,?,?)", id, corpCode, now, "system", now, "system", dtuSn, useDate, rs1, rs2);
        }
    }

    // ==================== 能耗历史数据全量/增量同步 ====================

    public void pullEnergyHistoryAndSave(String corpCode) {
        if (!corpConfigService.hasValidIotCredentials(corpCode)) {
            log.warn("【能耗历史-全量】IoT凭证为空, 跳过同步, corpCode={}", corpCode);
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        String endDate = sdf.format(cal.getTime());
        cal.set(cal.get(Calendar.YEAR), Calendar.JANUARY, 1);
        String startDate = sdf.format(cal.getTime());
        log.info("【能耗历史-全量】开始同步, corpCode:{}, 日期范围: {} ~ {}", corpCode, startDate, endDate);
        doSyncEnergyHistory(corpCode, startDate, endDate);
    }

    private void doSyncEnergyHistory(String corpCode, String startDate, String endDate) {
        String energyResult = getEnergyDeviceList(corpCode);
        if (StringUtils.isBlank(energyResult)) {
            log.error("【能耗历史】获取设备列表失败");
            return;
        }

        Map<String, Object> energyInfos = JSON.parseObject(energyResult, new TypeReference<>() {
        });
        Integer code = (Integer) energyInfos.get("code");
        if (code == null || code != 200) {
            log.error("【能耗历史】获取设备列表返回code异常, code:{}", code);
            return;
        }

        JSONArray deviceList = (JSONArray) energyInfos.get("data");
        if (CollectionUtils.isEmpty(deviceList)) {
            log.warn("【能耗历史】设备列表为空");
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();
        try {
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);
            Calendar cur = Calendar.getInstance();
            cur.setTime(start);
            while (!cur.getTime().after(end)) {
                dateList.add(sdf.format(cur.getTime()));
                cur.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (Exception e) {
            log.error("【能耗历史】日期解析失败: {} ~ {}", startDate, endDate, e);
            return;
        }

        log.info("【能耗历史】开始同步, corpCode:{}, 设备数:{}, 天数:{}, 总计{}条记录待处理", corpCode, deviceList.size(), dateList.size(), deviceList.size() * dateList.size());
        int totalSaved = 0;
        for (Object o : deviceList) {
            JSONObject deviceJson = (JSONObject) o;
            String dtuSn = deviceJson.getString("dtuSn");
            for (String dateStr : dateList) {
                try {
                    syncEnergyValueForDate(corpCode, dtuSn, dateStr);
                    syncRunStatusForDate(corpCode, dtuSn, dateStr);
                    totalSaved++;
                } catch (Exception e) {
                    log.error("【能耗历史】处理异常 - corpCode:{}, dtuSn:{}, date:{}", corpCode, dtuSn, dateStr, e);
                }
            }
        }
        log.info("【能耗历史】同步完成,共保存 {} 条记录", totalSaved);
    }

    private void syncEnergyValueForDate(String corpCode, String dtuSn, String dateStr) {
        String accessToken = getEnergyAccessToken(corpCode);
        Map<String, String> headerMap = new HashMap<>(1);
        headerMap.put("Authorization", "Bearer " + accessToken);
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("dtuSn", dtuSn);
        paramsMap.put("startDate", dateStr);
        paramsMap.put("type", "0");
        String result = sendRequestGet(energyDetailUrl, paramsMap, headerMap);
        if (StringUtils.isBlank(result)) return;
        Map<String, Object> resultMap = JSON.parseObject(result, new TypeReference<>() {
        });
        Integer resultCode = (Integer) resultMap.get("code");
        if (resultCode == null || resultCode != 200) {
            accessToken = getEnergyAccessToken(corpCode);
            if (StringUtils.isEmpty(accessToken)) return;
            headerMap.put("Authorization", "Bearer " + accessToken);
            result = sendRequestGet(energyDetailUrl, paramsMap, headerMap);
            if (StringUtils.isBlank(result)) return;
            resultMap = JSON.parseObject(result, new TypeReference<>() {
            });
            resultCode = (Integer) resultMap.get("code");
            if (resultCode == null || resultCode != 200) return;
        }
        JSONArray dataList = (JSONArray) resultMap.get("data");
        String description = dataList != null ? dataList.toJSONString() : "[]";
        saveOrUpdateEqKwh(corpCode, dtuSn, description, dateStr + " 00:00:00");
    }

    private void syncRunStatusForDate(String corpCode, String dtuSn, String dateStr) {
        String accessToken = getEnergyAccessToken(corpCode);
        Map<String, String> headerMap = new HashMap<>(1);
        headerMap.put("Authorization", "Bearer " + accessToken);
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("dtuSn", dtuSn);
        paramsMap.put("date", dateStr);
        String response = sendRequestGet(energyRunStatusUrl, paramsMap, headerMap);
        if (StringUtils.isBlank(response)) return;
        Map<String, Object> resultMap = JSON.parseObject(response, new TypeReference<>() {
        });
        Integer resultCode = (Integer) resultMap.get("code");
        if (resultCode == null || resultCode != 200) {
            accessToken = getEnergyAccessToken(corpCode);
            if (StringUtils.isEmpty(accessToken)) return;
            headerMap.put("Authorization", "Bearer " + accessToken);
            response = sendRequestGet(energyRunStatusUrl, paramsMap, headerMap);
            if (StringUtils.isBlank(response)) return;
            resultMap = JSON.parseObject(response, new TypeReference<>() {
            });
            resultCode = (Integer) resultMap.get("code");
            if (resultCode == null || resultCode != 200) return;
        }
        JSONArray dataList = (JSONArray) resultMap.get("data");
        String description = dataList != null ? dataList.toJSONString() : "[]";
        saveOrUpdateERunDtl(corpCode, dtuSn, description, dateStr + " 00:00:00");
    }

    private String getTodayEnergyValue(String corpCode, String dtuSn) {
        try {
            String accessToken = getEnergyAccessToken(corpCode);
            Map<String, String> headerMap = new HashMap<>(1);
            headerMap.put("Authorization", "Bearer " + accessToken);
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("dtuSn", dtuSn);
            paramsMap.put("startDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            paramsMap.put("type", "0");
            String result = sendRequestGet(energyDetailUrl, paramsMap, headerMap);
            if (StringUtils.isBlank(result)) return null;
            Map<String, Object> resultMap = JSON.parseObject(result, new TypeReference<>() {
            });
            Integer resultCode = (Integer) resultMap.get("code");
            if (resultCode == null || resultCode != 200) {
                accessToken = getEnergyAccessToken(corpCode);
                if (StringUtils.isEmpty(accessToken)) return null;
                headerMap.put("Authorization", "Bearer " + accessToken);
                result = sendRequestGet(energyDetailUrl, paramsMap, headerMap);
                if (StringUtils.isBlank(result)) return null;
                resultMap = JSON.parseObject(result, new TypeReference<>() {
                });
                resultCode = (Integer) resultMap.get("code");
                if (resultCode == null || resultCode != 200) return null;
            }
            JSONArray dataList = (JSONArray) resultMap.get("data");
            String description = dataList != null ? dataList.toJSONString() : "[]";
            saveOrUpdateEqKwh(corpCode, dtuSn, description, new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
            double totalValue = 0;
            if (!CollectionUtils.isEmpty(dataList)) {
                for (Object o : dataList) {
                    JSONObject item = (JSONObject) o;
                    totalValue += item.getDoubleValue("value");
                }
            }
            String evalueStr = String.valueOf(totalValue);
            log.info("【能耗用电量】corpCode:{}, dtuSn:{}, 今日用电量:{}", corpCode, dtuSn, evalueStr);
            return evalueStr;
        } catch (Exception e) {
            log.error("【能耗用电量】获取异常 - corpCode:{}, dtuSn:{}", corpCode, dtuSn, e);
            return null;
        }
    }

    private void saveOrUpdateEqKwh(String corpCode, String dtuSn, String description, String useDate) {
        String eqKwhTableName = corpConfigService.getEqKwhTableName(corpCode);
        JdbcTemplate jt = corpConfigService.getJdbcTemplate(corpCode);
        List<Map<String, Object>> existList = jt.queryForList(
                "SELECT id FROM " + eqKwhTableName + " WHERE corp_code = ? AND dtuSn = ? AND use_date = ?", corpCode, dtuSn, useDate);
        Date now = new Date();
        if (!existList.isEmpty()) {
            jt.update("UPDATE " + eqKwhTableName + " SET description = ?, updated_at = ? WHERE corp_code = ? AND dtuSn = ? AND use_date = ?", description, now, corpCode, dtuSn, useDate);
        } else {
            String id = UUID.randomUUID().toString().replace("-", "");
            jt.update("INSERT INTO " + eqKwhTableName + " (id, corp_code, created_at, created_by, updated_at, updated_by, dtuSn, use_date, description)" +
                    " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", id, corpCode, now, "system", now, "system", dtuSn, useDate, description);
        }
    }

    public static String sendRequestGet(String url, Map<String, String> params, Map<String, String> header) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        url = builderUrl(url, params);
        String content = "";
        HttpGet httpget = new HttpGet(url);
        if (!CollectionUtils.isEmpty(header)) {
            for (Map.Entry<String, String> entry : header.entrySet())
                httpget.setHeader(entry.getKey(), entry.getValue());
        }
        try (CloseableHttpResponse response = httpclient.execute(httpget)) {
            if (response.getStatusLine().getStatusCode() == 200)
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            log.error("sendRequest---GET Error!", e);
        }
        return content;
    }

    private static String builderUrl(String url, Map<String, String> params) {
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
        if (!CollectionUtils.isEmpty(params)) {
            MultiValueMap<String, String> paramsValue = new LinkedMultiValueMap<>();
            for (Map.Entry<String, String> entry : params.entrySet()) paramsValue.add(entry.getKey(), entry.getValue());
            uriBuilder = uriBuilder.queryParams(paramsValue);
        }
        return uriBuilder.toUriString();
    }

    private String sendPost(HttpPost httpPost, String jsonData) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        StringEntity entity = new StringEntity(jsonData, ContentType.create("application/json", Consts.UTF_8));
        httpPost.setEntity(entity);
        String result = null;
        try {
            CloseableHttpResponse execute = httpClient.execute(httpPost);
            HttpEntity res = execute.getEntity();
            InputStream is = res.getContent();
            int len;
            byte[] buf = new byte[128];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while ((len = is.read(buf)) != -1) byteArrayOutputStream.write(buf, 0, len);
            result = byteArrayOutputStream.toString();
        } catch (IOException e) {
            log.error("sendPost error!", e);
        }
        return result;
    }
}