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.ThirdPlatformTypeEnum;
import com.jsowell.common.enums.ykc.PileConnectorDataBaseStatusEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.common.util.PageUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.domain.ThirdPartyPlatformConfig;
import com.jsowell.pile.domain.ThirdPartyStationRelation;
import com.jsowell.pile.dto.PushRealTimeInfoDTO;
import com.jsowell.pile.dto.QueryStationInfoDTO;
import com.jsowell.pile.service.*;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.pile.thirdparty.EquipmentInfo;
import com.jsowell.pile.thirdparty.ZDLStationInfo;
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.web.OrderListVO;
import com.jsowell.pile.vo.web.PileConnectorInfoVO;
import com.jsowell.pile.vo.web.PileStationVO;
import com.jsowell.thirdparty.lianlian.domain.*;
import com.jsowell.thirdparty.lianlian.vo.AccessTokenVO;
import com.jsowell.thirdparty.platform.common.StationInfo;
import com.jsowell.thirdparty.platform.domain.BMSInfo;
import com.jsowell.thirdparty.platform.domain.StationChargeStatsInfo;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 深圳平台 Service
 *
 * @author Lemon
 * @Date 2024/5/14 9:51:12
 */
@Service
public class ShenZhenPlatformServiceImpl implements ThirdPartyPlatformService {

    @Autowired
    private PileStationInfoService pileStationInfoService;

    @Autowired
    private ThirdpartySecretInfoService thirdpartySecretInfoService;

    @Autowired
    private PileConnectorInfoService pileConnectorInfoService;

    @Autowired
    private OrderBasicInfoService orderBasicInfoService;

    @Autowired
    private ThirdPartyStationRelationService thirdPartyStationRelationService;

    @Autowired
    private PileBasicInfoService pileBasicInfoService;

    Logger logger = LoggerFactory.getLogger(this.getClass());

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

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

    /**
     * 充电站信息变化推送  notification_stationInfo
     * @param stationId 充电站id
     * @return
     */
    @Override
    public String notificationStationInfo(String stationId) {
        // 根据站点id查询站点资料
        PileStationVO stationVO = pileStationInfoService.getStationInfo(stationId);
        if (stationVO == null) {
            throw new BusinessException(ReturnCodeEnum.CODE_SELECT_INFO_IS_NULL);
        }

        StationInfo stationInfo = StationInfo.builder()
                .stationID(stationVO.getId())
                .operatorID(Constants.OPERATORID_JIANG_SU)
                // .equipmentOwnerID()
                .stationName(stationVO.getStationName())
                .countryCode(stationVO.getCountryCode())
                .areaCode(stationVO.getAreaCode())
                .address(stationVO.getAddress())
                .stationType(Integer.parseInt(stationVO.getStationType()))
                .stationStatus(stationVO.getStationStatus())
                .parkNums(0) // 默认 0：未知
                .stationLng(new BigDecimal(stationVO.getStationLng()))
                .stationLat(new BigDecimal(stationVO.getStationLat()))
                .construction(Integer.parseInt(stationVO.getConstruction()))

                .build();
        String stationTel = stationVO.getStationTel();
        if (StringUtils.isNotBlank(stationTel)) {
            stationInfo.setStationTel(stationTel);
            stationInfo.setServiceTel(stationTel);
        }
        if (StringUtils.isNotBlank(stationVO.getPictures())) {
            stationInfo.setPictures(Lists.newArrayList(stationVO.getPictures().split(",")));
        }
        // 设备信息列表
        List<EquipmentInfo> pileList = pileBasicInfoService.getPileListForLianLian(stationId);
        stationInfo.setEquipmentInfos(pileList);

        // 获取配置密钥信息
        ThirdPartySecretInfoVO shenZhenSecretInfo = getShenZhenSecretInfo();

        String operatorId = shenZhenSecretInfo.getTheirOperatorId();
        String operatorSecret = shenZhenSecretInfo.getTheirOperatorSecret();
        String signSecret = shenZhenSecretInfo.getTheirSigSecret();
        String dataSecret = shenZhenSecretInfo.getTheirDataSecret();
        String dataSecretIv = shenZhenSecretInfo.getTheirDataSecretIv();
        String urlAddress = shenZhenSecretInfo.getTheirUrlPrefix();
        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_STATION_INFO.getValue();
        // 发送请求
        String jsonString = JSONObject.toJSONString(stationInfo);
        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }

    /**
     * 请求令牌 query_token
     * @param dto
     * @return
     */
    @Override
    public Map<String, String> queryToken(CommonParamsDTO dto) {
        String operatorId = dto.getOperatorID();
        // 通过operatorId 查出 相关配置信息
        ThirdPartySecretInfoVO secretInfoVO = getShenZhenSecretInfo();

        String operatorSecret = secretInfoVO.getOurOperatorSecret();
        String dataSecret = secretInfoVO.getOurDataSecret();
        String dataSecretIv = secretInfoVO.getOurDataSecretIv();
        String signSecret = secretInfoVO.getOurSigSecret();

        // 解密data 获取参数中的OperatorSecret
        try {
            String decrypt = Cryptos.decrypt(dto.getData(), dataSecret, dataSecretIv);
            String inputOperatorSecret = null;
            if (StringUtils.isNotBlank(decrypt)) {
                inputOperatorSecret = JSON.parseObject(decrypt).getString("OperatorSecret");
            }
            if (!StringUtils.equals(operatorSecret, inputOperatorSecret)) {
                throw new RuntimeException("密钥不一致");
            }
        } catch (RuntimeException e) {
            throw new BusinessException("2", "密钥错误");
        }

        // 生成token
        String token = JWTUtils.createToken(operatorId, operatorSecret, JWTUtils.ttlMillis);

        // 组装返回参数
        AccessTokenVO vo = new AccessTokenVO();
        vo.setAccessToken(token);
        vo.setOperatorID(operatorId);
        vo.setTokenAvailableTime((int) (JWTUtils.ttlMillis / 1000));
        vo.setFailReason(0);
        vo.setSuccStat(0);

        Map<String, String> resultMap = ThirdPartyPlatformUtils.generateResultMap(vo, secretInfoVO);
        return resultMap;
    }


    /**
     * 查询充电站信息  query_stations_info
     * @param dto 查询站点信息dto
     * @return
     */
    @Override
    public Map<String, String> queryStationsInfo(QueryStationInfoDTO dto) {
        List<StationInfo> resultList = new ArrayList<>();
        // 查询出要查询的充电站id并set进 dto 的stationIds
        if (StringUtils.isNotBlank(dto.getThirdPlatformType())) {
            List<ThirdPartyStationRelation> relationList = thirdPartyStationRelationService.selectThirdPartyStationRelationList(dto.getThirdPlatformType());
            if (CollectionUtils.isNotEmpty(relationList)) {
                List<String> stationList = relationList.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;
        }

        PageInfo<ThirdPartyStationInfoVO> pageInfo = new PageInfo<>(stationInfos);
        StationInfo stationInfo = null;
        for (ThirdPartyStationInfoVO stationVO : pageInfo.getList()) {
            Long stationId = stationVO.getId();
            stationInfo = StationInfo.builder()
                    .stationID(String.valueOf(stationVO.getId()))
                    .operatorID(Constants.OPERATORID_JIANG_SU)
                    // .equipmentOwnerID()
                    .stationName(stationVO.getStationName())
                    .countryCode(stationVO.getCountryCode())
                    .areaCode(stationVO.getAreaCode())
                    .address(stationVO.getAddress())
                    .stationType(Integer.parseInt(stationVO.getStationType()))
                    .stationStatus(Integer.parseInt(stationVO.getStationStatus()))
                    .parkNums(0) // 默认 0：未知
                    .stationLng(new BigDecimal(stationVO.getStationLng()))
                    .stationLat(new BigDecimal(stationVO.getStationLat()))
                    .construction(Integer.parseInt(stationVO.getConstruction()))

                    .build();
            String stationTel = stationVO.getStationTel();
            if (StringUtils.isNotBlank(stationTel)) {
                stationInfo.setStationTel(stationTel);
                stationInfo.setServiceTel(stationTel);
            }
            if (StringUtils.isNotBlank(stationVO.getPictures())) {
                stationInfo.setPictures(Lists.newArrayList(stationVO.getPictures().split(",")));
            }
            // 设备信息列表
            List<EquipmentInfo> pileList = pileBasicInfoService.getPileListForLianLian(String.valueOf(stationId));
            stationInfo.setEquipmentInfos(pileList);

            resultList.add(stationInfo);
        }
        ThirdPartySecretInfoVO shenZhenSecretInfo = getShenZhenSecretInfo();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("PageNo", pageInfo.getPageNum());
        jsonObject.put("PageCount", pageInfo.getPages());
        jsonObject.put("ItemSize", resultList.size());
        jsonObject.put("StationInfos", resultList);

        Map<String, String> resultMap = ThirdPartyPlatformUtils.generateResultMap(jsonObject, shenZhenSecretInfo);
        return resultMap;
    }


    /**
     * 设备状态变化推送  notification_stationStatus
     * @param dto
     * @return
     */
    @Override
    public String notificationStationStatus(PushRealTimeInfoDTO dto) {
        String thirdPartyType = dto.getThirdPartyType();
        String status = dto.getStatus();
        String pileConnectorCode = dto.getPileConnectorCode();

        ThirdPartySecretInfoVO shenZhenSecretInfo = getShenZhenSecretInfo();
        String operatorId = shenZhenSecretInfo.getTheirOperatorId();
        String operatorSecret = shenZhenSecretInfo.getTheirOperatorSecret();
        String signSecret = shenZhenSecretInfo.getTheirSigSecret();
        String dataSecret = shenZhenSecretInfo.getTheirDataSecret();
        String dataSecretIv = shenZhenSecretInfo.getTheirDataSecretIv();
        String urlAddress = shenZhenSecretInfo.getTheirUrlPrefix();
        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_STATION_STATUS.getValue();
        ConnectorStatusInfo info = ConnectorStatusInfo.builder()
                .connectorID(pileConnectorCode)
                .status(Integer.parseInt(status))
                .build();
        // 调用平台接口
        String jsonString = JSON.toJSONString(info);
        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }


    /**
     * 设备接口状态查询  query_stations_status
     * @param dto 查询站点信息dto
     * @return
     */
    @Override
    public Map<String, String> queryStationStatus(QueryStationInfoDTO dto) {
        List<String> stationIds = dto.getStationIds();
        List<StationStatusInfo> StationStatusInfos = new ArrayList<>();
        List<Object> ConnectorStatusInfos = new ArrayList<>();
        ThirdPartySecretInfoVO shenZhenSecretInfo = getShenZhenSecretInfo();

        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 = ThirdPartyPlatformUtils.generateResultMap(map, shenZhenSecretInfo);
        return resultMap;

    }

    /**
     * 查询充电统计信息  query_station_charge_stats
     * @param dto 查询站点信息dto
     * @return
     */
    @Override
    public Map<String, String> queryStationStats(QueryStationInfoDTO dto) {
        // 查出配置密钥信息
        ThirdPartySecretInfoVO secretInfoVO = getShenZhenSecretInfo();
        // 根据站点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<StationChargeStatsInfo
                .EquipmentChargeStatsInfo> 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<StationChargeStatsInfo
                    .EquipmentChargeStatsInfo
                    .ConnectorChargeStatsInfo> 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(
                        StationChargeStatsInfo
                                .EquipmentChargeStatsInfo
                                .ConnectorChargeStatsInfo.builder()
                                .connectorId(pileConnectorCode)
                                .connectorChargeElectricity(connectorElec)
                                .build()
                );
                // 充电桩电量为枪口用电量累计
                pileElec = pileElec.add(connectorElec);
            }

            StationChargeStatsInfo
                    .EquipmentChargeStatsInfo build = StationChargeStatsInfo.EquipmentChargeStatsInfo.builder()
                    .equipmentId(pileSn)
                    .equipmentChargeElectricity(pileElec)
                    .connectorChargeStatsInfos(connectorStatsInfos)
                    .build();
            equipmentStatsInfoList.add(build);

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

        StationChargeStatsInfo stationChargeStatsInfo = StationChargeStatsInfo.builder()
                .stationId(dto.getStationID())
                .startTime(dto.getStartTime())
                .endTime(dto.getEndTime())
                .stationChargeElectricity(stationElectricity)
                .equipmentChargeStatsInfos(equipmentStatsInfoList) // 设备列表
                .build();

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

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

    }

    /**
     * 过程信息推送 notification_bmsInfo
     * 当运营商平台有充放电电池数据过程信息时，推送最新的信息通知到市级监控平台
     * @param pileConnectorCode
     * @return
     */
    @Override
    public String notificationBMSInfo(String pileConnectorCode) {
        BMSInfo bmsInfo = null;
        JSONObject resultJson = new JSONObject();
        String pileSn = StringUtils.substring(pileConnectorCode, 0, 14);
        // 查询枪口状态
        PileConnectorInfoVO info = pileConnectorInfoService.getPileConnectorInfoByConnectorCode(pileConnectorCode);
        Integer connectorStatus = info.getStatus();
        resultJson.put("ConnectorID", pileConnectorCode);
        resultJson.put("Status", connectorStatus);
        if (!StringUtils.equals(PileConnectorDataBaseStatusEnum.OCCUPIED_CHARGING.getValue(), String.valueOf(connectorStatus))) {
            resultJson.put("BmsInfo", null);
        }else {
            // 获取正在充电的订单信息
            List<OrderListVO> orderListVOS = orderBasicInfoService.selectChargingOrder(pileSn);
            if (CollectionUtils.isEmpty(orderListVOS)) {
                return null;
            }
            OrderListVO orderVO = orderListVOS.get(0);
            // 获取充电电池信息
            List<RealTimeMonitorData> chargingRealTimeData = orderBasicInfoService.getChargingRealTimeData(orderVO.getTransactionCode());
            if (CollectionUtils.isEmpty(chargingRealTimeData)) {
                return null;
            }
            RealTimeMonitorData data = chargingRealTimeData.get(0);
            bmsInfo = BMSInfo.builder()
                    .vinCode(orderVO.getVinCode())
                    .bmsCode("")
                    .bmsVer("")
                    .connectorID(orderVO.getPileConnectorCode())
                    .maxChargeCurrent(new BigDecimal(""))
                    .maxChargeCellVoltage(new BigDecimal(""))
                    .maxTemp(0)
                    .ratedCapacity(0)
                    .tatalVoltage(new BigDecimal(data.getOutputVoltage()))
                    .totalCurrent(new BigDecimal(data.getOutputCurrent()))
                    .soc(Integer.parseInt(data.getSOC()))
                    .voltageH(new BigDecimal(""))
                    .voltageHNumIndex(0)
                    .temptureH(0)
                    .temptureHNumIndex(0)
                    .temptureL(0)
                    .temptureLNumIndex(0)
                    .currentCapacity(new BigDecimal(""))
                    .freshTime(DateUtils.getDateTime())
                    .startChargingTime(orderVO.getChargeStartTime())
                    .chargingSessionMin(Integer.parseInt(data.getSumChargingTime()) * 60)

                    .build();

            resultJson.put("BmsInfo", bmsInfo);
        }
        ThirdPartySecretInfoVO shenZhenSecretInfo = getShenZhenSecretInfo();
        String operatorId = shenZhenSecretInfo.getTheirOperatorId();
        String operatorSecret = shenZhenSecretInfo.getTheirOperatorSecret();
        String signSecret = shenZhenSecretInfo.getTheirSigSecret();
        String dataSecret = shenZhenSecretInfo.getTheirDataSecret();
        String dataSecretIv = shenZhenSecretInfo.getTheirDataSecretIv();
        String urlAddress = shenZhenSecretInfo.getTheirUrlPrefix();
        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_BMS_INFO.getValue();

        // 调用平台接口
        String jsonString = JSON.toJSONString(resultJson);
        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }


    @Override
    public Map<String, String> queryBmsInfo(String pileConnectorCode) {
        JSONObject jsonObject = new JSONObject();
        // 根据枪口编号查询枪口信息
        PileConnectorInfoVO connectorInfoVO = pileConnectorInfoService.getPileConnectorInfoByConnectorCode(pileConnectorCode);
        if (!StringUtils.equals(PileConnectorDataBaseStatusEnum.OCCUPIED_CHARGING.getValue(), String.valueOf(connectorInfoVO.getStatus()))) {
            // 不为充电中, BmsInfo 为空
            jsonObject.put("BmsInfo", null);
        }else {
            // 充电中状态时，获取充电电池信息
            // 获取正在充电的订单信息
            List<OrderListVO> orderListVOS = orderBasicInfoService.selectChargingOrder(connectorInfoVO.getPileSn());
            if (CollectionUtils.isEmpty(orderListVOS)) {
                return null;
            }
            OrderListVO orderVO = orderListVOS.get(0);
            // 获取充电电池信息
            List<RealTimeMonitorData> chargingRealTimeData = orderBasicInfoService.getChargingRealTimeData(orderVO.getTransactionCode());
            if (CollectionUtils.isEmpty(chargingRealTimeData)) {
                return null;
            }
            RealTimeMonitorData data = chargingRealTimeData.get(0);
            BMSInfo bmsInfo = BMSInfo.builder()
                    .vinCode(orderVO.getVinCode())
                    .bmsCode("")
                    .bmsVer("")
                    .connectorID(orderVO.getPileConnectorCode())
                    .maxChargeCurrent(new BigDecimal(""))
                    .maxChargeCellVoltage(new BigDecimal(""))
                    .maxTemp(0)
                    .ratedCapacity(0)
                    .tatalVoltage(new BigDecimal(data.getOutputVoltage()))
                    .totalCurrent(new BigDecimal(data.getOutputCurrent()))
                    .soc(Integer.parseInt(data.getSOC()))
                    .voltageH(new BigDecimal(""))
                    .voltageHNumIndex(0)
                    .temptureH(0)
                    .temptureHNumIndex(0)
                    .temptureL(0)
                    .temptureLNumIndex(0)
                    .currentCapacity(new BigDecimal(""))
                    .freshTime(DateUtils.getDateTime())
                    .startChargingTime(orderVO.getChargeStartTime())
                    .chargingSessionMin(Integer.parseInt(data.getSumChargingTime()) * 60)

                    .build();

            jsonObject.put("BmsInfo", bmsInfo);
        }
        jsonObject.put("ConnectorID", pileConnectorCode);
        jsonObject.put("Status", connectorInfoVO.getStatus());

        ThirdPartySecretInfoVO shenZhenSecretInfo = getShenZhenSecretInfo();

        Map<String, String> map = ThirdPartyPlatformUtils.generateResultMap(jsonObject, shenZhenSecretInfo);
        return map;
    }

    /**
     * 获取深圳平台相关密钥信息
     * @return
     */
    private ThirdPartySecretInfoVO getShenZhenSecretInfo() {
        ThirdPartySecretInfoVO thirdPartySecretInfoVO = thirdpartySecretInfoService.queryByThirdPlatformType(ThirdPlatformTypeEnum.SHEN_ZHEN_PLATFORM.getTypeCode());
        if (thirdPartySecretInfoVO == null) {
            throw new BusinessException(ReturnCodeEnum.CODE_SELECT_INFO_IS_NULL);
        }
        return thirdPartySecretInfoVO;
    }
}
