package com.jsowell.thirdparty.platform.service.impl;

import cn.hutool.core.util.PageUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.RealTimeMonitorData;
import com.jsowell.common.enums.thirdparty.BusinessInformationExchangeEnum;
import com.jsowell.common.enums.thirdparty.ThirdPartyOperatorIdEnum;
import com.jsowell.common.enums.thirdparty.ThirdPlatformTypeEnum;
import com.jsowell.common.enums.ykc.OrderStatusEnum;
import com.jsowell.common.enums.ykc.PileConnectorDataBaseStatusEnum;
import com.jsowell.common.util.AdapayUtil;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.PageUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.*;
import com.jsowell.pile.domain.ykcCommond.StartChargingCommand;
import com.jsowell.pile.dto.*;
import com.jsowell.pile.service.*;
import com.jsowell.pile.thirdparty.ZDLEquipmentInfo;
import com.jsowell.pile.vo.ThirdPartySecretInfoVO;
import com.jsowell.pile.vo.base.ConnectorInfoVO;
import com.jsowell.pile.vo.base.ThirdPartyStationInfoVO;
import com.jsowell.pile.vo.base.ThirdPartyStationRelationVO;
import com.jsowell.pile.vo.lianlian.AccumulativeInfoVO;
import com.jsowell.pile.vo.uniapp.customer.BillingPriceVO;
import com.jsowell.pile.vo.web.BillingTemplateVO;
import com.jsowell.pile.vo.web.EchoBillingTemplateVO;
import com.jsowell.pile.vo.web.PileConnectorInfoVO;
import com.jsowell.pile.vo.zdl.EquipBusinessPolicyVO;
import com.jsowell.thirdparty.lianlian.domain.*;
import com.jsowell.thirdparty.lianlian.vo.EquipmentAuthVO;
import com.jsowell.thirdparty.lianlian.vo.QueryChargingStatusVO;
import com.jsowell.thirdparty.lianlian.vo.QueryStartChargeVO;
import com.jsowell.thirdparty.lianlian.vo.QueryStopChargeVO;
import com.jsowell.thirdparty.platform.service.ThirdPartyPlatformService;
import com.jsowell.thirdparty.platform.factory.ThirdPartyPlatformFactory;
import com.jsowell.thirdparty.platform.domain.HNStationInfo;
import com.jsowell.thirdparty.platform.util.Cryptos;
import com.jsowell.thirdparty.platform.util.Encodes;
import com.jsowell.thirdparty.platform.util.GBSignUtils;
import com.jsowell.thirdparty.platform.util.HttpRequestUtil;
import com.jsowell.thirdparty.zhongdianlian.service.ZDLService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author Lemon
 * @Date 2024/1/18 10:05:23
 */
@Service
public class HaiNanPlatformServiceImpl implements ThirdPartyPlatformService {
    Logger logger = LoggerFactory.getLogger(HaiNanPlatformServiceImpl.class);
    // 平台类型
    private final String thirdPlatformType = ThirdPlatformTypeEnum.HAI_NAN_1_PLATFORM.getTypeCode();

    @Autowired
    private PileMerchantInfoService pileMerchantInfoService;

    @Autowired
    private PileStationInfoService pileStationInfoService;

    @Autowired
    private PileBasicInfoService pileBasicInfoService;

    @Autowired
    private PileConnectorInfoService pileConnectorInfoService;

    @Autowired
    private PileBillingTemplateService pileBillingTemplateService;

    @Autowired
    private OrderBasicInfoService orderBasicInfoService;

    @Autowired
    private ThirdPartyPlatformConfigService thirdPartyPlatformConfigService;

    @Autowired
    private ThirdPartySettingInfoService thirdPartySettingInfoService;

    @Resource
    private ThirdPartyStationRelationService thirdPartyStationRelationService;

    @Autowired
    private YKCPushCommandService ykcPushCommandService;

    @Autowired
    private PileRemoteService pileRemoteService;

    @Autowired
    private ZDLService zdlService;

    @Override
    public void afterPropertiesSet() throws Exception {
        ThirdPartyPlatformFactory.register(thirdPlatformType, this);
    }

    @Override
    public void printServiceName() {
        System.out.println("当前类名：" + this.getClass().getSimpleName());
    }

    public String pushStationInfoV2(PushStationInfoDTO dto) {
        return zdlService.pushStationInfoV2(dto);
    }


    /**
     * 6.2 查询充电站信息
     */
    @Override
    public Map<String, String> queryStationsInfo(QueryStationInfoDTO dto) {
        // 查询出要查询的充电站id并set进 dto 的stationIds
        if (StringUtils.isNotBlank(dto.getThirdPlatformType())) {
            List<ThirdPartyStationRelation> xdtList = thirdPartyStationRelationService.selectThirdPartyStationRelationList(dto.getThirdPlatformType());
            if (CollectionUtils.isNotEmpty(xdtList)) {
                List<String> stationList = xdtList.stream()
                        .map(x -> String.valueOf(x.getStationId()))
                        .collect(Collectors.toList());
                dto.setStationIds(stationList);
            }
        }

        int pageNo = dto.getPageNo() == null ? 1 : dto.getPageNo();
        int pageSize = dto.getPageSize() == null ? 10 : dto.getPageSize();

        PageUtils.startPage(pageNo, pageSize);
        List<ThirdPartyStationInfoVO> stationInfos = pileStationInfoService.getStationInfosByThirdParty(dto);
        if (CollectionUtils.isEmpty(stationInfos)) {
            // 未查到数据
            return null;
        }
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorId());
        if (configInfo == null) {
            return null;
        }
        PageInfo<ThirdPartyStationInfoVO> pageInfo = new PageInfo<>(stationInfos);
        List<HNStationInfo> resultList = new ArrayList<>();
        HNStationInfo stationInfo = null;
        for (ThirdPartyStationInfoVO pileStationInfo : pageInfo.getList()) {
            stationInfo = new HNStationInfo();
            String stationId = String.valueOf(pileStationInfo.getId());
            stationInfo.setStationId(stationId);
            stationInfo.setOperatorId(Constants.OPERATORID_JIANG_SU); // 组织机构代码
            String organizationCode = pileStationInfo.getOrganizationCode();
            if (StringUtils.isNotBlank(organizationCode) && organizationCode.length() == 18) {
                String equipmentOwnerId = StringUtils.substring(organizationCode, organizationCode.length() - 10, organizationCode.length() - 1);
                stationInfo.setEquipmentOwnerId(equipmentOwnerId);
            } else {
                stationInfo.setEquipmentOwnerId(Constants.OPERATORID_JIANG_SU);
            }
            stationInfo.setStationName(pileStationInfo.getStationName());
            stationInfo.setCountryCode(pileStationInfo.getCountryCode());
            String areaCode = pileStationInfo.getAreaCode();  // 330000,330200,330213
            // 根据逗号分组
            String[] split = StringUtils.split(areaCode, ",");
            // 只取最后一部分  330213
            String subAreaCode = split[split.length - 1];
            stationInfo.setAreaCode(subAreaCode);
            stationInfo.setAddress(pileStationInfo.getAddress());
            stationInfo.setServiceTel(pileStationInfo.getStationTel());
            stationInfo.setStationType(Integer.parseInt(pileStationInfo.getStationType()));
            stationInfo.setStationStatus(Integer.parseInt(pileStationInfo.getStationStatus()));
            stationInfo.setParkNums(Integer.parseInt(pileStationInfo.getParkNums()));
            stationInfo.setStationLng(new BigDecimal(pileStationInfo.getStationLng()));
            stationInfo.setStationLat(new BigDecimal(pileStationInfo.getStationLat()));
            stationInfo.setConstruction(Integer.parseInt(pileStationInfo.getConstruction()));
            // 停车费率描述
            if (StringUtils.isNotBlank(pileStationInfo.getParkFeeDescribe())) {
                stationInfo.setParkFee(pileStationInfo.getParkFeeDescribe());
            }
            // 站点图片
            if (StringUtils.isNotBlank(pileStationInfo.getPictures())) {
                stationInfo.setPictures(Lists.newArrayList(pileStationInfo.getPictures().split(",")));
            } else {
                stationInfo.setPictures(Lists.newArrayList());
            }

            List<ZDLEquipmentInfo> pileList = pileBasicInfoService.getPileListForZDL(stationId);
            if (CollectionUtils.isNotEmpty(pileList)) {
                stationInfo.setEquipmentInfos(pileList); // 充电设备信息列表
            }

            Map<String, String> priceDescription = getPriceDescription(stationId);
            // 充电费描述
            stationInfo.setElectricityFee(priceDescription.get("electricityFee"));
            // 服务费描述
            stationInfo.setServiceFee(priceDescription.get("serviceFee"));

            resultList.add(stationInfo);
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("PageNo", pageInfo.getPageNum());
        map.put("PageCount", pageInfo.getPages());
        map.put("ItemSize", resultList.size());
        map.put("StationInfos", resultList);

        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        String encryptData = Cryptos.aesEncrypt(JSON.toJSONString(map), configInfo.getDataSecret(), configInfo.getDataSecretIv());
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getSignSecret());
        resultMap.put("Sig", resultSign);
        return resultMap;
    }

    private Map<String, String> getPriceDescription(String stationId) {
        Map<String, String> resultMap = Maps.newHashMap();
        StringBuilder electricityFee = new StringBuilder("电费:");
        StringBuilder serviceFee = new StringBuilder("服务费:");

        // 查询站点当前使用的计费模板
        BillingTemplateVO billingTemplate = pileBillingTemplateService.queryUsedBillingTemplate(stationId);
        if (billingTemplate == null) {
            resultMap.put("electricityFee", electricityFee.toString());
            resultMap.put("serviceFee", serviceFee.toString());
            return resultMap;
        }
        EchoBillingTemplateVO echoBillingTemplateVO = pileBillingTemplateService.queryPileBillingTemplateById(Long.parseLong(billingTemplate.getTemplateId()));
        if (echoBillingTemplateVO == null) {
            resultMap.put("electricityFee", electricityFee.toString());
            resultMap.put("serviceFee", serviceFee.toString());
            return resultMap;
        }

        List<BillingTimeDTO> timeArray = echoBillingTemplateVO.getTimeArray();
        for (BillingTimeDTO billingTimeDTO : timeArray) {
            String type = billingTimeDTO.getType();
            String startTime = billingTimeDTO.getStartTime();
            String endTime = billingTimeDTO.getEndTime();

            BigDecimal electricityPrice;
            BigDecimal servicePrice;
            if (StringUtils.equals(type, "1")) {
                electricityPrice = echoBillingTemplateVO.getElectricityPriceA();
                servicePrice = echoBillingTemplateVO.getServicePriceA();
            } else if (StringUtils.equals(type, "2")) {
                electricityPrice = echoBillingTemplateVO.getElectricityPriceB();
                servicePrice = echoBillingTemplateVO.getServicePriceB();
            } else if (StringUtils.equals(type, "3")) {
                electricityPrice = echoBillingTemplateVO.getElectricityPriceC();
                servicePrice = echoBillingTemplateVO.getServicePriceC();
            } else {
                electricityPrice = echoBillingTemplateVO.getElectricityPriceD();
                servicePrice = echoBillingTemplateVO.getServicePriceD();
            }

            electricityFee.append(startTime).append("~").append(endTime).append(":").append(AdapayUtil.formatAmount(electricityPrice, 4)).append(",");
            serviceFee.append(startTime).append("~").append(endTime).append(":").append(AdapayUtil.formatAmount(servicePrice, 4)).append(",");
        }

        electricityFee.deleteCharAt(electricityFee.length() - 1);
        serviceFee.deleteCharAt(serviceFee.length() - 1);

        resultMap.put("electricityFee", electricityFee.toString());
        resultMap.put("serviceFee", serviceFee.toString());
        logger.info("海南平台费用描述:{}", JSON.toJSONString(resultMap));
        return resultMap;
    }

    /**
     * 6.3 设备状态变化推送
     *
     * @param dto
     */
    @Override
    public String notificationStationStatus(PushRealTimeInfoDTO dto) {
        String thirdPartyType = dto.getThirdPartyType();
        String pileConnectorCode = dto.getPileConnectorCode();
        String status = dto.getStatus();
        // 通过第三方类型查询相关配置信息
        ThirdPartyStationRelation relation = new ThirdPartyStationRelation();
        relation.setThirdPartyType(thirdPartyType);
        ThirdPartyStationRelationVO relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        if (relationInfo == null) {
            return null;
        }
        String operatorId = relationInfo.getOperatorId();
        String operatorSecret = relationInfo.getOperatorSecret();
        String signSecret = relationInfo.getSignSecret();
        String dataSecret = relationInfo.getDataSecret();
        String dataSecretIv = relationInfo.getDataSecretIv();
        String urlAddress = relationInfo.getUrlAddress();

        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_STATION_STATUS.getValue();
        ConnectorStatusInfo info = ConnectorStatusInfo.builder()
                .connectorID(pileConnectorCode)
                .status(Integer.parseInt(status))
                .build();
        // 调用联联平台接口
        JSONObject json = new JSONObject();
        json.put("ConnectorStatusInfo", info);
        String jsonString = JSON.toJSONString(json);
        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }

    /**
     * 6.4 充电订单推送
     *
     * @param orderCode
     */
    @Override
    public String notificationChargeOrderInfo(String orderCode) {
        // 获取数据
        OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
        OrderDetail orderDetail = orderBasicInfoService.getOrderDetailByOrderCode(orderCode);

        // 通过第三方平台类型查询相关配置信息
        ThirdPartyStationRelation relation = new ThirdPartyStationRelation();
        relation.setThirdPartyType(orderBasicInfo.getThirdPartyType());
        ThirdPartyStationRelationVO relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        if (relationInfo == null) {
            return null;
        }

        // 向三方平台推送
        String operatorId = relationInfo.getOperatorId();
        String operatorSecret = relationInfo.getOperatorSecret();
        String signSecret = relationInfo.getSignSecret();
        String dataSecret = relationInfo.getDataSecret();
        String dataSecretIv = relationInfo.getDataSecretIv();
        String urlAddress = relationInfo.getUrlAddress();
        String thirdPartyType = relationInfo.getThirdPartyType();

        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_CHARGE_ORDER_INFO.getValue();
        JSONObject json = new JSONObject();
        json.put("StartChargeSeq", orderCode);
        json.put("ConnectorID", orderBasicInfo.getPileConnectorCode());
        json.put("StartTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderBasicInfo.getChargeStartTime()));
        json.put("EndTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderBasicInfo.getChargeEndTime()));
        json.put("TotalPower", orderDetail.getTotalUsedElectricity().setScale(2, RoundingMode.HALF_UP));
        json.put("TotalElecMoney", orderDetail.getTotalElectricityAmount().setScale(2, RoundingMode.HALF_UP));
        json.put("TotalSeviceMoney", orderDetail.getTotalServiceAmount().setScale(2, RoundingMode.HALF_UP));
        json.put("TotalMoney", orderDetail.getTotalOrderAmount().setScale(2, RoundingMode.HALF_UP));
        json.put("StopReason", 2); // 2：BMS 停止充电

        String jsonString = JSON.toJSONString(json);

        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }

    @Override
    public String notificationChargeOrderInfo(String orderCode, ThirdPartySecretInfoVO secretInfoVO) {
        // 获取数据
        OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
        OrderDetail orderDetail = orderBasicInfoService.getOrderDetailByOrderCode(orderCode);

        // 通过第三方平台类型查询相关配置信息
        // ThirdPartyStationRelation relation = new ThirdPartyStationRelation();
        // relation.setThirdPartyType(orderBasicInfo.getThirdPartyType());
        // ThirdPartyStationRelationVO relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        // if (relationInfo == null) {
        //     return null;
        // }

        // 向三方平台推送
        String operatorId = secretInfoVO.getTheirOperatorId();
        String operatorSecret = secretInfoVO.getTheirOperatorSecret();
        String signSecret = secretInfoVO.getTheirSigSecret();
        String dataSecret = secretInfoVO.getTheirDataSecret();
        String dataSecretIv = secretInfoVO.getTheirDataSecretIv();
        String urlAddress = secretInfoVO.getTheirUrlPrefix();
        String thirdPartyType = secretInfoVO.getPlatformType();

        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_CHARGE_ORDER_INFO.getValue();
        JSONObject json = new JSONObject();
        json.put("StartChargeSeq", orderCode);
        json.put("ConnectorID", orderBasicInfo.getPileConnectorCode());
        json.put("StartTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderBasicInfo.getChargeStartTime()));
        json.put("EndTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderBasicInfo.getChargeEndTime()));
        json.put("TotalPower", orderDetail.getTotalUsedElectricity().setScale(2, RoundingMode.HALF_UP));
        json.put("TotalElecMoney", orderDetail.getTotalElectricityAmount().setScale(2, RoundingMode.HALF_UP));
        json.put("TotalSeviceMoney", orderDetail.getTotalServiceAmount().setScale(2, RoundingMode.HALF_UP));
        json.put("TotalMoney", orderDetail.getTotalOrderAmount().setScale(2, RoundingMode.HALF_UP));
        json.put("StopReason", 2); // 2：BMS 停止充电

        String jsonString = JSON.toJSONString(json);

        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }

    /**
     * 6.5 设备接口状态查询
     *
     * @param dto
     */
    @Override
    public Map<String, String> queryStationStatus(QueryStationInfoDTO dto) {
        List<String> stationIds = dto.getStationIds();
        List<StationStatusInfo> StationStatusInfos = new ArrayList<>();
        List<Object> ConnectorStatusInfos = new ArrayList<>();
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorId());
        if (configInfo == null) {
            return null;
        }
        ConnectorStatusInfo connectorStatusInfo;
        for (String stationId : stationIds) {
            StationStatusInfo stationStatusInfo = new StationStatusInfo();
            stationStatusInfo.setStationId(stationId);
            // 根据站点id查询
            List<ConnectorInfoVO> list = pileConnectorInfoService.getConnectorListForLianLian(Long.parseLong(stationId));
            for (ConnectorInfoVO connectorInfoVO : list) {

                String connectorStatus = connectorInfoVO.getConnectorStatus();
                if (StringUtils.equals(connectorStatus, PileConnectorDataBaseStatusEnum.OCCUPIED_CHARGING.getValue())) {
                    // 充电中
                    ConnectorChargeStatusInfo info = new ConnectorChargeStatusInfo();
                    OrderBasicInfo orderBasicInfo = orderBasicInfoService.queryChargingByPileConnectorCode(connectorInfoVO.getPileConnectorCode());
                    if (orderBasicInfo == null) {
                        continue;
                    }
                    List<RealTimeMonitorData> chargingRealTimeData = orderBasicInfoService.getChargingRealTimeData(orderBasicInfo.getTransactionCode());
                    if (CollectionUtils.isNotEmpty(chargingRealTimeData)) {
                        RealTimeMonitorData realTimeMonitorData = chargingRealTimeData.get(0);

                        info.setStartChargeSeq(orderBasicInfo.getOrderCode());
                        info.setConnectorID(orderBasicInfo.getPileConnectorCode());
                        info.setConnectorStatus(Integer.valueOf(connectorInfoVO.getConnectorStatus()));
                        info.setCurrentA(new BigDecimal(realTimeMonitorData.getOutputCurrent()));
                        info.setVoltageA(new BigDecimal(realTimeMonitorData.getOutputVoltage()));
                        info.setSoc(new BigDecimal(realTimeMonitorData.getSOC()));
                        info.setStartTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderBasicInfo.getChargeStartTime()));
                        info.setEndTime(DateUtils.getDateTime()); // 本次采样时间
                        info.setTotalPower(new BigDecimal(realTimeMonitorData.getChargingDegree())); // 累计充电量
                        // info.setElecMoney(); // 累计电费
                        // info.setSeviceMoney(); // 累计服务费
                        info.setTotalMoney(new BigDecimal(realTimeMonitorData.getChargingAmount()));

                        ConnectorStatusInfos.add(info);
                    }
                } else {
                    // 其他
                    connectorStatusInfo = new ConnectorStatusInfo();
                    connectorStatusInfo.setConnectorID(connectorInfoVO.getPileConnectorCode());
                    connectorStatusInfo.setStatus(Integer.parseInt(connectorInfoVO.getConnectorStatus()));

                    ConnectorStatusInfos.add(connectorStatusInfo);
                }
            }
            stationStatusInfo.setConnectorStatusInfos(ConnectorStatusInfos);
            StationStatusInfos.add(stationStatusInfo);
        }
        // 将 StationStatusInfos 分页
        int pageNum = 1;
        int pageSize = 10;
        List<StationStatusInfo> collect = StationStatusInfos.stream()
                .skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());

        int total = StationStatusInfos.size();
        int pages = PageUtil.totalPage(total, pageSize);

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("Total", total);
        map.put("StationStatusInfos", collect);

        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        String encryptData = Cryptos.aesEncrypt(JSON.toJSONString(map), configInfo.getDataSecret(), configInfo.getDataSecretIv());
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getSignSecret());
        resultMap.put("Sig", resultSign);
        return resultMap;
    }

    /**
     * 查询统计信息 query_station_stats
     *
     * @param dto
     */
    @Override
    public Map<String, String> queryStationStats(QueryStationInfoDTO dto) {
        // 查询信息
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorId());
        if (configInfo == null) {
            return null;
        }
        // 根据站点id 查出这段时间的充电量
        List<AccumulativeInfoVO> list = orderBasicInfoService.getAccumulativeInfoForLianLian(dto);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }

        // 根据充电桩编号分组 key=充电桩编号
        Map<String, List<AccumulativeInfoVO>> pileMap = list.stream()
                .collect(Collectors.groupingBy(AccumulativeInfoVO::getPileSn));

        // 存放所有充电桩设备
        List<EquipmentStatsInfo> equipmentStatsInfoList = Lists.newArrayList();
        // 站点用电量
        BigDecimal stationElectricity = BigDecimal.ZERO;
        // 用于记录枪口用电量 在循环每个枪口的时候初始化
        BigDecimal pileElec;
        for (String pileSn : pileMap.keySet()) {
            // 该充电桩下 所有枪口的用电数据
            List<AccumulativeInfoVO> accumulativeInfoVOS = pileMap.get(pileSn);
            if (CollectionUtils.isEmpty(accumulativeInfoVOS)) {
                continue;
            }

            // 存放充电桩用电量
            pileElec = BigDecimal.ZERO;

            // key=枪口编号  value 该枪口的用电数据
            Map<String, List<AccumulativeInfoVO>> collect = accumulativeInfoVOS.stream()
                    .collect(Collectors.groupingBy(AccumulativeInfoVO::getPileConnectorCode));

            List<ConnectorStatsInfo> connectorStatsInfos = Lists.newArrayList();
            for (Map.Entry<String, List<AccumulativeInfoVO>> entry : collect.entrySet()) {
                String pileConnectorCode = entry.getKey();
                List<AccumulativeInfoVO> value = entry.getValue();
                // 枪口用电量求和
                BigDecimal connectorElec = value.stream()
                        .map(AccumulativeInfoVO::getConnectorElectricity)
                        .map(BigDecimal::new)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                connectorStatsInfos.add(
                        ConnectorStatsInfo.builder()
                                .connectorID(pileConnectorCode)
                                .connectorElectricity(connectorElec)
                                .build()
                );
                // 充电桩电量为枪口用电量累计
                pileElec = pileElec.add(connectorElec);
            }

            EquipmentStatsInfo build = EquipmentStatsInfo.builder()
                    .equipmentID(pileSn)
                    .equipmentElectricity(pileElec)
                    .connectorStatsInfos(connectorStatsInfos)
                    .build();
            equipmentStatsInfoList.add(build);

            // 所有充电桩用电量之和
            stationElectricity = stationElectricity.add(pileElec);
        }

        StationStatsInfo stationStatsInfo = StationStatsInfo.builder()
                .stationID(dto.getStationID())
                .startTime(dto.getStartTime())
                .endTime(dto.getEndTime())
                .stationElectricity(stationElectricity)
                .equipmentStatsInfos(equipmentStatsInfoList) // 设备列表
                .build();

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("StationStats", stationStatsInfo);

        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        String encryptData = Cryptos.aesEncrypt(JSON.toJSONString(map), configInfo.getDataSecret(), configInfo.getDataSecretIv());
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getSignSecret());
        resultMap.put("Sig", resultSign);
        return resultMap;
    }

    /**
     * 请求设备认证
     *
     * @param dto
     */
    @Override
    public Map<String, String> queryEquipAuth(QueryEquipmentDTO dto) {

        EquipmentAuthVO vo = new EquipmentAuthVO();

        String equipAuthSeq = dto.getEquipAuthSeq(); // MA1X78KH5202311071202015732
        String pileConnectorCode = dto.getConnectorID();
        // 先查询配置密钥相关信息
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
        if (configInfo == null) {
            return null;
        }
        // 根据桩编号查询数据
        // String merchantId = StringUtils.substring(equipAuthSeq, 0, 9);
        String pileSn = StringUtils.substring(pileConnectorCode, 0, 14);
        vo.setSuccStat(1); // 1-失败 0-成功  默认失败
        PileBasicInfo pileBasicInfo = pileBasicInfoService.selectPileBasicInfoBySN(pileSn);
        if (pileBasicInfo != null) {
            // 查询当前枪口数据
            PileConnectorInfoVO connectorInfo = pileConnectorInfoService.getPileConnectorInfoByConnectorCode(pileConnectorCode);
            if (StringUtils.equals(PileConnectorDataBaseStatusEnum.OCCUPIED_NOT_CHARGED.getValue(), String.valueOf(connectorInfo.getStatus()))
                    || StringUtils.equals(PileConnectorDataBaseStatusEnum.OCCUPIED_CHARGING.getValue(), String.valueOf(connectorInfo.getStatus()))
                    || StringUtils.equals(PileConnectorDataBaseStatusEnum.OCCUPIED_RESERVED_LOCK.getValue(), String.valueOf(connectorInfo.getStatus()))
            ) {
                vo.setSuccStat(0);
                vo.setFailReason(0);
            } else {
                vo.setSuccStat(1);
                vo.setFailReason(1); // 1- 此设备尚未插枪；
            }
            vo.setFailReasonMsg("");
            vo.setEquipAuthSeq(equipAuthSeq);
            vo.setConnectorID(pileConnectorCode);
        } else {
            vo.setFailReason(2); // 设备检测失败
            vo.setFailReasonMsg("未查到该桩的数据");
        }
        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        String encryptData = Cryptos.aesEncrypt(JSON.toJSONString(vo), configInfo.getDataSecret(), configInfo.getDataSecretIv());
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getSignSecret());
        resultMap.put("Sig", resultSign);
        return resultMap;
    }

    /**
     * 查询业务策略信息结果
     *
     * @param dto
     */
    @Override
    public Map<String, String> queryEquipBusinessPolicy(QueryStartChargeDTO dto) {
        List<EquipBusinessPolicyVO.PolicyInfo> policyInfoList = new ArrayList<>();
        String pileConnectorCode = dto.getConnectorID();
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorId());
        if (configInfo == null) {
            return null;
        }
        // 截取桩号
        String pileSn = StringUtils.substring(pileConnectorCode, 0, 14);
        // 查询该桩的站点id
        PileBasicInfo pileBasicInfo = pileBasicInfoService.selectPileBasicInfoBySN(pileSn);
        // 根据桩号查询正在使用的计费模板
        List<BillingPriceVO> billingPriceVOList = pileBillingTemplateService.queryBillingPrice(String.valueOf(pileBasicInfo.getStationId()));

        if (CollectionUtils.isEmpty(billingPriceVOList)) {
            return null;
        }
        EquipBusinessPolicyVO.PolicyInfo policyInfo = null;
        for (BillingPriceVO billingPriceVO : billingPriceVOList) {
            // 将时段开始时间、电费、服务费信息进行封装
            policyInfo = new EquipBusinessPolicyVO.PolicyInfo();
            String startTime = billingPriceVO.getStartTime() + ":00"; // 00:00:00 格式
            // 需要将中间的冒号去掉，改为 000000 格式
            String replace = StringUtils.replace(startTime, ":", "");
            policyInfo.setStartTime(replace);
            policyInfo.setElecPrice(new BigDecimal(billingPriceVO.getElectricityPrice()).setScale(4, BigDecimal.ROUND_HALF_UP));
            policyInfo.setServicePrice(new BigDecimal(billingPriceVO.getServicePrice()).setScale(4, BigDecimal.ROUND_HALF_UP));

            policyInfoList.add(policyInfo);
        }

        // 拼装所需要的数据格式
        EquipBusinessPolicyVO vo = EquipBusinessPolicyVO.builder()
                .equipBizSeq(dto.getEquipBizSeq())
                .connectorId(dto.getConnectorID())
                .succStat(0)
                .failReason(0)
                .sumPeriod(policyInfoList.size())
                .policyInfos(policyInfoList)
                .build();

        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        String encryptData = Cryptos.aesEncrypt(JSON.toJSONString(vo), configInfo.getDataSecret(), configInfo.getDataSecretIv());
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getSignSecret());
        resultMap.put("Sig", resultSign);
        return resultMap;
    }


    /**
     * 推送启动充电结果
     *
     * @param orderCode
     */
    @Override
    public String notificationStartChargeResult(String orderCode) {
        // 根据订单号查询订单信息
        OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
        if (orderInfo == null) {
            return null;
        }
        // 通过第三方平台类型查询相关配置信息
        ThirdPartyStationRelation relation = new ThirdPartyStationRelation();
        relation.setThirdPartyType(orderInfo.getThirdPartyType());
        ThirdPartyStationRelationVO relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        // ThirdPartySettingInfo settingInfo = thirdPartySettingInfoService.getInfoByStationId(Long.parseLong(orderBasicInfo.getStationId()));
        if (relationInfo == null) {
            return null;
        }
        String operatorId = relationInfo.getOperatorId();
        String operatorSecret = relationInfo.getOperatorSecret();
        String signSecret = relationInfo.getSignSecret();
        String dataSecret = relationInfo.getDataSecret();
        String dataSecretIv = relationInfo.getDataSecretIv();
        String urlAddress = relationInfo.getUrlAddress();
        String thirdPartyType = relationInfo.getThirdPartyType();

        // 推送启动充电结果(调用接口 notification_start_charge_result)
        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_START_CHARGE_RESULT.getValue();

        // String orderStatus = orderInfo.getOrderStatus();
        // // 订单状态统一
        // if (StringUtils.equals(OrderStatusEnum.IN_THE_CHARGING.getValue(), orderStatus)) {
        //     // 充电中
        //     orderStatus = "2";
        // } else if (StringUtils.equals(OrderStatusEnum.NOT_START.getValue(), orderStatus)) {
        //     // 未启动
        //     orderStatus = "1";
        // } else {
        //     // 其他状态都为 未知
        //     orderStatus = "5";
        // }
        // 拼装参数
        JSONObject json = new JSONObject();
        json.put("StartChargeSeq", orderCode);
        json.put("ConnectorID", orderInfo.getPileConnectorCode());
        json.put("StartChargeSeqStat", 2); // 一定要给 2-充电中
        json.put("StartTime", DateUtils.getDateTime());

        String jsonString = JSON.toJSONString(json);

        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }

    /**
     * 请求开始充电
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, String> queryStartCharge(QueryStartChargeDTO dto) {
        // 通过传过来的订单号和枪口号生成订单
        String pileConnectorCode = dto.getConnectorID();
        OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getStartChargeSeq());
        if (orderInfo != null) {
            // 平台已存在订单
            return null;
        }
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorId());
        if (configInfo == null) {
            return null;
        }
        // 生成订单
        Map<String, Object> map = orderBasicInfoService.generateOrderForThirdParty(dto);
        String orderCode = (String) map.get("orderCode");
        String transactionCode = (String) map.get("transactionCode");
        OrderBasicInfo orderBasicInfo = (OrderBasicInfo) map.get("orderBasicInfo");

        // 发送启机指令
        StartChargingCommand command = StartChargingCommand.builder()
                .pileSn(orderBasicInfo.getPileSn())
                .connectorCode(orderBasicInfo.getConnectorCode())
                .transactionCode(transactionCode)
                .chargeAmount(orderBasicInfo.getPayAmount())
                .logicCardNum(null)
                .physicsCardNum(null)
                .build();
        ykcPushCommandService.pushStartChargingCommand(command);

        // 拼装对应的数据并返回
        QueryStartChargeVO vo = QueryStartChargeVO.builder()
                .startChargeSeq(orderCode)
                .startChargeSeqStat(2) // 1、启动中 ；2、充电中；3、停止中；4、已结束；5、未知
                .connectorID(pileConnectorCode)
                .succStat(0)
                .failReason(0)

                .build();
        String type = ThirdPartyOperatorIdEnum.getTypeByOperatorId(dto.getOperatorId());
        if (StringUtils.equals(ThirdPlatformTypeEnum.XIN_DIAN_TU.getTypeCode(), type)) {
            // 如果是新电途平台，则将 startChargeSeqStat 改为 1-启动中
            vo.setStartChargeSeqStat(1);
        }

        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        String encryptData = Cryptos.aesEncrypt(JSON.toJSONString(vo), configInfo.getDataSecret(), configInfo.getDataSecretIv());
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getSignSecret());
        resultMap.put("Sig", resultSign);
        return resultMap;
    }

    /**
     * 查询充电状态
     *
     * @param dto
     */
    @Override
    public Map<String, String> queryEquipChargeStatus(QueryEquipChargeStatusDTO dto) {
        String operatorID = dto.getOperatorID();
        String type = ThirdPartyOperatorIdEnum.getTypeByOperatorId(operatorID);
        String operatorName = ThirdPlatformTypeEnum.getTypeLabelByTypeCode(type);
        // 通过订单号查询订单信息
        OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getStartChargeSeq());
        // logger.info(operatorName + "查询订单信息 orderInfo:{}", orderInfo);
        if (orderInfo == null) {
            return null;
        }
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(operatorID);
        // logger.info(operatorName + "查询密钥信息 configInfo:{}", configInfo);
        if (configInfo == null) {
            return null;
        }
        OrderDetail orderDetail = orderBasicInfoService.getOrderDetailByOrderCode(orderInfo.getOrderCode());
        // 通过订单号查询实时数据
        List<RealTimeMonitorData> realTimeData = orderBasicInfoService.getChargingRealTimeData(orderInfo.getTransactionCode());
        QueryChargingStatusVO vo;
        if (CollectionUtils.isEmpty(realTimeData)) {
            vo = new QueryChargingStatusVO();
        } else {
            RealTimeMonitorData data = realTimeData.get(0);
            String orderStatus = orderInfo.getOrderStatus();
            if (StringUtils.equals(orderStatus, OrderStatusEnum.IN_THE_CHARGING.getValue())) {
                // 充电中
                orderStatus = "2";
            } else if (StringUtils.equals(orderStatus, OrderStatusEnum.ORDER_COMPLETE.getValue())) {
                // 充电完成
                orderStatus = "4";
            } else {
                // 直接给 5-未知
                orderStatus = "5";
            }
            String status = data.getConnectorStatus();
            int connectorStatus = 0;
            if (StringUtils.isBlank(status)) {
                // 查询当前枪口状态
                PileConnectorInfoVO connectorInfoVO = pileConnectorInfoService.getPileConnectorInfoByConnectorCode(orderInfo.getPileConnectorCode());
                connectorStatus = connectorInfoVO.getStatus();
            } else {
                connectorStatus = Integer.parseInt(status);
            }
            BigDecimal totalElectricityAmount = orderDetail.getTotalElectricityAmount() == null ? BigDecimal.ZERO : orderDetail.getTotalElectricityAmount();
            BigDecimal totalServiceAmount = orderDetail.getTotalServiceAmount() == null ? BigDecimal.ZERO : orderDetail.getTotalServiceAmount();
            // 拼装联联平台数据
            vo = QueryChargingStatusVO.builder()
                    .startChargeSeq(dto.getStartChargeSeq()) // 订单号
                    .startChargeSeqStat(Integer.parseInt(orderStatus)) // 订单状态
                    .connectorID(orderInfo.getPileConnectorCode()) // 枪口编码
                    .connectorStatus(connectorStatus) // 枪口状态
                    .currentA(new BigDecimal(data.getOutputCurrent())) // 电流
                    .voltageA(new BigDecimal(data.getOutputVoltage())) // 电压
                    .soc(new BigDecimal(data.getSOC()))
                    .startTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderInfo.getChargeStartTime())) // 开始时间
                    .endTime(DateUtils.getDateTime()) // 本次采样时间
                    .totalPower(new BigDecimal(data.getChargingDegree()).setScale(2, BigDecimal.ROUND_HALF_UP)) // 累计充电量
                    .elecMoney(totalElectricityAmount.setScale(2, BigDecimal.ROUND_HALF_UP)) // 累计电费
                    .seviceMoney(totalServiceAmount.setScale(2, BigDecimal.ROUND_HALF_UP)) // 累计服务费
                    .totalMoney(new BigDecimal(data.getChargingAmount())) // 已充金额
                    .build();
        }

        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        String encryptData = Cryptos.aesEncrypt(JSON.toJSONString(vo), configInfo.getDataSecret(), configInfo.getDataSecretIv());
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getSignSecret());
        resultMap.put("Sig", resultSign);
        return resultMap;
    }

    /**
     * 推送充电状态
     *
     * @param orderCode
     */
    @Override
    public String notificationEquipChargeStatus(String orderCode) {
        // 根据订单号查询订单信息
        OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
        // 通过第三方平台类型查询相关配置信息
        ThirdPartyStationRelation relation = new ThirdPartyStationRelation();
        relation.setThirdPartyType(orderInfo.getThirdPartyType());
        ThirdPartyStationRelationVO relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        // ThirdPartySettingInfo settingInfo = thirdPartySettingInfoService.getInfoByStationId(Long.parseLong(orderInfo.getStationId()));
        if (relationInfo == null) {
            return null;
        }
        String operatorId = relationInfo.getOperatorId();
        String operatorSecret = relationInfo.getOperatorSecret();
        String signSecret = relationInfo.getSignSecret();
        String dataSecret = relationInfo.getDataSecret();
        String dataSecretIv = relationInfo.getDataSecretIv();
        String urlAddress = relationInfo.getUrlAddress();
        String thirdPartyType = relationInfo.getThirdPartyType();

        // 调用 查询充电状态方法
        QueryEquipChargeStatusDTO dto = new QueryEquipChargeStatusDTO();
        dto.setStartChargeSeq(orderCode);
        // 根据type获取operatorId
        String operatorIdByType = ThirdPartyOperatorIdEnum.getOperatorIdByType(thirdPartyType);
        dto.setOperatorID(operatorIdByType);
        Map<String, String> map = queryEquipChargeStatus(dto);
        if (map == null) {
            return null;
        }
        String data = map.get("Data");
        // 解密data (此处解密需用 thirdparty_platform_config 的密钥配置)
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(operatorIdByType);
        byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(data),
                configInfo.getDataSecret().getBytes(), configInfo.getDataSecretIv().getBytes());
        String dataStr = new String(plainText, StandardCharsets.UTF_8);
        // 转成对应的对象
        QueryChargingStatusVO vo = JSONObject.parseObject(dataStr, QueryChargingStatusVO.class);

        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_EQUIP_CHARGE_STATUS.getValue();
        // 调用联联平台接口
        String jsonString = JSON.toJSONString(vo);

        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }

    /**
     * 请求停止充电
     *
     * @param dto
     */
    @Override
    public Map<String, String> queryStopCharge(QueryStartChargeDTO dto) {
        QueryStopChargeVO vo = new QueryStopChargeVO();
        String orderCode = dto.getStartChargeSeq();
        // 根据订单号查询订单信息
        OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
        if (orderInfo == null) {
            return null;
        }
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorId());
        if (configInfo == null) {
            return null;
        }
        // 若状态为充电中，则发送停机指令
        if (StringUtils.equals(OrderStatusEnum.IN_THE_CHARGING.getValue(), orderInfo.getOrderStatus())) {
            // 充电中
            // StopChargingCommand command = StopChargingCommand.builder()
            //         .pileSn(orderInfo.getPileSn())
            //         .connectorCode(orderInfo.getConnectorCode())
            //         .build();
            // ykcPushCommandService.pushStopChargingCommand(command);
            pileRemoteService.remoteStopCharging(orderInfo.getPileSn(), orderInfo.getConnectorCode(), orderInfo.getTransactionCode());
            vo.setStartChargeSeq(orderCode);
            vo.setStartChargeSeqStat(4); // 1、启动中 ；2、充电中；3、停止中；4、已结束；5、未知
        }
        vo.setSuccStat(0);
        vo.setFailReason(0);

        String type = ThirdPartyOperatorIdEnum.getTypeByOperatorId(dto.getOperatorId());
        if (StringUtils.equals(ThirdPlatformTypeEnum.XIN_DIAN_TU.getTypeCode(), type)) {
            // 如果是新电途平台，则将 startChargeSeqStat 改为 3-停止中
            vo.setStartChargeSeqStat(3);
        }
        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        String encryptData = Cryptos.aesEncrypt(JSON.toJSONString(vo), configInfo.getDataSecret(), configInfo.getDataSecretIv());
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getSignSecret());
        resultMap.put("Sig", resultSign);
        return resultMap;
    }

    /**
     * 推送停止充电结果
     *
     * @param orderCode
     */
    @Override
    public String notificationStopChargeResult(String orderCode) {
        // 根据订单号查询订单信息
        OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
        if (orderInfo == null) {
            return null;
        }
        // 通过第三方平台类型查询相关配置信息
        ThirdPartyStationRelation relation = new ThirdPartyStationRelation();
        relation.setThirdPartyType(orderInfo.getThirdPartyType());
        ThirdPartyStationRelationVO relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        // ThirdPartySettingInfo settingInfo = thirdPartySettingInfoService.getInfoByStationId(Long.parseLong(orderInfo.getStationId()));
        if (relationInfo == null) {
            return null;
        }
        String operatorId = relationInfo.getOperatorId();
        String operatorSecret = relationInfo.getOperatorSecret();
        String signSecret = relationInfo.getSignSecret();
        String dataSecret = relationInfo.getDataSecret();
        String dataSecretIv = relationInfo.getDataSecretIv();
        String urlAddress = relationInfo.getUrlAddress();
        String thirdPartyType = relationInfo.getThirdPartyType();

        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_STOP_CHARGE_RESULT.getValue();

        // 拼装联联平台参数
        JSONObject json = new JSONObject();
        json.put("StartChargeSeq", orderCode);
        json.put("StartChargeSeqStat", 4); // 只能给 4-已结束
        json.put("ConnectorID", orderInfo.getPileConnectorCode());
        json.put("SuccStat", 0);
        json.put("FailReason", 0);

        String jsonString = JSON.toJSONString(json);

        // 获取token
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }


}
