package com.xhpc.evcs.api;

import cn.hutool.core.date.DateUtil;
import com.xhpc.common.api.dto.ChargingStationDto;
import com.xhpc.common.data.redis.CacheRateModel;
import com.xhpc.evcs.domain.XhpcChargingPile;
import com.xhpc.evcs.domain.XhpcChargingStation;
import com.xhpc.evcs.domain.XhpcInternetUser;
import com.xhpc.evcs.domain.XhpcStationInternetBlacklist;
import com.xhpc.evcs.dto.*;
import com.xhpc.evcs.jpa.*;
import com.xhpc.evcs.utils.JSONUtil;
import com.xhpc.order.domain.XhpcPlaceholderITime;
import com.xhpc.order.domain.XhpcPlaceholderTimeOrder;
import com.xhpc.order.domain.XhpcPlacreholder;
import io.lettuce.core.ScriptOutputType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;

@Slf4j
@RestController
public class QueryStationsInfoController {

    @Autowired
    private XhpcInternetUserRepository xhpcInternetUserRepository;
    @Autowired
    private XhpcChargingPileRepository xhpcChargingPileRepository;
    @Autowired
    private XhpcChargingStationRepository xhpcChargingStationRepository;
    @Autowired
    private XhpcStationInternetBlacklistRepository xhpcStationInternetBlacklistRepo;
    @Autowired
    private PlaceholderIRepository placeholderIRepository;
    @Autowired
    private PlaceholderITimeRepository placeholderITimeRepository;

    private final String[] GUNNAMES = {"", "A", "B", "C", "D"};

    /**
     *  查询充电站信息
     * @param commonRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/v1/query_stations_info")
    public CommonResponse queryStationsInfo(@RequestBody(required = false) CommonRequest<PageRequest> commonRequest) throws Exception {

        CommonResponse resp = new CommonResponse();
        //当前页数
        PageRequest pageRequest = commonRequest.transformDataType(PageRequest.class);
        //页码总数
        String operatorId = commonRequest.getOperatorId();
        if("MA005DBW1".equals(operatorId)){
            Integer pageNo = pageRequest.getPageNo();
            PageStationsInfoResponseKuaiDian response = new PageStationsInfoResponseKuaiDian();
            response.setPageNo(pageNo);
            Instant now = Instant.now();
            XhpcInternetUser xhpcInternetUser =xhpcInternetUserRepository.findByOperatorIdEvcsLikeAndCooperationStartTimeBeforeAndCooperationEndTimeAfter(operatorId, now, now);
            if (xhpcInternetUser == null) {
                resp.setRet("1");
                resp.setMsg("Not valid internet user/OperatorID");
                resp.setData(JSONUtil.toJSONString(response));
            } else {
                Long internetUserId = xhpcInternetUser.getInternetUserId();
                List<XhpcStationInternetBlacklist> xhpcStationInternetBlacklist =
                        xhpcStationInternetBlacklistRepo.findByInternetUserId(internetUserId);
                List<String> stationKeys = new ArrayList<>(REDIS.keys("station:*"));
                List<String> validStationKeys = new ArrayList<>();
                for (String stationKey : stationKeys) {
                    boolean isValid = true;
                    //查询不合作的电桩
                    for (XhpcStationInternetBlacklist xhpcStationInternetBlack : xhpcStationInternetBlacklist) {
                        if (stationKey.substring(8).equals(xhpcStationInternetBlack.getChargingStationId().toString())) {
                            isValid = false;
                        }
                    }
                    ChargingStationDto chargingStationDto = REDIS.getCacheObject(stationKey);
                    if (chargingStationDto.getPiles() != null) {
                        if (isValid) {
                            validStationKeys.add(stationKey);
                        }
                    }
                }
                if (validStationKeys.size() > 0) {
                    Integer pageSize = pageRequest.getPageSize();
                    int totalPage = validStationKeys.size() % pageSize == 0 ? validStationKeys.size() / pageSize :
                            (validStationKeys.size() / pageSize) + 1;
                    response.setPageCount(totalPage);
                }
                //总记录条数
                response.setItemSize(validStationKeys.size());

                //充电站信息列表
                List<StationInfoKuaiDian> stationInfos = new ArrayList<>();
                //计算每页开始索引
                int startIndex = -1;
                int endIndex = -1;
                if (pageNo == 1 && validStationKeys.size() <= 10) {
                    startIndex = 0;
                    endIndex = validStationKeys.size() - 1;
                } else {
                    Integer pageSize = pageRequest.getPageSize();
                    startIndex = (pageNo - 1) * pageSize;
                    endIndex = startIndex + (pageSize - 1);
                }
                for (int i = startIndex; i <= endIndex; i++) {
                    String stationKey = null;
                    try {
                        stationKey = validStationKeys.get(i);
                    } catch (Exception e) {
                        continue;
                    }
                    ChargingStationDto chargingStationDto = REDIS.getCacheObject(stationKey);
                    StationInfoKuaiDian stationInfo = new StationInfoKuaiDian();
                    //站点状态
                    stationInfo.setStationStatus(50);
                    //充电站Id
                    String stationId = stationKey.replace("station:", "");
                    stationInfo.setStationId(stationId);
                    Double lat = chargingStationDto.getLat();
                    if (lat == null) {
                        XhpcChargingStation stationExample = new XhpcChargingStation();
                        stationExample.setId(Long.parseLong(stationId));
                        Example<XhpcChargingStation> example = Example.of(stationExample);
                        XhpcChargingStation xhpcChargingStation =
                                xhpcChargingStationRepository.findOne(example).orElse(null);
                        if (xhpcChargingStation != null) {
                            //纬度
                            chargingStationDto.setLat(new BigDecimal(xhpcChargingStation.getLatitude()).setScale(6,
                                    RoundingMode.HALF_UP).doubleValue());
                            //经度
                            chargingStationDto.setLng(new BigDecimal(xhpcChargingStation.getLongitude()).setScale(6,
                                    RoundingMode.HALF_UP).doubleValue());
                            //站点类型
                            chargingStationDto.setType(xhpcChargingStation.getType());
                            //运营商id
                            String operatorIdEvcs = xhpcChargingStation.getOperatorIdEvcs();
                            chargingStationDto.setOperatorId(operatorIdEvcs == null ? "MA6DFCTD5"
                                    : operatorIdEvcs.length() == 9 ? operatorId : operatorIdEvcs.substring(8, 17));
                            //详细地址
                            chargingStationDto.setAddress(xhpcChargingStation.getAddress());
                            //充电站省直辖区编码
                            chargingStationDto.setAreaCode(xhpcChargingStation.getAreaCode().toString());
                            //充电站名称
                            chargingStationDto.setName(xhpcChargingStation.getName());
                            //服务电话
                            chargingStationDto.setServiceTel(xhpcChargingStation.getServiceTel());
                            //车位数量
                            chargingStationDto.setParkNums(xhpcChargingStation.getParkNums());
                            chargingStationDto.setParkFee(xhpcChargingStation.getParkingInstructions());
                            String[] split = xhpcChargingStation.getImgId().split(",");
                            for (int j = 0; j < split.length; j++) {
                                String s = split[j];
                                String url="https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com"+s;
                                split[j] =url;
                            }
                            chargingStationDto.setPictures(split);
                            REDIS.setCacheObject(stationKey, chargingStationDto);
                        }
                    }
                    stationInfo.setOperatorId(chargingStationDto.getOperatorId());
                    stationInfo.setEquipmentOwnerId(chargingStationDto.getOperatorId());
                    stationInfo.setStationName(chargingStationDto.getName());
                    stationInfo.setCountryCode("CN");
                    stationInfo.setAreaCode(chargingStationDto.getAreaCode());
                    stationInfo.setAddress(chargingStationDto.getAddress());
                    stationInfo.setServiceTel(chargingStationDto.getServiceTel());
                    stationInfo.setStationType(chargingStationDto.getType());
                    stationInfo.setParkNums(chargingStationDto.getParkNums());
                    stationInfo.setStationLng(chargingStationDto.getLng());
                    stationInfo.setStationLat(chargingStationDto.getLat());
                    stationInfo.setConstruction(chargingStationDto.getConstruction());
                    stationInfo.setParkFee(chargingStationDto.getParkFee());
                    String[] fees = getFees(chargingStationDto.getRateModelId());
                    if (fees != null) {
                        stationInfo.setElectricityFee(fees[0]);
                        stationInfo.setServiceFee(fees[1]);
                    }
                    //获取该充电站的下的所有充电设备列表
                    Set<String> piles = chargingStationDto.getPiles();
                    List<EquipmentInfo> equipmentInfos = getEquipmentInfos(piles);
                    stationInfo.setEquipmentInfos(equipmentInfos);

                    Long chargingStationId =Long.valueOf(stationInfo.getStationId());
                    //获取占位信息
                    XhpcPlacreholder xhpcPlacreholder = placeholderIRepository.findByStatusAndChargingStationIdAndDelFlag(1,chargingStationId, 0);
                    if(xhpcPlacreholder !=null){
                        PlaceHolder placeHolder = new PlaceHolder();
                        placeHolder.setFreeTime(xhpcPlacreholder.getFreeTime());
                        placeHolder.setMaxFee(xhpcPlacreholder.getMaxFee());

                        String startTime = DateUtil.format(xhpcPlacreholder.getStartTime(), "yyyy-MM-dd HH:mm:ss");
                        String endTime = DateUtil.format(xhpcPlacreholder.getEndTime(), "yyyy-MM-dd HH:mm:ss");

                        placeHolder.setEffectStartTime(DateUtil.parse(startTime,"yyyy-MM-dd HH:mm:ss"));
                        placeHolder.setEffectEndTime(DateUtil.parse(endTime,"yyyy-MM-dd HH:mm:ss"));

                        List<PlaceHolderPrice> placeHolderPrices =new ArrayList<>();
                        List<XhpcPlaceholderITime> xhpcPlaceholderITimeList = placeholderITimeRepository.findByPlaceholderIdAndDelFlagAndChargingStationId(xhpcPlacreholder.getPlaceholderId(), 0,chargingStationId);
                        if(xhpcPlaceholderITimeList !=null && xhpcPlaceholderITimeList.size()>0){
                            for (int j = 0; j < xhpcPlaceholderITimeList.size(); j++) {
                                XhpcPlaceholderITime xhpcPlaceholderTimeOrder = xhpcPlaceholderITimeList.get(j);
                                PlaceHolderPrice placeHolderPrice = new PlaceHolderPrice();
                                placeHolderPrice.setStartTime(DateUtil.format(xhpcPlaceholderTimeOrder.getStartTime(),"HH:mm:ss"));
                                placeHolderPrice.setEndTime(DateUtil.format(xhpcPlaceholderTimeOrder.getEndTime(),"HH:mm:ss"));
                                if("00:00:00".equals(placeHolderPrice.getEndTime())){
                                    placeHolderPrice.setEndTime("23:59:59");
                                }
                                placeHolderPrice.setPrice(xhpcPlaceholderTimeOrder.getPrice());
                                placeHolderPrices.add(placeHolderPrice);
                            }

                            placeHolder.setPlaceHolderPrices(placeHolderPrices);

                            stationInfo.setPlaceHolder(placeHolder);
                            stationInfo.setOvertimeFee(xhpcPlacreholder.getContent());
                        }
                    }
                    stationInfos.add(stationInfo);
                }
                response.setStationInfos(stationInfos);
                resp.setRet("0");
                resp.setMsg("Query station info success");
                resp.setData(JSONUtil.toJSONString(response));
            }
            return resp;
        }
        else if("MA25CNM38".equals(operatorId)){
            Integer pageNo = pageRequest.getPageNo();
            PageStationsInfoResponseXinDianTu response = new PageStationsInfoResponseXinDianTu();
            response.setPageNo(pageNo);
            Instant now = Instant.now();
            XhpcInternetUser xhpcInternetUser =xhpcInternetUserRepository.findByOperatorIdEvcsLikeAndCooperationStartTimeBeforeAndCooperationEndTimeAfter(operatorId, now, now);
            if (xhpcInternetUser == null) {
                resp.setRet("1");
                resp.setMsg("Not valid internet user/OperatorID");
                resp.setData(JSONUtil.toJSONString(response));
            } else {
                Long internetUserId = xhpcInternetUser.getInternetUserId();
                List<XhpcStationInternetBlacklist> xhpcStationInternetBlacklist =
                        xhpcStationInternetBlacklistRepo.findByInternetUserId(internetUserId);

                List<String> validStationKeys = new ArrayList<>();
                if(pageRequest.getStationID() !=null && !"".equals(pageRequest.getStationID())){
                    //查询不合作的电桩
                    for (XhpcStationInternetBlacklist xhpcStationInternetBlack : xhpcStationInternetBlacklist) {
                        if (!pageRequest.getStationID().equals(xhpcStationInternetBlack.getChargingStationId().toString())) {
                            ChargingStationDto chargingStationDto = REDIS.getCacheObject("station:"+pageRequest.getStationID());
                            if (chargingStationDto.getPiles() != null) {
                                    validStationKeys.add("station:"+pageRequest.getStationID());
                                    break;
                            }
                        }
                    }
                }else{
                    List<String> stationKeys = new ArrayList<>(REDIS.keys("station:*"));

                    for (String stationKey : stationKeys) {
                        boolean isValid = true;
                        //查询不合作的电桩
                        for (XhpcStationInternetBlacklist xhpcStationInternetBlack : xhpcStationInternetBlacklist) {
                            if (stationKey.substring(8).equals(xhpcStationInternetBlack.getChargingStationId().toString())) {
                                isValid = false;
                            }
                        }
                        ChargingStationDto chargingStationDto = REDIS.getCacheObject(stationKey);
                        if (chargingStationDto.getPiles() != null) {
                            if (isValid) {
                                validStationKeys.add(stationKey);
                            }
                        }
                    }
                }

                if (validStationKeys.size() > 0) {
                    Integer pageSize = pageRequest.getPageSize();
                    int totalPage = validStationKeys.size() % pageSize == 0 ? validStationKeys.size() / pageSize :
                            (validStationKeys.size() / pageSize) + 1;
                    response.setPageCount(totalPage);
                }
                //总记录条数
                response.setItemSize(validStationKeys.size());

                //充电站信息列表
                List<StationInfoXinDianTu> stationInfos = new ArrayList<>();
                //计算每页开始索引
                int startIndex = -1;
                int endIndex = -1;
                if (pageNo == 1 && validStationKeys.size() <= 10) {
                    startIndex = 0;
                    endIndex = validStationKeys.size() - 1;
                } else {
                    Integer pageSize = pageRequest.getPageSize();
                    startIndex = (pageNo - 1) * pageSize;
                    endIndex = startIndex + (pageSize - 1);
                }
                for (int i = startIndex; i <= endIndex; i++) {
                    String stationKey = null;
                    try {
                        stationKey = validStationKeys.get(i);
                    } catch (Exception e) {
                        continue;
                    }
                    ChargingStationDto chargingStationDto = REDIS.getCacheObject(stationKey);
                    StationInfoXinDianTu stationInfo = new StationInfoXinDianTu();
                    //站点状态
                    stationInfo.setStationStatus(50);
                    //充电站Id
                    String stationId = stationKey.replace("station:", "");
                    stationInfo.setStationId(stationId);
                    Double lat = chargingStationDto.getLat();
                    if (lat == null) {
                        XhpcChargingStation stationExample = new XhpcChargingStation();
                        stationExample.setId(Long.parseLong(stationId));
                        Example<XhpcChargingStation> example = Example.of(stationExample);
                        XhpcChargingStation xhpcChargingStation =
                                xhpcChargingStationRepository.findOne(example).orElse(null);
                        if (xhpcChargingStation != null) {
                            //纬度
                            chargingStationDto.setLat(new BigDecimal(xhpcChargingStation.getLatitude()).setScale(6,RoundingMode.HALF_UP).doubleValue());
                            //经度
                            chargingStationDto.setLng(new BigDecimal(xhpcChargingStation.getLongitude()).setScale(6, RoundingMode.HALF_UP).doubleValue());
                            //站点类型
                            chargingStationDto.setType(xhpcChargingStation.getType());
                            //运营商id
                            String operatorIdEvcs = xhpcChargingStation.getOperatorIdEvcs();
                            chargingStationDto.setOperatorId(operatorIdEvcs == null ? "MA6DFCTD5" : operatorIdEvcs.length() == 9 ? operatorId : operatorIdEvcs.substring(8, 17));
                            //详细地址
                            chargingStationDto.setAddress(xhpcChargingStation.getAddress());
                            //充电站省直辖区编码
                            chargingStationDto.setAreaCode(xhpcChargingStation.getAreaCode().toString());
                            //充电站名称
                            chargingStationDto.setName(xhpcChargingStation.getName());
                            //服务电话
                            chargingStationDto.setServiceTel(xhpcChargingStation.getServiceTel());
                            //车位数量
                            chargingStationDto.setParkNums(xhpcChargingStation.getParkNums());
                            chargingStationDto.setParkFee(xhpcChargingStation.getParkingInstructions());

                            String[] split = xhpcChargingStation.getImgId().split(",");
                            for (int j = 0; j < split.length; j++) {
                                String s = split[j];
                                String url="https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com"+s;
                                split[j] =url;
                            }
                            chargingStationDto.setPictures(split);
                            REDIS.setCacheObject(stationKey, chargingStationDto);
                        }
                    }
                    stationInfo.setOperatorId(chargingStationDto.getOperatorId());
                    stationInfo.setEquipmentOwnerId(chargingStationDto.getOperatorId());
                    stationInfo.setStationName(chargingStationDto.getName());
                    stationInfo.setCountryCode("CN");
                    stationInfo.setPictures(chargingStationDto.getPictures());
                    stationInfo.setAreaCode(chargingStationDto.getAreaCode());
                    stationInfo.setAddress(chargingStationDto.getAddress());
                    stationInfo.setServiceTel(chargingStationDto.getServiceTel());
                    stationInfo.setStationType(chargingStationDto.getType());
                    stationInfo.setParkNums(chargingStationDto.getParkNums());
                    stationInfo.setStationLng(chargingStationDto.getLng());
                    stationInfo.setStationLat(chargingStationDto.getLat());
                    stationInfo.setConstruction(chargingStationDto.getConstruction());
                    stationInfo.setParkFee(chargingStationDto.getParkFee());
                    String[] fees = getFees(chargingStationDto.getRateModelId());
                    if (fees != null) {
                        stationInfo.setElectricityFee(fees[0]);
                        stationInfo.setServiceFee(fees[1]);
                    }
                    Long chargingStationId =Long.valueOf(stationInfo.getStationId());
                    //获取占位信息
                    XhpcPlacreholder xhpcPlacreholder = placeholderIRepository.findByTypeAndChargingStationIdAndDelFlag(1,chargingStationId, 0);
                    if(xhpcPlacreholder !=null){
                        stationInfo.setIncrementExplain(xhpcPlacreholder.getContent());
                    }
                    //获取该充电站的下的所有充电设备列表
                    Set<String> piles = chargingStationDto.getPiles();
                    List<EquipmentInfo> equipmentInfos = getEquipmentInfos(piles);
                    stationInfo.setEquipmentInfos(equipmentInfos);
                    stationInfos.add(stationInfo);
                }
                response.setStationInfos(stationInfos);
                resp.setRet("0");
                resp.setMsg("Query station info success");
                resp.setData(JSONUtil.toJSONString(response));
            }
        }else{
            Integer pageNo = pageRequest.getPageNo();
            PageStationsInfoResponse response = new PageStationsInfoResponse();
            response.setPageNo(pageNo);
            Instant now = Instant.now();
            XhpcInternetUser xhpcInternetUser =xhpcInternetUserRepository.findByOperatorIdEvcsLikeAndCooperationStartTimeBeforeAndCooperationEndTimeAfter(operatorId, now, now);
            if (xhpcInternetUser == null) {
                resp.setRet("1");
                resp.setMsg("Not valid internet user/OperatorID");
                resp.setData(JSONUtil.toJSONString(response));
            } else {
                Long internetUserId = xhpcInternetUser.getInternetUserId();
                List<XhpcStationInternetBlacklist> xhpcStationInternetBlacklist =
                        xhpcStationInternetBlacklistRepo.findByInternetUserId(internetUserId);
                List<String> stationKeys = new ArrayList<>(REDIS.keys("station:*"));
                List<String> validStationKeys = new ArrayList<>();
                for (String stationKey : stationKeys) {
                    boolean isValid = true;
                    //查询不合作的电桩
                    for (XhpcStationInternetBlacklist xhpcStationInternetBlack : xhpcStationInternetBlacklist) {
                        if (stationKey.substring(8).equals(xhpcStationInternetBlack.getChargingStationId().toString())) {
                            isValid = false;
                        }
                    }
                    ChargingStationDto chargingStationDto = REDIS.getCacheObject(stationKey);
                    if (chargingStationDto.getPiles() != null) {
                        if (isValid) {
                            validStationKeys.add(stationKey);
                        }
                    }
                }
                if (validStationKeys.size() > 0) {
                    Integer pageSize = pageRequest.getPageSize();
                    int totalPage = validStationKeys.size() % pageSize == 0 ? validStationKeys.size() / pageSize :
                            (validStationKeys.size() / pageSize) + 1;
                    response.setPageCount(totalPage);
                }
                //总记录条数
                response.setItemSize(validStationKeys.size());

                //充电站信息列表
                List<StationInfo> stationInfos = new ArrayList<>();
                //计算每页开始索引
                int startIndex = -1;
                int endIndex = -1;
                if (pageNo == 1 && validStationKeys.size() <= 10) {
                    startIndex = 0;
                    endIndex = validStationKeys.size() - 1;
                } else {
                    Integer pageSize = pageRequest.getPageSize();
                    startIndex = (pageNo - 1) * pageSize;
                    endIndex = startIndex + (pageSize - 1);
                }
                for (int i = startIndex; i <= endIndex; i++) {
                    String stationKey = null;
                    try {
                        stationKey = validStationKeys.get(i);
                    } catch (Exception e) {
                        continue;
                    }
                    ChargingStationDto chargingStationDto = REDIS.getCacheObject(stationKey);
                    StationInfo stationInfo = new StationInfo();
                    //站点状态
                    stationInfo.setStationStatus(50);
                    //充电站Id
                    String stationId = stationKey.replace("station:", "");
                    stationInfo.setStationId(stationId);
                    Double lat = chargingStationDto.getLat();
                    if (lat == null) {
                        XhpcChargingStation stationExample = new XhpcChargingStation();
                        stationExample.setId(Long.parseLong(stationId));
                        Example<XhpcChargingStation> example = Example.of(stationExample);
                        XhpcChargingStation xhpcChargingStation =
                                xhpcChargingStationRepository.findOne(example).orElse(null);
                        if (xhpcChargingStation != null) {
                            //纬度
                            chargingStationDto.setLat(new BigDecimal(xhpcChargingStation.getLatitude()).setScale(6,
                                    RoundingMode.HALF_UP).doubleValue());
                            //经度
                            chargingStationDto.setLng(new BigDecimal(xhpcChargingStation.getLongitude()).setScale(6,
                                    RoundingMode.HALF_UP).doubleValue());
                            //站点类型
                            chargingStationDto.setType(xhpcChargingStation.getType());
                            //运营商id
                            String operatorIdEvcs = xhpcChargingStation.getOperatorIdEvcs();
                            chargingStationDto.setOperatorId(operatorIdEvcs == null ? "MA6DFCTD5"
                                    : operatorIdEvcs.length() == 9 ? operatorId : operatorIdEvcs.substring(8, 17));
                            //详细地址
                            chargingStationDto.setAddress(xhpcChargingStation.getAddress());
                            //充电站省直辖区编码
                            chargingStationDto.setAreaCode(xhpcChargingStation.getAreaCode().toString());
                            //充电站名称
                            chargingStationDto.setName(xhpcChargingStation.getName());
                            //服务电话
                            chargingStationDto.setServiceTel(xhpcChargingStation.getServiceTel());
                            //车位数量
                            chargingStationDto.setParkNums(xhpcChargingStation.getParkNums());
                            chargingStationDto.setParkFee(xhpcChargingStation.getParkingInstructions());
                            String[] split = xhpcChargingStation.getImgId().split(",");
                            for (int j = 0; j < split.length; j++) {
                                String s = split[j];
                                String url="https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com"+s;
                                split[j] =url;
                            }
                            chargingStationDto.setPictures(split);
                            REDIS.setCacheObject(stationKey, chargingStationDto);
                        }
                    }
                    stationInfo.setOperatorId(chargingStationDto.getOperatorId());
                    stationInfo.setEquipmentOwnerId(chargingStationDto.getOperatorId());
                    stationInfo.setStationName(chargingStationDto.getName());
                    stationInfo.setCountryCode("CN");
                    stationInfo.setAreaCode(chargingStationDto.getAreaCode());
                    stationInfo.setAddress(chargingStationDto.getAddress());
                    stationInfo.setServiceTel(chargingStationDto.getServiceTel());
                    stationInfo.setStationType(chargingStationDto.getType());
                    stationInfo.setParkNums(chargingStationDto.getParkNums());
                    stationInfo.setStationLng(chargingStationDto.getLng());
                    stationInfo.setStationLat(chargingStationDto.getLat());
                    stationInfo.setConstruction(chargingStationDto.getConstruction());
                    stationInfo.setParkFee(chargingStationDto.getParkFee());
                    String[] fees = getFees(chargingStationDto.getRateModelId());
                    if (fees != null) {
                        stationInfo.setElectricityFee(fees[0]);
                        stationInfo.setServiceFee(fees[1]);
                    }
                    //获取该充电站的下的所有充电设备列表
                    Set<String> piles = chargingStationDto.getPiles();
                    List<EquipmentInfo> equipmentInfos = getEquipmentInfos(piles);
                    stationInfo.setEquipmentInfos(equipmentInfos);
                    stationInfos.add(stationInfo);
                }
                response.setStationInfos(stationInfos);
                resp.setRet("0");
                resp.setMsg("Query station info success");
                resp.setData(JSONUtil.toJSONString(response));
            }
        }
        return resp;
    }


    private String[] getFees(Long rateModelId) {

        CacheRateModel cacheRateModel = REDIS.getCacheObject("rateModel:".concat(rateModelId.toString()));
        if (cacheRateModel == null) {
            log.error("rate model missing: {}", rateModelId);
            return null;
        }
        if (cacheRateModel.getPp() != null) {
            return cacheRateModel.getPp();
        }
        String[] tfPricesSeq = cacheRateModel.getTfPricesSeq();
        String startTf = "00:00";
        String endTf = "";
        String previousTf = tfPricesSeq[0];
        Integer elecPrice = 0;
        Integer svcPrice = 0;
        List<String> tfrmes = new ArrayList<>(); //电费
        List<String> tfrmss = new ArrayList<>(); // 服务费
        for (int i = 1; i < tfPricesSeq.length; i++) {
            if (!previousTf.equals(tfPricesSeq[i])) {
                if (previousTf.equals("00")) {
                    elecPrice = cacheRateModel.getT1Price();
                    svcPrice = cacheRateModel.getT1SvcPrice();
                } else if (previousTf.equals("01")) {
                    elecPrice = cacheRateModel.getT2Price();
                    svcPrice = cacheRateModel.getT2SvcPrice();
                } else if (previousTf.equals("02")) {
                    elecPrice = cacheRateModel.getT3Price();
                    svcPrice = cacheRateModel.getT3SvcPrice();
                } else { // 03
                    elecPrice = cacheRateModel.getT4Price();
                    svcPrice = cacheRateModel.getT4SvcPrice();
                }
                if (i % 2 != 0) {
                    endTf = String.format("%02d", i / 2).concat(":30");
                } else {
                    endTf = String.format("%02d", i / 2).concat(":00");
                }
                String electfrm =
                        startTf.concat("~").concat(endTf).concat(",").concat(BigDecimal.valueOf(elecPrice).divide(BigDecimal.valueOf(100000L)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                String svcfrm =
                        startTf.concat("~").concat(endTf).concat(",").concat(BigDecimal.valueOf(svcPrice).divide(BigDecimal.valueOf(100000L)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                previousTf = tfPricesSeq[i];
                startTf = endTf;
                tfrmes.add(electfrm);
                tfrmss.add(svcfrm);
            }
            if (i == 47 && !endTf.startsWith("24:00")) {
                endTf = "24:00";
                String electfrm =
                        startTf.concat("~").concat(endTf).concat(",").concat(BigDecimal.valueOf(elecPrice).divide(BigDecimal.valueOf(100000L)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                String svcfrm =
                        startTf.concat("~").concat(endTf).concat(",").concat(BigDecimal.valueOf(svcPrice).divide(BigDecimal.valueOf(100000L)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                tfrmes.add(electfrm);
                tfrmss.add(svcfrm);
            }
        }
        String[] pp = new String[2];
        pp[0] = "电费:".concat(String.join(";", tfrmes));
        pp[1] = "服务费:".concat(String.join(";", tfrmss));
        cacheRateModel.setPp(pp);
        REDIS.setCacheObject("rateModel:".concat(rateModelId.toString()), cacheRateModel);
        return pp;
    }

    private List<EquipmentInfo> getEquipmentInfos(Set<String> pileNoSet) {

        List<EquipmentInfo> equipmentInfos = new ArrayList<>();
        for (String pileNo : pileNoSet) {
            final Map<String, Object> cachePile = REDIS.getCacheMap("pile:".concat(pileNo));
            Integer connectorType = (Integer) cachePile.get("connectorType");
            if (connectorType == null) { //未缓存
                XhpcChargingPile pileExample = new XhpcChargingPile();
                pileExample.setSerialNumber(pileNo);
                Example<XhpcChargingPile> example = Example.of(pileExample);
                XhpcChargingPile xhpcChargingPile = xhpcChargingPileRepository.findOne(example).orElse(null);
                if (xhpcChargingPile != null) {
                    cachePile.put("connectorType", xhpcChargingPile.getConnectorType() == null ? 4 :
                            xhpcChargingPile.getConnectorType());
                    cachePile.put("voltageUpperLimits", xhpcChargingPile.getMaxVoltage().intValue());
                    cachePile.put("voltageLowerLimits", xhpcChargingPile.getMinVoltage().intValue());
                    cachePile.put("currentLimit", xhpcChargingPile.getCurrent());
                    cachePile.put("power", xhpcChargingPile.getPower());
                    cachePile.put("nationalStandard", xhpcChargingPile.getNationalStandard().equals("2011") ? 1 : 2);
                    cachePile.put("equipmentType", xhpcChargingPile.getEquipmentType());
                    REDIS.setCacheMap("pile:".concat(pileNo), cachePile);
                }
            }
            EquipmentInfo equipmentInfo = new EquipmentInfo();
            equipmentInfo.setEquipmentID(pileNo);
            Integer equipmentType = (Integer) cachePile.get("equipmentType");
            equipmentInfo.setEquipmentType(equipmentType == null ? 1 : equipmentType);
            Double power = (Double) cachePile.get("power");
            equipmentInfo.setPower(power == null ? 120.0 : power);
            equipmentInfo.setConnectorInfos(getConnectorInfos(pileNo, cachePile));
            equipmentInfos.add(equipmentInfo);
        }
        return equipmentInfos;
    }

    private List<ConnectorInfo> getConnectorInfos(String pileNo, Map<String, Object> cachePile) {

        List<ConnectorInfo> connectorInfoList = new ArrayList<>();
        Integer gunNumCache = (Integer) cachePile.get("gunNum");
        gunNumCache = gunNumCache == null ? 2 : gunNumCache;
        for (int i = 1; i <= gunNumCache; i++) {
            String gunId = pileNo.concat(String.format("%02d", i));
            ConnectorInfo connectorInfo = new ConnectorInfo();
            connectorInfo.setConnectorID(gunId);
            String connectorName = REDIS.getCacheMapValue("gun:".concat(gunId), "terminalName"); //todo set them in redis!
            connectorInfo.setConnectorName(connectorName == null ?
                    Integer.parseInt(pileNo.substring(10, 14)) + "号桩-" + GUNNAMES[i] +
                            "枪" : connectorName);
            Integer connectorType = (Integer) cachePile.get("connectorType");
            connectorInfo.setConnectorType(connectorType == null ? 4 : connectorType);
            Integer voltageUpperLimits = (Integer) cachePile.get("voltageUpperLimits");
            connectorInfo.setVoltageUpperLimits(voltageUpperLimits == null ? 750 : voltageUpperLimits);
            Integer voltageLowerLimits = (Integer) cachePile.get("voltageLowerLimits");
            connectorInfo.setVoltageLowerLimits(voltageLowerLimits == null ? 300 : voltageLowerLimits);
            Integer current = (Integer) cachePile.get("current");
            connectorInfo.setCurrent(current == null ? 250 : current);
            Double power = (Double) cachePile.get("power");
            connectorInfo.setPower(power == null ? 120.0 : power);
            Integer nationalStandard = (Integer) cachePile.get("nationalStandard");
            connectorInfo.setNationalStandard(nationalStandard == null ? 2 : nationalStandard);
            connectorInfoList.add(connectorInfo);
        }
        return connectorInfoList;
    }

}
