package com.artfess.yhxt.schedule;


import com.artfess.yhxt.basedata.manager.*;
import com.artfess.yhxt.basedata.model.*;
import com.artfess.yhxt.budget.dao.YearBudgetDetailedDao;
import com.artfess.yhxt.budget.manager.YearBudgetDetailedManager;
import com.artfess.yhxt.budget.manager.YearBudgetManager;
import com.artfess.yhxt.budget.model.YearBudget;
import com.artfess.yhxt.budget.model.YearBudgetDetailed;
import com.artfess.yhxt.check.regular.dao.BridgeOftenCheckDao;
import com.artfess.yhxt.check.regular.dao.CulvertOftenCheckDao;
import com.artfess.yhxt.check.regular.dao.SideSlopeOftenCheckDao;
import com.artfess.yhxt.check.regular.dao.TunnelOftenCheckDao;
import com.artfess.yhxt.contract.dao.WorkOrderInformationDao;
import com.artfess.yhxt.contract.manager.BillOfQuantitiesManager;
import com.artfess.yhxt.contract.manager.WorkOrderInformationManager;
import com.artfess.yhxt.contract.model.BillOfQuantities;
import com.artfess.yhxt.contract.model.WorkOrderInformation;
import com.artfess.yhxt.specialcheck.manager.SiteInspectionManager;
import com.artfess.yhxt.specialcheck.model.SiteInspection;
import com.artfess.yhxt.statistics.dao.SiteStatisticDao;
import com.artfess.yhxt.statistics.dao.WorkStatisticDao;
import com.artfess.yhxt.statistics.dao.YearBudgetSumDao;
import com.artfess.yhxt.statistics.manager.BaseDataStatisticsManager;
import com.artfess.yhxt.statistics.model.CamerasRequest;
import com.artfess.yhxt.statistics.model.SiteStatistic;
import com.artfess.yhxt.statistics.model.WorkStatistic;
import com.artfess.yhxt.statistics.model.YearBudgetSum;
import com.artfess.yhxt.yjjy.manager.SiteInspectionYjjyManager;
import com.artfess.yhxt.yjjy.model.SiteInspectionYjjy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhx
 * @create 2022/4/17
 */
@Component
@EnableScheduling
public class StatisticsSchedule {
    @Resource
    private WorkOrderInformationManager workOrderInformationManager;
    @Resource
    private RoadManager roadManager;
    @Resource
    private WorkStatisticDao workStatisticDao;
    @Resource
    private TunnelInformationManager tunnelInformationManager;
    @Resource
    private TunnelOftenCheckDao tunnelOftenCheckDao;
    @Resource
    private SideSlopeInformationManager sideSlopeInformationManager;
    @Resource
    private SideSlopeOftenCheckDao sideSlopeOftenCheckDao;
    @Resource
    private BridgeInformationManager bridgeInformationManager;
    @Resource
    private BridgeOftenCheckDao bridgeOftenCheckDao;
    @Resource
    private BizCulvertInformationManager bizCulvertInformationManager;
    @Resource
    private CulvertOftenCheckDao culvertOftenCheckDao;
    @Resource
    private SiteStatisticDao siteStatisticDao;
    @Resource
    private YearBudgetManager yearBudgetManager;
    @Resource
    private YearBudgetDetailedManager yearBudgetDetailedManager;
    @Resource
    BaseDataStatisticsManager baseDataStatisticsManager;
    @Resource
    private BillOfQuantitiesManager billOfQuantitiesManager;
    @Resource
    private YearBudgetSumDao yearBudgetSumDao;
    @Resource
    private SiteInspectionYjjyManager siteInspectionYjjyManager;
    @Resource
    private SiteInspectionManager siteInspectionManager;
    @Resource
    private BizVehicleManager bizVehicleManager;
    @Resource
    private WorkOrderInformationDao workOrderInformationDao;
    @Resource
    private YearBudgetDetailedDao yearBudgetDetailedDao;

    //车辆视频设备同步
    @Scheduled(cron = "0 0 5 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void carEquipment(){
        bizVehicleManager.synchronizationCarData();
    }


    //工单数定时器
    @Scheduled(cron = "0 0 2 * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void scheduleWorkeCount() throws ParseException {
        //计算逾期
        List<WorkOrderInformation> selectOverdue = workOrderInformationDao.selectOverdue();
        for (WorkOrderInformation overdue : selectOverdue){
            //未完成工单逾期
            if (overdue.getEndTime() == null && overdue.getDemandFinishTime().isBefore(LocalDate.now())){
                overdue.setOverdue(1);
                workOrderInformationDao.updateById(overdue);
            }
        }
        //已完成不计入逾期
        workOrderInformationDao.updateOverdue();

        Calendar c = Calendar.getInstance();
        c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(LocalDateTime.now().toString()));
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String first = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        String mouth = new SimpleDateFormat("yyyy-MM").format(c.getTime());
        String year = new SimpleDateFormat("yyyy").format(c.getTime());

        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = new SimpleDateFormat("yyyy-MM-dd").format(ca.getTime());


        QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IS_DELE_", "0");
        List<Road> list = this.roadManager.list(queryWrapper);
        for (Road road : list) {
            QueryWrapper<WorkOrderInformation> queryWrapperWork = new QueryWrapper<>();
            String rodeSegmentId = road.getId();
            queryWrapperWork.eq("ROAD_SEGMENT_ID_", rodeSegmentId);
            queryWrapperWork.ge("END_TIME_", first);
            queryWrapperWork.le("END_TIME_", last);
            //完成工单数量
            List<WorkOrderInformation> workOrderInformations = workOrderInformationManager.listFinishWork(rodeSegmentId, first, last);

            QueryWrapper<WorkOrderInformation> queryWrapperWorkOrder = new QueryWrapper<>();
            queryWrapperWorkOrder.eq("ROAD_SEGMENT_ID_", rodeSegmentId);
            queryWrapperWorkOrder.ge("ISSUE_DATE_", first);
            queryWrapperWorkOrder.le("ISSUE_DATE_", last);
            //所有工单数
            List<WorkOrderInformation> workOrderInformationList = workOrderInformationManager.listWorkAll(rodeSegmentId, first, last);
            QueryWrapper<WorkStatistic> queryWrapperStatistic = new QueryWrapper<>();
            queryWrapperStatistic.eq("ACC_DATE_MONTH_", mouth);
            queryWrapperStatistic.eq("ROAD_SEGMENT_ID_", rodeSegmentId);
            WorkStatistic workStatistic = workStatisticDao.selectOne(queryWrapperStatistic);
            if (workStatistic == null) {
                workStatistic = new WorkStatistic();
                if ((workOrderInformationList.size() - workOrderInformations.size()) > 0) {
                    workStatistic.setTotalNumsNo(String.valueOf(workOrderInformationList.size() - workOrderInformations.size()));
                } else {
                    workStatistic.setTotalNumsNo("0");
                }
                workStatistic.setAccDateMonth(mouth);
                workStatistic.setAccDateYear(year);
                workStatistic.setRoadSegmentId(rodeSegmentId);
                workStatistic.setRoadSegmentName(road.getName());
                workStatistic.setCompanyId(road.getCompanyId());
                workStatistic.setCompanyName(road.getCompanyName());
                workStatistic.setTotalNums(String.valueOf(workOrderInformations.size()));
                workStatisticDao.insert(workStatistic);
            } else {
                workStatistic.setTotalNums(String.valueOf(workOrderInformations.size()));
                if ((workOrderInformationList.size() - workOrderInformations.size()) > 0) {
                    workStatistic.setTotalNumsNo(String.valueOf(workOrderInformationList.size() - workOrderInformations.size()));
                } else {
                    workStatistic.setTotalNumsNo("0");
                }
                workStatisticDao.updateById(workStatistic);
            }


        }
    }

    //预算同步
//    @Scheduled(cron = "0 */1 * * * ?")
    @Scheduled(cron = "0 0 1 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void scheduleYearBudget() {
        try {
            //String year = new SimpleDateFormat("yyyy").parse(LocalDateTime.now().toString()).toString();
            int year = LocalDateTime.now().getYear();
            QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("IS_DELE_", "0");

            List<Road> roadList = roadManager.getBaseMapper().selectList(queryWrapper);
            for (Road road : roadList) {

                QueryWrapper<YearBudget> queryWrapperYearBudget = new QueryWrapper<>();
                queryWrapperYearBudget.eq("IS_DELE_", "0");
                queryWrapperYearBudget.eq("ROAD_SEGMENT_ID_", road.getId());
                queryWrapperYearBudget.eq("ASCRIPTION_YEAR_", String.valueOf(year));

                YearBudget yearBudget = yearBudgetManager.getOne(queryWrapperYearBudget);
                BigDecimal rcjf = new BigDecimal(0);
                BigDecimal frczx = new BigDecimal(0);

                BigDecimal rcjd = new BigDecimal(0);
                BigDecimal zxjd = new BigDecimal(0);
                if (yearBudget != null) {
                    QueryWrapper<YearBudgetDetailed> yearBudgetDetailedQueryWrapperFRCZX = new QueryWrapper<>();
                    yearBudgetDetailedQueryWrapperFRCZX.eq("YEAR_BUDGET_ID_", yearBudget.getId());
                    yearBudgetDetailedQueryWrapperFRCZX.eq("BUDGET_TYPE_", "FRCZX");
                    yearBudgetDetailedQueryWrapperFRCZX.eq("IS_DELE_", "0");

                    QueryWrapper<YearBudgetDetailed> yearBudgetDetailedQueryWrapperRCJF = new QueryWrapper<>();
                    yearBudgetDetailedQueryWrapperRCJF.eq("YEAR_BUDGET_ID_", yearBudget.getId());
                    yearBudgetDetailedQueryWrapperRCJF.eq("BUDGET_TYPE_", "RCJF");
                    yearBudgetDetailedQueryWrapperRCJF.eq("IS_DELE_", "0");



                    List<YearBudgetDetailed> zxList = yearBudgetDetailedManager.list(yearBudgetDetailedQueryWrapperFRCZX);


                    //专项预算总计
                    frczx = frczx.add(zxList.stream().filter(s -> s != null && s.getTotalPrice() != null).map(YearBudgetDetailed::getTotalPrice)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));


                    //专项形象进度总计
                    zxjd = zxjd.add(zxList.stream().filter(s -> s != null && s.getImageProgress() != null).map(YearBudgetDetailed::getImageProgress)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));


                    //日常养护已用金额
                    List<String> WorkOrderInformationIds = workOrderInformationManager.list
                            (new QueryWrapper<WorkOrderInformation>().eq("ROAD_SEGMENT_ID_", road.getId()).isNotNull("END_TIME_").apply("date_format(ISSUE_DATE_,'%Y') = {0}", year)).stream().map(WorkOrderInformation::getId).collect(Collectors.toList());
                    BigDecimal workOrderMoney = new BigDecimal(0);
                    if (WorkOrderInformationIds.size() > 0) {
                        List<Float> worlMoneyF = billOfQuantitiesManager.list(new QueryWrapper<BillOfQuantities>().in("WORK_ORDER_INFORMATION_ID_", WorkOrderInformationIds))
                                .stream().filter(s -> s != null && s.getTaxMoney() != null).map(BillOfQuantities::getTaxMoney).collect(Collectors.toList());
                        for (Float aFloat : worlMoneyF) {
                            workOrderMoney = workOrderMoney.add(new BigDecimal(Float.toString(aFloat)));
                        }
                    }

                    //计算形象金额
                    QueryWrapper<YearBudgetDetailed> detailedQueryWrapper = new QueryWrapper<>();
                    detailedQueryWrapper.eq("YEAR_BUDGET_ID_",yearBudget.getId());
                    detailedQueryWrapper.eq("IS_DELE_","0");
                    detailedQueryWrapper.eq("EXPENDITURE_TYPE_","FXCBXZC");
                    detailedQueryWrapper.eq("BUDGET_TYPE_","RCJF");
                    detailedQueryWrapper.eq("BUDGET_ITEM_","RCYH");
                    detailedQueryWrapper.eq("BUDGET_CONTENT","日常养护");
                    List<YearBudgetDetailed> detaileds = yearBudgetDetailedManager.list(detailedQueryWrapper);
                    for (YearBudgetDetailed detailed : detaileds){
                        detailed.setImageProgress(workOrderMoney.divide(new BigDecimal("10000"),2, RoundingMode.DOWN));
                        yearBudgetDetailedManager.update(detailed);
                    }

                    List<YearBudgetDetailed> rcList = yearBudgetDetailedManager.list(yearBudgetDetailedQueryWrapperRCJF);

                    //日常预算总计
                    rcjf = rcjf.add(rcList.stream().filter(s -> s != null && s.getTotalPrice() != null).map(YearBudgetDetailed::getTotalPrice).
                            reduce(BigDecimal.ZERO, BigDecimal::add));
                    //日常形象进度总计
                    rcjd = rcjd.add(rcList.stream().filter(s -> s != null && s.getImageProgress() != null).map(YearBudgetDetailed::getImageProgress)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));
                    yearBudget.setAlreadyCount(yearBudgetDetailedDao.sumImageProgress(yearBudget.getId()));
                    yearBudgetManager.updateById(yearBudget);

                }


                YearBudgetSum yearBudgetSum = yearBudgetSumDao.selectOne(new QueryWrapper<YearBudgetSum>().eq("ACC_DATE_YEAR_", year).eq("ROAD_SEGMENT_ID_", road.getId()));
                if (null == yearBudgetSum) {
                    yearBudgetSum = new YearBudgetSum();
                    yearBudgetSum.setCompanyId(road.getCompanyId());
                    yearBudgetSum.setCompanyName(road.getCompanyName());
                    yearBudgetSum.setRoadSegmentId(road.getId());
                    yearBudgetSum.setRoadSegmentName(road.getName());
                    yearBudgetSum.setAccDateYear(year);
                    yearBudgetSum.setBudgetSum(String.valueOf(rcjf.add(frczx)));
                    yearBudgetSum.setConserveMoneyBudget(String.valueOf(rcjf));
                    yearBudgetSum.setSpecialMoneyBudget(String.valueOf(frczx));
                    yearBudgetSum.setAlreadyCount(String.valueOf(rcjd.add(zxjd).setScale(2)));
                    yearBudgetSum.setConserveMoney(String.valueOf(rcjd));
                    yearBudgetSum.setSpecialMoney(String.valueOf(zxjd));
                    yearBudgetSumDao.insert(yearBudgetSum);

                } else {
                    yearBudgetSum.setBudgetSum(String.valueOf(rcjf.add(frczx)));
                    yearBudgetSum.setConserveMoneyBudget(String.valueOf(rcjf));
                    yearBudgetSum.setSpecialMoneyBudget(String.valueOf(frczx));
                    yearBudgetSum.setAlreadyCount(String.valueOf(rcjd.add(zxjd).setScale(2)));
                    yearBudgetSum.setConserveMoney(String.valueOf(rcjd));
                    yearBudgetSum.setSpecialMoney(String.valueOf(zxjd));
                    yearBudgetSumDao.updateById(yearBudgetSum);
                }

            }

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

    }


    @Scheduled(cron = "0 30 0 * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void scheduleSiteStatistic() {
        String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
        String year = new SimpleDateFormat("yyyy").format(new Date());
        QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IS_DELE_", "0");
        List<Road> list = this.roadManager.list(queryWrapper);
        for (Road road : list) {
            //桥梁
            QueryWrapper<BridgeInformation> queryWrapperBridge = new QueryWrapper<>();
            queryWrapperBridge.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperBridge.eq("IS_DELE_", "0");
            List<BridgeInformation> bridgeInformations = bridgeInformationManager.list(queryWrapperBridge);
            String ids = bridgeInformations.stream().map(s -> s.getId()).collect(Collectors.joining(","));
            int countBridgeOftenCheck;
            if (StringUtils.isEmpty(ids)) {
                countBridgeOftenCheck = 0;
            } else {
                countBridgeOftenCheck = bridgeOftenCheckDao.countBridgeOften(ids, mouth);
            }

            //涵洞
            QueryWrapper<BizCulvertInformation> queryWrapperCulvert = new QueryWrapper<>();
            queryWrapperCulvert.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperCulvert.eq("IS_DELE_", "0");
            String culvertIds = bizCulvertInformationManager.list(queryWrapperCulvert).stream().map(BizCulvertInformation::getId).collect(Collectors.joining(","));
            int countCulvertOften;
            if (StringUtils.isEmpty(culvertIds)) {
                countCulvertOften = 0;
            } else {
                countCulvertOften = culvertOftenCheckDao.countCulvertOften(culvertIds, mouth);
            }
            //边坡
            QueryWrapper<SideSlopeInformation> queryWrapperSide = new QueryWrapper<>();
            queryWrapperSide.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSide.eq("IS_DELE_", "0");
            String sideSlopeIds = sideSlopeInformationManager.list(queryWrapperSide).stream().map(SideSlopeInformation::getId).collect(Collectors.joining(","));

            int countSideSlope;
            if (StringUtils.isEmpty(sideSlopeIds)) {
                countSideSlope = 0;
            } else {
                countSideSlope = sideSlopeOftenCheckDao.countSideSlopeOften(sideSlopeIds, mouth);
            }

            //隧道
            QueryWrapper<TunnelInformation> queryWrapperTunnel = new QueryWrapper<>();
            queryWrapperTunnel.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperTunnel.eq("IS_DELE_", "0");
            String tunnelIds = tunnelInformationManager.list(queryWrapperTunnel).stream().map(TunnelInformation::getId).collect(Collectors.joining(","));
            int countTunnelOften;
            if (StringUtils.isEmpty(tunnelIds)) {
                countTunnelOften = 0;
            } else {
                countTunnelOften = tunnelOftenCheckDao.countTunnelOften(tunnelIds, mouth);
            }

            //日巡检
            QueryWrapper<SiteInspection> queryWrapperSiteInspection = new QueryWrapper<>();
            queryWrapperSiteInspection.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSiteInspection.eq("TYPE_", 1);
            queryWrapperSiteInspection.apply("date_format(PATROL_DATE_,'%Y-%m') = {0}", mouth);
            Long countDayFlish = 0L;
            Long countDayUnFlish = 0L;
            List<SiteInspection> listSiteDay = siteInspectionManager.list(queryWrapperSiteInspection);
            countDayFlish = listSiteDay.stream().filter(s -> "3".equals(s.getHandStatus())).count();
            countDayUnFlish = listSiteDay.stream().filter(s -> "2".equals(s.getHandStatus())).count();
            //夜巡检
            QueryWrapper<SiteInspection> queryWrapperSiteInspectionNight = new QueryWrapper<>();
            queryWrapperSiteInspectionNight.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSiteInspectionNight.eq("TYPE_", 2);
            queryWrapperSiteInspectionNight.apply("date_format(PATROL_DATE_,'%Y-%m') = {0}", mouth);
            List<SiteInspection> listNight = siteInspectionManager.list(queryWrapperSiteInspectionNight);
            Long countNightFlish = 0L;
            Long countNightUnFlish = 0L;
            countNightFlish = listNight.stream().filter(s -> "3".equals(s.getHandStatus())).count();
            countNightUnFlish = listNight.stream().filter(s -> "2".equals(s.getHandStatus())).count();

            QueryWrapper<SiteStatistic> queryWrapperSiteStatistic = new QueryWrapper<>();
            queryWrapperSiteStatistic.eq("ACC_DATE_MONTH_", mouth);
            queryWrapperSiteStatistic.eq("ACC_DATE_YEAR_", year);
            queryWrapperSiteStatistic.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSiteStatistic.eq("SITE_CODE_", 3);
            SiteStatistic siteStatisticBrideOften = siteStatisticDao.selectOne(queryWrapperSiteStatistic);
            if (siteStatisticBrideOften == null) {
                siteStatisticBrideOften = new SiteStatistic();
                //siteStatisticBrideOften.setCompleteTotal(countBridgeOftenCheck);
                siteStatisticBrideOften.setAccDateMonth(mouth);
                siteStatisticBrideOften.setAccDateYear(year);
                siteStatisticBrideOften.setCompanyId(road.getCompanyId());
                siteStatisticBrideOften.setCompanyName(road.getCompanyName());
                siteStatisticBrideOften.setSiteCode(3);
                siteStatisticBrideOften.setSiteName("桥梁经常检查");
                siteStatisticBrideOften.setRoadSegmentId(road.getId());
                siteStatisticBrideOften.setRoadSegmentName(road.getName());
                siteStatisticBrideOften.setComplete(String.valueOf(countBridgeOftenCheck));
                siteStatisticBrideOften.setCompleteNo("0");
                siteStatisticDao.insert(siteStatisticBrideOften);
            } else {
                siteStatisticBrideOften.setComplete(String.valueOf(countBridgeOftenCheck));
                siteStatisticDao.updateById(siteStatisticBrideOften);
            }

            QueryWrapper<SiteStatistic> queryWrapperSiteStatistic2 = new QueryWrapper<>();
            queryWrapperSiteStatistic2.eq("ACC_DATE_MONTH_", mouth);
            queryWrapperSiteStatistic2.eq("ACC_DATE_YEAR_", year);
            queryWrapperSiteStatistic2.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSiteStatistic2.eq("SITE_CODE_", 4);
            SiteStatistic siteStatisticTunnel = siteStatisticDao.selectOne(queryWrapperSiteStatistic2);
            if (siteStatisticTunnel == null) {
                siteStatisticTunnel = new SiteStatistic();
                siteStatisticTunnel.setAccDateMonth(mouth);
                siteStatisticTunnel.setAccDateYear(year);
                siteStatisticTunnel.setCompanyId(road.getCompanyId());
                siteStatisticTunnel.setCompanyName(road.getCompanyName());
                siteStatisticTunnel.setSiteCode(4);
                siteStatisticTunnel.setSiteName("隧道经常检查");
                siteStatisticTunnel.setRoadSegmentId(road.getId());
                siteStatisticTunnel.setRoadSegmentName(road.getName());
                siteStatisticTunnel.setComplete(String.valueOf(countTunnelOften));
                siteStatisticTunnel.setCompleteNo("0");
                siteStatisticDao.insert(siteStatisticTunnel);
            } else {
                siteStatisticTunnel.setComplete(String.valueOf(countTunnelOften));
                siteStatisticDao.updateById(siteStatisticTunnel);
            }


            QueryWrapper<SiteStatistic> queryWrapperSiteStatistic3 = new QueryWrapper<>();
            queryWrapperSiteStatistic3.eq("ACC_DATE_MONTH_", mouth);
            queryWrapperSiteStatistic3.eq("ACC_DATE_YEAR_", year);
            queryWrapperSiteStatistic3.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSiteStatistic3.eq("SITE_CODE_", 5);
            SiteStatistic siteStatisticCulvertOften = siteStatisticDao.selectOne(queryWrapperSiteStatistic3);
            if (siteStatisticCulvertOften == null) {
                siteStatisticCulvertOften = new SiteStatistic();
                siteStatisticCulvertOften.setAccDateMonth(mouth);
                siteStatisticCulvertOften.setAccDateYear(year);
                siteStatisticCulvertOften.setCompanyId(road.getCompanyId());
                siteStatisticCulvertOften.setCompanyName(road.getCompanyName());
                siteStatisticCulvertOften.setSiteCode(5);
                siteStatisticCulvertOften.setSiteName("涵洞经常检查");
                siteStatisticCulvertOften.setRoadSegmentId(road.getId());
                siteStatisticCulvertOften.setRoadSegmentName(road.getName());
                siteStatisticCulvertOften.setComplete(String.valueOf(countCulvertOften));
                siteStatisticCulvertOften.setCompleteNo("0");
                siteStatisticDao.insert(siteStatisticCulvertOften);
            } else {
                siteStatisticCulvertOften.setComplete(String.valueOf(countCulvertOften));
                siteStatisticDao.updateById(siteStatisticCulvertOften);
            }


            QueryWrapper<SiteStatistic> queryWrapperSiteStatistic4 = new QueryWrapper<>();
            queryWrapperSiteStatistic4.eq("ACC_DATE_MONTH_", mouth);
            queryWrapperSiteStatistic4.eq("ACC_DATE_YEAR_", year);
            queryWrapperSiteStatistic4.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSiteStatistic4.eq("SITE_CODE_", 6);
            SiteStatistic siteStatisticSideSlope = siteStatisticDao.selectOne(queryWrapperSiteStatistic4);
            if (siteStatisticSideSlope == null) {
                siteStatisticSideSlope = new SiteStatistic();
                siteStatisticSideSlope.setAccDateMonth(mouth);
                siteStatisticSideSlope.setAccDateYear(year);
                siteStatisticSideSlope.setCompanyId(road.getCompanyId());
                siteStatisticSideSlope.setCompanyName(road.getCompanyName());
                siteStatisticSideSlope.setSiteCode(6);
                siteStatisticSideSlope.setSiteName("边坡经常检查");
                siteStatisticSideSlope.setRoadSegmentId(road.getId());
                siteStatisticSideSlope.setRoadSegmentName(road.getName());
                siteStatisticSideSlope.setComplete(String.valueOf(countSideSlope));
                siteStatisticSideSlope.setCompleteNo("0");
                siteStatisticDao.insert(siteStatisticSideSlope);
            } else {
                siteStatisticSideSlope.setComplete(String.valueOf(countSideSlope));
                siteStatisticDao.updateById(siteStatisticSideSlope);
            }
            //日巡检
            QueryWrapper<SiteStatistic> queryWrapperSiteStatistic5 = new QueryWrapper<>();
            queryWrapperSiteStatistic5.eq("ACC_DATE_MONTH_", mouth);
            queryWrapperSiteStatistic5.eq("ACC_DATE_YEAR_", year);
            queryWrapperSiteStatistic5.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSiteStatistic5.eq("SITE_CODE_", 1);
            SiteStatistic siteInspectionDay = siteStatisticDao.selectOne(queryWrapperSiteStatistic5);
            if (siteInspectionDay == null) {
                siteInspectionDay = new SiteStatistic();
                siteInspectionDay.setAccDateMonth(mouth);
                siteInspectionDay.setAccDateYear(year);
                siteInspectionDay.setCompanyId(road.getCompanyId());
                siteInspectionDay.setCompanyName(road.getCompanyName());
                siteInspectionDay.setSiteCode(1);
                siteInspectionDay.setSiteName("日巡检");
                siteInspectionDay.setRoadSegmentId(road.getId());
                siteInspectionDay.setRoadSegmentName(road.getName());
                siteInspectionDay.setComplete(String.valueOf(countDayFlish));
                siteInspectionDay.setCompleteNo(String.valueOf(countDayUnFlish));
                siteStatisticDao.insert(siteInspectionDay);
            } else {
                siteInspectionDay.setComplete(String.valueOf(countDayFlish));
                siteInspectionDay.setCompleteNo(String.valueOf(countDayUnFlish));
                siteStatisticDao.updateById(siteInspectionDay);
            }

            //夜巡检
            QueryWrapper<SiteStatistic> queryWrapperSiteStatistic6 = new QueryWrapper<>();
            queryWrapperSiteStatistic6.eq("ACC_DATE_MONTH_", mouth);
            queryWrapperSiteStatistic6.eq("ACC_DATE_YEAR_", year);
            queryWrapperSiteStatistic6.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperSiteStatistic6.eq("SITE_CODE_", 2);
            SiteStatistic siteInspectionNight = siteStatisticDao.selectOne(queryWrapperSiteStatistic6);
            if (siteInspectionNight == null) {
                siteInspectionNight = new SiteStatistic();
                siteInspectionNight.setAccDateMonth(mouth);
                siteInspectionNight.setAccDateYear(year);
                siteInspectionNight.setCompanyId(road.getCompanyId());
                siteInspectionNight.setCompanyName(road.getCompanyName());
                siteInspectionNight.setSiteCode(2);
                siteInspectionNight.setSiteName("夜巡检");
                siteInspectionNight.setRoadSegmentId(road.getId());
                siteInspectionNight.setRoadSegmentName(road.getName());
                siteInspectionNight.setComplete(String.valueOf(countNightFlish));
                siteInspectionNight.setCompleteNo(String.valueOf(countNightUnFlish));
                siteStatisticDao.insert(siteInspectionNight);
            } else {
                siteInspectionNight.setComplete(String.valueOf(countNightFlish));
                siteInspectionNight.setCompleteNo(String.valueOf(countNightUnFlish));
                siteStatisticDao.updateById(siteInspectionNight);
            }


        }
    }

    @Scheduled(cron = "0 0 0/4 * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void scheduleSiteinspection() {
        List<SiteInspectionYjjy> list = siteInspectionYjjyManager.list(new QueryWrapper<SiteInspectionYjjy>().lambda().eq(SiteInspectionYjjy::getSStatus, "完成").or().eq(SiteInspectionYjjy::getSStatus, "巡查中"));

        ArrayList<SiteInspection> siteInspections = new ArrayList<>();
        list.forEach(s -> {
            Road road = roadManager.getOne(new QueryWrapper<Road>().lambda().eq(Road::getCode, s.getSRoad()).eq(Road::getIsDele, "0"));
            if (road != null) {
                SiteInspection siteInspection = new SiteInspection();
                siteInspection.setId(s.getId());
                siteInspection.setRoadSegmentId(road.getId());
                siteInspection.setRoadSegmentName(road.getName());
                siteInspection.setRouteId(road.getRouteId());
                siteInspection.setRouteName(road.getRouteName());
                siteInspection.setCompanyId(road.getCompanyId());
                siteInspection.setCompanyName(road.getCompanyName());
                if ("完成".equals(s.getSStatus())) {
                    siteInspection.setHandStatus("3");
                }
                if ("巡查中".equals(s.getSStatus())) {
                    siteInspection.setHandStatus("2");
                }
//                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                LocalDate parse = LocalDateTime.parse(s.getDBeginTime().toString(), dateTimeFormatter).toLocalDate();
                System.out.println(s.getDBeginTime().toLocalDate().toString());

                siteInspection.setPatrolDate(s.getDBeginTime().toLocalDate());

                siteInspection.setContent(s.getSTaskValue());
                if ("白班".equals(s.getSClass())) {
                    siteInspection.setType(1);
                } else {
                    siteInspection.setType(2);
                }
                siteInspection.setFullname(s.getSDoPersonName());
//                siteInspection.setWeather();
                siteInspection.setWeatherValue(s.getSWeather());

                siteInspections.add(siteInspection);
            }
        });

        siteInspectionManager.saveOrUpdateBatch(siteInspections);
    }




    /**
     * 定时任务同步所有shi监控点资源
     */
    @Scheduled(cron = "0 0 4 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void getCamerasSchedule() {
            CamerasRequest camerasRequest = new CamerasRequest();
            camerasRequest.setPageNo(1);
            camerasRequest.setPageSize(1);
            camerasRequest.setTreeCode("0");
            baseDataStatisticsManager.getCameras(camerasRequest);
    }



}
