package com.xhpc.charging.station.service;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.xhpc.charging.station.dto.XhpcActivityDiscountDto;
import com.xhpc.charging.station.mapper.XhpcChargingStationMapper;
import com.xhpc.charging.station.mapper.XhpcChargingStationPushStatusMapper;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.api.TenantService;
import com.xhpc.common.api.dto.XhpcChargingStationDto;
import com.xhpc.common.api.dto.XhpcRateDto;
import com.xhpc.common.api.dto.XhpcRateTimeDtoYang;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.DateUtils;
import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.data.redis.CacheRateModel;
import com.xhpc.common.domain.*;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.LogUserUtils;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.serialNumber;


/**
 * 电站Service业务层处理
 *
 * @author yuyang
 * @date 2021-07-19
 */
@Service
public class XhpcChargingStationServiceImpl extends BaseService implements IXhpcChargingStationService {

    @Autowired
    private XhpcChargingStationMapper xhpcChargingStationMapper;
    @Autowired
    private IXhpcRateTimeService xhpcRateTimeService;
    @Autowired
    private IXhpcTerminalService xhpcTerminalService;
    @Autowired
    private PowerPileService powerPileService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private LogUserUtils logUserUtils;
    @Autowired
    private TenantService tenantService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private XhpcChargingStationPushStatusMapper xhpcChargingStationPushStatusMapper;

    private static final Logger logger = LoggerFactory.getLogger(XhpcChargingStationServiceImpl.class);

    @Override
    public Integer editStationsStatus(List<Integer> chargingStationIds, Integer pushStatus) {

        return xhpcChargingStationPushStatusMapper.editStationsStatus(chargingStationIds, pushStatus);
    }

    @Override
    public Map<String, Object> getLandUser(Long userId) {

        return xhpcChargingStationMapper.getLandUser(userId);
    }

    /**
     * 删除该场站之前费率、费率时段
     */
    @Override
    public void updateXhpcRateTimeChargingStationId(Long chargingStationId) {
        xhpcChargingStationMapper.updateXhpcRateTime(chargingStationId);
        xhpcChargingStationMapper.updateXhpcRate(chargingStationId);
    }

    /**
     * 添加费率
     *
     * @param xhpcRate
     */
    @Override
    public int insertXhpcRate(XhpcRate xhpcRate) {
        return xhpcChargingStationMapper.insertXhpcRate(xhpcRate);
    }

    /**
     * 添加费率时段
     *
     * @param xhpcRateTime
     */
    @Override
    public int insertXhpcRateTime(XhpcRateTime xhpcRateTime) {
        return xhpcChargingStationMapper.insertXhpcRateTime(xhpcRateTime);
    }

    /**
     * 保存电站状态
     *
     * @param chargingStationId 要保存的电站的id
     * @param pushStatus        电站的状态 0，1（1表示修改了)
     * @return greater than 0 means success
     */
    @Override
    public Integer saveStationStatus(Integer chargingStationId, String stationName, Integer pushStatus) {

        Map<String, Object> map = xhpcChargingStationPushStatusMapper.findOne(chargingStationId);
        if (map != null) {
            return 0;
        }
        return xhpcChargingStationPushStatusMapper.insertStationPushStatus(chargingStationId, stationName, pushStatus);
    }

    /**
     * 查询电站
     *
     * @param chargingStationId 电站ID
     * @return 电站
     */
    @Override
    public XhpcChargingStation selectXhpcChargingStationById(Long chargingStationId) {

        return xhpcChargingStationMapper.selectXhpcChargingStationById(chargingStationId);
    }


    /**
     * 查询电站
     *
     * @param chargingStationName 电站名称
     * @return 电站
     */
    @Override
    public XhpcChargingStation selectXhpcChargingStationByName(String chargingStationName) {

        return xhpcChargingStationMapper.selectXhpcChargingStationByName(chargingStationName);
    }

    /**
     * 查询电站列表
     *
     * @param name         电站名称
     * @param operatorName 运营商名称
     * @return 电站
     */
    @Override
    public List<Map<String, Object>> selectXhpcChargingStationList(HttpServletRequest request,String tenantId,Long operatorId,Long chargingStationId, String name, String operatorName) {
        //获取登陆用户
        LoginUser loginUser = tokenService.getLoginUser(request);
        SysUser sysUser = loginUser.getSysUser();
        Long sysUserId = sysUser.getUserId();
        //桩的统计、该时段金额
        List<Map<String, Object>> list =new ArrayList<>();

        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                list = xhpcChargingStationMapper.selectXhpcChargingStationList(operatorId,chargingStationId,name,operatorName,logOperatorId,1,tenantId);
            }else{
                //查询赋值的场站
                list = xhpcChargingStationMapper.selectXhpcChargingStationList(operatorId,chargingStationId,name,operatorName,sysUserId,2,tenantId);
            }
        }else{
            startPage();
            list = xhpcChargingStationMapper.selectXhpcChargingStationList(operatorId,chargingStationId,name, operatorName,sysUserId,0,tenantId);
        }

        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            Long chargingStationIdMap = Long.valueOf(map.get("chargingStationId").toString());
            //获取该时段电费
            //HH:mm:ss
            String tiem = DateUtil.formatTime(new Date());
            if(map.get("imgId") !=null){
                String[] imgIds = map.get("imgId").toString().split(",");
                map.put("url",imgIds[0]);
            }

            Map<String, Object> xhpcRateTime = xhpcRateTimeService.getXhpcRateTime(tiem, chargingStationIdMap);
            if (xhpcRateTime != null) {
                map.putAll(xhpcRateTime);
            }
            map =getTerminalStatusSum(map, chargingStationIdMap,0);
        }
        return list;
    }



    /**
     * 新增电站
     *
     * @param xhpcChargingStation 电站
     * @return 结果
     */
    @Override
    public int insertXhpcChargingStation(XhpcChargingStation xhpcChargingStation) {

        xhpcChargingStation.setCreateTime(DateUtils.getNowDate());
        return xhpcChargingStationMapper.insertXhpcChargingStation(xhpcChargingStation);
    }

    /**
     * 修改电站
     *
     * @param xhpcChargingStation 电站
     * @return 结果
     */
    @Override
    public int updateXhpcChargingStation(XhpcChargingStation xhpcChargingStation) {

        xhpcChargingStation.setUpdateTime(DateUtils.getNowDate());
        return xhpcChargingStationMapper.updateXhpcChargingStation(xhpcChargingStation);
    }

    /**
     * 批量删除电站
     *
     * @param chargingStationIds 需要删除的电站ID
     * @return 结果
     */
    @Override
    public int updateXhpcChargingStationByIds(Long[] chargingStationIds) {

        return xhpcChargingStationMapper.updateXhpcChargingStationByIds(chargingStationIds);
    }

    /**
     * 删除电站信息
     *
     * @param chargingStationId 电站ID
     * @return 结果
     */
    @Override
    public int updateXhpcChargingStationById(Long chargingStationId) {

        int i = xhpcChargingStationMapper.updateXhpcChargingStationById(chargingStationId);
        if (i > 0) {
            extracted(1, chargingStationId);
        }
        return i;
    }

    /**
     * 状态（0正常 1停用）
     *
     * @param status            0正常 1停用
     * @param chargingStationId 场站id
     * @return 结果
     */
    @Override
    public int status(Integer status, Long chargingStationId) {

        if (status != null && (status == 0 || status == 1)) {
            xhpcChargingStationMapper.status(status, chargingStationId);
            extracted(status, chargingStationId);
            return 1;
        }
        return 0;
    }


    /**
     * APP端、小程序是否可见
     *
     * @param type              0可见 1不可见
     * @param clientVisible     值
     * @param chargingStationId 场站id
     * @return 结果
     */
    @Override
    public int clientVisible(Integer type, String clientVisible, Long chargingStationId) {

        //判断状态
        if (type != null && (type == 0 || type == 1)) {
            //获取场站数据
            XhpcChargingStation xhpcChargingStation = xhpcChargingStationMapper.selectXhpcChargingStationById(chargingStationId);
            String clientVisibleValue = xhpcChargingStation.getClientVisible();
            if (clientVisibleValue == null || clientVisibleValue == "") {
                if (type == 0) {
                    xhpcChargingStationMapper.clientVisible(clientVisible, chargingStationId);
                }
            } else {
                //去掉重复的值
                String[] split = clientVisibleValue.split(",");
                Set<String> set = new HashSet<>(Arrays.asList(split));
                if (type == 0) {
                    set.add(clientVisible);
                } else {
                    set.remove(clientVisible);
                }
                String str = String.join(",", set);
                xhpcChargingStationMapper.clientVisible(str, chargingStationId);
            }
            return 1;
        }
        return 0;
    }

    @Override
    public List<Map<String, Object>> stationInternetBlackList(Long chargingStationId) {

        return xhpcChargingStationMapper.stationInternetBlackList(chargingStationId);
    }

    @Override
    @Transactional
    public AjaxResult addXhpcChargingStation(HttpServletRequest request, XhpcChargingStationDto xhpcChargingStationDto) {
        LoginUser loginUser = logUserUtils.getLogUser(request);
        String userName = loginUser.getUsername();

        R r1 = tenantService.gettenantIdTime(loginUser.getTenantId());
        if(r1.getCode()!=200){
            return AjaxResult.error(1001, "请重新登录");
        }else{
            Map<String, Object> map = (Map<String, Object>)r1.getData();
            if(map !=null){
                if(!map.get("stationQuote").equals("-1")){
                    int count = xhpcChargingStationMapper.getCountXhpcChargingStation(loginUser.getTenantId());
                    if(Integer.parseInt(map.get("stationQuote").toString())<count){
                        return AjaxResult.error(1001, "场站已达到限额，如要在创建场站请联系管理员");
                    }
                }
            }else{
                return AjaxResult.error(1001, "无法创建场站请联系管理员");
            }
        }


        if (xhpcChargingStationDto.getName() == null || "".equals(xhpcChargingStationDto.getName())) {
            return AjaxResult.error(1001, "电站名称不能为空");
        }
        if (xhpcChargingStationDto.getOperatorId() == null) {
            return AjaxResult.error(1001, "运营商不能为空");
        }
        if (xhpcChargingStationDto.getName().length()> 50) {
            return AjaxResult.error(1001, "电站名称不能超过50字");
        }
        if (xhpcChargingStationDto.getAreaCode() == null) {
            return AjaxResult.error(1001, "电站地址不能为空");
        }
        if (xhpcChargingStationDto.getAddress() == null) {
            return AjaxResult.error(1001, "详细地址不能为空");
        }
        if (xhpcChargingStationDto.getServiceFacilities() == null) {
            return AjaxResult.error(1001, "服务设施不能为空");
        }
        if (xhpcChargingStationDto.getSerialNumber() == null) {
            return AjaxResult.error(1001, "站编号不能为空");
        }
        if (xhpcChargingStationDto.getParkingInstructions() == null) {
            return AjaxResult.error(1001, "停车说明不能为空");
        }
        if (xhpcChargingStationDto.getBusinessInstructions() == null) {
            return AjaxResult.error(1001, "营业时间说明不能为空");
        }
        if (xhpcChargingStationDto.getReminderInstructions() == null) {
            return AjaxResult.error(1001, "温馨提示说明不能为空");
        }
        if (xhpcChargingStationDto.getRemark() == null) {
            return AjaxResult.error(1001, "备注不能为空");
        }
        if (xhpcChargingStationDto.getImgId() == null) {
            return AjaxResult.error(1001, "图片不能为空");
        }
        if (xhpcChargingStationDto.getServiceTel() == null) {
            return AjaxResult.error(1001, "站点电话不能为空");
        }
        if (xhpcChargingStationDto.getParkNums() == null) {
            return AjaxResult.error(1001, "侧位数量不能为空");
        }
        if (xhpcChargingStationDto.getChargingMethod() == null) {
            return AjaxResult.error(1001, "允许充电方式为空");
        }

        //判断费率和费率时间段 是否有值
        if (xhpcChargingStationDto.getXhpcRateList() == null && xhpcChargingStationDto.getXhpcRateList().size() == 0) {
            return AjaxResult.error(1001, "费率不能为空");
        }
        if (xhpcChargingStationDto.getXhpcRateTimeList() == null && xhpcChargingStationDto.getXhpcRateTimeList().size() == 0) {
            return AjaxResult.error(1001, "费率时段不能为空");
        } else {
            for (int i = 0; i < xhpcChargingStationDto.getXhpcRateTimeList().size(); i++) {
                String id = xhpcChargingStationDto.getXhpcRateTimeList().get(i).getId();
                if ("00".equals(id) || "01".equals(id) || "02".equals(id) || "03".equals(id)) {
                } else {
                    return AjaxResult.error("1003", "费率id格式不对");
                }
            }
        }
        List<XhpcRateTimeDtoYang> xhpcRateTimeList = xhpcChargingStationDto.getXhpcRateTimeList();

        for (int i = 0; i < xhpcRateTimeList.size(); i++) {
            XhpcRateTimeDtoYang xhpcRateTime = xhpcRateTimeList.get(i);
            String start = xhpcRateTime.getStartTime();
            String end = xhpcRateTime.getEndTime();
            String id = xhpcRateTime.getId();
            //检查格式,正则验证   【[0-2][0-9]：[0-6][0]：[0]{2}】
            String pattern = "^([0-2][0-9]:([0]|[3])[0]:[0][0])";
            Pattern compile = Pattern.compile(pattern);
            Matcher m = compile.matcher(start);

            if ("00".equals(id) || "01".equals(id) || "02".equals(id) || "03".equals(id)) {
            } else {
                return AjaxResult.error("1003", "费率id格式不对");
            }
            boolean isMatch = m.matches();
            if (!isMatch) {
                return AjaxResult.error("1003", "时间格式不对");
            }
            Matcher m1 = compile.matcher(end);
            boolean isMatch1 = m1.matches();
            if (!isMatch1) {
                return AjaxResult.error("1003", "时间格式不对");
            }
            //判断结束时间是否小于开始时间
            Date startTime = DateUtil.parse(start);
            Date endTime = DateUtil.parse(end);
            if (startTime.getTime() > endTime.getTime()) {
                return AjaxResult.error("1002", "开始时间不能大于结束时间");
            }
        }
        //判断是否有重叠
        for (int i = 0; i < xhpcRateTimeList.size(); i++) {
            XhpcRateTimeDtoYang xhpcRateTimeOne = xhpcRateTimeList.get(i);
            Date startOne = DateUtil.parse(xhpcRateTimeOne.getStartTime());
            Date endOne = DateUtil.parse(xhpcRateTimeOne.getEndTime());
            for (int j = i + 1; j < xhpcRateTimeList.size(); j++) {
                XhpcRateTimeDtoYang xhpcRateTimeTwo = xhpcRateTimeList.get(j);
                Date startTwo = DateUtil.parse(xhpcRateTimeTwo.getStartTime());
                Date endTwo = DateUtil.parse(xhpcRateTimeTwo.getEndTime());
                if (DateUtil.compare(startOne, endTwo) < 0 && DateUtil.compare(startTwo, endOne) < 0) {
                    return AjaxResult.error("1004", "时间段有重叠");
                }
            }
        }
        String tenantId = loginUser.getTenantId();
        //添加费率计费模型
        XhpcRateModel xhpcRateModel = new XhpcRateModel();
        BeanUtils.copyProperties(xhpcChargingStationDto, xhpcRateModel);
        xhpcRateModel.setCreateBy(userName);
        xhpcRateModel.setUpdateBy(userName);
        xhpcRateModel.setTenantId(tenantId);
        int i = xhpcChargingStationMapper.insertXhpcRateModel(xhpcRateModel);
        if (i == 0) {
            return AjaxResult.error("1005", "费率计费模型添加失败");
        }
        //费率模型id
        Long rateModelId = xhpcRateModel.getRateModelId();
        //添加电站基本信息
        XhpcChargingStation xhpcChargingStation = new XhpcChargingStation();
        BeanUtils.copyProperties(xhpcChargingStationDto, xhpcChargingStation);
        xhpcChargingStation.setRateModelId(rateModelId);
        xhpcChargingStation.setTenantId(tenantId);
        Map<String, Object> xhpcOperator = xhpcChargingStationMapper.getXhpcOperator(xhpcChargingStation.getOperatorId());
        if(xhpcOperator !=null &&xhpcOperator.get("operatorIdEvcs") !=null){
            xhpcChargingStation.setOperatorIdEvcs(xhpcOperator.get("operatorIdEvcs").toString());
        }else{
            return AjaxResult.error("1005", "运营商少监管平台推送编号");
        }
        xhpcChargingStation.setServiceFee(xhpcChargingStation.getServiceFeeDescribe());
        int j = xhpcChargingStationMapper.insertxhpcChargingStation(xhpcChargingStation);
        if (j == 0) {
            return AjaxResult.error("1006", "电站基本信息添加失败");
        }
        Long chargingStationId = xhpcChargingStation.getChargingStationId();

        //添加费率
        Map<String, Long> map = new HashMap<>();
        List<XhpcRateDto> xhpcRateList = xhpcChargingStationDto.getXhpcRateList();
        for (int k = 0; k < xhpcRateList.size(); k++) {
            //存费率信息，并存储Map,费率时段使用，找到费率id
            XhpcRateDto xhpcRateDto = xhpcRateList.get(k);
            XhpcRate xhpcRate = new XhpcRate();
            xhpcRate.setChargingStationId(chargingStationId);

            if ("00".equals(xhpcRateDto.getId()) || "01".equals(xhpcRateDto.getId()) || "02".equals(xhpcRateDto.getId()) || "03".equals(xhpcRateDto.getId())) {

                if ("00".equals(xhpcRateDto.getId())) {
                    xhpcRate.setName("尖费率");
                } else if ("01".equals(xhpcRateDto.getId())) {
                    xhpcRate.setName("峰费率");
                } else if ("02".equals(xhpcRateDto.getId())) {
                    xhpcRate.setName("平费率");
                } else {
                    xhpcRate.setName("谷费率");
                }
                xhpcRate.setPowerFee(xhpcRateDto.getPowerFee());
                xhpcRate.setServiceFee(xhpcRateDto.getServiceFee());
                xhpcRate.setRateModelId(rateModelId);
                xhpcRate.setRateValue(xhpcRateDto.getId());
                xhpcRate.setCreateBy(userName);
                xhpcRate.setUpdateBy(userName);
                xhpcRate.setTenantId(tenantId);
                xhpcChargingStationMapper.insertXhpcRate(xhpcRate);
                map.put(xhpcRateDto.getId(), xhpcRate.getRateId());
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  AjaxResult.error("添加费率错误，请稍后在试");
            }
        }

        //添加费率时段
        //冒泡排序（结束时间小于开始时间排前面）
        //存费率时段，从Map中获取费率id
        //每个时间段都要存
        //返回计费模型 24:00 转成 00:00
        XhpcRateTimeDtoYang[] xhpcRateTimeDtosArr = new XhpcRateTimeDtoYang[xhpcRateTimeList.size()];
        xhpcRateTimeList.toArray(xhpcRateTimeDtosArr);
        XhpcRateTimeDtoYang[] xhpcRateTimeDtos = bubbleSort(xhpcRateTimeDtosArr);
        //排序好的费率时段
        List<XhpcRateTimeDtoYang> list = Arrays.asList(xhpcRateTimeDtos);
        //默认时段费率Id
        Long defaultPeriodId = null;
        if (xhpcChargingStationDto.getDefaultPeriodId() != null) {
            defaultPeriodId = map.get(xhpcChargingStationDto.getDefaultPeriodId());
        }
        //默认费率类型值
        String rateValue = xhpcChargingStationDto.getDefaultPeriodId();

        String[] tfPricesSeq = new String[48];
        for (int k = 0; k <48 ; k++) {
            tfPricesSeq[k]=rateValue;
        }
        int sort = 1;
        for (int k = 0; k < list.size(); k++) {
            XhpcRateTimeDtoYang xhpcRateTimeDto = list.get(k);
            String startTime = xhpcRateTimeDto.getStartTime();
            String endTime = xhpcRateTimeDto.getEndTime();
            String rateValues = xhpcRateTimeDto.getId();
            Long defaultPeriodIdMap = map.get(rateValues);

            String str = startTime.split(":")[0];
            int st= Integer.valueOf(str);
            String str1 = startTime.split(":")[1];
            if("30".equals(str1)){
                st=st*2+1;
            }else{
                st=st*2;
            }
            String endT = endTime.split(":")[0];
            int end= Integer.valueOf(endT);
            String endT1 = endTime.split(":")[1];
            if("30".equals(endT1)){
                end=end*2+1;
            }else{
                end=end*2;
            }
            for (int l = st; l <end ; l++) {
                tfPricesSeq[l]=rateValues;
                //System.out.println("=====tfPricesSeq["+l+"]=========="+rateValues+"===========");
            }

            if(list.size() == 1){
                if(!"00:00:00".equals(xhpcRateTimeDto.getStartTime())){
                    if(rateValue ==null || "".equals(rateValue)){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return  AjaxResult.error("请填写默认时间段费率");
                    }
                    sort= addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, "00:00:00", startTime, sort, 2, rateValue, userName,tenantId);
                }
                sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodIdMap, startTime, endTime, sort, 1, rateValues, userName,tenantId);
                if(!endTime.equals("24:00:00")) {
                    if(rateValue ==null || "".equals(rateValue)){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return  AjaxResult.error("请填写默认时间段费率");
                    }
                    sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, endTime, "24:00:00", sort, 2, rateValue, userName,tenantId);
                }
            }else{
                if(k == 0){
                    if(!"00:00:00".equals(xhpcRateTimeDto.getStartTime())){
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  AjaxResult.error("请填写默认时间段费率");
                        }
                        sort= addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, "00:00:00", startTime, sort, 2, rateValue, userName,tenantId);
                    }
                    sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodIdMap, startTime, endTime, sort, 1, rateValues, userName,tenantId);
                }else if(k < list.size()-1){
                    String endTimeK = list.get(k - 1).getEndTime();
                    if (!endTimeK.equals(startTime)) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  AjaxResult.error("请填写默认时间段费率");
                        }
                        sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, endTimeK, startTime, sort, 2, rateValue, userName,tenantId);
                    }
                    //并把本条数据也添加上
                    sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodIdMap, startTime, endTime, sort, 1, rateValues, userName,tenantId);
                }else{
                    String endTimeK = list.get(k - 1).getEndTime();
                    if (!endTimeK.equals(startTime)) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  AjaxResult.error("请填写默认时间段费率");
                        }
                        //添加一条默认费率时段
                        sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, endTimeK, startTime, sort, 2, rateValue, userName,tenantId);
                    }
                    //并把本条数据也添加上
                    sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodIdMap, startTime, endTime, sort, 1, rateValues, userName,tenantId);
                    if (!endTime.equals("24:00:00")) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  AjaxResult.error("请填写默认时间段费率");
                        }
                        //添加一条默认费率时段
                        sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, endTime, "24:00:00", sort, 2, rateValue, userName,tenantId);
                    }
                }
            }
        }

        //设置费率模型
        CacheRateModel cacheRateModel = new CacheRateModel();
        cacheRateModel.setLossRate(0);
        BigDecimal valueSec = new BigDecimal(100000);
        boolean t1 = true;
        boolean t2 = true;
        boolean t3 = true;
        boolean t4 = true;
        for (XhpcRateDto xhpcRateDto : xhpcRateList) {
            BigDecimal powerFee = xhpcRateDto.getPowerFee();
            BigDecimal serviceFee = xhpcRateDto.getServiceFee();
            String id = xhpcRateDto.getId();
            int i1 = powerFee.multiply(valueSec).intValue();
            int i2 = serviceFee.multiply(valueSec).intValue();
            if ("00".equals(id)) {
                cacheRateModel.setT1Price(i1);
                cacheRateModel.setT1SvcPrice(i2);
                t1 = false;
            } else if ("01".equals(id)) {
                cacheRateModel.setT2Price(i1);
                cacheRateModel.setT2SvcPrice(i2);
                t2 = false;
            } else if ("02".equals(id)) {
                cacheRateModel.setT3Price(i1);
                cacheRateModel.setT3SvcPrice(i2);
                t3 = false;
            } else if ("03".equals(id)) {
                cacheRateModel.setT4Price(i1);
                cacheRateModel.setT4SvcPrice(i2);
                t4 = false;
            }
        }
        if (t1) {
            cacheRateModel.setT1Price(0);
            cacheRateModel.setT1SvcPrice(0);
        }
        if (t2) {
            cacheRateModel.setT2Price(0);
            cacheRateModel.setT2SvcPrice(0);
        }
        if (t3) {
            cacheRateModel.setT3Price(0);
            cacheRateModel.setT3SvcPrice(0);
        }
        if (t4) {
            cacheRateModel.setT4Price(0);
            cacheRateModel.setT4SvcPrice(0);
        }
        cacheRateModel.setTfPricesSeq(tfPricesSeq);

        R r = powerPileService.setStationRateModel(chargingStationId, rateModelId, cacheRateModel);

        if (r.getCode() != 200) {
            logger.info("添加费率桩服务错误："+r.getMsg());
            //数据回滚-手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  AjaxResult.error("添加费率入缓存失败，请稍后在试");
        }else{
            //费率发生改变，缓存到redis
            powerPileService.getNotificationStationFee(chargingStationId);
            //生成场站推送数据信息
            powerPileService.addNotificationStationInfo(chargingStationId);
            //生成场站运行充电方式
            Map<String, Object> chargingMethodMap =new HashMap<>();
            String[] split = xhpcChargingStation.getChargingMethod().split(",");
            for (int k = 0; k <split.length ; k++) {
                String s = split[k];
                chargingMethodMap.put(s,s);
            }
            redisService.setCacheMap("chargingMethod:"+chargingStationId,chargingMethodMap);
        }

       //修改桩和终端的模板id
        xhpcChargingStationMapper.updateXhpcChargingPile(chargingStationId,rateModelId);
        xhpcChargingStationMapper.updateXhpcTerminal(chargingStationId,rateModelId);
        try{
            //获取登陆用户
            Long logUserId = SecurityUtils.getUserId();
            if(logUserId !=1){
                Map<String, Object> landUser = xhpcChargingStationMapper.getLandUser(logUserId);
                if(landUser !=null){
                    if(landUser.get("userType") !=null && "02".equals(landUser.get("userType").toString())){
                        xhpcChargingStationMapper.insertXhpcUserPrivilege(logUserId,chargingStationId);
                    }
                }
            }
        }catch (Exception e){
            logger.info("添加场站权限失败");
        }

        return AjaxResult.success();
    }

    /**
     * 场站详情接口
     *
     * @param chargingStationId
     * @param type              1编辑使用   2详情使用
     * @return
     */
    @Override
    public Map<String, Object> getXhpcChargingStationMessage(Long chargingStationId, Integer type) {

        Map<String, Object> map = xhpcChargingStationMapper.getXhpcChargingStationMessage(chargingStationId);

        if(map !=null&& map.get("stationType") !=null){
            map.put("stationType",map.get("stationType").toString());
        }

        if(map !=null&& map.get("constructionSite") !=null){
            map.put("constructionSite",map.get("constructionSite").toString());
        }

        //图片信息
        if (map !=null &&map.get("imgId") != null && map.get("imgId").toString() != "") {
            String[] split = map.get("imgId").toString().split(",");
            List<Map<String, Object>> mapList =new ArrayList<>();
            for (int j = 0; j <split.length ; j++) {
                List<Map<String, Object>> mapList1 =new ArrayList<>();
                Map<String, Object> map1 =new AjaxResult();
                map1.put("imgId",j+1);
                map1.put("url",split[j]);
                mapList1.add(map1);
                mapList.addAll(mapList1);
            }
            map.put("imgIdList", mapList);
        } else {
            map.put("imgIdList", new ArrayList<>());
        }
        //费率
        List<Map<String, Object>> xhpcRateList = xhpcChargingStationMapper.getXhpcRateList(chargingStationId);
        map.put("xhpcRateList", xhpcRateList);

        //费率时段,先反设置时段，在反默认时段
        List<Map<String, Object>> xhpcRateTimeTypeList = xhpcChargingStationMapper.getXhpcRateTimeTypeList(chargingStationId, 1);
        map.put("xhpcRateTimeList", xhpcRateTimeTypeList);
        if (type == 2) {
            //统计终端（充redis获取终端信息）
            map =getTerminalStatusSum(map, chargingStationId,0);
            map =getTerminalStatusSum(map, chargingStationId,1);
            Date beginOfDay = DateUtil.beginOfDay(new Date());
            map.putAll(xhpcChargingStationMapper.getXhpcRateTimeOrderStatistics(chargingStationId,beginOfDay.toString()));
        }
        return map;
    }

    private int addXhpcRateTime(Long chargingStationId, Long rateModelId, Long defaultPeriodId, String startTime, String endTime, int sort, int type, String rateValue, String userName,String tenantId) {

        XhpcRateTime xhpcRateTime = new XhpcRateTime();
        xhpcRateTime.setChargingStationId(chargingStationId);
        xhpcRateTime.setRateId(defaultPeriodId);
        Date start = DateUtil.parse(startTime);
        xhpcRateTime.setStartTime(start);
        Date emd = DateUtil.parse(endTime);
        xhpcRateTime.setEndTime(emd);
        xhpcRateTime.setRateModelId(rateModelId);
        xhpcRateTime.setSort(sort);
        xhpcRateTime.setType(type);
        xhpcRateTime.setRateValue(rateValue);
        xhpcRateTime.setCreateTime(Calendar.getInstance().getTime());
        xhpcRateTime.setCreateBy(userName);
        xhpcRateTime.setUpdateBy(userName);
        xhpcRateTime.setTenantId(tenantId);
        xhpcChargingStationMapper.insertXhpcRateTime(xhpcRateTime);
        return sort++;
    }

    @Override
    public List<Map<String, Object>> getWXList(String name, String serviceFacilities, Integer code, String longitude, String latitude,String tenantId) {

        if(null==longitude||"".equals(longitude)||null==latitude||"".equals(latitude)){
            longitude="104.065861"; latitude="30.657401";
        }
        //检查是否有用户登录
        LoginUser loginUser = tokenService.getLoginUser();

        List<String> stringList = new ArrayList<>();
        if (serviceFacilities != null && serviceFacilities != "") {
            String[] split = serviceFacilities.split(",");
            stringList = Arrays.asList(split);
        }
        String date = DateUtil.formatTime(new Date());

        List<Map<String, Object>> list = xhpcChargingStationMapper.getWXList(name, stringList, code, longitude, latitude, 2,date,tenantId);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);

                BigDecimal serviceFee =new BigDecimal(map.get("serviceFee").toString());
                BigDecimal powerFee =new BigDecimal(map.get("powerFee").toString());
                if(loginUser !=null){
                    //判断是否享受活动
                    Map<String, Object> objectMap = activityDiscountTime(loginUser.getUserid(), new Date(), loginUser.getUserType(), Long.valueOf(map.get("chargingStationId").toString()), loginUser.getTenantId());
                    if("1".equals(objectMap.get("state").toString())){
                        if("1".equals(objectMap.get("totalDiscountType").toString())){
                            BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                            serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                            powerFee = powerFee.subtract(powerFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                            map.put("activityServiceFee", serviceFee);
                            map.put("activityPowerFee", powerFee);
                            map.put("activityMoney", serviceFee.add(powerFee));
                        }else if ("3".equals(objectMap.get("totalDiscountType").toString())){
                            BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                            serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                            map.put("activityServiceFee", serviceFee);
                            map.put("activityPowerFee", powerFee);
                            map.put("activityMoney", serviceFee.add(powerFee));
                        }else{
                            BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                            serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                            map.put("activityServiceFee", serviceFee);
                            map.put("activityPowerFee", powerFee);
                            map.put("activityMoney", serviceFee.add(powerFee));
                        }
                        if(objectMap.get("appletActivityName") !=null && !"".equals(objectMap.get("appletActivityName").toString())){
                            map.put("appletActivityName", objectMap.get("appletActivityName").toString());
                        }else{
                            map.put("appletActivityName", "");
                        }
                        map.put("activityState", 1);
                    }else{
                        map.put("activityState", 0);
                    }
                }else{
                    map.put("activityState", 0);
                }
                //桩（空闲和使用从redis获取）
                Map<String, Object> map1 =new HashMap<>();
                map1 = getTerminalStatusSum(map1, Long.valueOf(map.get("chargingStationId").toString()), 0);
                if(map1 !=null && map1.get("freeTime") !=null){
                    map.put("free", map1.get("freeTime").toString());
                }else{
                    map.put("free", 0);
                }
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> getWXXhpcChargingStationMessage(Long chargingStationId, String longitude, String latitude) {
        if(null==longitude||"".equals(longitude)||null==latitude||"".equals(latitude)){
            longitude="104.065861"; latitude="30.657401";
        }
        //获取基本信息
        Map<String, Object> map = xhpcChargingStationMapper.getWXXhpcChargingStationMessage(chargingStationId, longitude, latitude);
        try{
        LoginUser loginUser = tokenService.getLoginUser();
        Map<String, Object> map1 =new HashMap<>();
        map1 = getTerminalStatusSum(map1, chargingStationId, 0);
        if(map1 !=null && map1.get("freeTime") !=null){
            map.put("free", map1.get("freeTime").toString());
        }else{
            map.put("free", 0);
        }
        //图片信息
        if (map !=null &&map.get("imgId") != null && map.get("imgId").toString() != "") {
            String[] split = map.get("imgId").toString().split(",");
            List<Map<String, Object>> mapList =new ArrayList<>();
            for (int j = 0; j <split.length ; j++) {
                List<Map<String, Object>> mapList1 =new ArrayList<>();
                Map<String, Object> map13 =new AjaxResult();
                map13.put("imgId",j+1);
                map13.put("url",split[j]);
                mapList1.add(map13);
                mapList.addAll(mapList1);
            }
            map.put("imgIdList", mapList);
        } else {
            map.put("imgIdList", new ArrayList<>());
        }
        String tiem = DateUtil.formatTime(new Date());
        Map<String, Object> xhpcRateTime = xhpcRateTimeService.getXhpcRateTime(tiem, chargingStationId);
        if (xhpcRateTime != null) {
            //桩（空闲和使用从redis获取）
            BigDecimal serviceFee =new BigDecimal(xhpcRateTime.get("serviceFee").toString());
            BigDecimal powerFee =new BigDecimal(xhpcRateTime.get("powerFee").toString());
            if(loginUser !=null){
                System.out.println("==111======用户登录======");
                //判断是否享受活动
                Map<String, Object> objectMap = activityDiscountTime(loginUser.getUserid(), new Date(), loginUser.getUserType(), Long.valueOf(map.get("chargingStationId").toString()), loginUser.getTenantId());
                if("1".equals(objectMap.get("state").toString())){
                    if("1".equals(objectMap.get("totalDiscountType").toString())||"3".equals(objectMap.get("totalDiscountType").toString())){
                        BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                        serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                        powerFee = powerFee.subtract(powerFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                        map.put("activityServiceFee", serviceFee);
                        map.put("activityPowerFee", powerFee);
                        map.put("activityMoney", serviceFee.add(powerFee));
                    }else if ("3".equals(objectMap.get("totalDiscountType").toString())){
                        BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                        serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                        map.put("activityServiceFee", serviceFee);
                        map.put("activityPowerFee", powerFee);
                        map.put("activityMoney", serviceFee.add(powerFee));
                    }else{
                        BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                        serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                        map.put("activityServiceFee", serviceFee);
                        map.put("activityPowerFee", powerFee);
                        map.put("activityMoney", serviceFee.add(powerFee));
                    }
                    if(objectMap.get("appletActivityName") !=null && !"".equals(objectMap.get("appletActivityName").toString())){
                        map.put("appletActivityName", objectMap.get("appletActivityName").toString());
                    }else{
                        map.put("appletActivityName", "");
                    }
                    map.put("activityState", 1);
                }else{
                    System.out.println("==222======用户登录======");
                    map.put("activityState", 0);
                }
            }else{
                System.out.println("===333=====用户登录======");
                map.put("activityState", 0);
            }
            map.putAll(xhpcRateTime);
            }
            //获取该时段占位费电费
            Map<String, Object> placeholderTime = xhpcChargingStationMapper.getPlaceholderTime(tiem, chargingStationId);
            if(placeholderTime !=null){
                map.putAll(placeholderTime);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> getWXXhpcRateTimeMassage(Long chargingStationId) {
        List<Map<String, Object>> list = xhpcChargingStationMapper.getWXXhpcRateTimeMassage(chargingStationId);
        LoginUser loginUser = tokenService.getLoginUser();
        try{
            for (int i = 0; i <list.size() ; i++) {
                Map<String, Object> map = list.get(i);
                BigDecimal serviceFee =new BigDecimal(map.get("serviceFee").toString());
                BigDecimal powerFee =new BigDecimal(map.get("powerFee").toString());
                if(loginUser !=null){
                    //判断是否享受活动
                    Map<String, Object> objectMap = activityDiscountTime(loginUser.getUserid(), new Date(), loginUser.getUserType(), chargingStationId, loginUser.getTenantId());
                    if("1".equals(objectMap.get("state").toString())){
                        if("1".equals(objectMap.get("totalDiscountType").toString())||"3".equals(objectMap.get("totalDiscountType").toString())){
                            BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                            serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                            powerFee = powerFee.subtract(powerFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                            map.put("activityServiceFee", serviceFee);
                            map.put("activityPowerFee", powerFee);
                            map.put("activityMoney", serviceFee.add(powerFee));
                        }else if ("3".equals(objectMap.get("totalDiscountType").toString())){
                            BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                            serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                            map.put("activityServiceFee", serviceFee);
                            map.put("activityPowerFee", powerFee);
                            map.put("activityMoney", serviceFee.add(powerFee));
                        }else{
                            BigDecimal discountRate = new BigDecimal(objectMap.get("totalDiscountRate").toString()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                            serviceFee = serviceFee.subtract(serviceFee.multiply(discountRate).setScale(2,BigDecimal.ROUND_HALF_UP));
                            map.put("activityServiceFee", serviceFee);
                            map.put("activityPowerFee", powerFee);
                            map.put("activityMoney", serviceFee.add(powerFee));
                        }
                        map.put("activityState", 1);
                    }else{
                        map.put("activityState", 0);
                    }
                }else{
                    map.put("activityState", 0);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }

    @Override
    public List<Map<String, Object>> getPlaceholderTimeMassage(Long chargingStationId) {
        List<Map<String, Object>> list = xhpcChargingStationMapper.getPlaceholderTimeMassage(chargingStationId);
        return list;
    }

    @Override
    public List<Map<String, Object>> getWXXhpcTerminalMassage(Long chargingStationId) {

        List<Map<String, Object>> list = xhpcChargingStationMapper.getWXXhpcTerminalMassage(chargingStationId);

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                //终端状态用 redis数据
                if(map.get("serialNumber") !=null){
                    Map<String, Object> cacheMap =redisService.getCacheMap("gun:"+map.get("serialNumber").toString());
                    if(!cacheMap.isEmpty()){
                        if ("离线".equals(cacheMap.get("status").toString())){
                            map.put("status", 0);
                        }else if("故障".equals(cacheMap.get("status").toString())){
                            map.put("status", 1);
                            if(cacheMap.get("hf")!=null){
                                map.put("cause", cacheMap.get("hf").toString());
                            }else{
                                map.put("cause", "--");
                            }
                        }else if("空闲".equals(cacheMap.get("status").toString()) || "插枪".equals(cacheMap.get("status").toString())){
                             if("是".equals(cacheMap.get("vehicleGunStatus").toString())){
                                 map.put("status", 4);
                                 continue;
                             }
                             map.put("status", 2);
                        }else{
                            //充电桩
                            map.put("status", 3);
                            if(cacheMap.get("status")!=null){
                                map.put("soc", cacheMap.get("status").toString()+"%");
                            }else{
                                map.put("soc", "0%");
                            }
                            if(cacheMap.get("remainingTime")!=null){
                               int number = (int)cacheMap.get("remainingTime");
                                if(number>300){
                                    map.put("remainingTime", "未知");
                                }else{
                                    int mins = number % 60;
                                    int hours = number / 60;
                                    if(hours>0){
                                        map.put("remainingTime", hours+"小时"+mins+"分钟");
                                    }else{
                                        map.put("remainingTime", mins+"分钟");
                                    }
                                }
                            }else{
                                map.put("remainingTime", "--");
                            }
                        }
                    }else{
                        map.put("status", 5);
                    }
                }else{
                    map.put("status", 5);
                }
            }
        }
        return list;
    }

    @Override
    @Transactional
    public AjaxResult updateXhpcTerminal(XhpcChargingStation xhpcChargingStation) {
        //电站id不能为空
        if (xhpcChargingStation.getChargingStationId() == null) {
            return AjaxResult.error("1001", "电站id为空");
        }
        if (xhpcChargingStation.getName().length()> 50) {
            return AjaxResult.error(1001, "电站名称不能超过50字");
        }
        if (xhpcChargingStation.getChargingMethod() == null) {
            return AjaxResult.error(1001, "允许充电方式为空");
        }
        xhpcChargingStation.setServiceFee(xhpcChargingStation.getServiceFeeDescribe());
        //获取之前的模板id
        Long chargingStationId = xhpcChargingStation.getChargingStationId();
        XhpcChargingStation xhpc = xhpcChargingStationMapper.selectXhpcChargingStationById(chargingStationId);
        xhpcChargingStation.setRateModelId(xhpc.getRateModelId());
        xhpcChargingStationMapper.updateXhpcChargingStation(xhpcChargingStation);

        //生成场站推送数据信息
        powerPileService.addNotificationStationInfo(chargingStationId);
        //生成场站运行充电方式
        Map<String, Object> chargingMethodMap =new HashMap<>();
        String[] split = xhpcChargingStation.getChargingMethod().split(",");
        for (int k = 0; k <split.length ; k++) {
            String s = split[k];
            chargingMethodMap.put(s,s);
        }
        redisService.setCacheMap("chargingMethod:"+chargingStationId,chargingMethodMap);
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult updateXhpcRateTime(HttpServletRequest request, XhpcChargingStationDto xhpcChargingStationDto) {
        LoginUser loginUser = logUserUtils.getLogUser(request);
        String userName = loginUser.getUsername();
        String tenantId = loginUser.getTenantId();
        //电站id不能为空
        if (xhpcChargingStationDto.getChargingStationId() == null) {
            return AjaxResult.error("1001", "电站id为空");
        }
        //判断费率和费率时间段 是否有值
        if (xhpcChargingStationDto.getXhpcRateList() == null && xhpcChargingStationDto.getXhpcRateList().size() == 0) {
            return AjaxResult.error(1001, "费率不能为空");
        }
        if (xhpcChargingStationDto.getXhpcRateTimeList() == null && xhpcChargingStationDto.getXhpcRateTimeList().size() == 0) {
            return AjaxResult.error(1001, "费率时段不能为空");
        }
        List<XhpcRateTimeDtoYang> xhpcRateTimeList = xhpcChargingStationDto.getXhpcRateTimeList();

        for (int i = 0; i < xhpcRateTimeList.size(); i++) {
            XhpcRateTimeDtoYang xhpcRateTime = xhpcRateTimeList.get(i);
            String start = xhpcRateTime.getStartTime();
            String end = xhpcRateTime.getEndTime();
            //检查格式,正则验证   【[0-2][0-9]：[0-6][0]：[0]{2}】
            String pattern = "^([0-2][0-9]:([0]|[3])[0]:[0][0])";
            Pattern compile = Pattern.compile(pattern);
            Matcher m = compile.matcher(start);
            boolean isMatch = m.matches();
            if (!isMatch) {
                return AjaxResult.error("1003", "时间格式不对");
            }
            Matcher m1 = compile.matcher(end);
            boolean isMatch1 = m1.matches();
            if (!isMatch1) {
                return AjaxResult.error("1003", "时间格式不对");
            }
            //判断结束时间是否小于开始时间
            Date startTime = DateUtil.parse(start);
            Date endTime = DateUtil.parse(end);
            if (startTime.getTime() > endTime.getTime()) {
                return AjaxResult.error("1002", "开始时间不能大于结束时间");
            }
        }
        //判断是否有重叠
        for (int i = 0; i < xhpcRateTimeList.size(); i++) {
            XhpcRateTimeDtoYang xhpcRateTimeOne = xhpcRateTimeList.get(i);
            Date startOne = DateUtil.parse(xhpcRateTimeOne.getStartTime());
            Date endOne = DateUtil.parse(xhpcRateTimeOne.getEndTime());
            for (int j = i + 1; j < xhpcRateTimeList.size(); j++) {
                XhpcRateTimeDtoYang xhpcRateTimeTwo = xhpcRateTimeList.get(j);
                Date startTwo = DateUtil.parse(xhpcRateTimeTwo.getStartTime());
                Date endTwo = DateUtil.parse(xhpcRateTimeTwo.getEndTime());
                if (DateUtil.compare(startOne, endTwo) < 0 && DateUtil.compare(startTwo, endOne) < 0) {
                    return AjaxResult.error("1004", "时间段有重叠");
                }
            }
        }
        //添加费率计费模型
        XhpcRateModel xhpcRateModel = new XhpcRateModel();
        BeanUtils.copyProperties(xhpcChargingStationDto, xhpcRateModel);
        xhpcRateModel.setRemark("修改");
        xhpcRateModel.setCreateTime(new Date());
        xhpcRateModel.setCreateBy(userName);
        xhpcRateModel.setUpdateBy(userName);
        int i = xhpcChargingStationMapper.insertXhpcRateModel(xhpcRateModel);
        if (i == 0) {
            return AjaxResult.error("1005", "费率计费模型添加失败");
        }
        //费率模型id
        Long rateModelId = xhpcRateModel.getRateModelId();
        Long chargingStationId = xhpcChargingStationDto.getChargingStationId();
        //获取之前的模板id
        XhpcChargingStation xhpc = xhpcChargingStationMapper.selectXhpcChargingStationById(chargingStationId);
        xhpc.setRateModelId(rateModelId);
        xhpcChargingStationMapper.updateXhpcChargingStation(xhpc);

        //删除之前费率、费率时段
        xhpcChargingStationMapper.updateXhpcRateTime(chargingStationId);
        xhpcChargingStationMapper.updateXhpcRate(chargingStationId);

        //添加费率
        Map<String, Long> map = new HashMap<>();
        List<XhpcRateDto> xhpcRateList = xhpcChargingStationDto.getXhpcRateList();
        for (int k = 0; k < xhpcRateList.size(); k++) {
            //存费率信息，并存储Map,费率时段使用，找到费率id
            XhpcRateDto xhpcRateDto = xhpcRateList.get(k);
            if ("00".equals(xhpcRateDto.getId()) || "01".equals(xhpcRateDto.getId()) || "02".equals(xhpcRateDto.getId()) || "03".equals(xhpcRateDto.getId())) {
                XhpcRate xhpcRate = new XhpcRate();
                xhpcRate.setChargingStationId(chargingStationId);
                xhpcRate.setName(xhpcRateDto.getName());
                xhpcRate.setPowerFee(xhpcRateDto.getPowerFee());
                xhpcRate.setServiceFee(xhpcRateDto.getServiceFee());
                xhpcRate.setRateModelId(rateModelId);
                xhpcRate.setRateValue(xhpcRateDto.getId());
                xhpcRate.setUpdateBy(userName);
                xhpcRate.setCreateBy(userName);
                xhpcChargingStationMapper.insertXhpcRate(xhpcRate);
                map.put(xhpcRateDto.getId(), xhpcRate.getRateId());
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  AjaxResult.error("添加费率错误，请稍后在试");
            }
        }

        //添加费率时段
        //冒泡排序（结束时间小于开始时间排前面）
        //存费率时段，从Map中获取费率id
        //每个时间段都要存
        //返回计费模型 24:00 转成 00:00
        XhpcRateTimeDtoYang[] xhpcRateTimeDtosArr = new XhpcRateTimeDtoYang[xhpcRateTimeList.size()];
        xhpcRateTimeList.toArray(xhpcRateTimeDtosArr);
        XhpcRateTimeDtoYang[] xhpcRateTimeDtos = bubbleSort(xhpcRateTimeDtosArr);
        //排序好的费率时段
        List<XhpcRateTimeDtoYang> list = Arrays.asList(xhpcRateTimeDtos);
        //默认时段费率Id
        Long defaultPeriodId = null;
        if (xhpcChargingStationDto.getDefaultPeriodId() != null) {
            defaultPeriodId = map.get(xhpcChargingStationDto.getDefaultPeriodId());
        }
        //默认费率类型值
        String rateValue = xhpcChargingStationDto.getDefaultPeriodId();

        String[] tfPricesSeq = new String[48];
        for (int k = 0; k <48 ; k++) {
            tfPricesSeq[k]=rateValue;
        }
        int sort = 1;
        for (int k = 0; k < list.size(); k++) {
            XhpcRateTimeDtoYang xhpcRateTimeDto = list.get(k);
            String startTime = xhpcRateTimeDto.getStartTime();
            String endTime = xhpcRateTimeDto.getEndTime();
            String rateValues = xhpcRateTimeDto.getId();
            Long defaultPeriodIdMap = map.get(rateValues);

            String str = startTime.split(":")[0];
            int st= Integer.valueOf(str);
            String str1 = startTime.split(":")[1];

            if("30".equals(str1)){
                st=st*2+1;
            }else{
                st=st*2;
            }
            String endT = endTime.split(":")[0];
            int end= Integer.valueOf(endT);
            String endT1 = endTime.split(":")[1];
            if("30".equals(endT1)){
                end=end*2+1;
            }else{
                end=end*2;
            }
            for (int l = st; l <end ; l++) {
                tfPricesSeq[l]=rateValues;
                //System.out.println("=====tfPricesSeq["+l+"]=========="+rateValues+"===========");
            }

            if(list.size() == 1){
                if(!"00:00:00".equals(xhpcRateTimeDto.getStartTime())){
                    if(rateValue ==null || "".equals(rateValue)){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return  AjaxResult.error("请填写默认时间段费率");
                    }
                    sort= addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, "00:00:00", startTime, sort, 2, rateValue, userName,tenantId);
                }
                sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodIdMap, startTime, endTime, sort, 1, rateValues, userName,tenantId);
                if(!endTime.equals("24:00:00")) {
                    if(rateValue ==null || "".equals(rateValue)){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return  AjaxResult.error("请填写默认时间段费率");
                    }
                    sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, endTime, "24:00:00", sort, 2, rateValue, userName,tenantId);
                }
            }else{
                if(k == 0){
                    if(!"00:00:00".equals(xhpcRateTimeDto.getStartTime())){
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  AjaxResult.error("请填写默认时间段费率");
                        }
                        sort= addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, "00:00:00", startTime, sort, 2, rateValue, userName,tenantId);
                    }
                    sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodIdMap, startTime, endTime, sort, 1, rateValues, userName,tenantId);
                }else if(k < list.size()-1){
                    String endTimeK = list.get(k - 1).getEndTime();
                    if (!endTimeK.equals(startTime)) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  AjaxResult.error("请填写默认时间段费率");
                        }
                        sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, endTimeK, startTime, sort, 2, rateValue, userName,tenantId);
                    }
                    //并把本条数据也添加上
                    sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodIdMap, startTime, endTime, sort, 1, rateValues, userName,tenantId);
                }else{
                    String endTimeK = list.get(k - 1).getEndTime();
                    if (!endTimeK.equals(startTime)) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  AjaxResult.error("请填写默认时间段费率");
                        }
                        //添加一条默认费率时段
                        sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, endTimeK, startTime, sort, 2, rateValue, userName,tenantId);
                    }
                    //并把本条数据也添加上
                    sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodIdMap, startTime, endTime, sort, 1, rateValues, userName,tenantId);
                    if (!endTime.equals("24:00:00")) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return  AjaxResult.error("请填写默认时间段费率");
                        }
                        //添加一条默认费率时段
                        sort = addXhpcRateTime(chargingStationId, rateModelId, defaultPeriodId, endTime, "24:00:00", sort, 2, rateValue, userName,tenantId);
                    }
                }
            }
        }
        //设置费率模型
        CacheRateModel cacheRateModel = new CacheRateModel();
        cacheRateModel.setLossRate(0);
        BigDecimal valueSec = new BigDecimal(100000);
        boolean t1 = true;
        boolean t2 = true;
        boolean t3 = true;
        boolean t4 = true;
        for (XhpcRateDto xhpcRateDto : xhpcRateList) {
            BigDecimal powerFee = xhpcRateDto.getPowerFee();
            BigDecimal serviceFee = xhpcRateDto.getServiceFee();
            String id = xhpcRateDto.getId();
            int i1 = powerFee.multiply(valueSec).intValue();
            int i2 = serviceFee.multiply(valueSec).intValue();
            if ("00".equals(id)) {
                cacheRateModel.setT1Price(i1);
                cacheRateModel.setT1SvcPrice(i2);
                t1 = false;
            } else if ("01".equals(id)) {
                cacheRateModel.setT2Price(i1);
                cacheRateModel.setT2SvcPrice(i2);
                t2 = false;
            } else if ("02".equals(id)) {
                cacheRateModel.setT3Price(i1);
                cacheRateModel.setT3SvcPrice(i2);
                t3 = false;
            } else if ("03".equals(id)) {
                cacheRateModel.setT4Price(i1);
                cacheRateModel.setT4SvcPrice(i2);
                t4 = false;
            }
        }
        if (t1) {
            cacheRateModel.setT1Price(0);
            cacheRateModel.setT1SvcPrice(0);
        }
        if (t2) {
            cacheRateModel.setT2Price(0);
            cacheRateModel.setT2SvcPrice(0);
        }
        if (t3) {
            cacheRateModel.setT3Price(0);
            cacheRateModel.setT3SvcPrice(0);
        }
        if (t4) {
            cacheRateModel.setT4Price(0);
            cacheRateModel.setT4SvcPrice(0);
        }
        cacheRateModel.setTfPricesSeq(tfPricesSeq);
        R r = powerPileService.setStationRateModel(chargingStationId, rateModelId, cacheRateModel);
        if (r.getCode() != 200) {
            logger.info("添加费率桩服务错误："+r.getMsg());
            //数据回滚-手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return  AjaxResult.error("添加费率入缓存失败，请稍后在试");
        }
        //费率发生改变，缓存到redis
        powerPileService.getNotificationStationFee(chargingStationId);
        //修改桩和终端的模板id
        xhpcChargingStationMapper.updateXhpcChargingPile(chargingStationId,rateModelId);
        xhpcChargingStationMapper.updateXhpcTerminal(chargingStationId,rateModelId);

        //发送校时校价命令
        Set<String> pileList = xhpcChargingStationMapper.getXchargingPileList(chargingStationId);
        if(pileList.size()>0){
            List<String> setlist = new ArrayList<>(pileList);
            for (int j = 0; j <setlist.size() ; j++) {
                String s = setlist.get(j);
                powerPileService.configTimeNRateModel(s);
            }
        }
        return AjaxResult.success();
    }

    public static XhpcRateTimeDtoYang[] bubbleSort(XhpcRateTimeDtoYang[] args) {
        //冒泡排序算法
        for (int i = 0; i < args.length - 1; i++) {
            for (int j = i + 1; j < args.length; j++) {
                String start = args[i].getEndTime();
                String end = args[j].getStartTime();
                if (DateUtil.parse(start).getTime() > DateUtil.parse(end).getTime()) {
                    XhpcRateTimeDtoYang temp = args[i];
                    args[i] = args[j];
                    args[j] = temp;
                }
            }
        }
        return args;
    }

    /**
     * 0 添加  1删除
     *
     * @param status
     * @param chargingStationId
     */
    @Override
    public void extracted(Integer status, Long chargingStationId) {

        Set<String> set = xhpcChargingStationMapper.getXchargingPileList(chargingStationId);
        if (set != null && set.size() > 0) {
            if (status == 0) {
                //添加场站下面的所有桩 todo add version :wenhui
                //powerPileService.addPileWhitelist(chargingStationId, set);
            } else {
                //删除场站下面的所有桩
                //powerPileService.deletePileWhitelist(chargingStationId, set);
            }
        }
    }


    public int countTerminal(String serialNumbers){
        int number =0;
        //获取空闲终端
        String[] split = serialNumbers.split(",");

        if(!"".equals(serialNumbers) && serialNumbers !=null){
            for (String serialNumber:split) {
                Map<String, Object> cacheMap =redisService.getCacheMap("gun:"+serialNumber);
                if(cacheMap !=null && ("空闲".equals(cacheMap.get("status"))|| "插枪".equals(cacheMap.get("status").toString()))){
                    number++;
                }
            }
        }
        return number;
    }

    @Override
    public Map<String, Object> getTerminalStatusSum(Map<String, Object> map, Long chargingStationId,Integer status) {

        //获取桩的统计.redis 数据
        List<String> terminal = xhpcTerminalService.getTerminal(chargingStationId,status);
        int offLine =0;//离线
        int fault =0;//故障
        int freeTime =0;//空闲
        int charge =0;//充电
        int unknown =0;//未知
        if(terminal !=null && terminal.size()>0){
            for (String st:terminal) {
                Map<String, Object> cacheMap = redisService.getCacheMap("gun:" + st);
                if(!cacheMap.isEmpty()){
                    if (cacheMap.containsKey("status") &&
                            "离线".equals(cacheMap.get("status").toString())){
                        offLine++;
                    }else if(cacheMap.containsKey("status") &&
                            "故障".equals(cacheMap.get("status").toString())){
                        fault++;
                    }else if(cacheMap.containsKey("status") &&
                            ("空闲".equals(cacheMap.get("status").toString())|| "插枪".equals(cacheMap.get("status").toString()))){
                        freeTime++;
                    }else{
                        charge++;
                    }
                }else{
                    unknown++;
                }
            }
        }
        if(status==0){
            map.put("offLine",offLine);
            map.put("fault",fault);
            map.put("freeTime",freeTime);
            map.put("charge",charge);
            map.put("unknown",unknown);
        }else{
            map.put("notOffLine",offLine);
            map.put("notFault",fault);
            map.put("notFreeTime",freeTime);
            map.put("notCharge",charge);
            map.put("notUnknown",unknown);
        }


        return map;
    }

    @Override
    public int getTerminalStatus(String serialNumber) {
        //0离线 1故障 2空闲 3充电 4 已插枪 5未知
       // Integer status =5;
        //终端状态用 redis数据
        if(!"".equals(serialNumber) && serialNumber!=null){
            Map<String, Object> cacheMap =redisService.getCacheMap("gun:"+serialNumber);
            if(cacheMap !=null && cacheMap.get("status") !=null){
                if ("离线".equals(cacheMap.get("status").toString())){
                    return 0;
                }else if("故障".equals(cacheMap.get("status").toString())){
                    return 1;
                }else if("空闲".equals(cacheMap.get("status").toString()) || "插枪".equals(cacheMap.get("status").toString())){
                    if("是".equals(cacheMap.get("vehicleGunStatus").toString())){
                        return 4;
                    }else{
                        return 2;
                    }
                }else{
                    //充电桩
                    return 3;
                }
            }
            return 5;
        }else{
            return 5;
        }
    }

    @Override
    public Boolean findOneByStationId(Integer chargingStationId) {

        XhpcChargingStation xhpcChargingStation = xhpcChargingStationMapper.selectXhpcChargingStationById(Long.valueOf(chargingStationId));
        return xhpcChargingStation != null;
    }

    //判断是否有活动
    @Override
    public Map<String,Object> activityDiscountTime(Long userId,Date startTime,Integer source,Long chargingStationId,String tenantId){
        Map<String,Object> map =new HashMap<>();
        List<XhpcActivityDiscountDto> activityDiscountTime = xhpcChargingStationMapper.getActivityDiscountTime(userId, DateUtil.formatDateTime(startTime), source, chargingStationId, tenantId);
        if(activityDiscountTime !=null && activityDiscountTime.size()>0){
            //折扣电费、服务费
            BigDecimal totalDiscountRate =new BigDecimal(0);
            int totalDiscountType = 0;
            String appletActivityName ="";
            for (int i = 0; i < activityDiscountTime.size(); i++) {
                XhpcActivityDiscountDto activity = activityDiscountTime.get(i);
                BigDecimal discountRate = activity.getDiscountRate();
                Integer discountType = activity.getDiscountType();
                if(discountType.equals(1)){
                    if(totalDiscountType==0){
                        totalDiscountRate =discountRate;
                        totalDiscountType = 1;
                        appletActivityName = activity.getAppletActivityName();
                    }else if(totalDiscountType==1 || totalDiscountType==3){
                        if(totalDiscountRate.compareTo(discountRate)<0){
                            totalDiscountRate =discountRate;
                            totalDiscountType=1;
                            appletActivityName = activity.getAppletActivityName();
                        }
                    }else{
                        if(totalDiscountRate.compareTo(discountRate.multiply(new BigDecimal(2)))<0){
                            totalDiscountRate =discountRate;
                            totalDiscountType = 1;
                            appletActivityName = activity.getAppletActivityName();
                        }
                    }
                }else if(discountType.equals(2)){
                    if(totalDiscountType==0){
                        totalDiscountRate =discountRate;
                        totalDiscountType = 2;
                        appletActivityName = activity.getAppletActivityName();
                    }else if(totalDiscountType==1 || totalDiscountType==3){
                        if(totalDiscountRate.multiply(new BigDecimal(2)).compareTo(discountRate)<0){
                            totalDiscountRate =discountRate;
                            totalDiscountType = 2;
                            appletActivityName = activity.getAppletActivityName();
                        }
                    }else {
                        if(totalDiscountRate.compareTo(discountRate)<0){
                            totalDiscountRate =discountRate;
                            appletActivityName = activity.getAppletActivityName();
                        }
                    }
                }else{
                    //电量抽成
                    if(totalDiscountType==0){
                        totalDiscountRate =discountRate;
                        totalDiscountType = 3;
                        appletActivityName = activity.getAppletActivityName();
                    }else if(totalDiscountType==1 || totalDiscountType==3){
                        if(totalDiscountRate.compareTo(discountRate)<0){
                            totalDiscountRate =discountRate;
                            totalDiscountType = 3;
                            appletActivityName = activity.getAppletActivityName();
                        }
                    }else{
                        if(totalDiscountRate.multiply(new BigDecimal(2)).compareTo(discountRate)<0){
                            totalDiscountRate =discountRate;
                            totalDiscountType = 3;
                            appletActivityName = activity.getAppletActivityName();
                        }
                    }
                }
            }
            map.put("appletActivityName",appletActivityName);
            map.put("state","1");
            map.put("totalDiscountRate",totalDiscountRate);
            map.put("totalDiscountType",totalDiscountType+"");
        }else{
            map.put("state","0");
        }
        return map;
    }

    @Override
    public R getNotificationStationInfo(Long stationId) {
        R r = powerPileService.getNotificationStationInfo(stationId);
        if (r.getCode() != 200) {
            logger.info("组合场站信息（成都市平台）失败，请稍后在试："+r.getMsg());
            //数据回滚-手动回滚
            return  R.fail("组合场站信息（成都市平台）失败，请稍后在试");
        }
        return R.ok(null,"组合场站信息（成都市平台）成功");
    }

    @Override
    public void getchargingMethodList() {
        List<Map<String, Object>> mapList = xhpcChargingStationMapper.getchargingMethodList();
        for (int i = 0; i < mapList.size(); i++) {
            Map<String, Object> map = mapList.get(i);
            String chargingStationId = map.get("chargingStationId").toString();
            String chargingNethod = map.get("chargingNethod").toString();
            if(chargingNethod!=null && !chargingNethod.equals("")){
                Map<String, Object> chargingMethodMap =new HashMap<>();
                String[] split = chargingNethod.split(",");
                for (int k = 0; k <split.length ; k++) {
                    String s = split[k];
                    chargingMethodMap.put(s,s);
                }
                redisService.setCacheMap("chargingMethod:"+chargingStationId,chargingMethodMap);
            }
        }
    }


    @Override
    public R getXhpcRateTimeOrder(Long rateModelId, String startTime, String endTime,String serialNumber) {
        List<com.xhpc.common.dto.XhpcRateTimeDto> reatTimeList = xhpcChargingStationMapper.getReatTimeList(startTime, endTime, rateModelId);
        Map<String, Object> cacheOrder =new HashMap<>();
        cacheOrder.put(serialNumber,reatTimeList);
        redisService.setCacheMap("Yu"+serialNumber,cacheOrder);
        return R.ok();
    }

    @Override
    public R getCrossDayXhpcRateTimeOrder(Long rateModelId, String startTime, String endTime,String serialNumber) {

        String start1 = endTime.substring(0,10)+" 00:00:00";
        String end1 = startTime.substring(0,10)+" 23:59:59";

        DateTime parse1 = DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss");
        DateTime parse2 = DateUtil.parse(end1, "yyyy-MM-dd HH:mm:ss");

        DateTime parse3 = DateUtil.parse(start1, "yyyy-MM-dd HH:mm:ss");
        DateTime parse4 = DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss");

        List<com.xhpc.common.dto.XhpcRateTimeDto> reatTimeList1 = xhpcChargingStationMapper.getReatTimeList(DateUtil.formatTime(parse1), DateUtil.formatTime(parse2), rateModelId);

        List<com.xhpc.common.dto.XhpcRateTimeDto> reatTimeList2 = xhpcChargingStationMapper.getReatTimeList(DateUtil.formatTime(parse3), DateUtil.formatTime(parse4), rateModelId);
        List<com.xhpc.common.dto.XhpcRateTimeDto> combinedList = new ArrayList<>();
        combinedList.addAll(reatTimeList1);
        combinedList.addAll(reatTimeList2);

        Map<String, Object> cacheOrder =new HashMap<>();
        cacheOrder.put(serialNumber,combinedList);
        redisService.setCacheMap("Yu"+serialNumber,cacheOrder);
        return R.ok();
    }


}
