package com.xhpc.charging.station.service;

import cn.hutool.core.date.DateUtil;
import com.xhpc.charging.station.mapper.XhpcChargingStationMapper;
import com.xhpc.charging.station.mapper.XhpcTimingChargingModelMapper;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.api.SmsService;
import com.xhpc.common.api.dto.XhpcRateDto;
import com.xhpc.common.api.dto.XhpcRateTimeDtoYang;
import com.xhpc.common.api.dto.XhpcTimingChargingModelDto;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.data.redis.CacheRateModel;
import com.xhpc.common.domain.*;
import com.xhpc.common.security.service.TokenService;
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.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.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yuyang
 * @date 2022/2/22 13:46
 */
@Service
public class XhpcTimingChargingModelServiceImpl extends BaseService implements IXhpcTimingChargingModelService{

    @Autowired
    private XhpcTimingChargingModelMapper xhpcTimingChargingModelMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PowerPileService powerPileService;
    @Autowired
    private IXhpcChargingStationService xhpcChargingStationService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private XhpcChargingStationMapper xhpcChargingStationMapper;

    private final ExecutorService executorService = Executors.newFixedThreadPool(20);

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

    @Override
    public List<Map<String, Object>> list(HttpServletRequest request,String tenantId,Long operatorId, String reason, Integer status, String startTime, String endTime, Long chargingStationId) {

        LoginUser loginUser = tokenService.getLoginUser(request);
        SysUser sysUser = loginUser.getSysUser();

        Long sysUserId = sysUser.getUserId();
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUserId)){
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                return xhpcTimingChargingModelMapper.list(operatorId,reason,status,startTime,endTime,chargingStationId,logOperatorId, 1,tenantId);
            }else{
                //查询赋值的场站
                return xhpcTimingChargingModelMapper.list(operatorId,reason,status,startTime,endTime,chargingStationId,sysUserId, 2,tenantId);
            }
        }else{
            return xhpcTimingChargingModelMapper.list(operatorId,reason,status,startTime,endTime,chargingStationId,sysUserId, 0,tenantId);
        }

    }

    @Override
    @Transactional
    public R addXhpcTimingChargingModel(HttpServletRequest request, XhpcTimingChargingModelDto xhpcTimingChargingModelDto) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(loginUser ==null){
            return R.fail(1001, "登录信息为空");
        }
        if (xhpcTimingChargingModelDto.getReason() == null || "".equals(xhpcTimingChargingModelDto.getReason())) {
            return R.fail(1001, "调整原因不能为空");
        }
        if (xhpcTimingChargingModelDto.getChargingStationId() == null || "".equals(xhpcTimingChargingModelDto.getChargingStationId())) {
            return R.fail(1001, "场站不能为空");
        }
        if (xhpcTimingChargingModelDto.getTimingTime() == null || "".equals(xhpcTimingChargingModelDto.getTimingTime())) {
            return R.fail(1001, "调整时间不能为空");
        }else{
            if(System.currentTimeMillis()>xhpcTimingChargingModelDto.getTimingTime().getTime()){
                return R.fail(1001, "调整时间不能小于现在时间");
            }
        }
        if (xhpcTimingChargingModelDto.getXhpcRateList() == null && xhpcTimingChargingModelDto.getXhpcRateList().size() == 0) {
            return R.fail(1001, "费率不能为空");
        }
        if (xhpcTimingChargingModelDto.getXhpcRateTimeList() == null && xhpcTimingChargingModelDto.getXhpcRateTimeList().size() == 0) {
            return R.fail(1001, "费率时段不能为空");
        } else {
            for (int i = 0; i < xhpcTimingChargingModelDto.getXhpcRateTimeList().size(); i++) {
                String id = xhpcTimingChargingModelDto.getXhpcRateTimeList().get(i).getId();
                if ("00".equals(id) || "01".equals(id) || "02".equals(id) || "03".equals(id)) {
                } else {
                    return R.fail("1003", "费率id格式不对");
                }
            }
        }
        List<XhpcRateTimeDtoYang> xhpcRateTimeList = xhpcTimingChargingModelDto.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 R.fail("1003", "费率id格式不对");
            }
            boolean isMatch = m.matches();
            if (!isMatch) {
                return R.fail("1003", "时间格式不对");
            }
            Matcher m1 = compile.matcher(end);
            boolean isMatch1 = m1.matches();
            if (!isMatch1) {
                return R.fail("1003", "时间格式不对");
            }
            //判断结束时间是否小于开始时间
            Date startTime = DateUtil.parse(start);
            Date endTime = DateUtil.parse(end);
            if (startTime.getTime() > endTime.getTime()) {
                return R.fail("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 R.fail("1004", "时间段有重叠");
                }
            }
        }
        Long chargingStationId = xhpcTimingChargingModelDto.getChargingStationId();
        //创建定时计费模型
        XhpcTimingChargingModel xhpcTimingChargingModel =new XhpcTimingChargingModel();
        xhpcTimingChargingModel.setReason(xhpcTimingChargingModelDto.getReason());
        xhpcTimingChargingModel.setTimingTime(xhpcTimingChargingModelDto.getTimingTime());
        xhpcTimingChargingModel.setCreateTime(new Date());
        xhpcTimingChargingModel.setChargingStationId(chargingStationId);
        xhpcTimingChargingModel.setPhone(xhpcTimingChargingModelDto.getPhone());

        if(xhpcTimingChargingModelDto.getChargingPileIds()!=null){
            Integer[] chargingPileIds = xhpcTimingChargingModelDto.getChargingPileIds();
            String PileIds ="";
            for (int i = 0; i <chargingPileIds.length ; i++) {
                if(i==0 && chargingPileIds.length>1){
                    PileIds =PileIds+chargingPileIds[i];
                }else if(chargingPileIds.length==1){
                    PileIds =chargingPileIds[i]+"";
                }else{
                    PileIds =PileIds+","+chargingPileIds[i];
                }
            }
            xhpcTimingChargingModel.setPileIds(PileIds);
        }



        if(xhpcTimingChargingModelDto.getTimingChargingModelId() !=null){
            xhpcTimingChargingModel.setTimingChargingModelId(xhpcTimingChargingModelDto.getTimingChargingModelId());
            xhpcTimingChargingModelMapper.updateXhpcTimingChargingModel(xhpcTimingChargingModel);

            //删除之前添加的费率和费率时段
            xhpcTimingChargingModelMapper.updateXhpcTtimingChargingRate(xhpcTimingChargingModel.getTimingChargingModelId());
            xhpcTimingChargingModelMapper.updateXhpcTimingChargingTime(xhpcTimingChargingModel.getTimingChargingModelId());
            xhpcTimingChargingModelMapper.updateXhpcTimingChargingCacheRateModel(xhpcTimingChargingModel.getTimingChargingModelId());
        }else{
            int i = xhpcTimingChargingModelMapper.insertXhpcTimingChargingModel(xhpcTimingChargingModel);
            if (i == 0) {
                return R.fail("1006", "定时计费模型添加失败");
            }
        }

        Long timingChargingModelId = xhpcTimingChargingModel.getTimingChargingModelId();


        //添加费率
        Map<String, Long> map = new HashMap<>();
        List<XhpcRateDto> xhpcRateList = xhpcTimingChargingModelDto.getXhpcRateList();
        for (int k = 0; k < xhpcRateList.size(); k++) {
            //存费率信息，并存储Map,费率时段使用，找到费率id
            XhpcRateDto xhpcRateDto = xhpcRateList.get(k);
            XhpcTimingChargingRate xhpcTtimingChargingRate = new XhpcTimingChargingRate();
            xhpcTtimingChargingRate.setChargingStationId(chargingStationId);
            if ("00".equals(xhpcRateDto.getId()) || "01".equals(xhpcRateDto.getId()) || "02".equals(xhpcRateDto.getId()) || "03".equals(xhpcRateDto.getId())) {

                if ("00".equals(xhpcRateDto.getId())) {
                    xhpcTtimingChargingRate.setName("尖费率");
                } else if ("01".equals(xhpcRateDto.getId())) {
                    xhpcTtimingChargingRate.setName("峰费率");
                } else if ("02".equals(xhpcRateDto.getId())) {
                    xhpcTtimingChargingRate.setName("平费率");
                } else {
                    xhpcTtimingChargingRate.setName("谷费率");
                }
                xhpcTtimingChargingRate.setPowerFee(xhpcRateDto.getPowerFee());
                xhpcTtimingChargingRate.setServiceFee(xhpcRateDto.getServiceFee());
                xhpcTtimingChargingRate.setTimingChargingModelId(timingChargingModelId);
                xhpcTtimingChargingRate.setRateValue(xhpcRateDto.getId());
                xhpcTimingChargingModelMapper.insertXhpcTtimingChargingRate(xhpcTtimingChargingRate);
                map.put(xhpcRateDto.getId(), xhpcTtimingChargingRate.getTimingChargingRateId());
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  R.fail("添加费率错误，请稍后在试");
            }
        }
        //添加费率时段
        //冒泡排序（结束时间小于开始时间排前面）
        //存费率时段，从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 (xhpcTimingChargingModelDto.getDefaultPeriodId() != null) {
            defaultPeriodId = map.get(xhpcTimingChargingModelDto.getDefaultPeriodId());
        }
        //默认费率类型值
        String rateValue = xhpcTimingChargingModelDto.getDefaultPeriodId();
        String[] tfPricesSeq = new String[48];
        for (int k = 0; k <48 ; k++) {
            tfPricesSeq[k]=rateValue;
        }
        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  R.fail("请填写默认时间段费率");
                    }
                    addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodId, "00:00:00", startTime, 2, rateValue);
                }
                    addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodIdMap, startTime, endTime,1, rateValues);
                if(!endTime.equals("24:00:00")) {
                    if(rateValue ==null || "".equals(rateValue)){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return  R.fail("请填写默认时间段费率");
                    }
                    addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodId, endTime, "24:00:00", 2, rateValue);
                }
            }else{
                if(k == 0){
                    if(!"00:00:00".equals(xhpcRateTimeDto.getStartTime())){
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.fail("请填写默认时间段费率");
                        }
                        addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodId, "00:00:00", startTime,2, rateValue);
                    }
                     addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodIdMap, startTime, endTime,1, rateValues);
                }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 R.fail("请填写默认时间段费率");
                        }
                       addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodId, endTimeK, startTime,2, rateValue);
                    }
                    //并把本条数据也添加上
                    addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodIdMap, startTime, endTime,1, rateValues);
                }else{
                    String endTimeK = list.get(k - 1).getEndTime();
                    if (!endTimeK.equals(startTime)) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.fail("请填写默认时间段费率");
                        }
                        //添加一条默认费率时段
                        addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodId, endTimeK, startTime,2, rateValue);
                    }
                    //并把本条数据也添加上
                    addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodIdMap, startTime, endTime,1, rateValues);
                    if (!endTime.equals("24:00:00")) {
                        if(rateValue ==null || "".equals(rateValue)){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.fail("请填写默认时间段费率");
                        }
                        //添加一条默认费率时段
                        addXhpcRateTime(chargingStationId, timingChargingModelId, defaultPeriodId, endTime, "24:00:00",2, rateValue);
                    }
                }
            }
        }
        XhpcTimingChargingCacheRateModel xhpcTimingChargingCacheRateModel=new XhpcTimingChargingCacheRateModel();
        xhpcTimingChargingCacheRateModel.setLossRate(0);
        xhpcTimingChargingCacheRateModel.setTenantId(xhpcTimingChargingModel.getTenantId());
        xhpcTimingChargingCacheRateModel.setTimingChargingModelId(timingChargingModelId);
        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)) {
                xhpcTimingChargingCacheRateModel.setOnePrice(i1);
                xhpcTimingChargingCacheRateModel.setOneSvcPrice(i2);
                t1 = false;
            } else if ("01".equals(id)) {
                xhpcTimingChargingCacheRateModel.setTwoPrice(i1);
                xhpcTimingChargingCacheRateModel.setTwoSvcPrice(i2);
                t2 = false;
            } else if ("02".equals(id)) {
                xhpcTimingChargingCacheRateModel.setThreePrice(i1);
                xhpcTimingChargingCacheRateModel.setThreeSvcPrice(i2);
                t3 = false;
            } else if ("03".equals(id)) {
                xhpcTimingChargingCacheRateModel.setFourPrice(i1);
                xhpcTimingChargingCacheRateModel.setFourSvcPrice(i2);
                t4 = false;
            }
        }
        if (t1) {
            xhpcTimingChargingCacheRateModel.setOneSvcPrice(0);
            xhpcTimingChargingCacheRateModel.setOnePrice(0);
        }
        if (t2) {
            xhpcTimingChargingCacheRateModel.setTwoSvcPrice(0);
            xhpcTimingChargingCacheRateModel.setTwoPrice(0);
        }
        if (t3) {
            xhpcTimingChargingCacheRateModel.setThreeSvcPrice(0);
            xhpcTimingChargingCacheRateModel.setThreePrice(0);
        }
        if (t4) {
            xhpcTimingChargingCacheRateModel.setFourSvcPrice(0);
            xhpcTimingChargingCacheRateModel.setFourPrice(0);
        }
        StringBuilder st = new StringBuilder();
        for (int i = 0; i < tfPricesSeq.length; i++) {
            if(i==0){
                st = new StringBuilder(tfPricesSeq[i]);
            }else{
                st.append(",").append(tfPricesSeq[i]);
            }
        }
        xhpcTimingChargingCacheRateModel.setTfPricesSeq(st.toString());
        xhpcTimingChargingCacheRateModel.setChargingStationId(chargingStationId);
        xhpcTimingChargingCacheRateModel.setPhone(xhpcTimingChargingModelDto.getPhone());
        xhpcTimingChargingModelMapper.insertXhpcTimingChargingCacheRateModel(xhpcTimingChargingCacheRateModel);
        return R.ok();
    }

    @Override
    public R updateXhpcTimingChargingModel(Long timingChargingModelId) {
        Map<String, Object> map =new HashMap<>();
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser ==null){
            return R.ok(map);
        }
        //查询是否是未执行状态
        map = xhpcTimingChargingModelMapper.getXhpcTimingChargingModelMapById(timingChargingModelId,loginUser.getTenantId());

        if(map.get("pileIds")!=null){
            String[] split = map.get("pileIds").toString().split(",");
            Integer [] piles =new Integer [split.length];
            for (int i = 0; i <split.length ; i++) {
                String s = split[i];
                piles[i] = Integer.parseInt(s);
            }
            map.put("chargingPileIds",piles);
        }
        //费率
        List<Map<String, Object>> xhpcRateList = xhpcTimingChargingModelMapper.getXhpcTimingChargingRateList(timingChargingModelId);

        map.put("xhpcRateList", xhpcRateList);
        //费率时段,先反设置时段，在反默认时段
        List<Map<String, Object>> xhpcRateTimeTypeList = xhpcTimingChargingModelMapper.getXhpcTimingChargingTimeTypeList(timingChargingModelId);
        map.put("xhpcRateTimeList", xhpcRateTimeTypeList);
        return R.ok(map);
    }

    @Override
    public R getXhpcTimingChargingModelMessage(Long timingChargingModelId) {
        Map<String, Object> map =new HashMap<>();
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser ==null){
            return R.ok(map);
        }
        //查询是否是未执行状态
        map = xhpcTimingChargingModelMapper.getXhpcTimingChargingModelMapById(timingChargingModelId,loginUser.getTenantId());
        //费率
        List<Map<String, Object>> xhpcRateList = xhpcTimingChargingModelMapper.getXhpcTimingChargingRateList(timingChargingModelId);

        map.put("xhpcRateList", xhpcRateList);
        //费率时段,先反设置时段，在反默认时段
        List<Map<String, Object>> xhpcRateTimeTypeList = xhpcTimingChargingModelMapper.getXhpcTimingChargingTimeTypeList(timingChargingModelId);
        map.put("xhpcRateTimeList", xhpcRateTimeTypeList);
        return R.ok(map);
    }

    @Override
    public XhpcTimingChargingModel getXhpcTimingChargingModelById(Long timingChargingModelId) {
        return xhpcTimingChargingModelMapper.getXhpcTimingChargingModelById(timingChargingModelId,null);
    }

    @Override
    public int updateXhpcTimingChargingModel(XhpcTimingChargingModel xhpcTimingChargingModel) {
        return xhpcTimingChargingModelMapper.updateXhpcTimingChargingModel(xhpcTimingChargingModel);
    }

    @Override
    @Transactional
    public R getXhpcTimingChargingModelCron() {
        //顺序排列
        List<XhpcTimingChargingCacheRateModel> list = xhpcTimingChargingModelMapper.getXhpcTimingChargingModelId();
        Date date = new Date();
        if(list !=null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                XhpcTimingChargingCacheRateModel timingCharging = list.get(i);
                if(timingCharging !=null && timingCharging.getTfPricesSeq() !=null) {
                    String[] tfPricesSeq = timingCharging.getTfPricesSeq().split(",");
                    if(tfPricesSeq.length==48){
                        CacheRateModel cacheRateModel = new CacheRateModel();
                        cacheRateModel.setLossRate(0);
                        cacheRateModel.setT1Price(timingCharging.getOnePrice());
                        cacheRateModel.setT1SvcPrice(timingCharging.getOneSvcPrice());
                        cacheRateModel.setT2Price(timingCharging.getTwoPrice());
                        cacheRateModel.setT2SvcPrice(timingCharging.getTwoSvcPrice());
                        cacheRateModel.setT3Price(timingCharging.getThreePrice());
                        cacheRateModel.setT3SvcPrice(timingCharging.getThreeSvcPrice());
                        cacheRateModel.setT4Price(timingCharging.getFourPrice());
                        cacheRateModel.setT4SvcPrice(timingCharging.getFourSvcPrice());
                        cacheRateModel.setTfPricesSeq(tfPricesSeq);

                        //添加费率计费模型
                        XhpcRateModel xhpcRateModel = new XhpcRateModel();
                        xhpcRateModel.setRemark("修改");
                        xhpcRateModel.setCreateTime(new Date());
                        int k = xhpcTimingChargingModelMapper.insertXhpcRateModel(xhpcRateModel);
                        if(k==0){
                            logger.info("定时计费模型-----添加费率模型失败:"+timingCharging.getTimingChargingModelId());
                            return R.fail("添加费率模型失败");
                        }
                        Long chargingStationId = timingCharging.getChargingStationId();
                        Long rateModelId = xhpcRateModel.getRateModelId();
                        Long timingChargingModelId = timingCharging.getTimingChargingModelId();
                        String tenantId = timingCharging.getTenantId();
                        //修改场站费率
                        XhpcChargingStation xhpcChargingStation = xhpcChargingStationService.selectXhpcChargingStationById(chargingStationId);
                        xhpcChargingStation.setRateModelId(rateModelId);
                        xhpcChargingStationService.updateXhpcChargingStation(xhpcChargingStation);
                        //删除该场站之前费率、费率时段
                        xhpcChargingStationService.updateXhpcRateTimeChargingStationId(chargingStationId);
                        //添加费率
                        List<XhpcTimingChargingRate> timingChargingRate = xhpcTimingChargingModelMapper.getRateTimingChargingModelId(timingChargingModelId);
                        if(timingChargingModelId ==null || timingChargingRate.size()==0){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.fail("费率查询为空");
                        }
                        //添加费率
                        Map<String, Long> map = new HashMap<>();
                        for (int j = 0; j < timingChargingRate.size(); j++) {
                            XhpcTimingChargingRate xhpcTimingChargingRate = timingChargingRate.get(j);
                            XhpcRate xhpcRate = new XhpcRate();
                            xhpcRate.setChargingStationId(chargingStationId);
                            xhpcRate.setName(xhpcTimingChargingRate.getName());
                            xhpcRate.setPowerFee(xhpcTimingChargingRate.getPowerFee());
                            xhpcRate.setServiceFee(xhpcTimingChargingRate.getServiceFee());
                            xhpcRate.setRateModelId(rateModelId);
                            xhpcRate.setRateValue(xhpcTimingChargingRate.getRateValue());
                            xhpcRate.setTenantId(xhpcTimingChargingRate.getTenantId());
                            xhpcRate.setCreateTime(date);
                            int number = xhpcChargingStationService.insertXhpcRate(xhpcRate);
                            if(number==0){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                logger.info("定时计费模型-----添加费率失败:"+timingCharging.getTimingChargingModelId());
                                return R.fail("添加费率失败");
                            }
                            map.put(xhpcTimingChargingRate.getRateValue(), xhpcRate.getRateId());
                        }
                        //添加费率时段
                        List<XhpcTimingChargingTime> timingChargingTime = xhpcTimingChargingModelMapper.getTimeTimingChargingModelId(timingChargingModelId);
                        if(timingChargingTime ==null || timingChargingTime.size()==0){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.fail("费率时段为空");
                        }
                        for (int j = 0; j < timingChargingTime.size(); j++) {
                            XhpcTimingChargingTime xhpcTimingChargingTime = timingChargingTime.get(j);
                            XhpcRateTime xhpcRateTime = new XhpcRateTime();
                            xhpcRateTime.setChargingStationId(chargingStationId);
                            xhpcRateTime.setStartTime(xhpcTimingChargingTime.getStartTime());
                            xhpcRateTime.setEndTime(xhpcTimingChargingTime.getEndTime());
                            xhpcRateTime.setRateModelId(rateModelId);
                            xhpcRateTime.setSort(xhpcTimingChargingTime.getSort());
                            xhpcRateTime.setType(xhpcTimingChargingTime.getType());
                            Long rateId = map.get(xhpcTimingChargingTime.getRateValue());
                            xhpcRateTime.setRateId(rateId);
                            xhpcRateTime.setRateValue(xhpcTimingChargingTime.getRateValue());
                            xhpcRateTime.setCreateTime(Calendar.getInstance().getTime());
                            int number = xhpcChargingStationService.insertXhpcRateTime(xhpcRateTime);
                            if(number==0){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                logger.info("定时计费模型-----添加费率时段失败:"+timingCharging.getTimingChargingModelId());
                                return R.fail("添加费率时段失败");
                            }
                        }
                        R r =powerPileService.setStationRateModel(chargingStationId,rateModelId,cacheRateModel);
                        if (r.getCode() != 200) {
                            //数据回滚-手动回滚
                            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            //短信通知
                            HashMap<String, String> paramMap = new HashMap<>();
                            paramMap.put("phone", timingCharging.getPhone());
                            paramMap.put("content", "计费--尊敬的用户，计费模型"+timingChargingModelId+"更新失败，请快速处理");
                            smsService.sendNotice(paramMap);

                            executorService.execute(new Runnable() {
                                @Override
                                public void run() {
                                    int k=0;
                                    do{
                                        R r =powerPileService.setStationRateModel(chargingStationId,rateModelId,cacheRateModel);
                                        if(r.getCode()==200){
                                            k++;
                                            XhpcTimingChargingModel xhpcTimingChargingModel = xhpcTimingChargingModelMapper.getXhpcTimingChargingModelById(timingChargingModelId, tenantId);
                                            xhpcTimingChargingModel.setStatus(2);
                                            xhpcTimingChargingModel.setNumber(k);
                                            xhpcTimingChargingModelMapper.updateXhpcTimingChargingModel(xhpcTimingChargingModel);
                                        }
                                    }while (k>0);
                                }
                            });
                        }else{
                            //改变定时计费模型状态
                            XhpcTimingChargingModel xhpcTimingChargingModel = xhpcTimingChargingModelMapper.getXhpcTimingChargingModelById(timingChargingModelId, tenantId);
                            xhpcTimingChargingModel.setStatus(1);
                            xhpcTimingChargingModel.setErrorReason(r.getMsg());
                            xhpcTimingChargingModelMapper.updateXhpcTimingChargingModel(xhpcTimingChargingModel);
                            //费率发生改变，缓存到redis
                            powerPileService.getNotificationStationFee(chargingStationId);

                            //发送校时校价命令
                            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 R.ok();
                    }
                }
            }
        }
        return  R.ok();
    }

    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;
    }
    private void addXhpcRateTime(Long chargingStationId, Long rateModelId, Long defaultPeriodId, String startTime, String endTime,int type, String rateValue) {

        XhpcTimingChargingTime xhpcTimingChargingTime = new XhpcTimingChargingTime();
        xhpcTimingChargingTime.setChargingStationId(chargingStationId);
        xhpcTimingChargingTime.setTimingChargingRateId(defaultPeriodId);
        Date start = DateUtil.parse(startTime);
        xhpcTimingChargingTime.setStartTime(start);
        Date emd = DateUtil.parse(endTime);
        xhpcTimingChargingTime.setEndTime(emd);
        xhpcTimingChargingTime.setTimingChargingModelId(rateModelId);
        xhpcTimingChargingTime.setType(type);
        xhpcTimingChargingTime.setRateValue(rateValue);
        xhpcTimingChargingTime.setCreateTime(new Date());
        xhpcTimingChargingModelMapper.insertXhpcTimingChargingTime(xhpcTimingChargingTime);
    }


}
