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

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.CacheConstants;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.RealTimeMonitorData;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.thirdparty.BusinessInformationExchangeEnum;
import com.jsowell.common.enums.thirdparty.JiangSuConstructionEnum;
import com.jsowell.common.enums.thirdparty.ThirdPlatformTypeEnum;
import com.jsowell.common.enums.ykc.PileStatusEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
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.nanrui.JiangSuOrderInfo;
import com.jsowell.pile.dto.*;
import com.jsowell.pile.dto.nanrui.NRQueryOrderDTO;
import com.jsowell.pile.dto.nanrui.PushAlarmInfoDTO;
import com.jsowell.pile.service.*;
import com.jsowell.pile.vo.ThirdPartySecretInfoVO;
import com.jsowell.pile.vo.base.MerchantInfoVO;
import com.jsowell.pile.vo.base.ThirdPartyStationInfoVO;
import com.jsowell.pile.vo.nanrui.JiangSuOrderInfoVO;
import com.jsowell.pile.vo.uniapp.customer.CurrentTimePriceDetails;
import com.jsowell.pile.vo.web.PileConnectorInfoVO;
import com.jsowell.pile.vo.web.PileModelInfoVO;
import com.jsowell.pile.vo.web.PileStationVO;
import com.jsowell.thirdparty.common.CommonService;
import com.jsowell.thirdparty.nanrui.domain.*;
import com.jsowell.thirdparty.platform.dto.QueryOrderDTO;
import com.jsowell.thirdparty.platform.factory.ThirdPartyPlatformFactory;
import com.jsowell.thirdparty.platform.service.ThirdPartyPlatformService;
import com.jsowell.thirdparty.platform.util.*;
import com.jsowell.thirdparty.service.ThirdpartySecretInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 江苏省平台(原南瑞平台)
 *
 * @author Lemon
 * @Date 2024/7/8 10:35:16
 */
@Service
public class JiangSuPlatformServiceImpl implements ThirdPartyPlatformService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private PileStationInfoService pileStationInfoService;

    @Autowired
    private ThirdpartySecretInfoService thirdpartySecretInfoService;

    @Autowired
    private PileBasicInfoService pileBasicInfoService;

    @Autowired
    private PileModelInfoService pileModelInfoService;

    @Autowired
    private PileConnectorInfoService pileConnectorInfoService;

    @Autowired
    private PileMerchantInfoService pileMerchantInfoService;

    @Autowired
    private PileBillingTemplateService pileBillingTemplateService;

    @Autowired
    private OrderBasicInfoService orderBasicInfoService;

    @Autowired
    private RedisCache redisCache;

    // 平台类型
    private final String thirdPlatformType = ThirdPlatformTypeEnum.JIANG_SU_PLATFORM.getTypeCode();

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

    @Override
    public String notificationStationInfo(String stationId) {
        PileStationVO stationInfoVO = pileStationInfoService.getStationInfo(stationId);
        if (stationInfoVO == null) {
            return null;
        }
        ThirdPartySecretInfoVO jiangSuSecretInfo = getJiangSuSecretInfo();

        String operatorId = jiangSuSecretInfo.getOurOperatorId();
        String operatorSecret = jiangSuSecretInfo.getTheirOperatorSecret();
        String signSecret = jiangSuSecretInfo.getTheirSigSecret();
        String dataSecret = jiangSuSecretInfo.getTheirDataSecret();
        String dataSecretIv = jiangSuSecretInfo.getTheirDataSecretIv();
        String urlAddress = jiangSuSecretInfo.getTheirUrlPrefix();

        // 拼装江苏平台所需参数
        NRStationInfo nrStationInfo = NRStationInfo.builder()
                .stationId(String.valueOf(stationInfoVO.getId()))
                .operatorID(Constants.OPERATORID_JIANG_SU)
                // .equipmentOwnerID(Constants.OPERATORID_JIANG_SU)
                .stationName(stationInfoVO.getStationName())
                .countryCode(stationInfoVO.getCountryCode())
                // .areaCode()
                .address(stationInfoVO.getAddress())
                .serviceTel(stationInfoVO.getStationTel())
                .stationStatus(stationInfoVO.getStationStatus())
                .parkNums(0)
                .stationLng(new BigDecimal(stationInfoVO.getStationLng()).setScale(6, BigDecimal.ROUND_HALF_UP))
                .stationLat(new BigDecimal(stationInfoVO.getStationLat()).setScale(6, BigDecimal.ROUND_HALF_UP))
                .openForBusinessDate(DateUtils.convertDateTimeToDate(stationInfoVO.getCreateTime()))
                .openAllDay(Integer.parseInt(stationInfoVO.getOpenAllDay()))
                .busineHours(stationInfoVO.getBusinessHours())
                .minElectricityPrice(stationInfoVO.getElectricityPrice().add(stationInfoVO.getServicePrice()))
                .loungeFlag(0)
                .isAloneApply(0)
                .printerFlag(0)
                .parkFree(0)
                .isPublicParkingLot(0)
                .payment(1)
                .restaurantFlag(0)
                .barrierFlag(0)
                .serviceFee(stationInfoVO.getServicePrice())
                .parkingLockFlag(0)
                .electricityFee(stationInfoVO.getElectricityPrice())
                .storeFlag(0)
                .canopyFlag(0)
                .toiletFlag(0)
                .supportOrder(0)
                .parkFeeType(1)

                .build();
        // 截取运营商组织机构代码(去除最后一位后的最后九位)
        MerchantInfoVO merchantInfo = pileMerchantInfoService.getMerchantInfoVO(String.valueOf(stationInfoVO.getMerchantId()));
        String organizationCode = merchantInfo.getOrganizationCode();
        if (StringUtils.isNotBlank(organizationCode) && organizationCode.length() == 18) {
            String equipmentOwnerId = StringUtils.substring(organizationCode, organizationCode.length() - 10, organizationCode.length() - 1);
            nrStationInfo.setEquipmentOwnerID(equipmentOwnerId);
        }
        // 站点地址
        String areaCode = stationInfoVO.getAreaCode();
        // 截取最后一组数据，例如将 320000,320500,320583 截取为 320583
        String[] split = StringUtils.split(areaCode, ",");
        String s = split[split.length - 1];
        nrStationInfo.setAreaCode(s);
        // 站点图片
        if (CollectionUtils.isNotEmpty(stationInfoVO.getPictureList())) {
            nrStationInfo.setPictures(stationInfoVO.getPictureList());
        }
        String stationType = stationInfoVO.getStationType();
        if (!StringUtils.equals("1", stationType) && !StringUtils.equals("255", stationType)) {
            // 不为1-公共并且不为255-其他，都为专用
            stationType = "2";
        }
        nrStationInfo.setStationType(Integer.parseInt(stationType));
        // 获取建设场所
        int jsConstructionCode = JiangSuConstructionEnum.getJSCodeByDataBaseCode(Integer.parseInt(stationInfoVO.getConstruction()));
        nrStationInfo.setConstruction(jsConstructionCode);

        List<NREquipmentInfo> nrEquipmentInfos = getEquipmentInfo(stationId);
        nrStationInfo.setEquipmentInfos(nrEquipmentInfos);

        // 推送到平台
        String url = urlAddress + "notification_stationInfo";

        JSONObject data = new JSONObject();
        data.put("StationInfo", nrStationInfo);

        String jsonString = data.toString();
        System.out.println("jsonString : " + jsonString);

        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        System.out.println(token);
        String result = HttpRequestUtil.nrSendPost(token, jsonString, url, dataSecret
                , dataSecretIv, operatorId, signSecret);

        // 新增数据库
        PushStationInfoDTO dto = new PushStationInfoDTO();
        dto.setThirdPartyType(thirdPlatformType);
        dto.setStationId(Long.parseLong(stationId));

        commonService.insertInfo2DataBase(dto);
        return thirdPlatformType + "：" + result;
    }


    /**
     * 获取充电站信息
     * @param dto
     * @return
     */
    @Override
    public Map<String, String> queryStationsInfo(QueryStationInfoDTO dto) {
        List<NRStationInfo> resultList = new ArrayList<>();
        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;
        }
        ThirdPartySecretInfoVO jiangSuSecretInfo = getJiangSuSecretInfo();

        PageInfo<ThirdPartyStationInfoVO> pageInfo = new PageInfo<>(stationInfos);
        for (ThirdPartyStationInfoVO pileStationInfo : pageInfo.getList()) {
            // 拼装参数
            NRStationInfo nrStationInfo = NRStationInfo.builder()
                    .stationId(String.valueOf(pileStationInfo.getId()))
                    .operatorID(Constants.OPERATORID_JIANG_SU)
                    .equipmentOwnerID(Constants.OPERATORID_JIANG_SU)
                    .stationName(pileStationInfo.getStationName())
                    .countryCode(pileStationInfo.getCountryCode())
                    .areaCode(pileStationInfo.getAreaCode())
                    .address(pileStationInfo.getAddress())
                    .serviceTel(pileStationInfo.getStationTel())
                    .stationStatus(Integer.parseInt(pileStationInfo.getStationStatus()))
                    .parkNums(0)
                    .stationLng(new BigDecimal(pileStationInfo.getStationLng()).setScale(6, BigDecimal.ROUND_HALF_UP))
                    .stationLat(new BigDecimal(pileStationInfo.getStationLat()).setScale(6, BigDecimal.ROUND_HALF_UP))
                    .openForBusinessDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, pileStationInfo.getCreateTime()))
                    .openAllDay(Integer.parseInt(pileStationInfo.getOpenAllDay()))
                    .busineHours(pileStationInfo.getBusinessHours())
                    .build();
            // 站点费率
            // 查计费模板
            CurrentTimePriceDetails currentTimePriceDetails = pileBillingTemplateService.getCurrentTimePriceDetails(String.valueOf(pileStationInfo.getId()));
            if (currentTimePriceDetails == null) {
                // 未设置计费模板
                continue;
            }
            String electricityPrice = currentTimePriceDetails.getElectricityPrice();
            electricityPrice = StringUtils.isBlank(electricityPrice) ? "0" : electricityPrice;

            String servicePrice = currentTimePriceDetails.getServicePrice();
            servicePrice = StringUtils.isBlank(servicePrice) ? "0" : servicePrice;

            BigDecimal price = new BigDecimal(electricityPrice).add(new BigDecimal(servicePrice));
            nrStationInfo.setMinElectricityPrice(price);

            // 站点图片
            if (StringUtils.isNotBlank(pileStationInfo.getPictures())) {
                nrStationInfo.setPictures(Lists.newArrayList(pileStationInfo.getPictures().split(",")));
            }
            // 站点类型
            String stationType = pileStationInfo.getStationType();
            if (!StringUtils.equals("1", stationType) && !StringUtils.equals("255", stationType)) {
                // 不为1-公共并且不为255-其他，都为专用
                stationType = "2";
            }
            nrStationInfo.setStationType(Integer.parseInt(stationType));
            nrStationInfo.setConstruction(255);

            List<NREquipmentInfo> nrEquipmentInfos = getEquipmentInfo(String.valueOf(pileStationInfo.getId()));
            nrStationInfo.setEquipmentInfos(nrEquipmentInfos);

            resultList.add(nrStationInfo);
        }
        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 = ThirdPartyPlatformUtils.generateResultMap(map, jiangSuSecretInfo);
        return resultMap;
    }

    /**
     * 推送告警信息
     * @param dto
     * @return
     */
    @Override
    public String notificationAlarmInfo(PushAlarmInfoDTO dto) {
        List<NRAlarmInfo> nrAlarmInfos = new ArrayList<>();

        ThirdPartySecretInfoVO jiangSuSecretInfo = getJiangSuSecretInfo();

        String operatorId = jiangSuSecretInfo.getOurOperatorId();
        String operatorSecret = jiangSuSecretInfo.getTheirOperatorSecret();
        String signSecret = jiangSuSecretInfo.getTheirSigSecret();
        String dataSecret = jiangSuSecretInfo.getTheirDataSecret();
        String dataSecretIv = jiangSuSecretInfo.getTheirDataSecretIv();
        String urlAddress = jiangSuSecretInfo.getTheirUrlPrefix();

        // 从缓存中获取故障原因
        String redisKey = CacheConstants.PILE_HARDWARE_FAULT + dto.getPileConnectorCode();
        String faultReason = redisCache.getCacheObject(redisKey);
        int status = 0;
        if (StringUtils.equals(dto.getConnectorStatus(), "01")) {
            // 故障
            status = 1;
        }
        // 封装对象
        NRAlarmInfo alarmInfo = NRAlarmInfo.builder()
                .connectorId(dto.getPileConnectorCode())
                .alertTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS))
                .alertCode(120) // 120-预留
                .describe(faultReason)
                .status(status)

                .build();
        nrAlarmInfos.add(alarmInfo);

        // 发送请求
        String url = urlAddress + "notification_alarmInfo";

        JSONObject data = new JSONObject();
        data.put("AlarmInfos", nrAlarmInfos);

        String jsonString = JSON.toJSONString(data);
        System.out.println("jsonString : " + jsonString);

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

    /**
     * 推送站点信息状态
     * @param stationId 站点id
     * @param pileConnectorCode 枪口号
     * @param status 枪口状态
     * @param secretInfoVO 第三方平台对应密钥
     * @return
     */
    @Override
    public String notificationStationStatus(String stationId, String pileConnectorCode, String status, ThirdPartySecretInfoVO secretInfoVO) {
        // 查询枪口信息
        PileConnectorInfoVO connectorInfo = pileConnectorInfoService.getPileConnectorInfoByConnectorCode(pileConnectorCode);
        if (Objects.isNull(connectorInfo)) {
            throw new BusinessException(ReturnCodeEnum.CODE_CONNECTOR_INFO_NULL_ERROR);
        }

        // 查询相关配置信息
        ThirdPartySecretInfoVO jiangSuSecretInfo = getJiangSuSecretInfo();

        String operatorId = jiangSuSecretInfo.getOurOperatorId();
        String operatorSecret = jiangSuSecretInfo.getTheirOperatorSecret();
        String signSecret = jiangSuSecretInfo.getTheirSigSecret();
        String dataSecret = jiangSuSecretInfo.getTheirDataSecret();
        String dataSecretIv = jiangSuSecretInfo.getTheirDataSecretIv();
        String urlAddress = jiangSuSecretInfo.getTheirUrlPrefix();

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

        Date chargeStartTime = new Date();
        RealTimeMonitorData realTimeMonitorData = null;
        if (StringUtils.equals(status, "03")) {
            // 查询充电中的订单信息
            OrderBasicInfo orderBasicInfo = orderBasicInfoService.queryChargingByPileConnectorCode(pileConnectorCode);
            if (orderBasicInfo == null) {
                return null;
            }
            chargeStartTime = orderBasicInfo.getChargeStartTime();
            // 查询实时数据缓存
            String redisKey = CacheConstants.PILE_REAL_TIME_MONITOR_DATA + pileConnectorCode + "_" + orderBasicInfo.getTransactionCode();
            realTimeMonitorData = redisCache.getCacheObject(redisKey);
        }
        if (realTimeMonitorData == null) {
            return null;
        }
        // 封装对象
        NRConnectorStatusInfo nrConnectorStatusInfo = NRConnectorStatusInfo.builder()
                .connectorID(pileConnectorCode)
                .status(Integer.parseInt(status))
                .currentA(new BigDecimal(realTimeMonitorData.getOutputCurrent()).intValue())
                .voltageA(new BigDecimal(realTimeMonitorData.getOutputVoltage()).intValue())
                .soc(BigDecimal.ZERO)
                .beginTime(DateUtils.formatDateTime(chargeStartTime))
                .currentKwh(new BigDecimal(realTimeMonitorData.getChargingDegree()).setScale(3, BigDecimal.ROUND_HALF_UP))
                .timeStamp((int) (System.currentTimeMillis() / 1000))

                .build();
        if (StringUtils.isNotBlank(realTimeMonitorData.getSOC())) {
            nrConnectorStatusInfo.setSoc(new BigDecimal(realTimeMonitorData.getSOC()).setScale(1, BigDecimal.ROUND_HALF_UP));
        }

        // 发送请求
        JSONObject json = new JSONObject();
        json.put("ConnectorStatusInfo", nrConnectorStatusInfo);
        String jsonString = JSON.toJSONString(json);

        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = "";
        // 江苏省平台(充电状态至少一分钟推送一次)
        if (StringUtils.equals(status, "03")) {
            // 充电状态
            String redisKey = CacheConstants.JIANGSU_PUSH_PILE_STATUS + pileConnectorCode;
            Object cacheObject = redisCache.getCacheObject(redisKey);
            // 如果缓存有数据，证明上次推送未超过一分钟，不予推送，若缓存中无数据，说明需要推送
            if (cacheObject == null) {
                result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
                // 存缓存
                redisCache.setCacheObject(redisKey, nrConnectorStatusInfo, 1, TimeUnit.MINUTES);
            }
        } else {
            // 如果不是充电状态，直接推送就可以
            result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        }
        return result;
    }

    /**
     * 查询设备接口状态
     * 此接口用于批量查询设备实时状态
     * 由充电运营商方实现此接口，省、市两级监管平台调用。
     * @param dto
     * @return
     */
    @Override
    public Map<String, String> queryStationStatus(QueryStationInfoDTO dto) {
        List<String> stationIds = dto.getStationIds();
        List<NRStationStatusInfo> resultList = new ArrayList<>();

        ThirdPartySecretInfoVO jiangSuSecretInfo = getJiangSuSecretInfo();

        // 将 stationIdList 转换成 List<Long>
        List<Long> stationLongList = stationIds.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());

        QueryConnectorListDTO queryConnectorListDTO = QueryConnectorListDTO.builder()
                .stationIdList(stationLongList)
                .build();
        List<PileConnectorInfoVO> connectorInfoVOS = pileConnectorInfoService.getConnectorInfoListByParams(queryConnectorListDTO);
        if (CollectionUtils.isEmpty(connectorInfoVOS)) {
            return new LinkedHashMap<>();
        }
        // 根据stationId分组
        Map<String, List<PileConnectorInfoVO>> collect = connectorInfoVOS.stream()
                .collect(Collectors.groupingBy(PileConnectorInfoVO::getStationId));
        // 遍历 map
        for (Map.Entry<String, List<PileConnectorInfoVO>> entry : collect.entrySet()) {
            String stationId = entry.getKey();
            List<PileConnectorInfoVO> connectorList = entry.getValue();
            List<NRConnectorStatusInfo> connectorStatusInfoList = new ArrayList<>();

            for (PileConnectorInfoVO connectorInfoVO : connectorList) {
                NRConnectorStatusInfo nrConnectorStatusInfo = NRConnectorStatusInfo.builder()
                        .connectorID(connectorInfoVO.getPileConnectorCode())
                        .status(connectorInfoVO.getStatus())
                        .currentA(0)
                        .voltageA(0)
                        .soc(BigDecimal.ZERO)
                        .beginTime(null)
                        .currentKwh(BigDecimal.ZERO)
                        .timeStamp((int) (System.currentTimeMillis() / 1000))

                        .build();
                if (StringUtils.equals(String.valueOf(connectorInfoVO.getStatus()), "3")) {
                    // 充电中
                    nrConnectorStatusInfo.setCurrentA(connectorInfoVO.getCurrent().intValue());
                    nrConnectorStatusInfo.setVoltageA(connectorInfoVO.getVoltage().intValue());
                    nrConnectorStatusInfo.setSoc(new BigDecimal(connectorInfoVO.getSOC()));
                    String chargingTime = connectorInfoVO.getChargingTime();
                    Date beginTime = DateUtils.addMinute(new Date(), -Integer.parseInt(chargingTime));
                    nrConnectorStatusInfo.setBeginTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, beginTime));
                }
                if (StringUtils.equals(String.valueOf(connectorInfoVO.getStatus()), "255")) {
                    // 故障
                    nrConnectorStatusInfo.setStatus(255);
                }
                connectorStatusInfoList.add(nrConnectorStatusInfo);
            }
            // 封装参数
            NRStationStatusInfo stationStatusInfo = NRStationStatusInfo.builder()
                    .stationId(stationId)
                    .connectorStatusInfos(connectorStatusInfoList)
                    .build();
            resultList.add(stationStatusInfo);
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("StationStatusInfos", resultList);

        Map<String, String> resultMap = ThirdPartyPlatformUtils.generateResultMap(map, jiangSuSecretInfo);
        return resultMap;
    }

    /**
     * 推送订单信息
     * @param orderCode
     * @param secretInfoVO
     * @return
     */
    @Override
    public String notificationChargeOrderInfo(String orderCode, ThirdPartySecretInfoVO secretInfoVO) {
        // 根据订单号查询订单信息
        JiangSuOrderInfoVO nrOrderInfoVO = orderBasicInfoService.getNROrderInfoByOrderCode(orderCode);
        JiangSuOrderInfo jiangSuOrderInfo = formatJiangSuOrderInfo(nrOrderInfoVO);

        ThirdPartySecretInfoVO jiangSuSecretInfo = getJiangSuSecretInfo();

        String operatorId = jiangSuSecretInfo.getOurOperatorId();
        String operatorSecret = jiangSuSecretInfo.getTheirOperatorSecret();
        String signSecret = jiangSuSecretInfo.getTheirSigSecret();
        String dataSecret = jiangSuSecretInfo.getTheirDataSecret();
        String dataSecretIv = jiangSuSecretInfo.getTheirDataSecretIv();
        String urlAddress = jiangSuSecretInfo.getTheirUrlPrefix();

        String url = urlAddress + "notification_orderInfo";

        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        if (StringUtils.isBlank(token)) {
            return null;
        }

        // 发送请求
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("OrderInfo", jiangSuOrderInfo);

        String jsonString = JSON.toJSONString(jsonObject);

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

    /**
     * 查询充电电量信息
     * 此接口用于批量查询时间区段内交易记录
     * @param dto
     * @return
     */
    @Override
    public Map<String, String> queryOrderInfo(QueryOrderDTO dto) {
        List<JiangSuOrderInfo> resultList = new ArrayList<>();
        ThirdPartySecretInfoVO jiangSuSecretInfo = getJiangSuSecretInfo();
        NRQueryOrderDTO queryOrderDTO = new NRQueryOrderDTO();
        queryOrderDTO.setOrderCode(dto.getOrderCode());
        queryOrderDTO.setQueryStartTime(dto.getQueryStartTime());
        queryOrderDTO.setQueryEndTime(dto.getQueryEndTime());
        List<JiangSuOrderInfoVO> nrOrderInfos = orderBasicInfoService.getNROrderInfos(queryOrderDTO);
        if (CollectionUtils.isEmpty(nrOrderInfos)) {
            return Maps.newLinkedHashMap();
        }
        for (JiangSuOrderInfoVO nrOrderInfoVO : nrOrderInfos) {
            JiangSuOrderInfo jiangSuOrderInfo = formatJiangSuOrderInfo(nrOrderInfoVO);
            resultList.add(jiangSuOrderInfo);
        }

        Map<String, String> resultMap = ThirdPartyPlatformUtils.generateResultMap(JSONObject.toJSONString(resultList), jiangSuSecretInfo);
        return resultMap;
    }

    /**
     * 格式化江苏平台订单对象
     * @param nrOrderInfoVO
     * @return
     */
    private JiangSuOrderInfo formatJiangSuOrderInfo(JiangSuOrderInfoVO nrOrderInfoVO) {
        JiangSuOrderInfo jiangSuOrderInfo = JiangSuOrderInfo.builder()
                .operatorId(Constants.OPERATORID_JIANG_SU)
                .connectorId(nrOrderInfoVO.getConnectorId())
                .startChargeSeq(nrOrderInfoVO.getStartChargeSeq())
                .userChargeType(1)
                .elect(nrOrderInfoVO.getElect())
                .cuspElect(nrOrderInfoVO.getCuspElect())
                .peakElect(nrOrderInfoVO.getPeakElect())
                .flatElect(nrOrderInfoVO.getFlatElect())
                .valleyElect(nrOrderInfoVO.getValleyElect())
                .startTime(nrOrderInfoVO.getStartTime())
                .endTime(nrOrderInfoVO.getEndTime())

                .build();
        // TODO 获取电表总起、止值
        // pileMsgRecordService.getPileFeedList()

        jiangSuOrderInfo.setMeterValueStart(BigDecimal.ZERO);
        jiangSuOrderInfo.setMeterValueEnd(BigDecimal.ZERO);
        return jiangSuOrderInfo;
    }


    /**
     * 获取设备信息
     * @param stationId
     * @return
     */
    private List<NREquipmentInfo> getEquipmentInfo(String stationId) {
        List<NREquipmentInfo> resultList = new ArrayList<>();
        List<PileBasicInfo> list = pileBasicInfoService.getPileListByStationId(stationId);
        if (CollectionUtils.isEmpty(list)) {
            return resultList;
        }
        // 封装成江苏平台对象
        for (PileBasicInfo pileBasicInfo : list) {
            String pileSn = pileBasicInfo.getSn();
            // 获取桩状态
            Map<String, String> pileStatusMap = pileConnectorInfoService.getPileStatus(Lists.newArrayList(pileSn));
            String pileStatus = pileStatusMap.get(pileSn);
            if (StringUtils.equals(PileStatusEnum.ON_LINE.getValue(), pileStatus)) {
                pileStatus = "50"; // 50-正常使用
            } else if (StringUtils.equals(PileStatusEnum.OFF_LINE.getValue(), pileStatus)
                    || StringUtils.equals(PileStatusEnum.FAULT.getValue(), pileStatus)) {
                pileStatus = "6"; // 6-维护中
            }
            // 获取桩型号信息
            PileModelInfoVO modelInfo = pileModelInfoService.getPileModelInfoByPileSn(pileSn);
            if (modelInfo == null) {
                continue;
            }
            NREquipmentInfo equipmentInfo = NREquipmentInfo.builder()
                    .equipmentID(pileSn)
                    .equipmentName(pileSn)
                    .openForBusinessDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, pileBasicInfo.getCreateTime()))
                    .equipmentType(Integer.parseInt(modelInfo.getSpeedType()))
                    .equipmentStatus(Integer.parseInt(pileStatus))
                    .power(new BigDecimal(modelInfo.getRatedPower()).setScale(1, BigDecimal.ROUND_HALF_UP))

                    .vinFlag(1)
                    .equipmentPower(new BigDecimal(modelInfo.getRatedPower()).setScale(1, BigDecimal.ROUND_HALF_UP))
                    .newNationalStandard(1)
                    .constructionTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, pileBasicInfo.getProductionDate()))
                    .manufacturerID("014406554")
                    .build();
            // 获取枪口信息
            List<NRConnectorInfo> connectorInfos = getConnectorInfo(pileSn);
            equipmentInfo.setConnectorInfos(connectorInfos);

            resultList.add(equipmentInfo);
        }
        return resultList;
    }

    /**
     * 获取枪口信息
     * @param pileSn
     * @return
     */
    private List<NRConnectorInfo> getConnectorInfo(String pileSn) {
        List<NRConnectorInfo> resultList = new ArrayList<>();
        List<PileConnectorInfo> list = pileConnectorInfoService.selectPileConnectorInfoList(pileSn);
        if (CollectionUtils.isEmpty(list)) {
            return resultList;
        }
        PileModelInfoVO modelInfo = pileModelInfoService.getPileModelInfoByPileSn(pileSn);
        int connectorType = StringUtils.equals("1", modelInfo.getSpeedType()) ? 4 : 3;
        // 封装成江苏平台对象
        for (PileConnectorInfo pileConnectorInfo : list) {
            NRConnectorInfo connectorInfo = NRConnectorInfo.builder()
                    .connectorId(pileConnectorInfo.getPileConnectorCode())
                    .connectorName(pileConnectorInfo.getPileConnectorCode())
                    .connectorType(connectorType)
                    .voltageUpperLimits(Integer.parseInt(modelInfo.getRatedVoltage()))
                    .voltageLowerLimits(Integer.parseInt(modelInfo.getRatedVoltage()))
                    .current(Integer.parseInt(modelInfo.getRatedCurrent()))
                    .power(new BigDecimal(modelInfo.getRatedPower()).setScale(1, BigDecimal.ROUND_HALF_UP))
                    .nationalStandard(2)

                    .build();
            resultList.add(connectorInfo);
        }
        return resultList;
    }

    private ThirdPartySecretInfoVO getJiangSuSecretInfo() {
        // 通过第三方平台类型查询相关配置信息
        ThirdPartySecretInfoVO thirdPartySecretInfoVO = thirdpartySecretInfoService.queryByThirdPlatformType(ThirdPlatformTypeEnum.JIANG_SU_PLATFORM.getTypeCode());
        if (thirdPartySecretInfoVO == null) {
            throw new BusinessException(ReturnCodeEnum.CODE_SELECT_INFO_IS_NULL);
        }
        thirdPartySecretInfoVO.setOurOperatorId(Constants.OPERATORID_JIANG_SU);
        return thirdPartySecretInfoVO;
    }


}
