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.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.OrderStatusEnum;
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.*;
import com.jsowell.pile.dto.PushRealTimeInfoDTO;
import com.jsowell.pile.dto.QueryConnectorListDTO;
import com.jsowell.pile.dto.QueryStartChargeDTO;
import com.jsowell.pile.dto.QueryStationInfoDTO;
import com.jsowell.pile.service.*;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.pile.thirdparty.ZDLEquipmentInfo;
import com.jsowell.pile.thirdparty.ZDLStationInfo;
import com.jsowell.pile.vo.base.ThirdPartyStationInfoVO;
import com.jsowell.pile.vo.base.ThirdPartyStationRelationVO;
import com.jsowell.pile.vo.uniapp.customer.BillingPriceVO;
import com.jsowell.pile.vo.uniapp.customer.OrderVO;
import com.jsowell.pile.vo.web.PileConnectorInfoVO;
import com.jsowell.pile.vo.web.PileMerchantInfoVO;
import com.jsowell.pile.vo.zdl.EquipBusinessPolicyVO;
import com.jsowell.thirdparty.lianlian.domain.ConnectorStatusInfo;
import com.jsowell.thirdparty.lianlian.vo.AccessTokenVO;
import com.jsowell.thirdparty.platform.service.ThirdPartyPlatformService;
import com.jsowell.thirdparty.platform.common.ChargeOrderInfo;
import com.jsowell.thirdparty.platform.common.ConnectorChargeStatusInfo;
import com.jsowell.thirdparty.platform.common.SupStationPowerInfo;
import com.jsowell.thirdparty.platform.factory.ThirdPartyPlatformFactory;
import com.jsowell.thirdparty.platform.util.*;
import com.jsowell.thirdparty.service.ThirdpartySecretInfoService;
import com.yi.business.geo.GeoCodeInfo;
import com.yi.business.geo.TermRelationTreeCoordinate;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 青海平台 Service
 *
 * @author Lemon
 * @Date 2024/4/8 15:12:35
 */
@Service
public class QingHaiPlatformServiceImpl implements ThirdPartyPlatformService {

    @Resource
    private ThirdPartyStationRelationService thirdPartyStationRelationService;

    @Autowired
    private PileStationInfoService pileStationInfoService;

    @Autowired
    private PileBasicInfoService pileBasicInfoService;

    @Autowired
    private OrderBasicInfoService orderBasicInfoService;

    @Autowired
    private PileConnectorInfoService pileConnectorInfoService;

    @Autowired
    private ThirdpartySecretInfoService thirdpartySecretInfoService;

    @Autowired
    private PileBillingTemplateService pileBillingTemplateService;

    @Autowired
    private PileMerchantInfoService pileMerchantInfoService;

    @Autowired
    private ThirdPartyPlatformConfigService thirdPartyPlatformConfigService;

    Logger logger = LoggerFactory.getLogger(QingHaiPlatformServiceImpl.class);

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

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

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

    /**
     * 请求令牌 query_token
     * @param dto
     * @return
     */
    @Override
    public Map<String, String>  queryToken(CommonParamsDTO dto) {
        String operatorId = dto.getOperatorID();
        // 通过operatorId 查出 operatorSecret
        ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(operatorId);
        if (platformConfig == null) {
            throw new BusinessException("1", "无此对接平台");
        }

        String operatorSecret = platformConfig.getOperatorSecret();
        String dataSecret = platformConfig.getDataSecret();
        String dataSecretIv = platformConfig.getDataSecretIv();
        String signSecret = platformConfig.getSignSecret();

        // 解密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 = Maps.newLinkedHashMap();
        // 加密数据
        byte[] encryptText = Cryptos.aesEncrypt(JSON.toJSONString(vo).getBytes(),
                dataSecret.getBytes(), dataSecretIv.getBytes());
        String encryptData = Encodes.encodeBase64(encryptText); // data
        resultMap.put("Ret", "0");
        resultMap.put("Msg", "请求令牌成功!");
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, signSecret);
        resultMap.put("Sig", resultSign);

        return resultMap;
    }

    public static void main(String[] args) {
        String data = "P1/F/NR6fTmwF0jBZ5zzSsuMBwkBgCaVRX1wnGuAtVDmbCJq5P4dAqw6hBh3l/c/nhYb+G32jZKwiWrfvAjY8/hUmOJHouHqfTfifQ2wMC5vZ+5OagGyU435iliW76oKx4O7jcmY9bLwFnHsuOoGRke6YuhhwVP5Q0hLXNuKu5vEGfVgMH8rccg4BOBe8WK0moV03pf9X+tWdNQC2kO/1IhiACDl/hst/doNLtyDI0plAekJHBYVFunAAWTUzKDzBdXBy4+r3rieOW/h5GHkPWbKiQOuptsjB1scURAFIQg5CtuQjhrRsSy/LoA8HkhWIlcvUhmf9MOYzgDDEjjeC3xwS/V2aroZ4KqVxyICH3E=";
        String signSecret = "1234567890abcdef";
        String sig = "E02F0364E6D842301C5093105BAF4BF4";

        Map<String, String> map = Maps.newLinkedHashMap();
        map.put("OperatorID", "MA1X78KH5");
        map.put("Data", data);
        map.put("TimeStamp", "1713925616685");
        map.put("Seq", "1043");
        String sign = GBSignUtils.sign(map, signSecret);

        // 验证签名 得到请求方传过来的签名sig->自己拿到请求体后，再按双方约定的协议生成一个sig->对比两个sig是否一致
        System.out.println(StringUtils.equals(sign, sig));
    }

    /**
     * 查询站点信息 query_stations_info
     * @param dto 查询站点信息dto
     * @return
     */
    @Override
    public Map<String, String> queryStationsInfo(QueryStationInfoDTO dto) {
        List<ZDLStationInfo> resultList = new ArrayList<>();
        // 查询出要查询的充电站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;
        }
        PageInfo<ThirdPartyStationInfoVO> pageInfo = new PageInfo<>(stationInfos);
        ZDLStationInfo stationInfo = null;
        for (ThirdPartyStationInfoVO stationInfoVO : pageInfo.getList()) {
            Long stationId = stationInfoVO.getId();
            stationInfo = ZDLStationInfo.builder()
                    .stationId(String.valueOf(stationId))
                    .operatorId(Constants.OPERATORID_JIANG_SU)
                    .stationName(stationInfoVO.getStationName())
                    .countryCode(stationInfoVO.getCountryCode())
                    .address(stationInfoVO.getAddress())
                    .serviceTel(stationInfoVO.getStationTel())
                    .stationClassification(Constants.one) // 1-充电站
                    .stationType(Integer.parseInt(stationInfoVO.getStationType()))
                    .stationStatus(Integer.parseInt(stationInfoVO.getStationStatus()))
                    .parkNums(Integer.parseInt(stationInfoVO.getParkNums()))
                    .stationLat(new BigDecimal(stationInfoVO.getStationLat()))
                    .stationLng(new BigDecimal(stationInfoVO.getStationLng()))
                    .construction(Integer.parseInt(stationInfoVO.getConstruction()))
                    .openAllDay(Integer.parseInt(stationInfoVO.getOpenAllDay()))
                    .parkFeeType(255) // 255-参考场地实际收费标准
                    .electricityType(1) // 用电类型 1-商业用电
                    .isAloneApply(Integer.parseInt(stationInfoVO.getAloneApply()))
                    // .ratedPower() // 站点额定总功率
                    .periodFee(1) // 峰谷分时 0-否；1-是
                    .runTime(DateUtils.formatDateTime(stationInfoVO.getCreateTime()))
                    .videoMonitor(0) // 视频监控配套情况 0-无；1-有

                    .build();

            String organizationCode = stationInfoVO.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);
            }

            String areaCode = stationInfoVO.getAreaCode();  // 330000,330200,330213
            // 根据逗号分组
            String[] split = StringUtils.split(areaCode, ",");
            // 只取最后一部分  330213
            String subAreaCode = split[split.length - 1];
            stationInfo.setAreaCode(subAreaCode);

            // areaCodeCountryside
            GeoCodeInfo geoCode = TermRelationTreeCoordinate.completeGeoCode(stationInfoVO.getAddress());
            if (geoCode != null) {
                String areaCodeCountryside = geoCode.getCounty_code();
                stationInfo.setAreaCodeCountryside(areaCodeCountryside);
            }

            // 查询桩列表
            List<ZDLEquipmentInfo> pileList = pileBasicInfoService.getPileListForZDL(String.valueOf(stationId));
            stationInfo.setEquipmentInfos(pileList);

            // 汇总站点额定总功率
            BigDecimal sumPower = pileList.stream()
                    .map(ZDLEquipmentInfo::getPower)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            stationInfo.setRatedPower(sumPower);

            resultList.add(stationInfo);

        }
        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 = getResultMap(jsonObject);

        return resultMap;
    }

    /**
     * 设备状态变化推送(在0x13中调用统一推送接口)
     * notification_stationStatus
     * @param dto
     * @return
     */
    @Override
    public String notificationStationStatus(PushRealTimeInfoDTO dto) {
        String thirdPartyType = dto.getThirdPartyType();
        String status = dto.getStatus();
        String pileConnectorCode = dto.getPileConnectorCode();

        ThirdPartyStationRelationVO settingInfo = getQingHaiSettingInfo();
        if (settingInfo == null) {
            return null;
        }
        String operatorId = settingInfo.getOperatorId();
        String operatorSecret = settingInfo.getOperatorSecret();
        String signSecret = settingInfo.getSignSecret();
        String dataSecret = settingInfo.getDataSecret();
        String dataSecretIv = settingInfo.getDataSecretIv();
        String urlAddress = settingInfo.getUrlAddress();
        String url = urlAddress + BusinessInformationExchangeEnum.NOTIFICATION_STATION_STATUS.getValue();
        ConnectorStatusInfo info = ConnectorStatusInfo.builder()
                .connectorID(pileConnectorCode)
                .status(Integer.parseInt(status))
                .build();
        // 调用平台接口
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ConnectorStatusInfo", info);
        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        String result = HttpRequestUtil.sendPost(token, jsonObject.toJSONString(), url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }

    /**
     * 推送充电状态 notification_equip_charge_status
     *
     * @param orderCode
     */
    @Override
    public String notificationEquipChargeStatus(String orderCode) {
        // 根据订单号查询订单信息
        OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
        ThirdPartyStationRelationVO settingInfo = getQingHaiSettingInfo();
        if (settingInfo == null) {
            return null;
        }
        String operatorId = settingInfo.getOperatorId();
        String operatorSecret = settingInfo.getOperatorSecret();
        String signSecret = settingInfo.getSignSecret();
        String dataSecret = settingInfo.getDataSecret();
        String dataSecretIv = settingInfo.getDataSecretIv();
        String urlAddress = settingInfo.getUrlAddress();

        String url = urlAddress + "notification_equip_charge_status";

        OrderDetail orderDetail = orderBasicInfoService.getOrderDetailByOrderCode(orderInfo.getOrderCode());
        // 通过订单号查询实时数据
        List<RealTimeMonitorData> realTimeData = orderBasicInfoService.getChargingRealTimeData(orderInfo.getTransactionCode());
        ConnectorChargeStatusInfo info;
        if (CollectionUtils.isEmpty(realTimeData)) {
            info = new ConnectorChargeStatusInfo();
        }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();

            // 拼装对应平台数据
            info = ConnectorChargeStatusInfo.builder()
                    .startChargeSeq(orderCode)
                    .connectorID(orderInfo.getPileConnectorCode())
                    .startchargeSeqStatus(Integer.parseInt(orderStatus))
                    .connectorStatus(connectorStatus)
                    .currentA(new BigDecimal(data.getOutputCurrent()).setScale(1, BigDecimal.ROUND_HALF_UP))
                    .voltageA(new BigDecimal(data.getOutputVoltage()).setScale(1, BigDecimal.ROUND_HALF_UP))
                    .soc(new BigDecimal(data.getSOC()).setScale(1, BigDecimal.ROUND_DOWN))
                    .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();
        }
        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String jsonString = JSON.toJSONString(info);
        // 发送请求
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }

    /**
     * 推送充换电站实时功率 supervise_notification_realtime_power_info
     * @return
     */
    public String notificationPowerInfo(List<String> stationIds) {
        SupStationPowerInfo supStationPowerInfo = null;
        List<SupStationPowerInfo> list = new ArrayList<>();
        String dateTimeNow = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS);

        List<SupStationPowerInfo
                .EquipmentPowerInfo> supPileInfoList = null;
        SupStationPowerInfo
                .EquipmentPowerInfo supPileInfo = null;

        List<SupStationPowerInfo
                .EquipmentPowerInfo
                .ConnectorPowerInfo> connectorPowerInfoList = null;
        SupStationPowerInfo
                .EquipmentPowerInfo
                .ConnectorPowerInfo  connectorPowerInfo = null;
        for (String stationId : stationIds) {
            BigDecimal stationPower = BigDecimal.ZERO;
            supStationPowerInfo = new SupStationPowerInfo();

            supStationPowerInfo.setOperatorID(Constants.OPERATORID_JIANG_SU);
            supStationPowerInfo.setStationId(stationId);
            supStationPowerInfo.setDataTime(dateTimeNow);
            supStationPowerInfo.setStationClassification(Constants.one);
            // 查询运营商基本信息
            PileMerchantInfoVO pileMerchantInfoVO = pileMerchantInfoService.queryMerchantInfoByStationId(stationId);
            String organizationCode = pileMerchantInfoVO.getOrganizationCode();
            if (StringUtils.isNotBlank(organizationCode) && organizationCode.length() == 18) {
                String equipmentOwnerId = StringUtils.substring(organizationCode, organizationCode.length() - 10, organizationCode.length() - 1);
                supStationPowerInfo.setEquipmentOwnerID(equipmentOwnerId);
            }else {
                supStationPowerInfo.setEquipmentOwnerID(Constants.OPERATORID_JIANG_SU);
            }

            // 根据站点id查询桩信息
            List<PileBasicInfo> pileList = pileBasicInfoService.getPileListByStationId(stationId);
            if (CollectionUtils.isEmpty(pileList)) {
                logger.error("推送充换电站实时功率 error, 查询桩列表信息为空");
                throw new BusinessException(ReturnCodeEnum.CODE_SELECT_INFO_IS_NULL);
            }
            // 将桩id筛选出来用于批量查询枪口数据
            List<Long> pileIds = pileList.stream()
                    .map(PileBasicInfo::getId)
                    .collect(Collectors.toList());
            QueryConnectorListDTO dto = new QueryConnectorListDTO();
            dto.setPileIds(pileIds);
            List<PileConnectorInfoVO> connectorList = pileConnectorInfoService.getConnectorInfoListByParams(dto);
            if (CollectionUtils.isEmpty(connectorList)) {
                logger.error("推送充换电站实时功率 error, 查询枪口列表信息为空");
                throw new BusinessException(ReturnCodeEnum.CODE_SELECT_INFO_IS_NULL);
            }
            supPileInfoList = new ArrayList<>();
            for (PileBasicInfo pileBasicInfo : pileList) {
                supPileInfo = new SupStationPowerInfo.EquipmentPowerInfo();
                supPileInfo.setEquipmentID(pileBasicInfo.getSn());
                supPileInfo.setEquipmentClassification(Constants.one);
                supPileInfo.setDataTime(dateTimeNow);
                BigDecimal pileInstantPower = BigDecimal.ZERO;
                connectorPowerInfoList = new ArrayList<>();
                for (PileConnectorInfoVO pileConnectorInfoVO : connectorList) {
                    if (!StringUtils.equals(pileBasicInfo.getSn(), pileConnectorInfoVO.getPileSn())) {
                        continue;
                    }
                    BigDecimal instantPower = pileConnectorInfoVO.getInstantPower() == null ? BigDecimal.ZERO : pileConnectorInfoVO.getInstantPower();
                    connectorPowerInfo = new SupStationPowerInfo
                            .EquipmentPowerInfo
                            .ConnectorPowerInfo();
                    connectorPowerInfo.setConnectorID(pileConnectorInfoVO.getPileConnectorCode());
                    connectorPowerInfo.setEquipmentClassification(Constants.one);
                    connectorPowerInfo.setDataTime(dateTimeNow);
                    BigDecimal InstantPower = instantPower.setScale(1, BigDecimal.ROUND_HALF_UP);
                    connectorPowerInfo.setConnectorRealTimePower(InstantPower);
                    // 计算桩此时实时功率
                    pileInstantPower = pileInstantPower.add(InstantPower);

                    connectorPowerInfoList.add(connectorPowerInfo);
                }
                supPileInfo.setConnectorPowerInfos(connectorPowerInfoList);
                // 桩实时功率
                supPileInfo.setEquipRealTimePower(pileInstantPower);
                stationPower = stationPower.add(pileInstantPower);

                supPileInfoList.add(supPileInfo);
            }
            supStationPowerInfo.setEquipmentPowerInfos(supPileInfoList);
            supStationPowerInfo.setStationRealTimePower(stationPower);
        }
        list.add(supStationPowerInfo);

        // 获取推送配置密钥信息
        ThirdPartyStationRelationVO settingInfo = getQingHaiSettingInfo();
        if (settingInfo == null) {
            return null;
        }
        String operatorId = settingInfo.getOperatorId();
        String operatorSecret = settingInfo.getOperatorSecret();
        String signSecret = settingInfo.getSignSecret();
        String dataSecret = settingInfo.getDataSecret();
        String dataSecretIv = settingInfo.getDataSecretIv();
        String urlAddress = settingInfo.getUrlAddress();

        String url = urlAddress + "supervise_notification_realtime_power_info";
        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        JSONObject json = new JSONObject();
        json.put("SupStationPowerInfos", list);
        String jsonString = JSON.toJSONString(json);
        // 发送请求
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }


    /**
     * 查询业务策略信息结果  query_equip_business_policy
     * @param dto 请求启动充电DTO
     * @return
     */
    @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();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("EquipBizSeq", dto.getEquipBizSeq());
        jsonObject.put("ConnectorID", pileConnectorCode);
        jsonObject.put("SuccStat", Constants.zero);
        jsonObject.put("FailReason", Constants.zero);
        jsonObject.put("SumPeriod", policyInfoList.size());
        jsonObject.put("PolicyInfos", policyInfoList);

        // 加密
        Map<String, String> resultMap = getResultMap(jsonObject);
        return resultMap;
    }

    /**
     * 推送充电订单信息  notification_charge_order_info
     * @param orderCode 订单编号
     * @return
     */
    @Override
    public String notificationChargeOrderInfo(String orderCode) {
        // 通过订单号查询订单信息
        OrderVO orderVO = orderBasicInfoService.getChargeOrderInfoByOrderCode(orderCode);
        BigDecimal startSoc = orderVO.getStartSoc() == null ? BigDecimal.ZERO : new BigDecimal(orderVO.getStartSoc());
        BigDecimal endSoc = orderVO.getEndSoc() == null ? BigDecimal.ZERO : new BigDecimal(orderVO.getEndSoc());

        ChargeOrderInfo chargeOrderInfo = ChargeOrderInfo.builder()
                .operatorId(Constants.OPERATORID_JIANG_SU)
                // .equipmentId()
                .stationId(orderVO.getStationId())
                .equipmentId(orderVO.getPileSn())
                .equipmentClassification(Constants.one)
                .connectorId(orderVO.getPileConnectorCode())
                .startChargeSeq(orderVO.getOrderCode())
                .startSoc(startSoc)
                .endSoc(endSoc)
                .totalMoney(orderVO.getOrderAmount())
                .totalElecMoney(orderVO.getTotalElectricityAmount())
                .totalSeviceMoney(orderVO.getTotalServiceAmount())
                .totalPower(new BigDecimal(orderVO.getTotalPower()))
                .startTime(orderVO.getStartTime())
                .endTime(orderVO.getEndTime())
                .paymentAmount(orderVO.getPayAmount())
                .payTime(orderVO.getPayTime())
                // .payWay(orderVO.getPayMode())
                .stopReason(Constants.two) // 2-BMS 停止充电
                .startMeterNum(BigDecimal.ZERO) // 电表起止值(暂时给0)
                .endMeterNum(BigDecimal.ZERO)

                .build();
        // 设备产权所属单位ID
        String organizationCode = orderVO.getOrganizationCode();
        if (StringUtils.isNotBlank(organizationCode) && organizationCode.length() == 18) {
            String equipmentOwnerId = StringUtils.substring(organizationCode, organizationCode.length() - 10, organizationCode.length() - 1);
            chargeOrderInfo.setEquipmentOwnerId(equipmentOwnerId);
        } else {
            chargeOrderInfo.setEquipmentOwnerId(Constants.OPERATORID_JIANG_SU);
        }
        // 支付方式
        String payMode = orderVO.getPayMode();
        if (StringUtils.equals("4", payMode)) {
            // 微信支付
            chargeOrderInfo.setPayWay(2);
        }else {
            chargeOrderInfo.setPayWay(6);
        }

        // 获取推送配置密钥信息
        ThirdPartyStationRelationVO settingInfo = getQingHaiSettingInfo();
        if (settingInfo == null) {
            return null;
        }
        String operatorId = settingInfo.getOperatorId();
        String operatorSecret = settingInfo.getOperatorSecret();
        String signSecret = settingInfo.getSignSecret();
        String dataSecret = settingInfo.getDataSecret();
        String dataSecretIv = settingInfo.getDataSecretIv();
        String urlAddress = settingInfo.getUrlAddress();

        String url = urlAddress + "notification_charge_order_info";
        // 获取令牌
        String token = getToken(urlAddress, operatorId, operatorSecret, dataSecretIv, signSecret, dataSecret);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        // 封装参数
        String jsonString = JSON.toJSONString(chargeOrderInfo);
        // 发送请求
        String result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        return result;
    }



    // 获取青海平台配置密钥信息
    private ThirdPartyStationRelationVO getQingHaiSettingInfo() {
        // 通过第三方平台类型查询相关配置信息
        ThirdPartyStationRelation relation = new ThirdPartyStationRelation();
        relation.setThirdPartyType(ThirdPlatformTypeEnum.QING_HAI_PLATFORM.getTypeCode());
        ThirdPartyStationRelationVO relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        return relationInfo;
    }


    /**
     * 将需要发送至对接平台的的返回参数加密返回
     * @param jsonObject
     * @return
     */
    private Map<String, String> getResultMap(JSONObject jsonObject) {
        String operatorId = ThirdPlatformTypeEnum.QING_HAI_PLATFORM.getOperatorId();
        ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(operatorId);
        if (platformConfig == null) {
            return null;
        }
        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        byte[] encryptText = Cryptos.aesEncrypt(jsonObject.toJSONString().getBytes(),
                platformConfig.getDataSecret().getBytes(), platformConfig.getDataSecretIv().getBytes());
        String encryptData = Encodes.encodeBase64(encryptText);
        resultMap.put("Ret", "0");
        resultMap.put("Msg", "请求令牌成功!");
        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, platformConfig.getSignSecret());
        resultMap.put("Sig", resultSign);

        return resultMap;
    }

}
