package com.jsowell.pile.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
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.page.PageResponse;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.ykc.PileConnectorDataBaseStatusEnum;
import com.jsowell.common.enums.ykc.PileStatusEnum;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.domain.PileBasicInfo;
import com.jsowell.pile.domain.PileConnectorInfo;
import com.jsowell.pile.dto.QueryConnectorDTO;
import com.jsowell.pile.dto.QueryConnectorListDTO;
import com.jsowell.pile.mapper.PileBasicInfoMapper;
import com.jsowell.pile.mapper.PileConnectorInfoMapper;
import com.jsowell.pile.service.*;
import com.jsowell.pile.vo.base.ConnectorInfoVO;
import com.jsowell.pile.vo.web.PileConnectorInfoVO;
import com.jsowell.pile.vo.web.PileDetailVO;
import com.jsowell.pile.vo.web.PileModelInfoVO;
import com.jsowell.pile.vo.web.PileStationVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

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

/**
 * 充电桩枪口信息Service业务层处理
 *
 * @author jsowell
 * @date 2022-08-31
 */
@Slf4j
@Service
public class PileConnectorInfoServiceImpl implements IPileConnectorInfoService {
	@Autowired
	private PileConnectorInfoMapper pileConnectorInfoMapper;

	@Autowired
	private PileBasicInfoMapper pileBasicInfoMapper;

	@Autowired
	private IPileBasicInfoService pileBasicInfoService;

	@Autowired
	private IPileModelInfoService pileModelInfoService;

	@Autowired
	private IOrderBasicInfoService orderBasicInfoService;

	@Autowired
	private IPileStationInfoService pileStationInfoService;

	@Autowired
	private RedisCache redisCache;

	private final String URL = "http://localhost/pileConnectorInfo&code=";

	@Value("${qrcodeurl.prefix}")
	private String QRCODE_URL_PREFIX;

	/**
	 * 查询充电桩枪口信息
	 *
	 * @param id 充电桩枪口信息主键
	 * @return 充电桩枪口信息
	 */
	@Override
	public PileConnectorInfo selectPileConnectorInfoById(Integer id) {
		return pileConnectorInfoMapper.selectPileConnectorInfoById(id);
	}

	/**
	 * 查询充电桩枪口信息列表
	 *
	 * @param pileConnectorInfo 充电桩枪口信息
	 * @return 充电桩枪口信息
	 */
	@Override
	public List<PileConnectorInfo> selectPileConnectorInfoList(PileConnectorInfo pileConnectorInfo) {
		return pileConnectorInfoMapper.selectPileConnectorInfoList(pileConnectorInfo);
	}

	/**
	 * 通过充电桩号查询枪口信息列表 加缓存
	 *
	 * @param pileSn 桩编号
	 * @return 枪口信息列表
	 */
	@Override
	public List<PileConnectorInfo> selectPileConnectorInfoList(String pileSn) {
		// 取缓存
		String redisKey = CacheConstants.SELECT_PILE_CONNECTOR_INFO_LIST + pileSn;
		List<PileConnectorInfo> result = redisCache.getCacheObject(redisKey);
		if (CollectionUtils.isEmpty(result)) {
			// 缓存为空，查数据库
			PileConnectorInfo pileConnectorInfo = new PileConnectorInfo();
			pileConnectorInfo.setPileSn(pileSn);
			result = selectPileConnectorInfoList(pileConnectorInfo);
			if (CollectionUtils.isNotEmpty(result)) {
				// 查询数据库不为空，存redis 2分钟
				redisCache.setCacheObject(redisKey, result, 15, TimeUnit.HOURS);
			}
		}
		return result;
	}

	/**
	 * 公共方法 根据桩编号删除redis缓存
	 */
	private void deleteRedisByPileSn(String pileSn) {
		List<String> keys = Lists.newArrayList();
		// 删除枪口信息缓存
		keys.add(CacheConstants.SELECT_PILE_CONNECTOR_INFO_LIST + pileSn);
		// 删除充电桩详情缓存
		keys.add(CacheConstants.PILE_DETAIL_KEY + pileSn);
		// 删除充电桩枪口状态缓存
		Set<String> scan = redisCache.scan(CacheConstants.PILE_CONNECTOR_STATUS_KEY + pileSn + "*");
		if (CollectionUtils.isNotEmpty(scan)) {
			keys.addAll(scan);
		}
		// 批量删除
		// log.debug("批量删除缓存 pileSn:{}, keys:{}", pileSn, keys);
		redisCache.deleteObject(keys);
	}

	/**
	 * 新增充电桩枪口信息
	 *
	 * @param pileConnectorInfo 充电桩枪口信息
	 * @return 结果
	 */
	// @Override
	// public int insertPileConnectorInfo(PileConnectorInfo pileConnectorInfo) {
	// 	pileConnectorInfo.setCreateTime(DateUtils.getNowDate());
	// 	return pileConnectorInfoMapper.insertPileConnectorInfo(pileConnectorInfo);
	// }

	/**
	 * 修改充电桩枪口信息
	 *
	 * @param pileConnectorInfo 充电桩枪口信息
	 * @return 结果
	 */
	// @Override
	// public int updatePileConnectorInfo(PileConnectorInfo pileConnectorInfo) {
	// 	pileConnectorInfo.setUpdateTime(DateUtils.getNowDate());
	// 	deleteRedisByPileSn(pileConnectorInfo.getPileSn());
	// 	return pileConnectorInfoMapper.updatePileConnectorInfo(pileConnectorInfo);
	// }

	/**
	 * 批量删除充电桩枪口信息
	 *
	 * @param ids 需要删除的充电桩枪口信息主键
	 * @return 结果
	 */
	// @Override
	// public int deletePileConnectorInfoByIds(Integer[] ids) {
	// 	return pileConnectorInfoMapper.deletePileConnectorInfoByIds(ids);
	// }

	@Override
	public int deletePileConnectorInfoByPileSnList(List<String> pileSnList) {
		return pileConnectorInfoMapper.deletePileConnectorInfoByPileSnList(pileSnList);
	}

	@Override
	public int batchInsertConnectorInfo(List<PileConnectorInfo> pileConnectorInfoList) {
		return pileConnectorInfoMapper.batchInsertConnectorInfo(pileConnectorInfoList);
	}

	/**
	 * 充电接口相关信息
	 *
	 * @param dto 前台参数
	 * @return 充电接口对象结果集
	 */
	@Override
	public List<PileConnectorInfoVO> getConnectorInfoListByParams(QueryConnectorDTO dto) {
		List<PileConnectorInfoVO> list = pileConnectorInfoMapper.getConnectorInfoList(dto);
		// 二维码、电量、设备订单号、平台订单暂时未传
		if (Objects.nonNull(list)) {
			for (PileConnectorInfoVO p : list) {
				// p.setConnectorQrCodeUrl(URL + p.getPileConnectorCode());
				// 获取二维码前缀
				PileStationVO stationInfo = pileStationInfoService.getStationInfo(p.getStationId());
				if (StringUtils.isNotBlank(stationInfo.getQrcodePrefix())) {
					p.setConnectorQrCodeUrl(stationInfo.getQrcodePrefix());
				}else {
					p.setConnectorQrCodeUrl(getPileConnectorQrCodeUrl(p.getPileConnectorCode()));
				}
			}
		}
		return list;
	}

	/**
	 * 通过充电站id查询充电枪信息
	 *
	 * @param stationId 充电站id
	 * @return 充电接口信息集合
	 */
	@Override
	public List<PileConnectorInfoVO> selectConnectorListByStationId(Long stationId) {
		return pileConnectorInfoMapper.selectConnectorListByStationId(stationId);
	}

	/**
	 * 通过入参查询枪口数据
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public List<PileConnectorInfoVO> getConnectorInfoListByParams(QueryConnectorListDTO dto) {
		int pageNum = dto.getPageNum() == 0 ? 1 : dto.getPageNum();
		int pageSize = dto.getPageSize() == 0 ? 10 : dto.getPageSize();
		List<String> pileSns = Lists.newArrayList();
		List<Long> connectorIds = dto.getConnectorIdList();
		List<Long> stationIdList = dto.getStationIdList();
		List<String> connectorCodeList = dto.getConnectorCodeList();

		// 通过运营商查询站点
		if (StringUtils.isNotBlank(dto.getMerchantId())) {
			// 查询站点idList
			List<Long> queryStationIdList = Lists.newArrayList();
			if (CollectionUtils.isNotEmpty(queryStationIdList)) {
				if (CollectionUtils.isEmpty(stationIdList)) {
					stationIdList = Lists.newArrayList();
				}
				stationIdList.addAll(queryStationIdList);
			}
		}

		// 站点不为空，拿到站点下所有的充电桩id
		if (CollectionUtils.isNotEmpty(stationIdList)) {
			List<PileDetailVO> pileInfoVOS = pileBasicInfoService.selectPileListByStationIds(stationIdList);
			if (CollectionUtils.isNotEmpty(pileInfoVOS)) {
				pileSns.addAll(pileInfoVOS.stream().map(PileDetailVO::getPileSn).collect(Collectors.toList()));
			}
		}

		// 通过充电桩id查询
		if (CollectionUtils.isNotEmpty(dto.getPileIds())) {
			// 批量查
			List<PileBasicInfo> pileList = pileBasicInfoMapper.selectByIdList(dto.getPileIds());
			if (CollectionUtils.isNotEmpty(pileList)) {
				pileSns.addAll(pileList.stream().map(PileBasicInfo::getSn).collect(Collectors.toList()));
			}
		}
		if (CollectionUtils.isEmpty(pileSns) && CollectionUtils.isEmpty(connectorIds) && CollectionUtils.isEmpty(connectorCodeList)) {
			return Lists.newArrayList();
		}
		PageHelper.startPage(pageNum, pageSize);

		List<PileConnectorInfoVO> pileConnectorInfoList = pileConnectorInfoMapper.getPileConnectorInfoList(pileSns, connectorIds, connectorCodeList);

		// 查询枪口当前订单
		for (PileConnectorInfoVO pileConnectorInfoVO : pileConnectorInfoList) {
			String pileConnectorCode = pileConnectorInfoVO.getPileConnectorCode();
			pileConnectorInfoVO.setConnectorQrCodeUrl(getPileConnectorQrCodeUrl(pileConnectorCode)); // 枪口号二维码
			OrderBasicInfo order = orderBasicInfoService.queryChargingByPileConnectorCode(pileConnectorCode);
			if (order != null) {
				pileConnectorInfoVO.setOrderCode(order.getOrderCode());
			}
		}

		queryRealTimeData(pileConnectorInfoList);
		return pileConnectorInfoList;
	}

	/**
	 * 充电桩枪口的二维码
	 * @param pileConnectorCode 枪口编号 如枪口编号为空，则返回前缀 https://api.jsowellcloud.com/app-xcx-h5/pile/connectorDetail/
	 * @return
	 */
	@Override
	public String getPileConnectorQrCodeUrl(String pileConnectorCode) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(QRCODE_URL_PREFIX);
		stringBuilder.append("/app-xcx-h5/pile/connectorDetail/");
		if (StringUtils.isNotBlank(pileConnectorCode)) {
			if (!stringBuilder.toString().endsWith("/")) {
				stringBuilder.append("/");
			}
			stringBuilder.append(pileConnectorCode);
		}
		return stringBuilder.toString();
	}

	/**
	 * uniapp通过入参查询枪口数据
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public PageResponse getUniAppConnectorInfoListByParams(QueryConnectorListDTO dto) {
		int pageNum = dto.getPageNum() == 0 ? 1 : dto.getPageNum();
		int pageSize = dto.getPageSize() == 0 ? 10 : dto.getPageSize();

		List<String> pileSns = Lists.newArrayList();
		List<Long> connectorIds = dto.getConnectorIdList();
		List<Long> stationIdList = dto.getStationIdList();
		List<String> connectorCodeList = dto.getConnectorCodeList();

		// 通过运营商查询站点
		if (StringUtils.isNotBlank(dto.getMerchantId())) {
			// 查询站点idList
			List<Long> queryStationIdList = Lists.newArrayList();
			if (CollectionUtils.isNotEmpty(queryStationIdList)) {
				if (CollectionUtils.isEmpty(stationIdList)) {
					stationIdList = Lists.newArrayList();
				}
				stationIdList.addAll(queryStationIdList);
			}
		}

		// 站点不为空，拿到站点下所有的充电桩id
		if (CollectionUtils.isNotEmpty(stationIdList)) {
			List<PileDetailVO> pileInfoVOS = pileBasicInfoService.selectPileListByStationIds(stationIdList);
			if (CollectionUtils.isNotEmpty(pileInfoVOS)) {
				pileSns.addAll(pileInfoVOS.stream().map(PileDetailVO::getPileSn).collect(Collectors.toList()));
			}
		}

		// 通过充电桩id查询
		if (CollectionUtils.isNotEmpty(dto.getPileIds())) {
			// 批量查
			List<PileBasicInfo> pileList = pileBasicInfoMapper.selectByIdList(dto.getPileIds());
			if (CollectionUtils.isNotEmpty(pileList)) {
				pileSns.addAll(pileList.stream().map(PileBasicInfo::getSn).collect(Collectors.toList()));
			}
		}
		if (CollectionUtils.isEmpty(pileSns) && CollectionUtils.isEmpty(connectorIds) && CollectionUtils.isEmpty(connectorCodeList)) {
			return new PageResponse();
		}
		// 分页
		PageHelper.startPage(pageNum, pageSize);

		List<PileConnectorInfoVO> pileConnectorInfoList = pileConnectorInfoMapper.getPileConnectorInfoList(pileSns, connectorIds, connectorCodeList);

		PageInfo<PileConnectorInfoVO> pageInfo = new PageInfo<>(pileConnectorInfoList);

		// 查询枪口当前订单
		for (PileConnectorInfoVO pileConnectorInfoVO : pageInfo.getList()) {
			String pileConnectorCode = pileConnectorInfoVO.getPileConnectorCode();
			pileConnectorInfoVO.setConnectorQrCodeUrl(getPileConnectorQrCodeUrl(pileConnectorCode)); // 枪口号二维码
			OrderBasicInfo order = orderBasicInfoService.queryChargingByPileConnectorCode(pileConnectorCode);
			if (order != null) {
				pileConnectorInfoVO.setOrderCode(order.getOrderCode());
			}
		}

		queryRealTimeData(pageInfo.getList());

		// 返回结果集
		PageResponse pageResponse = PageResponse.builder()
				.pageNum(pageNum)
				.pageSize(pageSize)
				.list(pageInfo.getList())
				.pages(pageInfo.getPages())
				.total(pageInfo.getTotal())
				.build();
		return pageResponse;
	}

	/**
	 * uniApp通过站点id查询枪口列表信息
	 *
	 * @param stationId 站点id
	 * @return
	 */
	@Override
	public List<ConnectorInfoVO> getUniAppConnectorList(Long stationId) {
		// TODO 加缓存
		// String redisKey = CacheConstants.GET_UNIAPP_CONNECTOR_LIST_BY_STATION_ID + stationId;
		// List<ConnectorInfoVO> list = redisCache.getCacheObject(redisKey);
		// if (CollectionUtils.isEmpty(list)) {
		// 	// 查数据库
		// 	list = pileConnectorInfoMapper.getUniAppConnectorList(stationId);
		// 	if (CollectionUtils.isNotEmpty(list)) {
		// 		redisCache.setCacheObject(redisKey, list, 5, TimeUnit.MINUTES);
		// 	}
		// }
		return pileConnectorInfoMapper.getUniAppConnectorList(stationId);
	}

	public List<ConnectorInfoVO> getConnectorListForLianLian(Long stationId) {
		return getUniAppConnectorList(stationId);
	}

	@Override
	public List<ConnectorInfoVO> selectConnectorInfoList(String pileSn) {
		// 查询充电桩型号信息
		PileModelInfoVO pileModelInfoVO = pileModelInfoService.getPileModelInfoByPileSn(pileSn);

		List<PileConnectorInfo> connectorList = selectPileConnectorInfoList(pileSn);
		List<ConnectorInfoVO> connectorInfoList = Lists.newArrayList();
		if (CollectionUtils.isNotEmpty(connectorList)) {
			for (PileConnectorInfo connectorInfo : connectorList) {
				ConnectorInfoVO infoVO = ConnectorInfoVO.builder()
						.connectorCode(StringUtils.replace(connectorInfo.getPileConnectorCode(), pileSn, ""))
						.pileConnectorCode(connectorInfo.getPileConnectorCode())
						.connectorStatus(connectorInfo.getStatus())
						.build();
				if (pileModelInfoVO != null) {
					infoVO.setChargingType(pileModelInfoVO.getSpeedType());
					infoVO.setRatedPower(pileModelInfoVO.getRatedPower());
					infoVO.setRatedCurrent(pileModelInfoVO.getRatedCurrent());
					infoVO.setRatedVoltage(pileModelInfoVO.getRatedVoltage());
				}
				connectorInfoList.add(infoVO);
			}
		}
		return connectorInfoList;
	}

	@Override
	public PageResponse selectStationConnectorList(QueryConnectorListDTO dto) {
		PageResponse response = getUniAppConnectorInfoListByParams(dto);
		return response;
	}

	/**
	 * 查询充电枪口的实时数据
	 */
	private void queryRealTimeData(List<PileConnectorInfoVO> pileConnectorInfoList) {
		if (CollectionUtils.isEmpty(pileConnectorInfoList)) {
			return;
		}

		// 获取枪口的日志记录
		for (PileConnectorInfoVO pileConnectorInfoVO : pileConnectorInfoList) {
			// 从redis中获取实时数据信息
			String orderCode = pileConnectorInfoVO.getOrderCode();
			if (StringUtils.isNotBlank(orderCode)) {
				OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
				List<RealTimeMonitorData> chargingRealTimeDataList = orderBasicInfoService.getChargingRealTimeData(orderBasicInfo.getTransactionCode());
				RealTimeMonitorData realTimeMonitorData = chargingRealTimeDataList.get(0);
				BigDecimal outputVoltage = new BigDecimal(realTimeMonitorData.getOutputVoltage());
				pileConnectorInfoVO.setVoltage(outputVoltage);
				BigDecimal outputCurrent = new BigDecimal(realTimeMonitorData.getOutputCurrent());
				pileConnectorInfoVO.setCurrent(outputCurrent);
				pileConnectorInfoVO.setSOC(realTimeMonitorData.getSOC()); // 充电百分比
				pileConnectorInfoVO.setChargingAmount(new BigDecimal(realTimeMonitorData.getChargingAmount()));
				pileConnectorInfoVO.setChargingDegree(new BigDecimal(realTimeMonitorData.getChargingDegree()));
				pileConnectorInfoVO.setGunLineTemperature(realTimeMonitorData.getGunLineTemperature()); // 枪线温度
				pileConnectorInfoVO.setTimeRemaining(realTimeMonitorData.getTimeRemaining()); // 剩余时间
				pileConnectorInfoVO.setChargingTime(realTimeMonitorData.getSumChargingTime()); // 已充时长
				// 计算实时功率（单位：kw）
				BigDecimal instantPowerTemp = outputVoltage.multiply(outputCurrent);
				BigDecimal instantPower = instantPowerTemp.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
				pileConnectorInfoVO.setInstantPower(instantPower);
				log.info("枪口实时数据：{}", JSONObject.toJSONString(pileConnectorInfoVO));
			}

			if (checkPileOffLine(pileConnectorInfoVO.getPileSn())) {
				// 最后收到消息的时间在1分钟前，则返回给前端枪口离线
				pileConnectorInfoVO.setStatus(Integer.valueOf(PileConnectorDataBaseStatusEnum.OFF_NETWORK.getValue()));
				// 并修改数据库状态为离线
				updateConnectorStatusByPileSn(pileConnectorInfoVO.getPileSn(), PileConnectorDataBaseStatusEnum.OFF_NETWORK.getValue());
			}
		}
	}

	/**
	 * 通过桩编号修改枪口状态
	 * 仅用于登录逻辑使用
	 *
	 * @param pileSn 充电桩编号
	 * @param status 充电桩枪口状态
	 */
	public int updateConnectorStatusByPileSn(String pileSn, String status) {
		if (StringUtils.isBlank(pileSn) || StringUtils.isBlank(status)) {
			return 0;
		}
		// 通过pileSn查询枪口列表
		List<PileConnectorInfo> connectorInfoList = selectPileConnectorInfoList(pileSn);
		if (CollectionUtils.isEmpty(connectorInfoList)) {
			return 0;
		}
		int i = 0;
		for (PileConnectorInfo connectorInfo : connectorInfoList) {
			i = i + updateConnectorStatus(connectorInfo.getPileConnectorCode(), status);
		}
		return i;
	}

	/**
	 * 修改枪口状态
	 * 所有修改枪口状态的都要使用这个方法，和数据库交互只有这一个口子
	 *
	 * @param pileConnectorCode 枪口编号 桩编号+枪口号
	 * @param status        状态 0：离网 (默认)；1：空闲；2：占用（未充电）；3：占用（充电中）；4：占用（预约锁定） ；255：故障
	 */
	@Override
	public int updateConnectorStatus(String pileConnectorCode, String status) {
		int num = 0;
		if (StringUtils.isBlank(pileConnectorCode) || StringUtils.isBlank(status)) {
			return num;
		}
		String redisKey = CacheConstants.PILE_CONNECTOR_STATUS_KEY + pileConnectorCode;
		String redisStatus = redisCache.getCacheObject(redisKey);
		// log.info("修改充电桩枪口状态 缓存状态：{}, 传来的状态：{}", redisStatus, status);
		if (!StringUtils.equals(redisStatus, status)) {
			log.info("更新枪口状态 枪口编号:{}, 缓存状态：{}, 状态值:{}, 状态:{}", pileConnectorCode, redisStatus, status, PileConnectorDataBaseStatusEnum.getStatusDescription(status));
			String pileSn = pileConnectorCode.substring(0, pileConnectorCode.length() - 2);
			// 只修改一个枪口的状态
			num = pileConnectorInfoMapper.updateConnectorStatus(pileConnectorCode, status);
			deleteRedisByPileSn(pileSn);
			redisCache.setCacheObject(redisKey, status);

			// TODO 推送联联平台 设备状态变化推送接口  ConnectorStatusInfo

		}
		return num;
	}

	/**
	 * 批量获取桩状态
	 * 桩的状态有 在线 离线 故障
	 *
	 * @param pileSnList 桩编号列表
	 * @return key:桩编号; value:状态
	 */
	@Override
	public Map<String, String> getPileStatus(List<String> pileSnList) {
		StopWatch watch = new StopWatch("批量获取桩状态");
		Map<String, String> resultMap = Maps.newHashMap();
		for (String pileSn : pileSnList) {
			String pileStatus = "";

			// 标识桩故障或者离线
			boolean flag = false;
			// 判断故障状态
			List<PileConnectorInfo> connectorList = selectPileConnectorInfoList(pileSn); // 获取枪口信息
			List<String> connectorStatusList = connectorList.stream().map(PileConnectorInfo::getStatus).collect(Collectors.toList());
			// 桩下面的枪口，任意一个故障，桩的状态就是故障
			if (connectorStatusList.contains(PileConnectorDataBaseStatusEnum.FAULT.getValue())) {
				pileStatus = PileStatusEnum.FAULT.getValue();
				flag = true;
			}

			// 判断离线状态 显示优先级 离线>故障
			// if (checkPileOffLine(pileSn)) {
			// 	pileStatus = PileStatusEnum.OFF_LINE.getValue();
			// 	flag = true;
			// }

			// 2023年1月10日11点32分 改成如果枪口离线，那么充电桩就是离线
			if (connectorStatusList.contains(PileConnectorDataBaseStatusEnum.OFF_NETWORK.getValue())) {
				pileStatus = PileStatusEnum.OFF_LINE.getValue();
				flag = true;
				// 异步将此桩正在进行充电的订单状态改为 异常
				CompletableFuture.runAsync(() -> {
					orderBasicInfoService.updateOrderStatusAsAbnormal(pileSn);
				});
			}

			// 没有故障或者离线，就是在线状态
			if (!flag) {
				pileStatus = PileStatusEnum.ON_LINE.getValue();
			}

			resultMap.put(pileSn, pileStatus);
		}
		return resultMap;
	}

	@Override
	public PileConnectorInfoVO getPileConnectorInfoByConnectorCode(String pileConnectorCode) {
		return pileConnectorInfoMapper.getPileConnectorInfoByConnectorCode(pileConnectorCode);
	}

	/**
	 * 判断充电桩是否离线
	 *
	 * @param pileSn 桩编号
	 * @return true离线
	 */
	private boolean checkPileOffLine(String pileSn) {
		// 获取桩最后连接时间，最后连接到平台的时间在1分钟之前，判定为离线
		String lastConnectionTime = redisCache.getCacheObject(CacheConstants.PILE_LAST_CONNECTION + pileSn);
		if (StringUtils.isBlank(lastConnectionTime)) {
			// 没有最后连接时间，返回离线
			return true;
		}
		long l = DateUtils.intervalTime(lastConnectionTime, DateUtils.getTime());
		return l >= 1L;
	}

	/**
	 * 根据站点id查询快、慢充设备数量
	 * @param stationId
	 * @return
	 */
	public Map<String, Integer> getPileTypeNum(Long stationId) {
		int fastTotal = 0;
		int fastFree = 0;
		int slowTotal = 0;
		int slowFree = 0;
		List<ConnectorInfoVO> connectorList = getUniAppConnectorList(stationId);
		for (ConnectorInfoVO connectorVO : connectorList) {
			if (StringUtils.equals(connectorVO.getChargingType(), Constants.ONE)) {
				// 快充
				fastTotal += 1;
				if (StringUtils.equals(connectorVO.getConnectorStatus(), Constants.ONE)) {
					fastFree += 1;
				}
			} else {
				// 慢充
				slowTotal += 1;
				if (StringUtils.equals(connectorVO.getConnectorStatus(), Constants.ONE)) {
					slowFree += 1;
				}
			}
		}
		Map<String, Integer> map = new LinkedHashMap<>();
		map.put("fastTotal", fastTotal);
		map.put("fastFree", fastFree);
		map.put("slowTotal", slowTotal);
		map.put("slowFree", slowFree);

		return map;
	}
}
