package com.xhpc.order.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.xhpc.common.api.WorkOrderYuService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.page.TableDataInfo;
import com.xhpc.common.log.annotation.Log;
import com.xhpc.common.log.enums.BusinessType;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.order.domain.XhpcHistoryOrder;
import com.xhpc.order.domain.XhpcStatisticsStation;
import com.xhpc.order.domain.XhpcStatisticsTimeInterval;
import com.xhpc.order.dto.XhpcChargeHistoryOrder;
import com.xhpc.order.service.IXhpcChargeOrderService;
import com.xhpc.order.service.IXhpcHistoryOrderService;
import com.xhpc.order.service.IXhpcStatisticsService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 历史订单
 * @author yuyang
 * @date 2021/8/3 21:19
 */
@EnableScheduling
@RestController
@RequestMapping("/histotyOrder")
@Api(value = "历史订单接口", tags = "历史订单接口")
public class XhpcHistoryOrderController extends BaseController {

    @Autowired
    private IXhpcHistoryOrderService xhpcHistoryOrderService;
    @Autowired
    private IXhpcStatisticsService xhpcStatisticsService;

    @Autowired
    private IXhpcChargeOrderService chargeOrderService;
    @Autowired
    private WorkOrderYuService workOrderYuService;
    @Autowired
    private RedisService redisService;

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

    /**
     * 历史订单
     * @param phone                         用户账号
     * @param transactionNumber             订单编号
     * @param type                        1 自动结算 2 平台结算
     * @param chargingStationName           电站名称
     * @param operatorId                    运营商id
     * @param source                        用户类型  0C端用户 1流量用户
     * @param beginStartTime                     订单开始-开始时间
     * @param beginEndTime                       订单开始-结束时间
     * @param userId                        用户id
     * @param status                        1 平台 2 运营商 3流量方
     * @param affiliationOrganization       归属机构
     * @param evcsOrderNo                   互联单号
     * @param plateNum                    车牌号
     * @param internetId                  流量方名称
     * @param internetSerialNumber        流量方订单号
     * @param terminalName                终端名称
     * @param vinCode                     VIN码
     * @param overStartTime               订单结束-开始时间
     * @param overEndTime                 订单结束-开始时间
     * @param personnelId                 人员id
     * @return
     */
    @GetMapping("/getListPage")
    public TableDataInfo  getListPage(String tenantId,Long chargingStationId,Long chargingPileId,Long terminalId, String phone,String transactionNumber,Integer status,String chargingStationName,Long operatorId,Integer source,String beginStartTime,String beginEndTime,Long userId, Integer type,
                                      String affiliationOrganization,String evcsOrderNo,String plateNum,Integer internetId,String internetSerialNumber,String terminalName,String vinCode,String overStartTime,String overEndTime,Long personnelId, Integer confirmResult,String mark)

    {
        List<Map<String, Object>> listPage = xhpcHistoryOrderService.getListPage(tenantId,chargingStationId,chargingPileId,terminalId,phone, transactionNumber, status, chargingStationName, operatorId, source, beginStartTime, beginEndTime, userId, type, affiliationOrganization,evcsOrderNo,plateNum,internetId,internetSerialNumber,terminalName,vinCode,overStartTime,overEndTime,personnelId,confirmResult,mark);
        return getDataTable(listPage);
    }

    /**
     * 历史订单详情
     * @param historyOrderId 历史订单id
     * @return
     */
    @GetMapping("/getById")
    public AjaxResult getById(@RequestParam("historyOrderId")Long historyOrderId){
        return xhpcHistoryOrderService.getById(historyOrderId);
    }


    /**
     * 历史订单导出
     * @param response 返回数据流
     * @throws IOException 文件创建异常
     */
    @PostMapping("/export")
    public void getExport(HttpServletResponse response,
                          String tenantId,
                          Long chargingStationId,
                          Long chargingPileId,
                          Long terminalId,
                          String phone,
                          String transactionNumber,
                          @RequestParam("status")Integer status,
                          String chargingStationName,
                          Long operatorId,
                          Integer source,
                          String beginStartTime,
                          String beginEndTime,
                          @RequestParam("userId") Long userId,
                          Integer type,
                          String affiliationOrganization,
                          String evcsOrderNo,
                          String plateNum,
                          Integer internetId,
                          String internetSerialNumber,
                          String terminalName,
                          String vinCode,
                          String overStartTime,
                          String overEndTime,
                          Long personnelId,
                          Integer confirmResult,
                          String mark) throws IOException {

        xhpcHistoryOrderService.export(response,tenantId,chargingStationId,chargingPileId,terminalId, phone, transactionNumber, status, chargingStationName, operatorId, source, beginStartTime, beginEndTime, userId, type,affiliationOrganization,evcsOrderNo,plateNum,internetId,internetSerialNumber,terminalName,vinCode,overStartTime,overEndTime,personnelId,confirmResult,mark);
    }


    /**
     * 日期统计\场站统计\终端统计
     */
    @GetMapping("/test1")
    @Scheduled(cron = "0 0/2 * * * ?")
    public void test1(){
        add(3000,1);
    }
    /**
     * 日期统计(已废弃)
     */
    @GetMapping("/test7")
    //@Scheduled(cron = "0 0/6 * * * ?")
    public void test7(){
//        int type =1;
//        List<XhpcChargeHistoryOrder> list = xhpcHistoryOrderService.getStatistisList(1000,type);
//        //是否跨天
//        if(list !=null && list.size()>0){
//            for (XhpcChargeHistoryOrder xhpc:list) {
//                //是否跨天
//                Date startTime = xhpc.getStartTime();
//                Date endTime = xhpc.getEndTime();
//                //1时间没有跨天
//                DateTime parse = DateUtil.parse(DateUtil.format(startTime, "yyyy-MM-dd"), "yyyy-MM-dd");
//                DateTime parse1 = DateUtil.parse(DateUtil.format(endTime, "yyyy-MM-dd"), "yyyy-MM-dd");
//                long betweenDay = DateUtil.between(parse,parse1, DateUnit.DAY);
//
//                if(xhpc.getTotalPrice().compareTo(new BigDecimal(0)) !=1){
//                    continue;
//                }
//                if(xhpc.getChargingDegree().compareTo(new BigDecimal(0)) !=1){
//                    continue;
//                }
//                //每分钟多少度电
//                BigDecimal decimal = new BigDecimal((endTime.getTime() - startTime.getTime())).divide(new BigDecimal(60000),2,BigDecimal.ROUND_HALF_UP);
//                if(decimal.compareTo(new BigDecimal(0)) !=1){
//                    continue;
//                }
//                BigDecimal divide = xhpc.getChargingDegree().divide(decimal,2,BigDecimal.ROUND_HALF_UP);
//
//                if(betweenDay==0){
//                    XhpcStatisticsStation xhpcSt =new XhpcStatisticsStation();
//                    xhpcSt.setChargingDegree(xhpc.getChargingDegree());
//                    xhpcSt.setChargingTime(decimal);
//                    xhpcSt.setChargingNumber(1);
//                    xhpcSt.setPowerPrice(xhpc.getPowerPriceTotal());
//                    xhpcSt.setServicePrice(xhpc.getServicePriceTotal());
//                    xhpcSt.setTotalPrice(xhpc.getTotalPrice());
//                    xhpcSt.setPromotionDiscount(xhpc.getPromotionDiscount());
//                    xhpcSt.setActPrice(xhpc.getActPrice());
//                    xhpcSt.setInternetCommission(xhpc.getInternetCommission());
//                    xhpcSt.setInternetSvcCommission(xhpc.getInternetSvcCommission());
//                    xhpcSt.setPlatformCommission(xhpc.getPlatformCommission());
//                    xhpcSt.setPlatformSvcCommisssion(xhpc.getPlatformSvcCommisssion());
//                    xhpcSt.setOperationCommission(xhpc.getOperationCommission());
//                    xhpcSt.setOperationSvcCommission(xhpc.getOperationSvcCommission());
//                    xhpcSt.setActPowerPrice(xhpc.getActPowerPrice());
//                    xhpcSt.setActServicePrice(xhpc.getActServicePrice());
//                    if(xhpc.getSource()==1){
//                        xhpcSt.setInternetUserId(xhpc.getUserId());
//                    }
//                    xhpcSt.setOperatorId(xhpc.getOperatorId());
//                    xhpcSt.setChargingStationId(xhpc.getChargingStationId());
//                    xhpcSt.setCreateTime(Calendar.getInstance().getTime());
//                    xhpcSt.setTerminalId(xhpc.getTerminalId());
//                    xhpcSt.setHistoryOrderId(xhpc.getHistoryOrderId());
//                    xhpcSt.setChargingPileId(xhpc.getChargingPileId());
//                    xhpcSt.setType(type);
//                    xhpcSt.setCreateTime(xhpc.getEndTime());
//                    xhpcStatisticsService.addStatisticsStation(xhpcSt);
//                    //修改历史订单表状态
//                    xhpcHistoryOrderService.updateXhpcHistoryOrder(xhpc.getHistoryOrderId(),type + 1);
//                }else{
//                    //跨天
//                    DateTime tomorrow = DateUtil.offsetDay(startTime,1);
//                    Date startTime3 =DateUtil.beginOfDay(tomorrow);
//
//                    Map<String, BigDecimal> map =addStatisticsStation(new HashMap<String,BigDecimal>(),xhpc, DateUtil.formatTime(startTime), "23:59:59",divide,1,1);
//
//                    addStatisticsStation(map,xhpc, DateUtil.formatTime(startTime3), DateUtil.formatTime(endTime),divide,2,1);
//
//                }
//
//            }
//        }
    }

    private Map<String,BigDecimal> addStatisticsStation(Map<String,BigDecimal> map1, XhpcChargeHistoryOrder xhpc, String startTime, String endTime, BigDecimal divide,int number,int type) {

//        //总金额
//        BigDecimal totalPrice =new BigDecimal(0);
//        //总电费
//        BigDecimal powerPriceTotal =new BigDecimal(0);
//        //总服务费
//        BigDecimal servicePriceTotal =new BigDecimal(0);
//        //实收电费
//        BigDecimal actPowerPrice =new BigDecimal(0);
//        //实收服务费
//        BigDecimal actServicePrice =new BigDecimal(0);
//        //总充电电量
//        BigDecimal chargingDegree =new BigDecimal(0);
//        //电站活动抵扣--抵扣的总金额
//        BigDecimal promotionDiscount =new BigDecimal(0);
//        //实际价格-用户支付的钱
//        BigDecimal actPrice =new BigDecimal(0);
//        if(number ==2){
//            totalPrice =map1.get("totalPrice");
//            powerPriceTotal =map1.get("powerPriceTotal");
//            servicePriceTotal =map1.get("servicePriceTotal");
//            actPowerPrice =map1.get("actPowerPrice");
//            actServicePrice =map1.get("actServicePrice");
//            chargingDegree =map1.get("chargingDegree");
//            promotionDiscount =map1.get("promotionDiscount");
//            actPrice =map1.get("actPrice");
//        }else{
//            totalPrice = xhpc.getTotalPrice();
//            powerPriceTotal =xhpc.getPowerPriceTotal();
//            servicePriceTotal =xhpc.getServicePriceTotal();
//            actPowerPrice =xhpc.getActPowerPrice();
//            actServicePrice =xhpc.getActServicePrice();
//            chargingDegree =xhpc.getChargingDegree();
//            promotionDiscount = xhpc.getPromotionDiscount();
//            actPrice = xhpc.getActPrice();
//        }
//
//        //叠加总电费
//        BigDecimal powerPriceTotal1 =new BigDecimal(0);
//        //叠加总服务费
//        BigDecimal servicePriceTotal1 =new BigDecimal(0);
//
//
//        //时长
//        BigDecimal timeInterval = new BigDecimal(0);
//        //时长
//        BigDecimal chargingDegree2 = new BigDecimal(0);
//
//
//        List<Map<String, Object>> reatTimeList = xhpcHistoryOrderService.getReatTimeList(startTime, endTime, xhpc.getRateModelId());
//        for (int i = 0; i <reatTimeList.size() ; i++) {
//            BigDecimal powerFee =new BigDecimal(0);
//            BigDecimal serviceFee =new BigDecimal(0);
//            String startTime1 =startTime;
//            String endTime1 =endTime;
//            Map<String, Object> map = reatTimeList.get(i);
//            //获取费率
//            if(reatTimeList.size()==1){
//                powerFee =new BigDecimal(map.get("powerFee").toString());
//                serviceFee =new BigDecimal(map.get("serviceFee").toString());
//            }else if (i==0){
//                powerFee =new BigDecimal(map.get("powerFee").toString());
//                serviceFee =new BigDecimal(map.get("serviceFee").toString());
//                endTime1 = map.get("endTime").toString();
//                if("00:00:00".equals(endTime1)){
//                    endTime1="23:59:59";
//                }
//            }else if(i!=reatTimeList.size()-1){
//                powerFee =new BigDecimal(map.get("powerFee").toString());
//                serviceFee =new BigDecimal(map.get("serviceFee").toString());
//                startTime1 = map.get("startTime").toString();
//                endTime1 = map.get("endTime").toString();
//                if("00:00:00".equals(endTime1)){
//                    endTime1="23:59:59";
//                }
//            }else{
//                powerFee =new BigDecimal(map.get("powerFee").toString());
//                serviceFee =new BigDecimal(map.get("serviceFee").toString());
//                startTime1 = map.get("startTime").toString();
//            }
//            timeInterval =timeInterval.add(new BigDecimal((DateUtil.parse(endTime1).getTime()-DateUtil.parse(startTime1).getTime())).divide(new BigDecimal(60000),2, BigDecimal.ROUND_HALF_UP));
//            powerPriceTotal1 = powerPriceTotal1.add(powerFee.multiply(divide).setScale(2, BigDecimal.ROUND_HALF_UP));
//            servicePriceTotal1 = servicePriceTotal1.add(serviceFee.multiply(divide).setScale(2, BigDecimal.ROUND_HALF_UP));
//            chargingDegree2 =chargingDegree2.add(timeInterval.multiply(divide).setScale(2,BigDecimal.ROUND_HALF_UP));
//        }
//        XhpcStatisticsStation xhpcSt =new XhpcStatisticsStation();
//        xhpcSt.setChargingDegree(chargingDegree2);
//        xhpcSt.setChargingTime(timeInterval.divide(new BigDecimal(60),2,BigDecimal.ROUND_HALF_UP));
//        xhpcSt.setChargingNumber(1);
//        xhpcSt.setPowerPrice(powerPriceTotal1);
//        xhpcSt.setServicePrice(servicePriceTotal1);
//        xhpcSt.setActPowerPrice(powerPriceTotal1);
//        xhpcSt.setActServicePrice(servicePriceTotal1);
//        xhpcSt.setTotalPrice(powerPriceTotal1.add(servicePriceTotal1));
//        BigDecimal actPrice2 =powerPriceTotal1.add(servicePriceTotal1);
//        BigDecimal promotion =new BigDecimal(2);
//        xhpcSt.setPromotionDiscount(xhpc.getPromotionDiscount().divide(promotion,2, BigDecimal.ROUND_HALF_UP));
//        xhpcSt.setInternetCommission(xhpc.getInternetCommission().divide(promotion,2, BigDecimal.ROUND_HALF_UP));
//        xhpcSt.setInternetSvcCommission(xhpc.getInternetSvcCommission().divide(promotion,2, BigDecimal.ROUND_HALF_UP));
//        xhpcSt.setPlatformCommission(xhpc.getPlatformCommission().divide(promotion,2, BigDecimal.ROUND_HALF_UP));
//        xhpcSt.setPlatformSvcCommisssion(xhpc.getPlatformSvcCommisssion().divide(promotion,2, BigDecimal.ROUND_HALF_UP));
//        xhpcSt.setOperationCommission(xhpc.getOperationCommission().divide(promotion,2, BigDecimal.ROUND_HALF_UP));
//        xhpcSt.setOperationSvcCommission(xhpc.getOperationSvcCommission().divide(promotion,2, BigDecimal.ROUND_HALF_UP));
//        if(number==1){
//            BigDecimal internetCommission = xhpcSt.getInternetCommission();
//            if(internetCommission.compareTo(new BigDecimal(0))!=0){
//                actPrice2 = actPrice2.subtract(internetCommission);
//            }else{
//                actPrice2 =actPrice2.subtract(xhpcSt.getInternetSvcCommission());
//            }
//            actPrice2 = actPrice2.subtract(xhpcSt.getPromotionDiscount());
//            xhpcSt.setActPrice(actPrice2);
//            //总金额
//            BigDecimal totalPrice1 = xhpcSt.getTotalPrice();
//            if(totalPrice.compareTo(totalPrice1)==1){
//                totalPrice=totalPrice.subtract(totalPrice1);
//            }else{
//                xhpcSt.setTotalPrice(totalPrice);
//            }
//            //总电费
//            BigDecimal powerPrice1 = xhpcSt.getPowerPrice();
//            if(powerPriceTotal.compareTo(powerPrice1)==1){
//                powerPriceTotal=powerPriceTotal.subtract(powerPrice1);
//            }else{
//                xhpcSt.setPowerPrice(powerPriceTotal);
//            }
//            //总服务费
//            BigDecimal servicePrice1 = xhpcSt.getServicePrice();
//            if(servicePriceTotal.compareTo(servicePrice1)==1){
//                servicePriceTotal=servicePriceTotal.subtract(servicePrice1);
//            }else{
//                xhpcSt.setServicePrice(servicePriceTotal);
//            }
//            //实收电费
//            BigDecimal actPowerPrice1 = xhpcSt.getActPowerPrice();
//            if(actPowerPrice.compareTo(actPowerPrice1)==1){
//                actPowerPrice=actPowerPrice.subtract(actPowerPrice1);
//            }else{
//                xhpcSt.setActPowerPrice(actPowerPrice);
//            }
//            //实收服务费
//            BigDecimal actServicePrice1 = xhpcSt.getActServicePrice();
//            if(actServicePrice.compareTo(actServicePrice1)==1){
//                actServicePrice=actServicePrice.subtract(actServicePrice1);
//            }else{
//                xhpcSt.setActServicePrice(actServicePrice);
//            }
//            //总充电电量
//            BigDecimal chargingDegree1 = xhpcSt.getChargingDegree();
//            if(chargingDegree.compareTo(chargingDegree1)==1){
//                chargingDegree=chargingDegree.subtract(chargingDegree1);
//            }else{
//                xhpcSt.setChargingDegree(chargingDegree);
//            }
//
//            //实际价格-用户支付的钱
//            BigDecimal actPrice1 = xhpcSt.getActPrice();
//            if(actPrice.compareTo(actPrice1)==1){
//                actPrice=actPrice.subtract(actPrice1);
//            }else{
//                xhpcSt.setActPrice(actPrice);
//            }
//        }else{
//            xhpcSt.setPowerPrice(powerPriceTotal);
//            xhpcSt.setServicePrice(servicePriceTotal);
//            xhpcSt.setTotalPrice(totalPrice);
//            xhpcSt.setPromotionDiscount(promotionDiscount);
//            xhpcSt.setActPrice(actPrice);
//            xhpcSt.setActPowerPrice(actPowerPrice);
//            xhpcSt.setActServicePrice(actServicePrice);
//            xhpcSt.setChargingDegree(chargingDegree);
//        }
//
//        if(xhpc.getSource()==1){
//            xhpcSt.setInternetUserId(xhpc.getUserId());
//        }
//        xhpcSt.setOperatorId(xhpc.getOperatorId());
//        xhpcSt.setChargingStationId(xhpc.getChargingStationId());
//        xhpcSt.setCreateTime(Calendar.getInstance().getTime());
//        xhpcSt.setTerminalId(xhpc.getTerminalId());
//        xhpcSt.setHistoryOrderId(xhpc.getHistoryOrderId());
//        xhpcSt.setChargingPileId(xhpc.getChargingPileId());
//        xhpcSt.setType(type);
//        xhpcSt.setCreateTime(xhpc.getEndTime());
//        xhpcStatisticsService.addStatisticsStation(xhpcSt);
//
//        //修改历史订单表状态
//        xhpcHistoryOrderService.updateXhpcHistoryOrder(xhpc.getHistoryOrderId(),type + 1);
//
        Map<String,BigDecimal> map2 =new HashMap<>();
//        map2.put("totalPrice",totalPrice);
//        map2.put("powerPriceTotal",powerPriceTotal);
//        map2.put("servicePriceTotal",servicePriceTotal);
//        map2.put("actPowerPrice",actPowerPrice);
//        map2.put("actServicePrice",actServicePrice);
//        map2.put("chargingDegree",chargingDegree);
//        map2.put("promotionDiscount",promotionDiscount);
//        map2.put("actPrice",actPrice);
        return map2;

    }

    /**
     * 小时统计
     */
    @GetMapping("/test")
   @Scheduled(cron = "0 0/2 * * * ?")
    public void test(){
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>小时统计定时任务>>>>>>>>>>>>>>>>>>>>>");
        //小时统计
        List<XhpcChargeHistoryOrder> list = xhpcHistoryOrderService.getStatistisList(3000,0);
        if(list !=null && list.size()>0){
            for (XhpcChargeHistoryOrder xhpc:list) {
                try{
                    Long historyOrderId = xhpc.getHistoryOrderId();
                    int count = xhpcStatisticsService.getStatisticsTimeHistoryOrderId(historyOrderId);
                    if(count>0){
                        XhpcHistoryOrder historyOrder = xhpcHistoryOrderService.getHistoryOrderById(historyOrderId,null);
                        if(historyOrder.getState()==0){
                            xhpcHistoryOrderService.updateXhpcHistoryOrder(historyOrderId,1);
                        }
                    }
                    if(count==0){
                        //开始时间、结束时间、模型id、状态、用户id、运营商、订单id、场站id、终端id、历史订单id、时间
                        Long operatorId =xhpc.getOperatorId();
                        Long chargingStationId = xhpc.getChargingStationId();
                        Long terminalId = xhpc.getTerminalId();
                        //Date data = Calendar.getInstance().getTime();
//                    if(xhpc.getTotalPrice().compareTo(new BigDecimal(0)) !=1){
//                        continue;
//                    }
//                    if(xhpc.getChargingDegree().compareTo(new BigDecimal(0)) !=1){
//                        continue;
//                    }
                        //每分钟多少度电
                        //BigDecimal v = new BigDecimal((endTime.getTime() - startTime.getTime())).divide(new BigDecimal(60000),2,BigDecimal.ROUND_HALF_UP);
//                    if(v.compareTo(new BigDecimal(0)) !=1){
//                        continue;
//                    }

                        //没有跨时段
                        XhpcStatisticsTimeInterval xhpcSt = new XhpcStatisticsTimeInterval();

                        xhpcSt.setChargingDegree(xhpc.getChargingDegree());
                        if(xhpc.getChargingTimeNumber() !=null){
                            xhpcSt.setChargingTime(new BigDecimal(xhpc.getChargingTimeNumber()).divide(new BigDecimal(3600), 2, BigDecimal.ROUND_HALF_UP));
                        }
                        xhpcSt.setChargingNumber(1);
                        xhpcSt.setClearingType(xhpc.getClearingType());
                        xhpcSt.setClearingPrice(xhpc.getClearingPrice());
                        xhpcSt.setPowerPrice(xhpc.getPowerPriceTotal());
                        xhpcSt.setServicePrice(xhpc.getServicePriceTotal());
                        xhpcSt.setTotalPrice(xhpc.getTotalPrice());
                        xhpcSt.setPromotionDiscount(xhpc.getPromotionDiscount());
                        xhpcSt.setActPrice(xhpc.getActPrice());
                        xhpcSt.setActPowerPrice(xhpc.getActPowerPrice());
                        xhpcSt.setActServicePrice(xhpc.getActServicePrice());
                        xhpcSt.setActTotalPrice(xhpc.getActTotalPrice());
                        xhpcSt.setInternetCommission(xhpc.getInternetCommission());
                        xhpcSt.setInternetSvcCommission(xhpc.getInternetSvcCommission());
                        xhpcSt.setPlatformCommission(xhpc.getPlatformCommission());
                        xhpcSt.setPlatformSvcCommisssion(xhpc.getPlatformSvcCommisssion());
                        xhpcSt.setOperationCommission(xhpc.getOperationCommission());
                        xhpcSt.setOperationSvcCommission(xhpc.getOperationSvcCommission());
                        xhpcSt.setOperatorId(operatorId);
                        xhpcSt.setChargingStationId(chargingStationId);
                        xhpcSt.setActivityPowerPriceTotal(xhpc.getActivityPowerPriceTotal());
                        xhpcSt.setActivityServicePriceTotal(xhpc.getActivityServicePriceTotal());
                        xhpcSt.setActivityTotalPrice(xhpc.getActivityTotalPrice());
                        //xhpcSt.setCreateTime(data);
                        xhpcSt.setTerminalId(terminalId);
                        xhpcSt.setHistoryOrderId(historyOrderId);
                        if(xhpc.getSource()!=null && xhpc.getSource()== UserTypeUtil.INTERNET_TYPE){
                            xhpcSt.setInternetUserId(xhpc.getUserId());
                        }
                        //时间没有跨天
                        xhpcSt.setInternetDegreeCommission(xhpc.getInternetDegreeCommission());
                        if(xhpc.getStartTime() !=null){
                            xhpcSt.setStartTimeEvcs(DateUtil.format(xhpc.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                        }
                        if(xhpc.getEndTime() !=null){
                            int endHour = DateUtil.hour(xhpc.getEndTime(), true);
                            xhpcSt.setStatus(endHour+1);
                            xhpcSt.setEndTimeEvcs(DateUtil.format(xhpc.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                            xhpcSt.setCreateTime(xhpc.getEndTime());
                        }
                        xhpcStatisticsService.addStatisticsTime(xhpcSt);
                        //修改历史订单表状态
                        xhpcHistoryOrderService.updateXhpcHistoryOrder(xhpc.getHistoryOrderId(),1);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    logger.info(">>>>>>>>>>>>>>>>>>>>>>>小时统计定时任务异常>>>>>>>>>>>>>>>>>>>>>"+xhpc.getHistoryOrderId());
                }
            }
        }
    }



    /**
     * 小时统计(精确统计)
     */
    @GetMapping("/test8")
    //@Scheduled(cron = "0 0/5 * * * ?")
    public void test8(){
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>小时统计定时任务>>>>>>>>>>>>>>>>>>>>>");
        //获取500条待统计历史订单
        //跨时段，跨费率，计费模型
        try{
            //小时统计
            List<XhpcChargeHistoryOrder> list = xhpcHistoryOrderService.getStatistisList(500,0);
            if(list !=null && list.size()>0){
                for (XhpcChargeHistoryOrder xhpc:list) {
                    //开始时间、结束时间、模型id、状态、用户id、运营商、订单id、场站id、终端id、历史订单id、时间
                    Date startTime = xhpc.getStartTime();
                    Date endTime = xhpc.getEndTime();
                    Long rateModelId = xhpc.getRateModelId();
                    Long operatorId =xhpc.getOperatorId();
                    Long chargingStationId = xhpc.getChargingStationId();
                    Long terminalId = xhpc.getTerminalId();
                    Long historyOrderId = xhpc.getHistoryOrderId();
                    Date data = Calendar.getInstance().getTime();
                    if(xhpc.getTotalPrice().compareTo(new BigDecimal(0)) !=1){
                        continue;
                    }
                    if(xhpc.getChargingDegree().compareTo(new BigDecimal(0)) !=1){
                        continue;
                    }
                    //每分钟多少度电
                    BigDecimal v = new BigDecimal((endTime.getTime() - startTime.getTime())).divide(new BigDecimal(60000),2,BigDecimal.ROUND_HALF_UP);
                    if(v.compareTo(new BigDecimal(0)) !=1){
                        continue;
                    }
                    //1时间没有跨天
                    DateTime parse = DateUtil.parse(DateUtil.format(startTime, "yyyy-MM-dd"), "yyyy-MM-dd");
                    DateTime parse1 = DateUtil.parse(DateUtil.format(endTime, "yyyy-MM-dd"), "yyyy-MM-dd");
                    long betweenDay = DateUtil.between(parse,parse1, DateUnit.DAY);
                    if(betweenDay==0){
                        //没有跨天
                        //是否跨时段
                        int startHour = DateUtil.hour(startTime, true);
                        int endHour = DateUtil.hour(endTime, true);
                        if(endHour==startHour){
                            //没有跨时段
                            XhpcStatisticsTimeInterval xhpcSt = new XhpcStatisticsTimeInterval();
                            xhpcSt.setStatus(endHour+1);
                            xhpcSt.setChargingDegree(xhpc.getChargingDegree());
                            xhpcSt.setChargingTime(new BigDecimal(xhpc.getChargingTimeNumber()).divide(new BigDecimal(3600),2, BigDecimal.ROUND_HALF_UP));
                            xhpcSt.setChargingNumber(1);
                            xhpcSt.setPowerPrice(xhpc.getPowerPriceTotal());
                            xhpcSt.setServicePrice(xhpc.getServicePriceTotal());
                            xhpcSt.setTotalPrice(xhpc.getTotalPrice());
                            xhpcSt.setPromotionDiscount(xhpc.getPromotionDiscount());
                            xhpcSt.setActPrice(xhpc.getActPrice());
                            xhpcSt.setActPowerPrice(xhpc.getActPowerPrice());
                            xhpcSt.setActServicePrice(xhpc.getActServicePrice());
                            xhpcSt.setActTotalPrice(xhpc.getActTotalPrice());
                            xhpcSt.setInternetCommission(xhpc.getInternetCommission());
                            xhpcSt.setInternetSvcCommission(xhpc.getInternetSvcCommission());
                            xhpcSt.setPlatformCommission(xhpc.getPlatformCommission());
                            xhpcSt.setPlatformSvcCommisssion(xhpc.getPlatformSvcCommisssion());
                            xhpcSt.setOperationCommission(xhpc.getOperationCommission());
                            xhpcSt.setOperationSvcCommission(xhpc.getOperationSvcCommission());
                            xhpcSt.setOperatorId(operatorId);
                            xhpcSt.setChargingStationId(chargingStationId);
                            xhpcSt.setCreateTime(data);
                            xhpcSt.setTerminalId(terminalId);
                            xhpcSt.setHistoryOrderId(historyOrderId);
                            if(xhpc.getSource()==UserTypeUtil.INTERNET_TYPE){
                                xhpcSt.setInternetUserId(xhpc.getUserId());
                            }
                            String endTime1 = DateUtil.formatTime(endTime);
                            if("00:00:00".equals(endTime1)){
                                endTime1="23:59:59";
                            }
                            List<Map<String, Object>> reatTimeList = xhpcHistoryOrderService.getReatTimeList(DateUtil.formatTime(startTime), endTime1, rateModelId);
                            Map<String, Object> map = reatTimeList.get(0);
                            xhpcSt.setElecPriceEvcs(new BigDecimal(map.get("powerFee").toString()));
                            xhpcSt.setServicePriceEvcs(new BigDecimal(map.get("serviceFee").toString()));
                            xhpcSt.setStartTimeEvcs(DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss"));
                            xhpcSt.setEndTimeEvcs(DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss"));
                            xhpcSt.setCreateTime(xhpc.getEndTime());
                            xhpcStatisticsService.addStatisticsTime(xhpcSt);
                            //修改历史订单表状态
                            xhpcHistoryOrderService.updateXhpcHistoryOrder(xhpc.getHistoryOrderId(),1);
                        }else {
                            //总共多少时段
                            int number=endHour + 1 - startHour;
                            addStatisticsTime(new HashMap<String,BigDecimal>(),xhpc, startTime, endTime, rateModelId, startHour, endHour,1,number);
                        }
                    }else{
                        //跨天
                        Date updateTime2= DateUtil.endOfDay(startTime);
                        int startHour = DateUtil.hour(startTime, true);
                        int endHour = DateUtil.hour(updateTime2, true);
                        int number=endHour + 1 - startHour;

                        //明天
                        DateTime tomorrow = DateUtil.offsetDay(startTime,1);
                        Date startTime3 =DateUtil.beginOfDay(tomorrow);
                        int startHour1 = DateUtil.hour(startTime3, true);
                        int endHour1 = DateUtil.hour(endTime, true);
                        int number1=endHour1 + 1 - startHour1;
                        Map<String, BigDecimal> map = addStatisticsTime(new HashMap<String,BigDecimal>(),xhpc, startTime, updateTime2, rateModelId, startHour, endHour, 2, number + number1);
                        addStatisticsTime(map,xhpc, startTime3, endTime, rateModelId, startHour1, endHour1,3,number+number1);
                    }

                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>小时统计定时任务异常>>>>>>>>>>>>>>>>>>>>>");
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>小时统计定时任务异常>>>>>>>>>>>>>>>>>>>>");
        }
    }

    /**
     *
     * @param xhpc
     * @param startTime
     * @param endTime
     * @param rateModelId
     * @param startHour
     * @param endHour
     * @param type        1 需要减去之前统计的值 2 不需要
     */
    private Map<String,BigDecimal> addStatisticsTime(Map<String,BigDecimal> map1,XhpcChargeHistoryOrder xhpc, Date startTime, Date endTime, Long rateModelId, int startHour, int endHour,int type,int number) {

        //跨时段
        //总共时段 endHour+1-startHour
        String yyyyMMdd = DateUtil.format(startTime, "yyyy-MM-dd");

        //总金额
        BigDecimal totalPrice =new BigDecimal(0);
        //总电费
        BigDecimal powerPriceTotal =new BigDecimal(0);
        //总服务费
        BigDecimal servicePriceTotal =new BigDecimal(0);
        //实收电费
        BigDecimal actPowerPrice =new BigDecimal(0);
        //实收服务费
        BigDecimal actServicePrice =new BigDecimal(0);
        //总充电电量
        BigDecimal chargingDegree =new BigDecimal(0);
        //电站活动抵扣--抵扣的总金额
        BigDecimal promotionDiscount =new BigDecimal(0);
        //实际价格-用户支付的钱
        BigDecimal actPrice =new BigDecimal(0);
        if(type==3){
            totalPrice =map1.get("totalPrice");
            powerPriceTotal =map1.get("powerPriceTotal");
            servicePriceTotal =map1.get("servicePriceTotal");
            actPowerPrice =map1.get("actPowerPrice");
            actServicePrice =map1.get("actServicePrice");
            chargingDegree =map1.get("chargingDegree");
            promotionDiscount =map1.get("promotionDiscount");
            actPrice =map1.get("actPrice");
        }else{
            totalPrice = xhpc.getTotalPrice();
            powerPriceTotal =xhpc.getPowerPriceTotal();
            servicePriceTotal =xhpc.getServicePriceTotal();
            actPowerPrice =xhpc.getActPowerPrice();
            actServicePrice =xhpc.getActServicePrice();
            chargingDegree =xhpc.getChargingDegree();
            promotionDiscount = xhpc.getPromotionDiscount();
            actPrice = xhpc.getActPrice();
        }
        //总时长
        BigDecimal time = new BigDecimal((xhpc.getEndTime().getTime()-xhpc.getStartTime().getTime())).divide(new BigDecimal(60000),2, BigDecimal.ROUND_HALF_UP);
        //每分钟多少度电
        BigDecimal decimal = chargingDegree.divide(time,2,BigDecimal.ROUND_HALF_UP);
        BigDecimal powerFee =new BigDecimal(0);
        BigDecimal serviceFee =new BigDecimal(0);
        BigDecimal timeInterval = new BigDecimal(0);
        String srt ="";
        String endt ="";
        for (int i = startHour; i < endHour + 1; i++) {
            String end = String.format("%02d", i);
            //获取费率
            if (i == startHour) {
                srt = DateUtil.formatTime(startTime);
                endt = end + ":59:59";
                Map<String, Object> map =getReatTimeList(srt,endt,rateModelId);
                powerFee =new BigDecimal(map.get("powerFee").toString());
                serviceFee =new BigDecimal(map.get("serviceFee").toString());
                timeInterval =new BigDecimal((DateUtil.parse(endt).getTime()-DateUtil.parse(srt).getTime())).divide(new BigDecimal(60000),2, BigDecimal.ROUND_HALF_UP);
            } else if (i != endHour) {
                srt = end + ":00:00";
                endt = end + ":59:59";
                Map<String, Object> map =getReatTimeList(srt,endt,rateModelId);
                powerFee =new BigDecimal(map.get("powerFee").toString());
                serviceFee =new BigDecimal(map.get("serviceFee").toString());
                timeInterval =new BigDecimal((DateUtil.parse(endt).getTime()-DateUtil.parse(srt).getTime())).divide(new BigDecimal(60000),2, BigDecimal.ROUND_HALF_UP);
            } else {
                srt = end + ":00:00";
                endt = DateUtil.formatTime(endTime);
                Map<String, Object> map =getReatTimeList(srt,endt,rateModelId);
                powerFee =new BigDecimal(map.get("powerFee").toString());
                serviceFee =new BigDecimal(map.get("serviceFee").toString());
                timeInterval =new BigDecimal((DateUtil.parse(endt).getTime()-DateUtil.parse(srt).getTime())).divide(new BigDecimal(60000),2, BigDecimal.ROUND_HALF_UP);
            }
            XhpcStatisticsTimeInterval xhpcSt = new XhpcStatisticsTimeInterval();
            xhpcSt.setStatus(i+1);
            xhpcSt.setChargingTime(timeInterval.divide(new BigDecimal(60),2,BigDecimal.ROUND_HALF_UP));
            //电量
            BigDecimal decimal1 = timeInterval.multiply(decimal).setScale(2, BigDecimal.ROUND_HALF_UP);
            xhpcSt.setChargingDegree(decimal1);
            xhpcSt.setChargingNumber(1);
            xhpcSt.setPromotionDiscount(xhpc.getPromotionDiscount().divide(new BigDecimal(number),2,BigDecimal.ROUND_HALF_UP));
            xhpcSt.setInternetCommission(xhpc.getInternetCommission().divide(new BigDecimal(number),2,BigDecimal.ROUND_HALF_UP));
            xhpcSt.setInternetSvcCommission(xhpc.getInternetSvcCommission().divide(new BigDecimal(number),2,BigDecimal.ROUND_HALF_UP));
            xhpcSt.setPlatformCommission(xhpc.getPlatformCommission().divide(new BigDecimal(number),2,BigDecimal.ROUND_HALF_UP));
            xhpcSt.setPlatformSvcCommisssion(xhpc.getPlatformSvcCommisssion().divide(new BigDecimal(number),2,BigDecimal.ROUND_HALF_UP));
            xhpcSt.setOperationCommission(xhpc.getOperationCommission().divide(new BigDecimal(number),2,BigDecimal.ROUND_HALF_UP));
            xhpcSt.setOperationSvcCommission(xhpc.getOperationSvcCommission().divide(new BigDecimal(number),2,BigDecimal.ROUND_HALF_UP));
            if(i!=endHour || type==2){

                xhpcSt.setPowerPrice(powerFee.multiply(decimal1).setScale(2, BigDecimal.ROUND_HALF_UP));
                xhpcSt.setServicePrice(serviceFee.multiply(decimal1).setScale(2, BigDecimal.ROUND_HALF_UP));
                BigDecimal powerPrice =xhpcSt.getPowerPrice();
                BigDecimal servicePrice =xhpcSt.getServicePrice();
                xhpcSt.setTotalPrice(powerPrice.add(servicePrice));

                BigDecimal internetCommission = xhpcSt.getInternetCommission();

                BigDecimal actPrice2 = powerPrice.add(servicePrice);

                if(internetCommission.compareTo(new BigDecimal(0))!=0){
                    powerPrice =powerPrice.multiply(internetCommission.divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                    servicePrice=servicePrice.multiply(internetCommission.divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                    actPrice2 = actPrice2.subtract(internetCommission);
                }else{
                    servicePrice=servicePrice.multiply(xhpcSt.getInternetSvcCommission());
                    actPrice2 =actPrice2.subtract(xhpcSt.getInternetSvcCommission());
                }
                BigDecimal platformCommission = xhpcSt.getPlatformCommission();
                if(platformCommission.compareTo(new BigDecimal(0))!=0){
                    powerPrice =powerPrice.multiply(platformCommission.divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                    servicePrice=servicePrice.multiply(platformCommission.divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                }else{
                    servicePrice=servicePrice.multiply(xhpcSt.getPlatformSvcCommisssion());
                }

                BigDecimal operationCommission = xhpcSt.getOperationCommission();
                if(operationCommission.compareTo(new BigDecimal(0))!=0){
                    powerPrice =powerPrice.multiply(operationCommission.divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                    servicePrice=servicePrice.multiply(operationCommission.divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP));
                }else{
                    servicePrice=servicePrice.multiply(xhpcSt.getOperationSvcCommission());
                }

                xhpcSt.setActPowerPrice(powerPrice);
                xhpcSt.setActServicePrice(servicePrice);

                xhpcSt.setElecPriceEvcs(powerFee);
                xhpcSt.setServicePriceEvcs(serviceFee);
                //电站活动抵扣--抵扣的总金额
                BigDecimal promotionDiscount1 = xhpcSt.getPromotionDiscount();
                if(promotionDiscount.compareTo(promotionDiscount1)==1){
                    promotionDiscount=promotionDiscount.subtract(promotionDiscount1);
                    actPrice2 = actPrice2.subtract(promotionDiscount1);
                }else{
                    xhpcSt.setPromotionDiscount(promotionDiscount);
                    actPrice2 = actPrice2.subtract(promotionDiscount);
                }
                xhpcSt.setActPrice(actPrice2);
                //总金额
                BigDecimal totalPrice1 = xhpcSt.getTotalPrice();
                if(totalPrice.compareTo(totalPrice1)==1){
                    totalPrice=totalPrice.subtract(totalPrice1);
                }else{
                    xhpcSt.setTotalPrice(totalPrice);
                }
                //总电费
                BigDecimal powerPrice1 = xhpcSt.getPowerPrice();
                if(powerPriceTotal.compareTo(powerPrice1)==1){
                    powerPriceTotal=powerPriceTotal.subtract(powerPrice1);
                }else{
                    xhpcSt.setPowerPrice(powerPriceTotal);
                }
                //总服务费
                BigDecimal servicePrice1 = xhpcSt.getServicePrice();
                if(servicePriceTotal.compareTo(servicePrice1)==1){
                    servicePriceTotal=servicePriceTotal.subtract(servicePrice1);
                }else{
                    xhpcSt.setServicePrice(servicePriceTotal);
                }
                //实收电费
                BigDecimal actPowerPrice1 = xhpcSt.getActPowerPrice();
                if(actPowerPrice.compareTo(actPowerPrice1)==1){
                    actPowerPrice=actPowerPrice.subtract(actPowerPrice1);
                }else{
                    xhpcSt.setActPowerPrice(actPowerPrice);
                }
                //实收服务费
                BigDecimal actServicePrice1 = xhpcSt.getActServicePrice();
                if(actServicePrice.compareTo(actServicePrice1)==1){
                    actServicePrice=actServicePrice.subtract(actServicePrice1);
                }else{
                    xhpcSt.setActServicePrice(actServicePrice);
                }
                //总充电电量
                BigDecimal chargingDegree1 = xhpcSt.getChargingDegree();
                if(chargingDegree.compareTo(chargingDegree1)==1){
                    chargingDegree=chargingDegree.subtract(chargingDegree1);
                }else{
                    xhpcSt.setChargingDegree(chargingDegree);
                }

                //实际价格-用户支付的钱
                BigDecimal actPrice1 = xhpcSt.getActPrice();
                if(actPrice.compareTo(actPrice1)==1){
                    actPrice=actPrice.subtract(actPrice1);
                }else{
                    xhpcSt.setActPrice(actPrice);
                }
            }else{
                xhpcSt.setPowerPrice(powerPriceTotal);
                xhpcSt.setServicePrice(servicePriceTotal);
                xhpcSt.setTotalPrice(totalPrice);
                xhpcSt.setPromotionDiscount(promotionDiscount);
                xhpcSt.setActPrice(actPrice);
                xhpcSt.setActPowerPrice(actPowerPrice);
                xhpcSt.setActServicePrice(actServicePrice);
                xhpcSt.setChargingDegree(chargingDegree);
            }
            xhpcSt.setActPrice(xhpcSt.getTotalPrice().subtract(xhpcSt.getPromotionDiscount()));
            if(xhpc.getSource()==UserTypeUtil.INTERNET_TYPE){
                xhpcSt.setInternetUserId(xhpc.getUserId());
            }
            xhpcSt.setOperatorId(xhpc.getOperatorId());
            xhpcSt.setChargingStationId(xhpc.getChargingStationId());
            xhpcSt.setDelFlag(0);
            xhpcSt.setCreateTime(xhpc.getEndTime());
            xhpcSt.setTerminalId(xhpc.getTerminalId());
            xhpcSt.setHistoryOrderId(xhpc.getHistoryOrderId());
            xhpcSt.setStartTimeEvcs(yyyyMMdd+" "+srt);
            xhpcSt.setEndTimeEvcs(yyyyMMdd+" "+endt);
            xhpcSt.setActTotalPrice(xhpc.getActTotalPrice());
            xhpcStatisticsService.addStatisticsTime(xhpcSt);
            //修改历史订单表状态
            xhpcHistoryOrderService.updateXhpcHistoryOrder(xhpc.getHistoryOrderId(),1);
        }
        Map<String,BigDecimal> map2 =new HashMap<>();
        map2.put("totalPrice",totalPrice);
        map2.put("powerPriceTotal",powerPriceTotal);
        map2.put("servicePriceTotal",servicePriceTotal);
        map2.put("actPowerPrice",actPowerPrice);
        map2.put("actServicePrice",actServicePrice);
        map2.put("chargingDegree",chargingDegree);
        map2.put("promotionDiscount",promotionDiscount);
        map2.put("actPrice",actPrice);
        return map2;
    }

    private Map<String, Object> getReatTimeList(String startTime,String endTime,Long rateModelId) {
        Map<String, Object> map =new HashMap<>();
        if("00:00:00".equals(endTime)){
            endTime="23:59:59";
        }
        List<Map<String, Object>> reatTimeList = xhpcHistoryOrderService.getReatTimeList(startTime,endTime, rateModelId);
        for (int j = 0; j < reatTimeList.size(); j++) {
            Map<String, Object> map1 = reatTimeList.get(j);
            return map1;
        }

        return map;
    }

    /**
     * 24小时异常订单自动结算
     */
    @GetMapping("/test4")
    @Scheduled(cron = "0 0/10 * * * ?")
    public void test4(){
        try {
            //1自动 2 4小时  3 6小时  4 8小时  5 12小时  6 44小时
            Integer pilePrompts = redisService.getCacheObject("pilePrompt:000000");
            if(pilePrompts!=null && pilePrompts!=1){
                //获取异常的订单 24小时之外的异常订单
                List<Map<String,Object>> xhpcChargeOrderList= chargeOrderService.getXhpcChargeOrderStatus(2,pilePrompts);
                if(xhpcChargeOrderList !=null && xhpcChargeOrderList.size()>0){
                    for (int i = 0; i <xhpcChargeOrderList.size() ; i++) {
                        Map<String,Object> map = xhpcChargeOrderList.get(i);
                        if(map !=null){
                            Long chargeOrderId = Long.valueOf(map.get("chargeOrderId").toString());
                            if(map.get("realTimeOrderId")!=null){
                                Long realTimeOrderId = Long.valueOf(map.get("realTimeOrderId").toString());
                                xhpcHistoryOrderService.addXhpcChargeOrder(realTimeOrderId,chargeOrderId);
                            }else{
                                xhpcHistoryOrderService.addXhpcChargeOrder(null,chargeOrderId);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){

        }
    }

    /**
     * 标记异常大于创建4小时，标记为异常
     * @param
     * @param
     */
    @GetMapping("/test5")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void test5(){
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>标记异常大于创建4小时，标记为异常>>>>>>>>>>>>>>>>>>>>>");
        chargeOrderService.updateStatus();
    }


    /**
     * 订单状态为null,每5分钟检测一次
     * @param
     * @param
     */
    @GetMapping("/test6")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void test6(){
        chargeOrderService.updateStatusNull();
    }

    /**
     * 订单状态为-1的流量方订单,每5分钟检测一次
     * @param
     * @param
     */
    @GetMapping("/test9")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void test9(){
        chargeOrderService.updateStatusNegativeOne();
    }


    //@Scheduled(cron = "0 0/1 * * * ?")
    @GetMapping("/getInvoiceInfo")
    public void getInvoiceInfo(){
        logger.info("++++++++++++每1分钟，扫描一次，异常订单，自动生成工单++++++++++++++++");
        try {
            List<Map<String, Object>> invoiceInfo = chargeOrderService.getChargeOrderStatus();
            if(invoiceInfo !=null && invoiceInfo.size()>0){
                Date date = DateUtil.date();
                String format = DateUtil.format(date, "yyyy-MM-dd");
                R r = workOrderYuService.workOrderMessage(2, format);
                if(r.getCode()==200){
                    for (int i = 0; i <invoiceInfo.size() ; i++) {
                        Map<String, Object> map = invoiceInfo.get(i);
                        String stationId = map.get("chargingStationId").toString();
                        String serialNumber = map.get("serialNumber").toString().substring(0,16);
                        workOrderYuService.addNewOrder("2","有异常订单订单待处理","定时任务自动扫描申请异常订单","",stationId,"",serialNumber);
                    }
                }
            }
        }catch (Exception e){
            logger.info("++++++++++++每1分钟，扫描一次，异常订单，自动生成工单异常++++++++++++++++");
            e.printStackTrace();
            //后期可以增加短信通知
        }
    }



    //检查统计没有入库的订单（小时)
    @Scheduled(cron = "0 5 * * * ?")
    @GetMapping("/getInvoTime")
    public void getNoStatisticsOrderTime(){
        List<XhpcChargeHistoryOrder> list = xhpcHistoryOrderService.getNoStatisticsOrderTime(300);
        if(list !=null && list.size()>0){
            for (XhpcChargeHistoryOrder xhpc:list) {
                try{
                    Long historyOrderId = xhpc.getHistoryOrderId();
                    int count = xhpcStatisticsService.getStatisticsTimeHistoryOrderId(historyOrderId);
                    if(count==0){
                        //开始时间、结束时间、模型id、状态、用户id、运营商、订单id、场站id、终端id、历史订单id、时间
                        Long operatorId =xhpc.getOperatorId();
                        Long chargingStationId = xhpc.getChargingStationId();
                        Long terminalId = xhpc.getTerminalId();
                        XhpcStatisticsTimeInterval xhpcSt = new XhpcStatisticsTimeInterval();
                        xhpcSt.setChargingDegree(xhpc.getChargingDegree());
                        if(xhpc.getChargingTimeNumber() !=null){
                            xhpcSt.setChargingTime(new BigDecimal(xhpc.getChargingTimeNumber()).divide(new BigDecimal(3600), 2, BigDecimal.ROUND_HALF_UP));
                        }
                        xhpcSt.setChargingNumber(1);
                        xhpcSt.setClearingType(xhpc.getClearingType());
                        xhpcSt.setClearingPrice(xhpc.getClearingPrice());
                        xhpcSt.setPowerPrice(xhpc.getPowerPriceTotal());
                        xhpcSt.setServicePrice(xhpc.getServicePriceTotal());
                        xhpcSt.setTotalPrice(xhpc.getTotalPrice());
                        xhpcSt.setPromotionDiscount(xhpc.getPromotionDiscount());
                        xhpcSt.setActPrice(xhpc.getActPrice());
                        xhpcSt.setActPowerPrice(xhpc.getActPowerPrice());
                        xhpcSt.setActServicePrice(xhpc.getActServicePrice());
                        xhpcSt.setActTotalPrice(xhpc.getActTotalPrice());
                        xhpcSt.setInternetCommission(xhpc.getInternetCommission());
                        xhpcSt.setInternetSvcCommission(xhpc.getInternetSvcCommission());
                        xhpcSt.setPlatformCommission(xhpc.getPlatformCommission());
                        xhpcSt.setPlatformSvcCommisssion(xhpc.getPlatformSvcCommisssion());
                        xhpcSt.setOperationCommission(xhpc.getOperationCommission());
                        xhpcSt.setOperationSvcCommission(xhpc.getOperationSvcCommission());
                        xhpcSt.setOperatorId(operatorId);
                        xhpcSt.setChargingStationId(chargingStationId);
                        xhpcSt.setActivityPowerPriceTotal(xhpc.getActivityPowerPriceTotal());
                        xhpcSt.setActivityServicePriceTotal(xhpc.getActivityServicePriceTotal());
                        xhpcSt.setActivityTotalPrice(xhpc.getActivityTotalPrice());
                        //xhpcSt.setCreateTime(data);
                        xhpcSt.setTerminalId(terminalId);
                        xhpcSt.setHistoryOrderId(historyOrderId);
                        if(xhpc.getSource()!=null && xhpc.getSource()==UserTypeUtil.INTERNET_TYPE){
                            xhpcSt.setInternetUserId(xhpc.getUserId());
                        }
                        //时间没有跨天
                        xhpcSt.setInternetDegreeCommission(xhpc.getInternetDegreeCommission());
                        if(xhpc.getStartTime() !=null){
                            xhpcSt.setStartTimeEvcs(DateUtil.format(xhpc.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                        }
                        if(xhpc.getEndTime() !=null){
                            int endHour = DateUtil.hour(xhpc.getEndTime(), true);
                            xhpcSt.setStatus(endHour+1);
                            xhpcSt.setEndTimeEvcs(DateUtil.format(xhpc.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                            xhpcSt.setCreateTime(xhpc.getEndTime());
                        }
                        Map<String, Object> xhpcRateTimeFee = xhpcHistoryOrderService.getXhpcRateTimeFee(xhpc.getRateModelId());
                        if(xhpcRateTimeFee !=null){
                            if(xhpcRateTimeFee.get("powerFee") !=null){
                                xhpcSt.setElecPriceEvcs(new BigDecimal(xhpcRateTimeFee.get("powerFee").toString()));
                            }
                            if(xhpcRateTimeFee.get("serviceFee") !=null){
                                xhpcSt.setServicePrice(new BigDecimal(xhpcRateTimeFee.get("serviceFee").toString()));
                            }
                        }
                        if(xhpc.getSource()==UserTypeUtil.MOTORCADE_TYPE){
                            xhpcSt.setMark(xhpc.getMark());
                            xhpcSt.setMotorcadeId(xhpc.getMotorcadeId());
                        }
                        xhpcStatisticsService.addStatisticsTime(xhpcSt);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    logger.info(">>>>>>>>>>>>>>>>>>>>>>>小时统计定时任务异常>>>>>>>>>>>>>>>>>>>>>"+xhpc.getHistoryOrderId());
                }
            }
        }
    }
    //检查统计没有入库的订单（日期、电站）
    @Scheduled(cron = "0 30 * * * ?")
    @GetMapping("/getInvoDay")
    public void getInvoDay(){
        List<XhpcChargeHistoryOrder> listOrder = xhpcHistoryOrderService.getNoStatisticsOrderDay(500);
        if(listOrder !=null && listOrder.size()>0){
            for (XhpcChargeHistoryOrder xhpc:listOrder) {
                try{
                    Long historyOrderId = xhpc.getHistoryOrderId();
                    for (int i = 1; i <4 ; i++) {
                        //查询统计表是否有已添加的数据
                        int count = xhpcStatisticsService.getStatisticsStationHistoryOrderId(historyOrderId, i);
                        if(count==0){
                            XhpcStatisticsStation xhpcSt =new XhpcStatisticsStation();
                            xhpcSt.setChargingDegree(xhpc.getChargingDegree());
                            if(xhpc.getChargingTimeNumber() !=null){
                                xhpcSt.setChargingTime(new BigDecimal(xhpc.getChargingTimeNumber()).divide(new BigDecimal(3600), 2, BigDecimal.ROUND_HALF_UP));
                            }
                            xhpcSt.setChargingNumber(1);
                            xhpcSt.setClearingType(xhpc.getClearingType());
                            xhpcSt.setClearingPrice(xhpc.getClearingPrice());
                            xhpcSt.setPowerPrice(xhpc.getPowerPriceTotal());
                            xhpcSt.setServicePrice(xhpc.getServicePriceTotal());
                            xhpcSt.setTotalPrice(xhpc.getTotalPrice());
                            xhpcSt.setPromotionDiscount(xhpc.getPromotionDiscount());
                            xhpcSt.setActPrice(xhpc.getActPrice());
                            xhpcSt.setInternetCommission(xhpc.getInternetCommission());
                            xhpcSt.setInternetSvcCommission(xhpc.getInternetSvcCommission());
                            xhpcSt.setPlatformCommission(xhpc.getPlatformCommission());
                            xhpcSt.setPlatformSvcCommisssion(xhpc.getPlatformSvcCommisssion());
                            xhpcSt.setOperationCommission(xhpc.getOperationCommission());
                            xhpcSt.setOperationSvcCommission(xhpc.getOperationSvcCommission());
                            xhpcSt.setActPowerPrice(xhpc.getActPowerPrice());
                            xhpcSt.setActServicePrice(xhpc.getActServicePrice());
                            xhpcSt.setActTotalPrice(xhpc.getActTotalPrice());
                            if(xhpc.getSource()!=null && xhpc.getSource()==UserTypeUtil.INTERNET_TYPE){
                                xhpcSt.setInternetUserId(xhpc.getUserId());
                            }
                            xhpcSt.setOperatorId(xhpc.getOperatorId());
                            xhpcSt.setChargingStationId(xhpc.getChargingStationId());
                            //xhpcSt.setCreateTime(Calendar.getInstance().getTime());
                            xhpcSt.setTerminalId(xhpc.getTerminalId());
                            xhpcSt.setChargingMode(xhpc.getChargingMode());
                            xhpcSt.setActivityPowerPriceTotal(xhpc.getActivityPowerPriceTotal());
                            xhpcSt.setActivityServicePriceTotal(xhpc.getActivityServicePriceTotal());
                            xhpcSt.setActivityTotalPrice(xhpc.getActivityTotalPrice());
                            xhpcSt.setHistoryOrderId(historyOrderId);
                            xhpcSt.setChargingPileId(xhpc.getChargingPileId());
                            xhpcSt.setCreateTime(xhpc.getEndTime());
                            xhpcSt.setStartTime(xhpc.getStartTime());
                            xhpcSt.setSource(xhpc.getSource());
                            xhpcSt.setInternetDegreeCommission(xhpc.getInternetDegreeCommission());
                            xhpcSt.setType(i);
                            if(xhpc.getSource()==UserTypeUtil.MOTORCADE_TYPE){
                                xhpcSt.setMark(xhpc.getMark());
                                xhpcSt.setMotorcadeId(xhpc.getMotorcadeId());
                            }
                            xhpcStatisticsService.addStatisticsStation(xhpcSt);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    logger.info(">>>>>>>>>>>>>>>>>>>>>>日期电站统计定时任务异常>>>>>>>>>>>>>>>>>>>>>"+xhpc.getHistoryOrderId());
                }
            }
        }
    }


    public void add(int number,int type){
        //获取500条待统计历史订单
        List<XhpcChargeHistoryOrder> list = xhpcHistoryOrderService.getStatistisList(number,type);
        //场站、运营商、流量方
        if(list !=null && list.size()>0){
            for (XhpcChargeHistoryOrder xhpc:list) {
                Long historyOrderId = xhpc.getHistoryOrderId();
                try{
                for (int i = type; i <4 ; i++) {

                        //查询统计表是否有已添加的数据
                        int count = xhpcStatisticsService.getStatisticsStationHistoryOrderId(historyOrderId, i);

                        if(count==0){
                            XhpcStatisticsStation xhpcSt =new XhpcStatisticsStation();
                            xhpcSt.setChargingDegree(xhpc.getChargingDegree());
                            if(xhpc.getChargingTimeNumber() !=null){
                                xhpcSt.setChargingTime(new BigDecimal(xhpc.getChargingTimeNumber()).divide(new BigDecimal(3600), 4, BigDecimal.ROUND_HALF_UP));
                            }
                            xhpcSt.setChargingNumber(1);
                            xhpcSt.setClearingType(xhpc.getClearingType());
                            xhpcSt.setClearingPrice(xhpc.getClearingPrice());
                            xhpcSt.setPowerPrice(xhpc.getPowerPriceTotal());
                            xhpcSt.setServicePrice(xhpc.getServicePriceTotal());
                            xhpcSt.setTotalPrice(xhpc.getTotalPrice());
                            xhpcSt.setPromotionDiscount(xhpc.getPromotionDiscount());
                            xhpcSt.setActPrice(xhpc.getActPrice());
                            xhpcSt.setInternetCommission(xhpc.getInternetCommission());
                            xhpcSt.setInternetSvcCommission(xhpc.getInternetSvcCommission());
                            xhpcSt.setPlatformCommission(xhpc.getPlatformCommission());
                            xhpcSt.setPlatformSvcCommisssion(xhpc.getPlatformSvcCommisssion());
                            xhpcSt.setOperationCommission(xhpc.getOperationCommission());
                            xhpcSt.setOperationSvcCommission(xhpc.getOperationSvcCommission());
                            xhpcSt.setActPowerPrice(xhpc.getActPowerPrice());
                            xhpcSt.setActServicePrice(xhpc.getActServicePrice());
                            xhpcSt.setActTotalPrice(xhpc.getActTotalPrice());
                            if(xhpc.getSource()!=null && xhpc.getSource()==UserTypeUtil.INTERNET_TYPE){
                                xhpcSt.setInternetUserId(xhpc.getUserId());
                            }
                            xhpcSt.setOperatorId(xhpc.getOperatorId());
                            xhpcSt.setChargingStationId(xhpc.getChargingStationId());
                            //xhpcSt.setCreateTime(Calendar.getInstance().getTime());
                            xhpcSt.setTerminalId(xhpc.getTerminalId());
                            xhpcSt.setChargingMode(xhpc.getChargingMode());
                            xhpcSt.setActivityPowerPriceTotal(xhpc.getActivityPowerPriceTotal());
                            xhpcSt.setActivityServicePriceTotal(xhpc.getActivityServicePriceTotal());
                            xhpcSt.setActivityTotalPrice(xhpc.getActivityTotalPrice());
                            xhpcSt.setHistoryOrderId(historyOrderId);
                            xhpcSt.setChargingPileId(xhpc.getChargingPileId());
                            xhpcSt.setCreateTime(xhpc.getEndTime());
                            xhpcSt.setStartTime(xhpc.getStartTime());
                            xhpcSt.setSource(xhpc.getSource());
                            xhpcSt.setInternetDegreeCommission(xhpc.getInternetDegreeCommission());
                            xhpcSt.setType(i);
                            if(xhpc.getSource()==4){
                                xhpcSt.setMark(xhpc.getMark());
                                xhpcSt.setMotorcadeId(xhpc.getMotorcadeId());
                            }

                            xhpcStatisticsService.addStatisticsStation(xhpcSt);
                        }
                    }
                }catch (Exception e){
                    logger.info(">>>>>>>>>>>>>>>>>>>>>>>小时统计定时任务异常>>>>>>>>>>>>>>>>>>>>>"+xhpc.getHistoryOrderId());
                }
                //修改历史订单表状态
                xhpcHistoryOrderService.updateXhpcHistoryOrder(historyOrderId,type+1);
            }
        }
    }

    @GetMapping("/getToday")
    public AjaxResult getToday(){
        return AjaxResult.success(xhpcHistoryOrderService.getToday());
    }

    @GetMapping("/getConfirmResultPage")
    public TableDataInfo  getConfirmResultPage(Integer status) {
        List<Map<String, Object>> listPage = xhpcHistoryOrderService.getConfirmResultPage(status);
        return getDataTable(listPage);
    }

    //修改有争议的订单
    @GetMapping("/updateOrderConfirmResult")
    public AjaxResult  updateOrderConfirmResult(Long historyOrderId) {
        return xhpcHistoryOrderService.updateOrderConfirmResult(historyOrderId);
    }

    //修改流量方订单状态，系统自动推送
    @GetMapping("/updateOrderInternetPush")
    public AjaxResult  updateOrderInternetPush(Long historyOrderId) {
        return xhpcHistoryOrderService.updateOrderInternetPush(historyOrderId);
    }

    //修改成都市监管平台订单状态，系统自动推送
    @GetMapping("/updateChengDuPush")
    public AjaxResult  updateChengDuPush(Long historyOrderId) {
        return xhpcHistoryOrderService.updateChengDuPush(historyOrderId);
    }

    //有争议的订单，平台自己修改订单转改
    @GetMapping("/cancelOrders")
    public AjaxResult  cancelOrders(Long historyOrderId) {
        return xhpcHistoryOrderService.cancelOrders(historyOrderId);
    }


    @PostMapping("/file/upload")
    public R fileUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file, int type, String startTime, String endTime) throws Exception {
        if (file ==null || type < 1){
            return R.fail("文件或者对账类型为空");
        }
        return xhpcHistoryOrderService.fileUpload(request,response,"000000", file, type, startTime, endTime);
    }



    @GetMapping("/getTerminalListPage")
    public TableDataInfo  getTerminalListPage(HttpServletRequest request,Long terminalId,Long chargingStationId)

    {
        List<Map<String, Object>> listPage = xhpcHistoryOrderService.getTerminalListPage(request,terminalId,chargingStationId);
        return getDataTable(listPage);
    }


    //未推送订单信息
    @GetMapping("/getOrderMassageOrRateTime")
    public AjaxResult getOrderMassageOrRateTime(String serialNumber) throws Exception {
        return xhpcHistoryOrderService.getOrderMassageOrRateTime(serialNumber);
    }


    @GetMapping("/addOrderMassageOrRateTime")
    public AjaxResult addOrderMassageOrRateTime(String serialNumber,String chargeOrderInfo) throws Exception {
        return xhpcHistoryOrderService.addOrderMassageOrRateTime(serialNumber,chargeOrderInfo);
    }


}
