package com.jsowell.pile.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.entity.SysDept;
import com.jsowell.common.core.domain.entity.SysUser;
import com.jsowell.common.core.domain.vo.AuthorizedDeptVO;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.thirdparty.BusinessInformationExchangeEnum;
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.*;
import com.jsowell.common.util.ip.AddressUtils;
import com.jsowell.pile.domain.PileBasicInfo;
import com.jsowell.pile.domain.PileStationInfo;
import com.jsowell.pile.domain.SettleOrderReport;
import com.jsowell.pile.domain.ThirdpartyParkingConfig;
import com.jsowell.pile.dto.*;
import com.jsowell.pile.dto.amap.GetStationInfoDTO;
import com.jsowell.pile.dto.lutongyunting.BindParkingPlatformDTO;
import com.jsowell.pile.dto.ningxiajiaotou.NXJTQueryStationInfoDTO;
import com.jsowell.pile.mapper.PileStationInfoMapper;
import com.jsowell.pile.service.*;
import com.jsowell.pile.util.UserUtils;
import com.jsowell.pile.vo.SupStationStatsVO;
import com.jsowell.pile.vo.base.*;
import com.jsowell.pile.vo.ningxiajiaotou.NXJTStationInfoVO;
import com.jsowell.pile.vo.uniapp.business.StationStatisticsInfosVO;
import com.jsowell.pile.vo.uniapp.customer.CurrentTimePriceDetails;
import com.jsowell.pile.vo.web.MerchantOrderReportVO;
import com.jsowell.pile.vo.web.PileStationVO;
import com.jsowell.system.service.SysDeptService;
import com.jsowell.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 充电站信息Service业务层处理
 *
 * @author jsowell
 * @date 2022-08-30
 */
@Slf4j
@Service
public class PileStationInfoServiceImpl implements PileStationInfoService {
	@Autowired
	private PileStationInfoMapper pileStationInfoMapper;

	@Autowired
	private PileConnectorInfoService pileConnectorInfoService;

	@Autowired
	private PileBillingTemplateService pileBillingTemplateService;

	@Autowired
	private PileMerchantInfoService pileMerchantInfoService;

	@Autowired
	private SysDeptService sysDeptService;

	@Autowired
	private PileBasicInfoService pileBasicInfoService;

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private SysUserService userService;

	@Autowired
	private ThirdPartyParkingConfigService parkingConfigService;

	@Autowired
	private OrderBasicInfoService orderBasicInfoService;

	@Autowired
	private SettleOrderReportService settleOrderReportService;


	/**
	 * 查询充电站信息
	 *
	 * @param id 充电站信息主键
	 * @return 充电站信息
	 */
	@Override
	public PileStationInfo selectPileStationInfoById(Long id) {
		// 加缓存
		String redisKey = CacheConstants.SELECT_PILE_STATION_INFO_BY_ID + id;
		PileStationInfo pileStationInfo = redisCache.getCacheObject(redisKey);
		if (pileStationInfo == null) {
			// 查数据库
			pileStationInfo = pileStationInfoMapper.selectPileStationInfoById(id);
			redisCache.setCacheObject(redisKey, pileStationInfo, 15, TimeUnit.MINUTES);
		}
		return pileStationInfo;
	}

	/**
	 * 查询站点基本资料
	 * 加缓存
	 * @param stationId
	 * @return
	 */
	@Override
	public PileStationVO getStationInfo(String stationId) {
		PileStationVO vo = new PileStationVO();
		PileStationInfo pileStationInfo = selectPileStationInfoById(Long.parseLong(stationId));
		// 查计费模板
		CurrentTimePriceDetails currentTimePriceDetails = pileBillingTemplateService.getCurrentTimePriceDetails(stationId);
		if (currentTimePriceDetails != null) {
			String electricityPrice = currentTimePriceDetails.getElectricityPrice();
			electricityPrice = StringUtils.isBlank(electricityPrice) ? "0" : electricityPrice;

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

			vo.setElectricityPrice(new BigDecimal(electricityPrice));
			vo.setServicePrice(new BigDecimal(servicePrice));

			if (StringUtils.isNotBlank(String.valueOf(currentTimePriceDetails.getFreeTime()))) {
				vo.setFreeTime(currentTimePriceDetails.getFreeTime());
			}
			if (StringUtils.isNotBlank(String.valueOf(currentTimePriceDetails.getOccupyFee()))) {
				vo.setOccupyFee(currentTimePriceDetails.getOccupyFee());
			}
		}

		if (pileStationInfo != null) {
			vo.setMerchantId(pileStationInfo.getMerchantId().toString());
			vo.setStationName(pileStationInfo.getStationName());
			vo.setId(pileStationInfo.getId().toString());
			vo.setAreaCode(pileStationInfo.getAreaCode());
			vo.setAddress(pileStationInfo.getAddress());
			if (StringUtils.isNotBlank(pileStationInfo.getParkingId())) {
				vo.setParkingId(pileStationInfo.getParkingId());
			}
			if (StringUtils.isNotBlank(pileStationInfo.getQrcodePrefix())) {
				vo.setQrcodePrefix(pileStationInfo.getQrcodePrefix());
			}
			if (StringUtils.isNotBlank(pileStationInfo.getParkingNumber())) {
				vo.setParkingNumber(pileStationInfo.getParkingNumber());
			}
			if (StringUtils.isNotBlank(pileStationInfo.getParkFeeDescribe())) {
				vo.setParkFeeDescribe(pileStationInfo.getParkFeeDescribe());
			}
			if (StringUtils.isNotBlank(pileStationInfo.getAccountNumber())) {
				vo.setAccountNumber(pileStationInfo.getAccountNumber());
			}
			if (StringUtils.isNotBlank(String.valueOf(pileStationInfo.getCapacity()))) {
				vo.setCapacity(pileStationInfo.getCapacity());
			}
			if (StringUtils.isNotBlank(pileStationInfo.getOperatorName())) {
				vo.setOperatorName(pileStationInfo.getOperatorName());
			}
			if (StringUtils.isNotBlank(pileStationInfo.getAMapStationName())) {
				vo.setAMapStationName(pileStationInfo.getAMapStationName());
			}
			vo.setMerchantAdminName(pileStationInfo.getStationAdminName());
			vo.setStationStatus(Integer.parseInt(pileStationInfo.getStationStatus()));
			vo.setStationType(pileStationInfo.getStationType());
			vo.setCreateTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, pileStationInfo.getCreateTime()));
			vo.setStationTel(pileStationInfo.getStationTel());
			vo.setMatchCars(pileStationInfo.getMatchCars());
			if (StringUtils.isNotBlank(pileStationInfo.getMatchCars())) {
				vo.setSelectMatchCars(Lists.newArrayList(pileStationInfo.getMatchCars().split(",")));
			}
			vo.setStationLat(pileStationInfo.getStationLat());
			vo.setStationLng(pileStationInfo.getStationLng());
			vo.setCountryCode(pileStationInfo.getCountryCode());
			vo.setConstruction(pileStationInfo.getConstruction());
			vo.setBusinessHours(pileStationInfo.getBusinessHours());
			// vo.setOrganizationCode(pileStationInfo.getor);
			vo.setPublicFlag(pileStationInfo.getPublicFlag());
			vo.setOpenFlag(pileStationInfo.getOpenFlag());
			vo.setOpenAllDay(pileStationInfo.getOpenAllDay());
			vo.setDeptId(pileStationInfo.getDeptId());
			if (StringUtils.isNotBlank(pileStationInfo.getPictures())) {
				vo.setPictures(pileStationInfo.getPictures());
				vo.setPictureList(Lists.newArrayList(pileStationInfo.getPictures().split(",")));
			}
		}
		return vo;
	}

	/**
	 * 通过充电桩枪口编号查询充电站信息
	 * @param pileConnectorCode 充电桩枪口编号
	 * @return 充电站信息
	 */
	@Override
	public PileStationVO getStationInfoByPileConnectorCode(String pileConnectorCode) {
		if (StringUtils.isBlank(pileConnectorCode)) {
			return null;
		}
		String pileSn = StringUtils.substring(pileConnectorCode, 0, 14);
		return getStationInfoByPileSn(pileSn);
	}

	/**
	 * 通过充电桩sn查询充电站信息
	 * @param pileSn 充电桩sn
	 * @return 充电站信息
	 */
	@Override
	public PileStationVO getStationInfoByPileSn(String pileSn) {
		// 通过pileSn查询充电桩（缓存方法）
		PileInfoVO pileInfoVO = pileBasicInfoService.selectPileInfoBySn(pileSn);
		if (pileInfoVO == null) {
			return null;
		}
		// 通过stationId查询充电站信息（缓存方法）
		PileStationVO stationInfo = getStationInfo(pileInfoVO.getStationId());
		return stationInfo;
	}

	@Override
	public List<ThirdPartyStationInfoVO> getStationInfosByThirdParty(QueryStationInfoDTO dto) {
		// PageUtils.startPage(pageNum, pageSize);
		return pileStationInfoMapper.getStationInfoForLianLian(dto);
	}

	@Override
	public List<PileStationInfo> getStationInfosByAmap(GetStationInfoDTO dto) {
		return pileStationInfoMapper.getStationInfoForAmap(dto);
	}

	@Override
	public List<String> queryByStationDeptIds(List<String> stationIds) {
		return pileStationInfoMapper.queryByStationDeptIds(stationIds);
	}

	/**
	 * 查询充电站信息列表
	 *
	 * @param pileStationInfo 充电站信息
	 * @return 充电站信息
	 */
	@Override
	public List<PileStationInfo> selectPileStationInfoList(PileStationInfo pileStationInfo) {
		return pileStationInfoMapper.selectPileStationInfoList(pileStationInfo);
	}

	/**
	 * 通过运营商id查询站点信息
	 *
	 * @param merchantId 运营商id
	 * @return 站点信息列表
	 */
    @Override
    public List<PileStationInfo> selectStationListByMerchantId(Long merchantId) {
        return pileStationInfoMapper.selectStationListByMerchantId(merchantId);
    }

    /**
	 * 新增充电站信息
	 *
	 * @param pileStationInfo 充电站信息
	 * @return 结果
	 */
	@Override

	public int insertPileStationInfo(PileStationInfo pileStationInfo) {
		pileStationInfo.setCreateTime(DateUtils.getNowDate());
		pileStationInfo.setCreateBy(SecurityUtils.getUsername());
		return pileStationInfoMapper.insertPileStationInfo(pileStationInfo);
	}

	/**
	 * 快速建站
	 * @param dto
	 * @return
	 */
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public int fastCreateStation(FastCreateStationDTO dto) {
		MerchantInfoVO merchantInfo = pileMerchantInfoService.getMerchantInfoVO(dto.getMerchantId());
		if (merchantInfo == null) {
			return 0;
		}

		// 创建站点对应部门
		SysDept dept = sysDeptService.createStationDept(Long.valueOf(merchantInfo.getDeptId()), dto.getStationName(), dto.getStationAdminName(), dto.getStationTel());

		PileStationInfo pileStationInfo = new PileStationInfo();
		pileStationInfo.setDeptId(String.valueOf(dept.getDeptId()));
		// 前端输入信息
		pileStationInfo.setMerchantId(Long.valueOf(dto.getMerchantId()));
		pileStationInfo.setStationName(StringUtils.trim(dto.getStationName()));
		pileStationInfo.setAddress(StringUtils.trim(dto.getAddress()));
		pileStationInfo.setAreaCode(StringUtils.trim(dto.getAreaCode()));
		pileStationInfo.setCapacity(BigDecimal.ZERO); // 容量
		pileStationInfo.setStationTel(StringUtils.trim(dto.getStationTel()));
		pileStationInfo.setStationAdminName(StringUtils.trim(dto.getStationAdminName()));
		// 获取经纬度
		Map<String, String> longitudeAndLatitude = AddressUtils.getLongitudeAndLatitude(dto.getAreaCode(), dto.getAddress());
		if (longitudeAndLatitude != null) {
			pileStationInfo.setStationLng(longitudeAndLatitude.get("lng"));
			pileStationInfo.setStationLat(longitudeAndLatitude.get("lat"));
		}
		pileStationInfo.setCreateBy(SecurityUtils.getUsername());
		int i = pileStationInfoMapper.insertPileStationInfo(pileStationInfo);
		return i;
	}

	/**
	 * 修改充电站信息
	 *
	 * @param pileStationInfo 充电站信息
	 * @return 结果
	 */
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public int updatePileStationInfo(PileStationInfo pileStationInfo) {
		// 清缓存
		String redisKey = CacheConstants.SELECT_PILE_STATION_INFO_BY_ID + pileStationInfo.getId();
		redisCache.deleteObject(redisKey);

		String templateRedisKey = CacheConstants.QUERY_STATION_BILLING_TEMPLATE_LIST + pileStationInfo.getId();
		redisCache.deleteObject(templateRedisKey);

		// 先查询一下当前数据库的充电站数据
		PileStationInfo queryStationInfo = selectPileStationInfoById(pileStationInfo.getId());
		String oldMerchantId = String.valueOf(queryStationInfo.getMerchantId());
		String newMerchantId = String.valueOf(pileStationInfo.getMerchantId());
		// 对比一下运营商有没有变化
		if (!StringUtils.equals(oldMerchantId, newMerchantId)) {
			// 新旧运营商不一致，执行站点更换运营商逻辑
			stationUpdateMerchant(pileStationInfo, newMerchantId);
		} else {
			// 查询部门
			SysDept sysDept = sysDeptService.selectDeptById(Long.parseLong(pileStationInfo.getDeptId()));
			// 同步组织中的名称，联系人，电话
			if (sysDept != null) {
				sysDept.setDeptName(pileStationInfo.getStationName());
				sysDept.setLeader(pileStationInfo.getStationAdminName());
				sysDept.setPhone(pileStationInfo.getStationTel());
				sysDept.setUpdateTime(DateUtils.getNowDate());
				sysDept.setDeptLevel("3");
				// 修改站点对应的部门
				sysDeptService.updateDept(sysDept);
			}
		}

		pileStationInfo.setUpdateBy(SecurityUtils.getUsername());
		pileStationInfo.setUpdateTime(DateUtils.getNowDate());
		int i = pileStationInfoMapper.updatePileStationInfo(pileStationInfo);

		// 再次清缓存
		redisCache.deleteObject(redisKey);
		return i;
	}

	/**
	 * 充电站更换运营商逻辑
	 */
	private void stationUpdateMerchant(PileStationInfo pileStationInfo, String newMerchantId) {
		/*
		修改充电桩所属运营商
		 */
		List<PileBasicInfo> pileInfoList = pileBasicInfoService.getPileListByStationId(String.valueOf(pileStationInfo.getId()));
		if (CollectionUtils.isNotEmpty(pileInfoList)) {
			List<Long> pileIdList = pileInfoList.stream().map(PileBasicInfo::getId).collect(Collectors.toList());
			// 修改桩基本信息
			pileBasicInfoService.updatePileMerchantBatch(pileIdList, newMerchantId);
		}

		/*
		 修改组织部门
		 */
		MerchantInfoVO merchantInfo = pileMerchantInfoService.getMerchantInfoVO(newMerchantId);
		if (merchantInfo != null) {
			// 创建一个新的站点对应部门
			SysDept dept = sysDeptService.createStationDept(Long.valueOf(merchantInfo.getDeptId()),
					pileStationInfo.getStationName(), pileStationInfo.getStationAdminName(), pileStationInfo.getStationTel());
			Long newDeptId = dept.getDeptId();

			// 修改账号归属部门
			SysUser user = new SysUser();
			user.setDeptId(Long.valueOf(pileStationInfo.getDeptId()));
			List<SysUser> userList = userService.selectUserList(user);
			if (CollectionUtils.isNotEmpty(userList)) {
				for (SysUser sysUser : userList) {
					sysUser.setDeptId(newDeptId);
					userService.updateUser(sysUser);
				}
			}

			// 逻辑删除老的部门
			sysDeptService.deleteDeptById(Long.parseLong(pileStationInfo.getDeptId()));

			// 设置新部门id
			pileStationInfo.setDeptId(String.valueOf(newDeptId));
		}

		/**
		 * 修改订单中的 merchantId
		 */
		orderBasicInfoService.updateMerchantByStationId(pileStationInfo.getId(), newMerchantId);

	}

	/**
	 * 批量删除充电站信息
	 *
	 * @param ids 需要删除的充电站信息主键
	 * @return 结果
	 */
	@Override
	public int deletePileStationInfoByIds(Long[] ids) {
		return pileStationInfoMapper.deletePileStationInfoByIds(ids);
	}

	/**
	 * 充电站列表信息
	 * @param dto 前台参数
	 * @return 充电站对象集合
	 */
	@Override
	// @DataScope(deptAlias = "t3")
	public List<PileStationVO> queryStationInfos(QueryStationDTO dto) {
		AuthorizedDeptVO authorizedMap = UserUtils.getAuthorizedMap();
		if (authorizedMap == null) {
			// 为空表示没有权限，返回空数组
			return Lists.newArrayList();
		}
		dto.setStationDeptIds(authorizedMap.getStationDeptIds());
		dto.setMerchantDeptIds(authorizedMap.getMerchantDeptIds());
		List<PileStationVO> list = pileStationInfoMapper.queryStationInfos(dto);
		return list;
	}

	/**
	 * uniApp查询充电站信息并通过经纬度排序
	 *
	 * @param dto 前台参数
	 * @return 充电站对象集合
	 */
	@Override
	public PageResponse uniAppQueryStationInfoList(QueryStationDTO dto) {
		int pageNum = dto.getPageNum() == 0 ? 1 : dto.getPageNum();
		int pageSize = dto.getPageSize() == 0 ? 10 : dto.getPageSize();

		// 小程序站点列表页只展示对外开放的站点
		dto.setPublicFlag(Constants.ONE);
		// 根据前台参数分页
		PageHelper.startPage(pageNum, pageSize);
		List<PileStationVO> list = pileStationInfoMapper.queryStationInfos(dto);
		PageInfo<PileStationVO> pageInfo = new PageInfo<>(list);

		List<StationInfoVO> stationVOList = Lists.newArrayList();
		StationInfoVO stationVO;
		String stationLng = dto.getStationLng();
		String stationLat = dto.getStationLat();
		double distance = 0d;
		for (PileStationVO pileStationVO : pageInfo.getList()) {
			stationVO = new StationInfoVO();
			if (StringUtils.isNotEmpty(stationLng) && StringUtils.isNotEmpty(stationLat)) {
				try{
					// 计算当前经纬度和站点之间的距离
					distance = DistanceUtils.getDistance(Double.parseDouble(stationLng), Double.parseDouble(stationLat),
							Double.parseDouble(pileStationVO.getStationLng()), Double.parseDouble(pileStationVO.getStationLat()));
					// 保留两位小数
					stationVO.setDistance(String.format("%.2f", distance));
				}catch (Exception e){
					stationVO.setDistance("0.00");
				}

			}
			stationVO.setStationId(pileStationVO.getId());
			stationVO.setStationName(pileStationVO.getStationName());
			stationVO.setStationAddress(pileStationVO.getAddress());
			stationVO.setStationLat(pileStationVO.getStationLat());
			stationVO.setStationLng(pileStationVO.getStationLng());
			if (StringUtils.isNotBlank(pileStationVO.getParkFeeDescribe())) {
				stationVO.setParkFeeDescribe(pileStationVO.getParkFeeDescribe());
			}
			// 站点联系电话
			if (StringUtils.isNotBlank(pileStationVO.getStationTel())) {
				stationVO.setStationTel(pileStationVO.getStationTel());
			}
			// 站点图片
			if (StringUtils.isNotBlank(pileStationVO.getPictures())) {
				stationVO.setStationImgList(Lists.newArrayList(pileStationVO.getPictures().split(",")));
			}

			// 查询快慢充数量
			Map<String, Integer> map = pileConnectorInfoService.getPileTypeNum(Long.parseLong(pileStationVO.getId()));
			Integer fastFree = map.get("fastFree");
			Integer slowFree = map.get("slowFree");
			stationVO.setFastTotal(map.get("fastTotal"));
			stationVO.setFastFree(fastFree);
			stationVO.setSlowTotal(map.get("slowTotal"));
			stationVO.setSlowFree(map.get("slowFree"));
			stationVO.setTotalFree(fastFree + slowFree);

			// 查询当前时段电费
			CurrentTimePriceDetails currentTimePriceDetails = pileBillingTemplateService.getCurrentTimePriceDetails(stationVO.getStationId());
			if (currentTimePriceDetails != null) {
				stationVO.setElectricityPrice(currentTimePriceDetails.getElectricityPrice());
				stationVO.setServicePrice(currentTimePriceDetails.getServicePrice());
				stationVO.setTotalPrice(currentTimePriceDetails.getTotalPrice());
				stationVO.setFreeTime(currentTimePriceDetails.getFreeTime());
				stationVO.setOccupyFee(currentTimePriceDetails.getOccupyFee());
				// vip价
				stationVO.setVipElectricityPrice(currentTimePriceDetails.getVipElectricityPrice());
				stationVO.setVipServicePrice(currentTimePriceDetails.getVipServicePrice());
				stationVO.setVipTotalPrice(currentTimePriceDetails.getVipTotalPrice());
			}
			stationVOList.add(stationVO);
		}

		if (distance != 0.00) {
			// 对集合按照距离排序，距离小的在前
			stationVOList.sort((o1, o2) -> {
				Double a = Double.valueOf(o1.getDistance());
				Double b = Double.valueOf(o2.getDistance());
				return a.compareTo(b);
			});
		}

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

	/**
	 * 根据站点id查询运营商配置的汇付会员id
	 * @param stationId
	 * @return
	 */
	@Override
	public String selectAdapayMemberId(String stationId) {
		return null;
	}

	@Override
	public int updateAmapFlag(String stationId, String amapFlag) {
		return pileStationInfoMapper.updateAmapFlag(stationId, amapFlag);
	}

	/**
	 * 通过站点部门id查询站点id
	 * @param deptId
	 * @return
	 */
    @Override
    public List<String> getIdsByDeptId(String deptId) {
        return pileStationInfoMapper.getIdsByDeptId(deptId);
    }

	/**
	 * 绑定停车系统平台
	 * @param dto
	 */
    @Override
    public int bindParkingPlatform(BindParkingPlatformDTO dto) {
		String parkingId = dto.getParkingId();
		String stationId = dto.getStationId();
		// 先根据停车系统平台查询一下是否有数据
		ThirdpartyParkingConfig basicInfo = parkingConfigService.selectByPrimaryKey(Integer.parseInt(parkingId));
		if (basicInfo == null) {
			throw new BusinessException(ReturnCodeEnum.CODE_QUERY_PARKING_INFO_IS_NULL);
		}
		// 先删除缓存
		String redisKey = CacheConstants.SELECT_PILE_STATION_INFO_BY_ID + stationId;
		redisCache.deleteObject(redisKey);
		// 再将站点信息表中绑定上parkingId
        return pileStationInfoMapper.updateParkingPlatform(parkingId, stationId);
    }

	/**
	 * 查询充电站下拉列表
	 * @param dto
	 * @return
	 */
	@Override
	public List<PileStationVO> getStationSelectList(QueryStationDTO dto) {
		AuthorizedDeptVO authorizedMap = UserUtils.getAuthorizedMap();
		if (authorizedMap == null) {
			// 为空表示没有权限，返回空数组
			return Lists.newArrayList();
		}
		dto.setStationDeptIds(authorizedMap.getStationDeptIds());
		dto.setMerchantDeptIds(authorizedMap.getMerchantDeptIds());

		return pileStationInfoMapper.getStationSelectList(dto);
	}

	/**
	 * 宁夏交投查询充电站信息
	 * @param dto
	 * @return
	 */
	@Override
	public List<NXJTStationInfoVO> NXJTQueryStationsInfo(NXJTQueryStationInfoDTO dto) {
		return pileStationInfoMapper.NXJTQueryStationsInfo(dto);
	}

    @Override
    public PileStationInfo queryInfoByDeptId(String deptId) {
		if (StringUtils.isBlank(deptId)) {
			return null;
		}
        return pileStationInfoMapper.queryInfoByDeptId(deptId);
    }

    @Override
    public List<PileStationInfo> getStationInfosByMerchantIds(List<String> merchantIds){
		return pileStationInfoMapper.getStationInfosByMerchantIds(merchantIds);
	}

	/**
	 * 获取站点统计信息
	 * @param dto
	 */
	@Override
	public List<StationStatisticsInfosVO> getStationStatisticsInfos(StationStatisticsInfoDTO dto) {
		String merchantId = dto.getMerchantId();
		// 获取当前登录账号的运营商权限
		List<MerchantInfoVO> merchantInfoVOList = UserUtils.getMerchantInfoVOList();
		List<String> merchantIds = new ArrayList<>();
		List<StationStatisticsInfosVO> resultList = new ArrayList<>();
		if (StringUtils.isBlank(merchantId)) {
			merchantIds = merchantInfoVOList.stream()
					.map(MerchantInfoVO::getMerchantId)
					.collect(Collectors.toList());
		}else {
			merchantIds.add(merchantId);
		}
		// 根据运营商ids查出所有站点id
		List<PileStationInfo> pileStationInfos = getStationInfosByMerchantIds(merchantIds);
		if (CollectionUtils.isEmpty(pileStationInfos)) {
			// 未查到该运营商下的站点
			throw new BusinessException(ReturnCodeEnum.CODE_SELECT_INFO_IS_NULL);
		}
		List<String> stationIds = pileStationInfos.stream()
				.map(x -> String.valueOf(x.getId()))
				.collect(Collectors.toList());
		// 创建DecimalFormat对象并设置格式
		DecimalFormat df = new DecimalFormat("0.00%");
		// 根据站点ids查询站点营收报表
		List<SettleOrderReport> list = settleOrderReportService.queryOrderReport(stationIds, dto.getStartTime(), dto.getEndTime());
		if (CollectionUtils.isEmpty(list)) {
			throw new BusinessException(ReturnCodeEnum.CODE_SELECT_INFO_IS_NULL);
		}
		// 根据站点id分组，将充电度数、充电金额、充电次数进行累加
		Map<String, SettleOrderReport> collect = list.stream()
				.sorted(Comparator.comparing(SettleOrderReport::getStationId))
				// .filter(vo -> vo.getChargingTime() != null && vo.getTotalPower() != null)
				.collect(Collectors.toMap(SettleOrderReport::getStationId, Function.identity(),
						(a, b) -> {
							a.setUseElectricity(a.getUseElectricity().add(b.getUseElectricity()));
							a.setTotalAmount(a.getTotalAmount().add(b.getTotalAmount()));
							a.setChargeNum(String.valueOf(Integer.parseInt(a.getChargeNum()) + Integer.parseInt(b.getChargeNum())));
							return a;
						}));


		for (Map.Entry<String, SettleOrderReport> entry: collect.entrySet()) {
			String stationId = entry.getKey();
			SettleOrderReport report = entry.getValue();

			// 查询枪口列表
			List<ConnectorInfoVO> uniAppConnectorList = pileConnectorInfoService.getUniAppConnectorList(Long.parseLong(stationId));

			int chargingConnectorNum = Constants.zero; // 充电中
			int freeConnectorNum = Constants.zero; // 空闲
			int occupiedConnectorNum = Constants.zero; // 占用
			int hangingConnectorNum = Constants.zero; // 挂起
			int offlineConnectorNum = Constants.zero; // 离线
			int faultConnectorNum = Constants.zero; // 故障

			for (ConnectorInfoVO connectorInfoVO : uniAppConnectorList) {
				String connectorStatus = connectorInfoVO.getConnectorStatus();
				if (StringUtils.equals(PileConnectorDataBaseStatusEnum.FREE.getValue(), connectorStatus)) {
					// 空闲
					freeConnectorNum += 1;
				}else if (StringUtils.equals(PileConnectorDataBaseStatusEnum.OCCUPIED_NOT_CHARGED.getValue(), connectorStatus)) {
					// 占用（未充电）
					occupiedConnectorNum += 1;
				}else if (StringUtils.equals(PileConnectorDataBaseStatusEnum.OCCUPIED_CHARGING.getValue(), connectorStatus)) {
					// 充电中
					chargingConnectorNum += 1;
				}else if (StringUtils.equals(PileConnectorDataBaseStatusEnum.OFF_NETWORK.getValue(), connectorStatus)) {
					// 离线
					offlineConnectorNum += 1;
				}else if(StringUtils.equals(PileConnectorDataBaseStatusEnum.FAULT.getValue(), connectorStatus)) {
					// 故障
					faultConnectorNum += 1;
				}
			}
			// 计算枪口可使用率
			int totalConnectorNum = uniAppConnectorList.size();
			double connectorAvailability = (double) freeConnectorNum / totalConnectorNum;
			String format = df.format(connectorAvailability);

			StationStatisticsInfosVO vo = StationStatisticsInfosVO.builder()
					.stationId(stationId)
					// .stationName(pileStationInfo.getStationName())
					.chargeDegree(report.getUseElectricity())
					.chargeAmount(report.getTotalAmount())
					.orderQuantity(Integer.parseInt(report.getChargeNum()))
					.connectorAvailability(format)
					.chargingConnectorNum(chargingConnectorNum)
					.freeConnectorNum(freeConnectorNum)
					.occupiedConnectorNum(occupiedConnectorNum)
					.hangingConnectorNum(hangingConnectorNum)
					.offlineConnectorNum(offlineConnectorNum)
					.faultConnectorNum(faultConnectorNum)
					.build();

			resultList.add(vo);
		}

		return resultList;
	}

}

