package com.shcd.scheduling;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.shanghaigeography.Util.DateUtils;
import com.shanghaigeography.entity.ResultMsg;
import com.shanghaigeography.eum.ResultState;
import com.shcd.entity.ShorePowerBerthInfo;
import com.shcd.entity.ShorePowerBerthInfoNew;
import com.shcd.entity.ShorePowerBlberthmonthuse;
import com.shcd.entity.ShorePowerChdevicefbo;
import com.shcd.entity.ShorePowerConnRecordInfo;
import com.shcd.entity.ShorePowerConnectorInfo;
import com.shcd.entity.ShorePowerDeviceInfo;
import com.shcd.entity.ShorePowerDeviceInfoNew;
import com.shcd.entity.ShorePowerDeviceStatusInfo;
import com.shcd.entity.ShorePowerPortInfo;
import com.shcd.entity.ShorePowerPortInfoNew;
import com.shcd.enums.GhjgPortThreeUrl;
import com.shcd.service.*;
import com.shcd.utils.PrintLogUtils;
import com.shcd.utils.secret.Encodes;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.parallel.Execution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@Component
@Slf4j
public class ShorePowerScheduler {

  @Resource
  private IShorePowerDeviceInfoService deviceInfoService;

  @Resource
  private IShorePowerBerthInfoService berthInfoService;

  @Resource
  private IShorePowerPortInfoService portInfoService;

  @Resource
  private IShorePowerConnRecordInfoService connRecordInfoService;

  @Resource
  private IShorePowerDeviceStatusInfoService deviceStatusInfoService;

  @Resource
  ShorePowerBlberthmonthuseService shorePowerBlberthmonthuseService;

  @Resource
  ShorePowerChdevicefboService shorePowerChdevicefboService;

  @Resource
  IShorePowerPortInfoNewService portInfoNewService;

  @Resource
  IShorePowerBerthInfoNewService berthInfoNewService;

  @Resource
  IShorePowerDeviceInfoNewService deviceInfoNewService;

  @Resource
  IShorePowerConnectorInfoService shorePowerConnectorInfoService;

  @Value("${queryConnRecordInfo}")
  String queryConnRecordInfo;

  @Value("${shorePower}")
  String shorePower;

  ExecutorService service = Executors.newFixedThreadPool(2);

  @Scheduled(cron = "0 0 0/1 * * ? ")
//  @Scheduled(cron = "0 0/1 * * * ? ")
  public void executeShorePowerScheduler() {
    try {
      service.execute(this::getConnRecordInfo);
      service.execute(this::getUserBerthRecordInfo);
      service.execute(this::getPortInfoNew);
      service.execute(this::getBerthInfoNew);
      service.execute(this::getDeviceInfoNew);
      service.execute(this::getDeviceConnectorInfo);
      service.execute(this::getConnectorStatusInfo);
    } catch (Exception e) {
      log.error("执行出错,原因=====>{}", e.getMessage());
    }
  }

  public String getToken() {
    String result = null;
    String token = null;
    try {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Sig", "59962D299728C732F772AD9CDE6A9456");
      jsonObject.put("PlatformID", "425009768");
      jsonObject.put("Data","/J9njgV+VvzgibMjaU4c0HH+Zbr9n5DRkJkfxLy0Z8agH7kzqKIbtm97MilBq0XaMbHfhxW+Vwd/JqfFVnvSbA==");
      jsonObject.put("TimeStamp", "16880151424323");
      jsonObject.put("Seq", "0001");
      result = HttpUtil.createPost(GhjgPortThreeUrl.PROXY_SHORE_POWER.getUrl())
//      result = HttpUtil.createPost(GhjgPortThreeUrl.SHORE_POWER.getUrl())
          .setConnectionTimeout(3600000)
          .setReadTimeout(3600000)
          .header("Content-Type", "application/json")
          .body(jsonObject.toString())
          .charset("UTF-8").execute().body();
      JSONObject resultJsonObject = JSONObject.parseObject(result);
      String returnData = (String) resultJsonObject.get("Data");
      token = new String(Encodes.aesDecrypt(
          Encodes.decodeBase64(returnData),
          GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
          GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
      log.info("岸电数据对接token解码后的结果为:{}", JSONObject.toJSONString(token));
    } catch (Exception e) {
      log.error("岸电数据对接token接口调用失败! ===>原因:{}",
          JSONObject.toJSONString(e.getMessage()));
      return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("调用失败")
          .setData(JSONObject.toJSONString(e.getMessage())).toJSON();
    }
    return new ResultMsg<String>().setCode(ResultState.SUCCESS).setMsg("调用成功")
        .setData(JSON.toJSONString(token)).toJSON();
  }


  public String getConnectorStatusInfo() {
    try {
//      String portId = (String) map.get("portId");
//      String deviceId = (String) map.get("deviceId");
//      String platformId = (String) map.get("platformId");
//      String operatorId = (String) map.get("operatorId");
//      String page = (String) map.get("current");
//      String limit = (String) map.get("size");
      String portId = "";
      String deviceId = "";
      String platformId = "";
      String operatorId = "";
      String page = "1";
      String limit = "500";
      String result = executeConnectorStatusInfoUrl(portId, deviceId, platformId, operatorId, page,
          limit);
      log.info("岸电设备接口状态信息查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data));
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerDeviceStatusInfo> deviceStatusInfos = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerDeviceStatusInfo deviceStatusInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerDeviceStatusInfo.class);
          deviceStatusInfos.add(deviceStatusInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(deviceStatusInfos));
//        deviceStatusInfos.forEach(x -> deviceStatusInfoService.saveOrUpdate(x));
//        deviceStatusInfoService.saveOrUpdateBatch(deviceStatusInfos);
        for (ShorePowerDeviceStatusInfo deviceStatusInfo : deviceStatusInfos) {
          deviceStatusInfoService.saveOrUpdate(deviceStatusInfo);
        }
        log.info("操作完成,共有{}条数据", deviceStatusInfos.size());
//        deviceStatusInfoService.saveBatch(deviceStatusInfos);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new ResultMsg<String>().setCode(ResultState.SUCCESS).setMsg("调用成功")
        .setData(JSON.toJSONString(null)).toJSON();
  }


  public void getDeviceConnectorInfo() {
    try {
//      String portId = (String) map.get("portId");
//      String platformId = (String) map.get("platformId");
//      String operatorId = (String) map.get("operatorId");
//      String deviceId = (String) map.get("deviceId");
//      String page = (String) map.get("current");
//      String limit = (String) map.get("size");
      String portId = "";
      String platformId = "";
      String operatorId = "";
      String deviceId = "";
      String page = "1";
      String limit = "500";
      String result = executeDeviceConnectorInfoUrl(portId, platformId, operatorId, deviceId, page,
          limit);
      log.info("岸电设备接口信息查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data));
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerConnectorInfo> shorePowerConnectorInfos = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerConnectorInfo connRecordInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerConnectorInfo.class);
          connRecordInfo.setCurrent1(Optional.of(connRecordInfo.getCurrent()).orElse(null));
          shorePowerConnectorInfos.add(connRecordInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(shorePowerConnectorInfos));
        for (ShorePowerConnectorInfo shorePowerConnectorInfo : shorePowerConnectorInfos) {
          shorePowerConnectorInfoService.saveOrUpdate(shorePowerConnectorInfo);
        }
        log.info("操作完成,共有{}条数据", shorePowerConnectorInfos.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  private String executeDeviceConnectorInfoUrl(String portId, String platformId, String operatorId,
      String deviceId, String page,
      String limit) {
    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    berthInfo.put("portId", portId);
    berthInfo.put("platformId", platformId);
    berthInfo.put("operatorId", operatorId);
    berthInfo.put("deviceId", deviceId);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime oneHourAgo = now.minusHours(24);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    berthInfo.put("updateDate", formatter.format(oneHourAgo));
    data.put("connectorInfo", berthInfo);
    JSONObject deviceRequest = new JSONObject();
    deviceRequest.put("PlatformID", platformID);
    deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    deviceRequest.put("Seq", "0001");
    deviceRequest.put("Data", data);
    JSONObject sss = (JSONObject) deviceRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    deviceRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", deviceRequest.getString("PlatformID"));
    param.put("Data", deviceRequest.getString("Data"));
    param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
    param.put("Seq", deviceRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.PROXY_QUERY_CONNECTOR_INFO.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }



  public void getDeviceInfoNew() {
    try {
//      String portId = (String) map.get("portId");
//      String platformId = (String) map.get("platformId");
//      String operatorId = (String) map.get("operatorId");
//      String deviceId = (String) map.get("deviceId");
//      String page = (String) map.get("current");
//      String limit = (String) map.get("size");
      String portId = "";
      String platformId = "";
      String operatorId = "";
      String deviceId = "";
      String page = "1";
      String limit = "500";
      String result = executeDeviceInfoNewUrl(portId, platformId, operatorId, deviceId, page,
          limit);
      log.info("长航 - 设备信息设备查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data).toLowerCase());
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerDeviceInfoNew> deviceInfoList = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerDeviceInfoNew deviceInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerDeviceInfoNew.class);
          deviceInfoList.add(deviceInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(deviceInfoList));
        deviceInfoList.forEach(x -> deviceInfoNewService.saveOrUpdate(x));
        log.info("操作完成,共有{}条数据", deviceInfoList.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private String executeDeviceInfoNewUrl(String portId, String platformId, String operatorId,
      String deviceId, String page, String limit) {
    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    berthInfo.put("portId", portId);
    berthInfo.put("platformId", platformId);
    berthInfo.put("operatorId", operatorId);
    berthInfo.put("deviceId", deviceId);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime oneHourAgo = now.minusHours(24);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    berthInfo.put("updateDate", formatter.format(oneHourAgo));
    data.put("deviceInfo", berthInfo);
    JSONObject deviceRequest = new JSONObject();
    deviceRequest.put("PlatformID", platformID);
    deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    deviceRequest.put("Seq", "0001");
    deviceRequest.put("Data", data);
    JSONObject sss = (JSONObject) deviceRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    deviceRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", deviceRequest.getString("PlatformID"));
    param.put("Data", deviceRequest.getString("Data"));
    param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
    param.put("Seq", deviceRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.PROXY_DEVICE_INFO.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }


  public void getBerthInfoNew() {
    try {
//      String portId = (String) map.get("portId");
//      String berthId = (String) map.get("berthId");
//      String berthName = (String) map.get("berthName");
//      String berthType = (String) map.get("berthType");
//      String page = (String) map.get("current");
//      String limit = (String) map.get("size");
      String portId = "";
      String berthId = "";
      String berthName = "";
      String berthType = "";
      String page = "1";
      String limit = "500";
      String result = executeBerthInfoNewUrl(portId, berthId, berthName, berthType, page, limit);
      log.info("泊位信息设备查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data).toLowerCase());
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerBerthInfoNew> berthInfoList = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerBerthInfoNew deviceInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerBerthInfoNew.class);
          berthInfoList.add(deviceInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(berthInfoList));
        berthInfoList.forEach(x -> berthInfoNewService.saveOrUpdate(x));
        log.info("操作完成,共有{}条数据", berthInfoList.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  private String executeBerthInfoNewUrl(String portId, String berthId, String berthName,
      String berthType, String page, String limit) {
    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    berthInfo.put("portId", portId);
    berthInfo.put("berthId", berthId);
    berthInfo.put("berthName", berthName);
    berthInfo.put("berthType", berthType);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime oneHourAgo = now.minusHours(24);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    berthInfo.put("updateDate", formatter.format(oneHourAgo));
    data.put("berthInfo", berthInfo);
    JSONObject deviceRequest = new JSONObject();
    deviceRequest.put("PlatformID", platformID);
    deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    deviceRequest.put("Seq", "0001");
    deviceRequest.put("Data", data);
    JSONObject sss = (JSONObject) deviceRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    deviceRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", deviceRequest.getString("PlatformID"));
    param.put("Data", deviceRequest.getString("Data"));
    param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
    param.put("Seq", deviceRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.PROXY_BERTH_INFO.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }


  public void getPortInfoNew() {
    try {
//      String platformId = (String) map.get("platformId");
//      String portName = (String) map.get("portName");
//      String operatorName = (String) map.get("operatorName");
//      String enterprisesName = (String) map.get("enterprisesName");
//      String page = (String) map.get("current");
//      String limit = (String) map.get("size");
      String platformId = "";
      String portName = "";
      String operatorName = "";
      String enterprisesName = "";
      String page = "1";
      String limit = "500";
      String result = executePortInfoNewUrl(platformId, portName, operatorName, enterprisesName,
          page, limit);
      log.info("港口信息设备查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data));
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerPortInfoNew> portInfoList = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerPortInfoNew portInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerPortInfoNew.class);
          portInfoList.add(portInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(portInfoList));
        for (ShorePowerPortInfoNew portInfo : portInfoList) {
          portInfoNewService.saveOrUpdate(portInfo);
        }
        log.info("操作完成,共有{}条数据", portInfoList.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


   public void getUserBerthRecordInfo() {
    try {
//      String realName = (String) map.get("realName");
//      String page = (String) map.get("current");
//      String limit = (String) map.get("size");
      String realName = "";
      String page = "1";
      String limit = "500";
      String result = executeUserBerthRecordInfoUrl(realName, page, limit);
      log.info("3.12手动填报泊位（月度）信息查询 接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data).toLowerCase());
        JSONArray jsonArray = (JSONArray) JSONObject.parse(data.toLowerCase());
        log.info("records  ====>{}", jsonArray);
        String arrayJSON = JSONObject.toJSONString(jsonArray, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerChdevicefbo> chdevicefboList = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerChdevicefbo chdevicefbo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerChdevicefbo.class);
          chdevicefboList.add(chdevicefbo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(chdevicefboList));
        List<ShorePowerBlberthmonthuse> subList = new ArrayList<>();
        chdevicefboList.forEach(x -> {
          log.info("==============> 泊位本月使用情况数据:{}",
              JSONObject.toJSONString(x.getUseMonthList()));
          if (!CollectionUtils.isEmpty(x.getUseMonthList())) {
            subList.addAll(x.getUseMonthList());
          }
        });
        chdevicefboList.forEach(x -> shorePowerChdevicefboService.saveOrUpdate(x));
        subList.forEach(x -> shorePowerBlberthmonthuseService.saveOrUpdate(x));
        log.info("操作完成,共有{}条数据,其中子集合的数据有:{}条", chdevicefboList.size(),
            subList.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  public void getConnRecordInfo() {
    try {
      String portId = "";
      String deviceId = "";
      String berthId = "";
      String page = "1";
      String limit = "500";
      String startTime = "";
      String endTime = "";
      // 查询数据库中最新modifyTime，全部增量数据
      startTime = connRecordInfoService.getMaxModifyTime();
      endTime = DateUtils.dateToString(new Date(),DateUtils.DATE_FORMAT_19);
      // 默认按照500分页查询，根据返回的total总数判断是否需要继续分页查询
      String result = executeConnRecordInfoUrl(portId, deviceId, berthId, page, limit, startTime, endTime);
      log.info("连船记录信息查询查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      Integer total = getTotal(result);
      // total > limit 继续分页调用，else 保存数据
      if(total > Integer.parseInt(limit) * Integer.parseInt(page)){
        while (total > Integer.parseInt(limit) * Integer.parseInt(page)){
          page = String.valueOf(Integer.parseInt(page) + 1);
          String res = executeConnRecordInfoUrl(portId, deviceId, berthId, page, limit, startTime, endTime);
          saveConnRecordInfos(res);
        }
      }else{
        saveConnRecordInfos(result);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 获取总条数
   * @param result
   * @return
   */
  public Integer getTotal(String result) {
    Integer total = 0;
    try{
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
                Encodes.decodeBase64(lightData),
                GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
                GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        total = (Integer) dataJsonObject.get("total");
      }
    }catch (Exception e){
      PrintLogUtils.printErrorLogInfo(e,"getTotal异常：");
    }
    return total;
  }

  public boolean saveConnRecordInfos(String result){
    boolean flag = false;
    try{
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
                Encodes.decodeBase64(lightData),
                GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
                GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data));
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
                JSONObject.class);
        List<ShorePowerConnRecordInfo> connRecordInfos = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerConnRecordInfo connRecordInfo = JSONObject.parseObject(JSON.toJSONString(x),
                  ShorePowerConnRecordInfo.class);
          connRecordInfos.add(connRecordInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
                JSONObject.toJSONString(connRecordInfos));
//        connRecordInfos.forEach(x -> connRecordInfoService.saveOrUpdate(x));
//        connRecordInfoService.saveOrUpdateBatch(connRecordInfos);
        for (ShorePowerConnRecordInfo connRecordInfo : connRecordInfos) {
          connRecordInfoService.saveOrUpdate(connRecordInfo);
        }
        log.info("操作完成,共有{}条数据", connRecordInfos.size());
//        connRecordInfoService.saveBatch(connRecordInfos);
        flag = true;
      }
    }catch (Exception e){
      PrintLogUtils.printErrorLogInfo(e,"saveConnRecordInfos异常：");
    }
    return flag;
  }

  @Scheduled(cron = "0 0/1 * * * ?")
  public void logScheduled() {
    log.info("schedule is starting");
  }

  @Autowired
  private SpStatementShipUsageMonthService spStatementShipUsageMonthService;

  //@Scheduled(cron = "")
//  @PostConstruct
//  public void makeShangHaiShorePowerUsageRecord() {
//    spStatementShipUsageMonthService.makeShangHaiShorePowerUsageRecord();
//  }

  @XxlJob("connectorStatusInfo")
  public ReturnT<String> getConnectorStatusInfo(String params) {
    try {
      JSONObject map = JSONObject.parseObject(params);
      String portId = (String) map.get("portId");
      String deviceId = (String) map.get("deviceId");
      String platformId = (String) map.get("platformId");
      String operatorId = (String) map.get("operatorId");
      String page = (String) map.get("current");
      String limit = (String) map.get("size");
      String result = executeConnectorStatusInfoUrl(portId, deviceId, platformId, operatorId, page,
          limit);
      log.info("岸电设备接口状态信息查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data));
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerDeviceStatusInfo> deviceStatusInfos = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerDeviceStatusInfo deviceStatusInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerDeviceStatusInfo.class);
          deviceStatusInfos.add(deviceStatusInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(deviceStatusInfos));
//        deviceStatusInfos.forEach(x -> deviceStatusInfoService.saveOrUpdate(x));
//        deviceStatusInfoService.saveOrUpdateBatch(deviceStatusInfos);
        for (ShorePowerDeviceStatusInfo deviceStatusInfo : deviceStatusInfos) {
          deviceStatusInfoService.saveOrUpdate(deviceStatusInfo);
        }
        log.info("操作完成,共有{}条数据", deviceStatusInfos.size());
//        deviceStatusInfoService.saveBatch(deviceStatusInfos);
      }
    } catch (Exception e) {
      return ReturnT.FAIL;
    }
    return ReturnT.SUCCESS;
  }


  @XxlJob("portInfo")
  public ReturnT<String> getPortInfo(String params) {
    try {
      JSONObject map = JSONObject.parseObject(params);
      String portId = (String) map.get("portId");
      String page = (String) map.get("current");
      String limit = (String) map.get("size");
      String result = executePortInfoUrl(portId, page, limit);
      log.info("长航 - 港口信息设备查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data));
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerPortInfo> portInfoList = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerPortInfo portInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerPortInfo.class);
          portInfoList.add(portInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(portInfoList));
//        portInfoList.forEach(x -> portInfoService.saveOrUpdate(x));
//        portInfoService.saveOrUpdateBatch(portInfoList);
        for (ShorePowerPortInfo portInfo : portInfoList) {
          portInfoService.saveOrUpdate(portInfo);
        }
        log.info("操作完成,共有{}条数据", portInfoList.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return ReturnT.FAIL;
    }
    return ReturnT.SUCCESS;
  }


  @XxlJob("berthInfo")
  public ReturnT<String> getBerthInfo(String params) {
    try {
      JSONObject map = JSONObject.parseObject(params);
      String portId = (String) map.get("portId");
      String berthId = (String) map.get("berthId");
      String page = (String) map.get("current");
      String limit = (String) map.get("size");
      String result = executeBerthInfoUrl(portId, berthId, page, limit);
      log.info("长航 - 泊位信息设备查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data).toLowerCase());
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerBerthInfo> berthInfoList = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerBerthInfo deviceInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerBerthInfo.class);
          berthInfoList.add(deviceInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(berthInfoList));
        berthInfoList.forEach(x -> berthInfoService.saveOrUpdate(x));
        log.info("操作完成,共有{}条数据", berthInfoList.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return ReturnT.FAIL;
    }
    return ReturnT.SUCCESS;
  }

  @XxlJob("deviceInfo")
  public ReturnT<String> getDeviceInfo(String params) {
    try {
      JSONObject map = JSONObject.parseObject(params);
      String deviceId = (String) map.get("deviceId");
      String berthId = (String) map.get("berthId");
      String page = (String) map.get("current");
      String limit = (String) map.get("size");
      String result = executeDeviceInfoUrl(deviceId, berthId, page, limit);
      log.info("长航 - 设备信息设备查询接口调用成功! ===>返回结果:{}",
          JSONObject.toJSONString(result));
      JSONObject jsonObject = JSONObject.parseObject(result);
      if (0 == ((int) jsonObject.get("Ret"))) {
        String lightData = (String) jsonObject.get("Data");
        String data = new String(Encodes.aesDecrypt(
            Encodes.decodeBase64(lightData),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
        log.info("==============> 业务数据:{}", JSONObject.toJSONString(data).toLowerCase());
        JSONObject dataJsonObject = (JSONObject) JSONObject.parse(data.toLowerCase());
        JSONArray records = (JSONArray) dataJsonObject.get("records");
        log.info("records  ====>{}", records);
        String arrayJSON = JSONObject.toJSONString(records, SerializerFeature.WriteClassName);
        List<JSONObject> JSONObjectList = JSONObject.parseArray(arrayJSON,
            JSONObject.class);
        List<ShorePowerDeviceInfo> deviceInfoList = new ArrayList<>();
        JSONObjectList.forEach(x -> {
          ShorePowerDeviceInfo deviceInfo = JSONObject.parseObject(JSON.toJSONString(x),
              ShorePowerDeviceInfo.class);
          deviceInfo.setIs_jcbg(
              deviceInfo.getIs_constructionspecification_jcbg());
          deviceInfoList.add(deviceInfo);
        });
        log.info("==============> 业务转换为港航数据:{}",
            JSONObject.toJSONString(deviceInfoList));
        deviceInfoList.forEach(x -> deviceInfoService.saveOrUpdate(x));
        log.info("操作完成,共有{}条数据", deviceInfoList.size());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return ReturnT.FAIL;
    }
    return ReturnT.SUCCESS;
  }

  private String executeConnRecordInfoUrl(String portId, String deviceId, String berthId,
      String page, String limit) {
    try {
      JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
      JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
      String accessToken = (String) tokenData.get("AccessToken");
      String platformID = (String) tokenData.get("PlatformID");
      JSONObject data = new JSONObject();
      JSONObject berthInfo = new JSONObject();
      LocalDateTime now = LocalDateTime.now();
      LocalDateTime oneHourAgo = now.minusHours(24);
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
      berthInfo.put("startTime", formatter.format(oneHourAgo));
      berthInfo.put("endTime", formatter.format(now));
      berthInfo.put("portId", portId);
      berthInfo.put("deviceId", deviceId);
      berthInfo.put("berthId", berthId);
      berthInfo.put("page", page);
      berthInfo.put("limit", limit);
      data.put("connRecordInfo", berthInfo);
      JSONObject deviceRequest = new JSONObject();
      deviceRequest.put("PlatformID", platformID);
      deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
      deviceRequest.put("Seq", "0001");
      deviceRequest.put("Data", data);
      JSONObject sss = (JSONObject) deviceRequest.get("Data");
      String mvData = Encodes.encodeBase64(
          Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
              GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
              GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
      deviceRequest.put("Data", mvData);
      Map<String, String> param = Maps.newLinkedHashMap();
      param.put("PlatformID", deviceRequest.getString("PlatformID"));
      param.put("Data", deviceRequest.getString("Data"));
      param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
      param.put("Seq", deviceRequest.getString("Seq"));
      String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
      param.put("Sig", reqSign);
      log.info("=====> 入参:{}", JSONObject.toJSONString(param));
      HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.PROXY_QUERY_CONNRECORD_INFO.getUrl());
      Map<String, String> headers = new HashMap<>();
      headers.put("Authorization", "Bearer" + " " + accessToken);
      headers.put("Content-Type", "application/json;charset=utf-8");
      post.addHeaders(headers);
      return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
    } catch (Exception e) {
      log.error("=====> 调用接口异常:{}", e.getMessage());
      return e.getMessage();
    }
  }

  public String executeConnRecordInfoUrl(String portId, String deviceId, String berthId,
                                          String page, String limit, String startTime, String endTime) {
    try {
      JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
      JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
      String accessToken = (String) tokenData.get("AccessToken");
      String platformID = (String) tokenData.get("PlatformID");
      JSONObject data = new JSONObject();
      JSONObject berthInfo = new JSONObject();
      berthInfo.put("startTime", startTime);
      berthInfo.put("endTime", endTime);
      berthInfo.put("portId", portId);
      berthInfo.put("deviceId", deviceId);
      berthInfo.put("berthId", berthId);
      berthInfo.put("page", page);
      berthInfo.put("limit", limit);
      data.put("connRecordInfo", berthInfo);
      JSONObject deviceRequest = new JSONObject();
      deviceRequest.put("PlatformID", platformID);
      deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
      deviceRequest.put("Seq", "0001");
      deviceRequest.put("Data", data);
      JSONObject sss = (JSONObject) deviceRequest.get("Data");
      String mvData = Encodes.encodeBase64(
              Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
                      GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
                      GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
      deviceRequest.put("Data", mvData);
      Map<String, String> param = Maps.newLinkedHashMap();
      param.put("PlatformID", deviceRequest.getString("PlatformID"));
      param.put("Data", deviceRequest.getString("Data"));
      param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
      param.put("Seq", deviceRequest.getString("Seq"));
      String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
      param.put("Sig", reqSign);
      log.info("=====> 入参:{}", JSONObject.toJSONString(param));
      //TODO 本地测试和生产发布地址不同
      HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.PROXY_QUERY_CONNRECORD_INFO.getUrl());
//      HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.QUERY_CONNRECORD_INFO.getUrl());
      Map<String, String> headers = new HashMap<>();
      headers.put("Authorization", "Bearer" + " " + accessToken);
      headers.put("Content-Type", "application/json;charset=utf-8");
      post.addHeaders(headers);
      return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
    } catch (Exception e) {
      log.error("=====> 调用接口异常:{}", e.getMessage());
      return e.getMessage();
    }
  }

  private String executeConnectorStatusInfoUrl(String portId, String deviceId, String platformId,
      String operatorId, String page, String limit) {
    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    berthInfo.put("portId", portId);
    berthInfo.put("deviceId", deviceId);
    berthInfo.put("platformId", platformId);
    berthInfo.put("operatorId", operatorId);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime oneHourAgo = now.minusHours(24);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    berthInfo.put("updateDate", formatter.format(oneHourAgo));
    data.put("connectorStatusInfo", berthInfo);
    JSONObject deviceRequest = new JSONObject();
    deviceRequest.put("PlatformID", platformID);
    deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    deviceRequest.put("Seq", "0001");
    deviceRequest.put("Data", data);
    JSONObject sss = (JSONObject) deviceRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    deviceRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", deviceRequest.getString("PlatformID"));
    param.put("Data", deviceRequest.getString("Data"));
    param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
    param.put("Seq", deviceRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.PROXY_QUERY_CONNECTOR_STATUS_INFO.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }


  private String executeBerthInfoUrl(String portId, String berthId, String page, String limit) {
    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    berthInfo.put("portId", portId);
    berthInfo.put("berthId", berthId);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    data.put("berthRequest", berthInfo);
    JSONObject deviceRequest = new JSONObject();
    deviceRequest.put("PlatformID", platformID);
    deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    deviceRequest.put("Seq", "0001");
    deviceRequest.put("Data", data);
    JSONObject sss = (JSONObject) deviceRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    deviceRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", deviceRequest.getString("PlatformID"));
    param.put("Data", deviceRequest.getString("Data"));
    param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
    param.put("Seq", deviceRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.CHANG_HANG_BERTH_INFO.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }

  private String executeDeviceInfoUrl(String deviceId, String berthId, String page, String limit) {
    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    berthInfo.put("deviceId", deviceId);
    berthInfo.put("berthId", berthId);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    data.put("deviceRequest", berthInfo);
    JSONObject deviceRequest = new JSONObject();
    deviceRequest.put("PlatformID", platformID);
    deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    deviceRequest.put("Seq", "0001");
    deviceRequest.put("Data", data);
    JSONObject sss = (JSONObject) deviceRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    deviceRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", deviceRequest.getString("PlatformID"));
    param.put("Data", deviceRequest.getString("Data"));
    param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
    param.put("Seq", deviceRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.CHANG_HANG_DEVICE_INFO.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }

  private String executePortInfoUrl(String portId, String page, String limit) {
    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    berthInfo.put("portId", portId);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    data.put("portRequest", berthInfo);
    JSONObject portRequest = new JSONObject();
    portRequest.put("PlatformID", platformID);
    portRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    portRequest.put("Seq", "0001");
    portRequest.put("Data", data);
    JSONObject sss = (JSONObject) portRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    portRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", portRequest.getString("PlatformID"));
    param.put("Data", portRequest.getString("Data"));
    param.put("TimeStamp", portRequest.getString("TimeStamp"));
    param.put("Seq", portRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.CHANG_HANG_PORT_INFO.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }

  private String executeUserBerthRecordInfoUrl(String realName, String page, String limit) {
    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime oneHourAgo = now.minusHours(12);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    berthInfo.put("realName", realName);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    berthInfo.put("startTime", formatter.format(oneHourAgo));
    berthInfo.put("endTime", formatter.format(now));
    data.put("userBerthRecordInfo", berthInfo);
    JSONObject deviceRequest = new JSONObject();
    deviceRequest.put("PlatformID", platformID);
    deviceRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    deviceRequest.put("Seq", "0001");
    deviceRequest.put("Data", data);
    JSONObject sss = (JSONObject) deviceRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    deviceRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", deviceRequest.getString("PlatformID"));
    param.put("Data", deviceRequest.getString("Data"));
    param.put("TimeStamp", deviceRequest.getString("TimeStamp"));
    param.put("Seq", deviceRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.PROXY_FILL_IN_THE_BERTHS_MANUALLY.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }

  private String executePortInfoNewUrl(String platformId, String portName, String operatorName,
      String enterprisesName, String page, String limit) {

    JSONObject tokenJsonObject = JSONObject.parseObject(getToken());
    JSONObject tokenData = JSONObject.parseObject((String) tokenJsonObject.get("data"));
    String accessToken = (String) tokenData.get("AccessToken");
    String platformID = (String) tokenData.get("PlatformID");
    JSONObject data = new JSONObject();
    JSONObject berthInfo = new JSONObject();
    berthInfo.put("platformId", platformId);
    berthInfo.put("portName", portName);
    berthInfo.put("operatorName", operatorName);
    berthInfo.put("enterprisesName", enterprisesName);
    berthInfo.put("page", page);
    berthInfo.put("limit", limit);
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime oneHourAgo = now.minusHours(24);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    berthInfo.put("updateDate", formatter.format(oneHourAgo));
    data.put("portInfo", berthInfo);
    JSONObject portRequest = new JSONObject();
    portRequest.put("PlatformID", platformID);
    portRequest.put("TimeStamp", String.valueOf(System.currentTimeMillis()));
    portRequest.put("Seq", "0001");
    portRequest.put("Data", data);
    JSONObject sss = (JSONObject) portRequest.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    portRequest.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", portRequest.getString("PlatformID"));
    param.put("Data", portRequest.getString("Data"));
    param.put("TimeStamp", portRequest.getString("TimeStamp"));
    param.put("Seq", portRequest.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    param.put("Sig", reqSign);
    log.info("=====> 入参:{}", JSONObject.toJSONString(param));
    HttpRequest post = HttpUtil.createPost(GhjgPortThreeUrl.PORT_INFO.getUrl());
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer" + " " + accessToken);
    headers.put("Content-Type", "application/json;charset=utf-8");
    post.addHeaders(headers);
    return post.body(JSONObject.toJSONString(param)).setReadTimeout(3600000).execute().body();
  }


  public static void main(String[] args) {
    JSONObject data = new JSONObject();
    JSONObject jsonObject = new JSONObject();
    JSONObject portRequest = new JSONObject();
    portRequest.put("limit", "20");
    portRequest.put("page", "1");
    portRequest.put("portId", "0001");
    data.put("portRequest", portRequest);
    jsonObject.put("PlatformID", "425009768");
    jsonObject.put("Data", data);
    jsonObject.put("TimeStamp", "16880151424323");
    jsonObject.put("Seq", "001");
    JSONObject sss = (JSONObject) jsonObject.get("Data");
    String mvData = Encodes.encodeBase64(
        Encodes.aesEncrypt(sss.toString().getBytes(StandardCharsets.UTF_8),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
            GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()));
    jsonObject.put("Data", mvData);
    Map<String, String> param = Maps.newLinkedHashMap();
    param.put("PlatformID", jsonObject.getString("PlatformID"));
    param.put("Data", jsonObject.getString("Data"));
    param.put("TimeStamp", jsonObject.getString("TimeStamp"));
    param.put("Seq", jsonObject.getString("Seq"));
    String reqSign = Encodes.sign(param, GhjgPortThreeUrl.TOKEN_KEY.getUrl());
    jsonObject.put("Sig", reqSign);
    System.out.println(jsonObject);

    String result = new String(Encodes.aesDecrypt(
        Encodes.decodeBase64(
            "gbc4kk0TAbgF+OyUUsVxR3w8cuJzO2d9KH+1wVvB5gyJSYOucNO4UEmyToekslu+BoGIyRH/2FCTMem/oQI7WHlwGPUbETN0rQ2JBF+S/p0="),
        GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes(),
        GhjgPortThreeUrl.TOKEN_KEY.getUrl().getBytes()), StandardCharsets.UTF_8);
    System.out.println(result);
  }
}
