package com.jsowell.pile.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Bytes;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.vo.AuthorizedDeptVO;
import com.jsowell.common.enums.DelFlagEnum;
import com.jsowell.common.enums.ykc.BillingTimeEnum;
import com.jsowell.common.util.BytesUtil;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.SecurityUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.YKCUtils;
import com.jsowell.common.util.id.Seq;
import com.jsowell.pile.domain.PileBillingDetail;
import com.jsowell.pile.domain.PileBillingRelation;
import com.jsowell.pile.domain.PileBillingTemplate;
import com.jsowell.pile.dto.BillingTimeDTO;
import com.jsowell.pile.dto.CreateOrUpdateBillingTemplateDTO;
import com.jsowell.pile.dto.ImportBillingTemplateDTO;
import com.jsowell.pile.mapper.PileBillingTemplateMapper;
import com.jsowell.pile.service.IPileBasicInfoService;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.transaction.dto.BillingTemplateTransactionDTO;
import com.jsowell.pile.transaction.service.TransactionService;
import com.jsowell.pile.vo.uniapp.BillingPriceVO;
import com.jsowell.pile.vo.uniapp.CurrentTimePriceDetails;
import com.jsowell.pile.vo.web.BillingDetailVO;
import com.jsowell.pile.vo.web.BillingTemplateVO;
import com.jsowell.pile.vo.web.EchoBillingTemplateVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 计费模板Service业务层处理
 *
 * @author jsowell
 * @date 2022-09-20
 */
@Slf4j
@Service
public class PileBillingTemplateServiceImpl implements IPileBillingTemplateService {
	@Autowired
	private PileBillingTemplateMapper pileBillingTemplateMapper;

	@Autowired
	private TransactionService transactionService;

	@Autowired
	private IPileBasicInfoService pileBasicInfoService;

	/**
	 * 查询计费模板
	 *
	 * @param id 计费模板主键
	 * @return 计费模板
	 */
	@Override
	public PileBillingTemplate selectPileBillingTemplateById(Long id) {
		return pileBillingTemplateMapper.selectPileBillingTemplateById(id);
	}

	/**
	 * 查询计费模板列表
	 *
	 * @param pileBillingTemplate 计费模板
	 * @return 计费模板
	 */
	@Override
	public List<PileBillingTemplate> selectPileBillingTemplateList(PileBillingTemplate pileBillingTemplate) {
		return pileBillingTemplateMapper.selectPileBillingTemplateList(pileBillingTemplate);
	}

	/**
	 * 新增计费模板
	 *
	 * @param pileBillingTemplate 计费模板
	 * @return 结果
	 */
	@Transactional
	@Override
	public int insertPileBillingTemplate(PileBillingTemplate pileBillingTemplate) {
		pileBillingTemplate.setCreateTime(DateUtils.getNowDate());
		int rows = pileBillingTemplateMapper.insertPileBillingTemplate(pileBillingTemplate);
		insertPileBillingDetail(pileBillingTemplate);
		return rows;
	}

	/**
	 * 修改计费模板
	 *
	 * @param pileBillingTemplate 计费模板
	 * @return 结果
	 */
	@Transactional
	@Override
	public int updatePileBillingTemplate(PileBillingTemplate pileBillingTemplate) {
		return pileBillingTemplateMapper.updatePileBillingTemplate(pileBillingTemplate);
	}

	/**
	 * 批量删除计费模板
	 *
	 * @param ids 需要删除的计费模板主键
	 * @return 结果
	 */
	@Transactional
	@Override
	public int deletePileBillingTemplateByIds(Long[] ids) {
		// 查询计费模板详情列表
		List<PileBillingDetail> pileBillingDetails = pileBillingTemplateMapper.queryBillingDetailByTemplateIds(ids);
		if (CollectionUtils.isNotEmpty(pileBillingDetails)) {
			List<String> templateCodes = pileBillingDetails.stream().map(PileBillingDetail::getTemplateCode).collect(Collectors.toList());
			pileBillingTemplateMapper.deletePileBillingDetailByTemplateCodes(templateCodes);
		}
		return pileBillingTemplateMapper.deletePileBillingTemplateByIds(ids);
	}

	/**
	 * 删除计费模板信息
	 *
	 * @param id 计费模板主键
	 * @return 结果
	 */
	@Transactional
	@Override
	public int deletePileBillingTemplateById(Long id) {
		// pileBillingTemplateMapper.deletePileBillingDetailByTemplateCode(id);
		return pileBillingTemplateMapper.deletePileBillingTemplateById(id);
	}

	@Override
	public void createBillingTemplate(CreateOrUpdateBillingTemplateDTO dto) {
		// 生成计费模板编号
		String templateCode = Seq.getId();
		// 组装入库参数
		PileBillingTemplate billingTemplate = new PileBillingTemplate();
		billingTemplate.setName(dto.getName());
		billingTemplate.setType(String.valueOf(dto.getType()));
		billingTemplate.setRemark(dto.getRemark());
		billingTemplate.setTemplateCode(templateCode);
		billingTemplate.setCreateBy(SecurityUtils.getUsername());
		billingTemplate.setDelFlag(DelFlagEnum.normal.getValue());
		if (StringUtils.isBlank(dto.getStationId())) {
			// 公共模板标识（0-私有；1-公共）
			billingTemplate.setPublicFlag(Constants.ONE);
		} else {
			billingTemplate.setPublicFlag(Constants.ZERO);
		}

		// key为时间类型，value为时间描述
		Map<String, List<BillingTimeDTO>> map = dto.getTimeArray().stream()
				.collect(Collectors.groupingBy(BillingTimeDTO::getType));

		// 计费模板详情
		List<PileBillingDetail> detailList = Lists.newArrayList();
		PileBillingDetail detail = null;
		for (BillingTimeEnum billingTimeEnum : BillingTimeEnum.values()) {
			detail = new PileBillingDetail();
			detail.setTemplateCode(templateCode);
			String type = billingTimeEnum.getValue(); // 时段类型
			detail.setTimeType(type);
			Map<String, BigDecimal> priceMap = getPriceMap(dto, type);
			detail.setElectricityPrice(priceMap.get("electricityPrice"));
			detail.setServicePrice(priceMap.get("servicePrice"));
			List<BillingTimeDTO> entryValue = map.get(type);
			String applyTime = "";
			if (CollectionUtils.isNotEmpty(entryValue)) {
				applyTime = entryValue.stream()
						.map(x -> x.getStartTime() + "-" + x.getEndTime())
						.collect(Collectors.joining(","));
			}
			detail.setApplyTime(applyTime);
			detail.setCreateBy(SecurityUtils.getUsername());
			detailList.add(detail);
		}

		BillingTemplateTransactionDTO build = BillingTemplateTransactionDTO.builder()
				.billingTemplate(billingTemplate)
				.detailList(detailList)
				.build();
		// 入库
		transactionService.doCreateBillingTemplate(build);
	}

	@Override
	public void updateBillingTemplate(CreateOrUpdateBillingTemplateDTO dto) {
		PileBillingTemplate billingTemplate = selectPileBillingTemplateById(Long.valueOf(dto.getBillingTemplateId()));
		if (billingTemplate == null) {
			log.info("根据计费模板id：{}，查询为null。无法修改直接返回", dto.getBillingTemplateId());
			return;
		}
		billingTemplate.setName(dto.getName());
		billingTemplate.setType(String.valueOf(dto.getType()));
		billingTemplate.setRemark(dto.getRemark());
		billingTemplate.setUpdateBy(SecurityUtils.getUsername());

		// key为时间类型，value为时间描述
		Map<String, List<BillingTimeDTO>> map = dto.getTimeArray().stream()
				.collect(Collectors.groupingBy(BillingTimeDTO::getType));

		// 计费模板详情
		List<PileBillingDetail> detailList = Lists.newArrayList();
		PileBillingDetail detail = null;
		for (BillingTimeEnum billingTimeEnum : BillingTimeEnum.values()) {
			detail = new PileBillingDetail();
			detail.setTemplateCode(billingTemplate.getTemplateCode());
			String type = billingTimeEnum.getValue(); // 时段类型
			detail.setTimeType(type);
			Map<String, BigDecimal> priceMap = getPriceMap(dto, type);
			detail.setElectricityPrice(priceMap.get("electricityPrice"));
			detail.setServicePrice(priceMap.get("servicePrice"));
			List<BillingTimeDTO> entryValue = map.get(type);
			String applyTime = "";
			if (CollectionUtils.isNotEmpty(entryValue)) {
				applyTime = entryValue.stream()
						.map(x -> x.getStartTime() + "-" + x.getEndTime())
						.collect(Collectors.joining(","));
			}
			detail.setApplyTime(applyTime);
			detail.setCreateBy(SecurityUtils.getUsername());
			detailList.add(detail);
		}

		BillingTemplateTransactionDTO build = BillingTemplateTransactionDTO.builder()
				.billingTemplate(billingTemplate)
				.detailList(detailList)
				.build();
		// 入库
		transactionService.doUpdateBillingTemplate(build);
	}

	@Override
	public EchoBillingTemplateVO queryPileBillingTemplateById(Long id) {
		PileBillingTemplate pileBillingTemplate = selectPileBillingTemplateById(id);
		if (pileBillingTemplate == null) {
			return null;
		}
		EchoBillingTemplateVO result = new EchoBillingTemplateVO();
		result.setBillingTemplateId(String.valueOf(id));
		result.setName(pileBillingTemplate.getName());
		result.setRemark(pileBillingTemplate.getRemark());
		result.setType(pileBillingTemplate.getType());

		// 查计费模板详情
		List<PileBillingDetail> detailList = pileBillingTemplateMapper.queryBillingDetailByTemplateIds(new Long[]{id});
		if (CollectionUtils.isNotEmpty(detailList)) {
			List<BillingTimeDTO> timeArray = Lists.newArrayList();
			// 取出4个时间段类型
			for (PileBillingDetail billingDetail : detailList) {
				String type = billingDetail.getTimeType();
				BigDecimal electricityPrice = billingDetail.getElectricityPrice();
				BigDecimal servicePrice = billingDetail.getServicePrice();
				if (StringUtils.equals(type, BillingTimeEnum.SHARP.getValue())) {
					result.setElectricityPriceA(electricityPrice);
					result.setServicePriceA(servicePrice);
				} else if (StringUtils.equals(type, BillingTimeEnum.PEAK.getValue())) {
					result.setElectricityPriceB(electricityPrice);
					result.setServicePriceB(servicePrice);
				} else if (StringUtils.equals(type, BillingTimeEnum.FLAT.getValue())) {
					result.setElectricityPriceC(electricityPrice);
					result.setServicePriceC(servicePrice);
				} else if (StringUtils.equals(type, BillingTimeEnum.VALLEY.getValue())) {
					result.setElectricityPriceD(electricityPrice);
					result.setServicePriceD(servicePrice);
				}
				// 逗号拼接的时间段 00:00-01:30,01:30-04:00,23:30-24:00
				String applyTime = billingDetail.getApplyTime();
				if (StringUtils.isBlank(applyTime)) {
					continue;
				}
				List<String> list = Lists.newArrayList(applyTime.split(","));
				BillingTimeDTO timeDTO;
				for (String s : list) {
					String[] split = s.split("-");
					timeDTO = new BillingTimeDTO();
					timeDTO.setType(type);
					timeDTO.setStartTime(split[0]);
					timeDTO.setEndTime(split[1]);
					timeArray.add(timeDTO);
				}
			}
			// timeArray重新排序
			result.setTimeArray(timeArray.stream().sorted(Comparator.comparing(BillingTimeDTO::getStartTime)).collect(Collectors.toList()));
		}
		return result;
	}

	/**
	 * 通过站点id查询当前时间的收费详情
	 *
	 * @param stationId 站点id
	 */
	@Override
	public CurrentTimePriceDetails getCurrentTimePriceDetails(String stationId) {
		CurrentTimePriceDetails result = null;
		// 查询当前时段电费
		LocalTime localTime = LocalTime.now();
		String now = LocalTime.of(localTime.getHour(), localTime.getMinute(), localTime.getSecond()).toString();
		// 通过站点id查询计费模板
		BillingTemplateVO billingTemplateVO = pileBillingTemplateMapper.selectBillingTemplateByStationId(stationId);
		if (Objects.nonNull(billingTemplateVO)) {
			result = new CurrentTimePriceDetails();
			result.setTemplateCode(billingTemplateVO.getTemplateCode());
			result.setStationId(stationId);
			result.setDateTime(localTime.toString());

			List<BillingDetailVO> billingDetailList = billingTemplateVO.getBillingDetailList();
			for (BillingDetailVO detailVO : billingDetailList) {
				List<String> applyTimeList = detailVO.getApplyTime();
				for (String applyTime : applyTimeList) {
					boolean b = DateUtils.checkTime(now + "-" + now, applyTime);
					if (b) {
						// 将桩的费率存入stationVO
						BigDecimal electricityPrice = detailVO.getElectricityPrice();
						BigDecimal servicePrice = detailVO.getServicePrice();

						result.setElectricityPrice(electricityPrice.toString());
						result.setServicePrice(servicePrice.toString());
						result.setTotalPrice(electricityPrice.add(servicePrice).toString());
					}
				}
			}
		}
		log.info("通过站点id查询当前时间的收费详情 stationId:{}, result:{}", stationId, JSON.toJSONString(result));
		return result;
	}

	@Override
	public List<BillingTemplateVO> queryPublicBillingTemplateList() {
		return pileBillingTemplateMapper.queryPublicBillingTemplateList();
	}

	@Override
	public List<BillingTemplateVO> queryStationBillingTemplateList(String stationId) {
		if (StringUtils.isBlank(stationId)) {
			return Lists.newArrayList();
		}
		AuthorizedDeptVO authorizedMap = SecurityUtils.getAuthorizedMap();
		if (authorizedMap == null) {
			// 为空表示没有权限，返回空数组
			return Lists.newArrayList();
		}
		return pileBillingTemplateMapper.queryStationBillingTemplateList(stationId, authorizedMap.getStationDeptIds());
	}

	@Override
	public List<BillingTemplateVO> queryStationBillingTemplateListForUniApp(String stationId) {
		return pileBillingTemplateMapper.queryStationBillingTemplateListForUniApp(stationId);
	}

	/**
	 * 查询正在使用中的计费模板
	 * 1 发布时间不为null
	 * 2 最近发布的为正在使用中的
	 * @param stationId 站点id
	 * @return
	 */
	@Override
	public BillingTemplateVO queryUsedBillingTemplate(String stationId) {
		List<BillingTemplateVO> list = queryStationBillingTemplateListForUniApp(stationId);
		Optional<BillingTemplateVO> max = list.stream()
				.filter(x -> StringUtils.isNotBlank(x.getPublishTime()))
				.max(Comparator.comparing(BillingTemplateVO::getPublishTime));
		return max.orElse(null);
	}

	@Override
	public List<BillingPriceVO> queryBillingPrice(String stationId) {
		BillingTemplateVO billingTemplateVO = queryUsedBillingTemplate(stationId);
		if (billingTemplateVO == null) {
			return Lists.newArrayList();
		}
		EchoBillingTemplateVO echoBillingTemplateVO = queryPileBillingTemplateById(Long.parseLong(billingTemplateVO.getTemplateId()));
		List<BillingTimeDTO> timeArray = echoBillingTemplateVO.getTimeArray();
		log.info("计费模板时段:{}", JSONObject.toJSONString(timeArray));

		List<BillingPriceVO> resultList = Lists.newArrayList();
		for (BillingTimeDTO billingTimeDTO : timeArray) {
			BillingPriceVO vo = new BillingPriceVO();
			String type = billingTimeDTO.getType();
			if (StringUtils.equals(type, BillingTimeEnum.SHARP.getValue())) {
				vo.setElectricityPrice(billingTemplateVO.getSharpElectricityPrice().toString());
				vo.setServicePrice(billingTemplateVO.getSharpServicePrice().toString());
			} else if (StringUtils.equals(type, BillingTimeEnum.PEAK.getValue())) {
				vo.setElectricityPrice(billingTemplateVO.getPeakElectricityPrice().toString());
				vo.setServicePrice(billingTemplateVO.getPeakServicePrice().toString());
			} else if (StringUtils.equals(type, BillingTimeEnum.FLAT.getValue())) {
				vo.setElectricityPrice(billingTemplateVO.getFlatElectricityPrice().toString());
				vo.setServicePrice(billingTemplateVO.getFlatServicePrice().toString());
			} else if (StringUtils.equals(type, BillingTimeEnum.VALLEY.getValue())) {
				vo.setElectricityPrice(billingTemplateVO.getValleyElectricityPrice().toString());
				vo.setServicePrice(billingTemplateVO.getValleyServicePrice().toString());
			}
			// 总费用
			vo.setTotalPrice(new BigDecimal(vo.getElectricityPrice()).add(new BigDecimal(vo.getServicePrice())).toString());
			// 开始时间
			vo.setStartTime(billingTimeDTO.getStartTime());
			// 结束时间
			String endTime = StringUtils.equals("24:00", billingTimeDTO.getEndTime()) ? "23:59" : billingTimeDTO.getEndTime();
			vo.setEndTime(endTime);
			// 时段类型
			vo.setTimeType(type);
			// 是否当前时间
			boolean in = DateUtils.isIn(LocalTime.now(), LocalTime.parse(vo.getStartTime()), LocalTime.parse(vo.getEndTime()));
			vo.setIsCurrentTime(in ? Constants.ONE : Constants.ZERO);
			resultList.add(vo);
		}
		return resultList;
	}

	public static void main(String[] args) {
		// 21:30-23:00
		String startTime = "01:30";
		String endTime = "23:00";
		boolean in = DateUtils.isIn(LocalTime.now(), LocalTime.parse(startTime), LocalTime.parse(endTime));
		System.out.println(in);

	}

	/**
	 * 通过桩sn号查询计费模板
	 *
	 * @param pileSn 桩sn
	 * @return 计费模板编号
	 */
	@Override
	public BillingTemplateVO selectBillingTemplateDetailByPileSn(String pileSn) {
		return pileBillingTemplateMapper.selectBillingTemplateByPileSn(pileSn);
	}

	@Override
	public boolean stationImportBillingTemplate(ImportBillingTemplateDTO dto) {
		// 查询公共计费模板是否存在
		PileBillingTemplate pileBillingTemplate = pileBillingTemplateMapper.selectPileBillingTemplateById(Long.valueOf(dto.getBillingTemplateId()));
		if (pileBillingTemplate == null) {
			log.warn("根据计费模板id：{}，查询为空", dto.getBillingTemplateId());
			return false;
		}
		List<PileBillingDetail> billingDetailList = pileBillingTemplate.getPileBillingDetailList();
		// 复制计费模板
		PileBillingTemplate stationBillingTemplate = new PileBillingTemplate();

		String templateCode = Seq.getId(); // 生成计费模板编号
		BeanUtils.copyProperties(pileBillingTemplate, stationBillingTemplate, "id", "createBy", "createTime", "updateBy", "updateTime");
		stationBillingTemplate.setStationId(Long.valueOf(dto.getStationId())); // 站点id
		stationBillingTemplate.setPublicFlag(Constants.ZERO); // 站点私有计费模板
		stationBillingTemplate.setTemplateCode(templateCode);
		stationBillingTemplate.setCreateBy(SecurityUtils.getUsername());
		stationBillingTemplate.setDelFlag(DelFlagEnum.normal.getValue());
		// 复制计费模板详情
		List<PileBillingDetail> stationBillingDetailList = Lists.newArrayList();
		PileBillingDetail pileBillingDetail;
		for (PileBillingDetail detail : billingDetailList) {
			pileBillingDetail = new PileBillingDetail();
			BeanUtils.copyProperties(detail, pileBillingDetail, "id", "templateCode", "createBy", "createTime", "updateBy", "updateTime");
			pileBillingDetail.setTemplateCode(templateCode);
			pileBillingDetail.setCreateBy(SecurityUtils.getUsername());
			pileBillingDetail.setDelFlag(DelFlagEnum.normal.getValue());
			stationBillingDetailList.add(pileBillingDetail);
		}
		// 入库
		BillingTemplateTransactionDTO billingTemplateTransactionDTO = new BillingTemplateTransactionDTO();
		billingTemplateTransactionDTO.setBillingTemplate(stationBillingTemplate);
		billingTemplateTransactionDTO.setDetailList(stationBillingDetailList);
		transactionService.doCreateBillingTemplate(billingTemplateTransactionDTO);
		return true;
	}

	@Override
	public byte[] generateBillingTemplateMsgBody(String pileSn, BillingTemplateVO billingTemplateVO) {
		if (StringUtils.isBlank(pileSn) || billingTemplateVO == null) {
			log.error("生成发给充电桩的计费模板msgBody 参数不能为空");
			return null;
		}

		// 桩编码
		byte[] pileSnByte = BytesUtil.str2Bcd(pileSn);

		// 计费模型编号  固定值： 01 00
		byte[] billingTemplateCode = new byte[]{0x01, 0x00};

		// 尖时段电费
		byte[] sharpElectricityPrice = YKCUtils.getPriceByte(billingTemplateVO.getSharpElectricityPrice().toString(), 5);
		// 尖时段服务费
		byte[] sharpServicePrice = YKCUtils.getPriceByte(billingTemplateVO.getSharpServicePrice().toString(), 5);

		// 峰时段电费
		byte[] peakElectricityPrice = YKCUtils.getPriceByte(billingTemplateVO.getPeakElectricityPrice().toString(), 5);
		// 峰时段服务费
		byte[] peakServicePrice = YKCUtils.getPriceByte(billingTemplateVO.getPeakServicePrice().toString(), 5);

		// 平时段电费
		byte[] flatElectricityPrice = YKCUtils.getPriceByte(billingTemplateVO.getFlatElectricityPrice().toString(), 5);
		// 平时段服务费
		byte[] flatServicePrice = YKCUtils.getPriceByte(billingTemplateVO.getFlatServicePrice().toString(), 5);

		// 谷时段电费
		byte[] valleyElectricityPrice = YKCUtils.getPriceByte(billingTemplateVO.getValleyElectricityPrice().toString(), 5);
		// 谷时段服务费
		byte[] valleyServicePrice = YKCUtils.getPriceByte(billingTemplateVO.getValleyServicePrice().toString(), 5);
		// 计损比例（目前置0）
		byte[] PlanLossRatio = Constants.zeroByteArray;

		// 48个时段费率（半小时为一个时段）
		Map<Integer, List<String>> timeMap = billingTemplateVO.getTimeMap();
		List<String> periodOfTime = DateUtils.getPeriodOfTime();
		byte[] timeArray = new byte[periodOfTime.size()];
		for (int i = 0; i < periodOfTime.size(); i++) {
			// 对比时间段
			byte timeType = getTimeType(periodOfTime.get(i), timeMap);
			// log.info("时间段:{}, 对应费率类型:{}", periodOfTime.get(i), timeType);
			timeArray[i] = timeType;
		}

		// 消息体
		byte[] msgBody = Bytes.concat(pileSnByte, billingTemplateCode, sharpElectricityPrice, sharpServicePrice,
				peakElectricityPrice, peakServicePrice, flatElectricityPrice, flatServicePrice, valleyElectricityPrice,
				valleyServicePrice, PlanLossRatio, timeArray);
		log.warn("generateBillingTemplateMsgBody:{}", BytesUtil.binary(msgBody, 16));
		return msgBody;
	}

	/**
	 * 获取时段费率号
	 *
	 * @param timeRange 时间段 例如：07:30:00-10:30:00
	 * @param timeMap   尖峰平谷4个类型的时间段，每个类型都包含一个时间段集合
	 * @return
	 */
	private byte getTimeType(String timeRange, Map<Integer, List<String>> timeMap) {
		byte b = 5;
		// 这里的timeRange是00:00-00:30 这样的格式
		String[] split = timeRange.split("-");
		LocalTime startTime1 = DateUtils.getLocalTime(split[0]);
		LocalTime endTime1 = DateUtils.getLocalTime(split[1]);

		for (Map.Entry<Integer, List<String>> entry : timeMap.entrySet()) {
			List<String> value = entry.getValue().stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()); // 每个类型时间段集合
			if (CollectionUtils.isEmpty(value)) {
				continue;
			}
			for (String s : value) {
				// 这里的s是07:30-10:30 这样的格式
				List<String> list = Lists.newArrayList(s.split("-"));
				LocalTime startTime2 = DateUtils.getLocalTime(list.get(0));
				LocalTime endTime2 = DateUtils.getLocalTime(list.get(1));

				boolean overlap = DateUtils.isOverlap(startTime1, endTime1, startTime2, endTime2, false);
				if (overlap) {
					return (byte) entry.getKey().intValue();
				}
			}
		}
		return b;
	}

	@Override
	public BillingTemplateVO selectBillingTemplateByTemplateId(String templateId) {
		return pileBillingTemplateMapper.selectBillingTemplateByTemplateId(templateId);
	}

	@Override
	public void insertPileBillingRelation(List<PileBillingRelation> relationList) {
		if (CollectionUtils.isEmpty(relationList)) {
			return;
		}
		// 根据桩号删除计费模板关系
		List<String> pileSnList = relationList.stream().map(PileBillingRelation::getPileSn).collect(Collectors.toList());
		pileBillingTemplateMapper.deleteRelationByPileSn(pileSnList);
		pileBillingTemplateMapper.insertPileBillingRelation(relationList);
	}

	private Map<String, BigDecimal> getPriceMap(CreateOrUpdateBillingTemplateDTO dto, String type) {
		BigDecimal electricityPrice = null;
		BigDecimal servicePrice = null;
		if (StringUtils.equals(type, "1")) {
			electricityPrice = dto.getElectricityPriceA();
			servicePrice = dto.getServicePriceA();
		} else if (StringUtils.equals(type, "2")) {
			electricityPrice = dto.getElectricityPriceB();
			servicePrice = dto.getServicePriceB();
		} else if (StringUtils.equals(type, "3")) {
			electricityPrice = dto.getElectricityPriceC();
			servicePrice = dto.getServicePriceC();
		} else if (StringUtils.equals(type, "4")) {
			electricityPrice = dto.getElectricityPriceD();
			servicePrice = dto.getServicePriceD();
		}
		Map<String, BigDecimal> resultMap = Maps.newHashMap();
		resultMap.put("electricityPrice", electricityPrice);
		resultMap.put("servicePrice", servicePrice);
		return resultMap;
	}

	/**
	 * 新增计费模板详情信息
	 *
	 * @param pileBillingTemplate 计费模板对象
	 */
	public void insertPileBillingDetail(PileBillingTemplate pileBillingTemplate) {
		List<PileBillingDetail> pileBillingDetailList = pileBillingTemplate.getPileBillingDetailList();
		String templateCode = pileBillingTemplate.getTemplateCode();
		if (StringUtils.isNotNull(pileBillingDetailList)) {
			List<PileBillingDetail> list = new ArrayList<PileBillingDetail>();
			for (PileBillingDetail pileBillingDetail : pileBillingDetailList) {
				pileBillingDetail.setTemplateCode(templateCode);
				list.add(pileBillingDetail);
			}
			if (list.size() > 0) {
				pileBillingTemplateMapper.batchPileBillingDetail(list);
			}
		}
	}
}
