package com.artfess.yhxt.contract.manager.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.artfess.activemq.model.JmsMessage;
import com.artfess.application.jms.JmsHandler;
import com.artfess.application.jms.impl.InnerHandler;
import com.artfess.base.context.BaseContext;
import com.artfess.base.jms.JmsActor;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.*;
import com.artfess.base.util.FileUtil;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.webSocket.PushService;
import com.artfess.bpm.persistence.dao.BpmProcessInstanceDao;
import com.artfess.bpm.persistence.dao.BpmTaskDao;
import com.artfess.bpm.persistence.model.DefaultBpmProcessInstance;
import com.artfess.bpm.persistence.model.DefaultBpmTask;
import com.artfess.file.util.MinioUtil;
import com.artfess.sysConfig.persistence.manager.SysIdentityManager;
import com.artfess.uc.api.model.IUser;
import com.artfess.uc.dao.OrgDao;
import com.artfess.uc.exception.BaseException;
import com.artfess.uc.manager.OrgUserManager;
import com.artfess.uc.manager.UserManager;
import com.artfess.uc.model.Org;
import com.artfess.uc.model.OrgUser;
import com.artfess.uc.model.User;
import com.artfess.uc.util.ContextUtil;
import com.artfess.workflow.runtime.manager.IFlowManager;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.basedata.model.Road;
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.contract.dao.WorkOrderInformationDao;
import com.artfess.yhxt.contract.manager.*;
import com.artfess.yhxt.contract.model.*;
import com.artfess.yhxt.contract.vo.*;
import com.artfess.yhxt.disease.manager.DiseaseManager;
import com.artfess.yhxt.disease.model.Disease;
import com.artfess.yhxt.specialproject.manager.BizEngineeringProjectManager;
import com.artfess.yhxt.specialproject.manager.BizProjectBeginApplyForManager;
import com.artfess.yhxt.specialproject.manager.MeasurementPaymentManager;
import com.artfess.yhxt.specialproject.model.BizEngineeringProject;
import com.artfess.yhxt.specialproject.model.BizProjectBeginApplyFor;
import com.artfess.yhxt.specialproject.model.MeasurementPayment;
import com.artfess.yhxt.statistics.dao.WorkStatisticDao;
import com.artfess.yhxt.statistics.vo.Org4AppVO;
import com.artfess.yhxt.statistics.vo.OrgVO;
import com.artfess.yhxt.util.ArithUtil;
import com.artfess.yhxt.util.PermissionUtils;
import com.artfess.yhxt.util.PoiStyleUtil;
import com.artfess.yhxt.util.StreamUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.artfess.yhxt.util.PoiStyleUtil.setExcelStyle;

/**
 * 工单信息表 服务实现类
 *
 * @author wangping
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-08-20
 */
@Service
public class WorkOrderInformationManagerImpl extends BaseManagerImpl<WorkOrderInformationDao, WorkOrderInformation> implements WorkOrderInformationManager {

    @Resource
    private BillOfQuantitiesManager billOfQuantitiesManager;
    @Resource
    private ContractItemManager contractItemManager;
    @Resource
    private DiseaseManager diseaseManager;
    @Resource
    private SysIdentityManager sysIdentityManager;
    @Resource
    private ContractManager contractManager;
    @Resource
    private AccessoryManager accessoryManager;
    @Resource
    private IFlowManager iFlowManager;
    @Resource
    private RoadManager roadManager;
    @Resource
    private OrgUserManager orgUserManager;
    @Resource
    private UserManager userManager;
    @Resource
    private BpmTaskDao bpmTaskDao;
    @Resource
    private BillQuantiTypeManagManager billQuantiTypeManagManager;

    @Resource
    private BpmProcessInstanceDao bpmProcessInstanceDao;

    @Resource
    private OrgDao orgDao;

    @Resource
    BaseContext baseContext;

    @Resource
    private WorkStatisticDao workStatisticDao;

    @Autowired
    private YearBudgetManager yearBudgetManager;

    @Autowired
    private YearBudgetDetailedManager yearBudgetDetailedManager;
    @Autowired
    private PermissionUtils permissionUtils;
    @Autowired
    private YearBudgetDetailedDao yearBudgetDetailedDao;
    @Autowired
    private WorkOrderInformationDao workOrderInformationDao;
    @Resource
    InnerHandler innerHandler;
    @Autowired
    private BizEngineeringProjectManager bizEngineeringProjectManager;

    @Override
    public List<OrderMonthVO> getMonthReport(String year, String orgId) {
        List<OrderMonthVO> vos =  new ArrayList<>();
        QueryWrapper<Road> roadWrapper = new QueryWrapper<>();
        roadWrapper.eq("IS_DELE_","0");
        roadWrapper.like("COMPANY_IDS_",orgId);
        List<Road> roads = roadManager.list(roadWrapper);
        for (Road road : roads){
            OrderMonthVO vo = new OrderMonthVO();
            vo.setRoadName(road.getName());
            vo.setOrgName("重庆运营管理总部");
            //获取金额
            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);

            if (yearBudget!=null){
                //日常
                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");
                List<YearBudgetDetailed> daily = yearBudgetDetailedManager.list(detailedQueryWrapper);

                //专项
                QueryWrapper<YearBudgetDetailed> speQueryWrapper = new QueryWrapper<>();
                speQueryWrapper.eq("YEAR_BUDGET_ID_",yearBudget.getId());
                speQueryWrapper.eq("IS_DELE_","0");
                speQueryWrapper.eq("EXPENDITURE_TYPE_","FXCBXZC");
                speQueryWrapper.eq("BUDGET_TYPE_","FRCZX");
                List<YearBudgetDetailed> spe = yearBudgetDetailedManager.list(detailedQueryWrapper);

                BigDecimal dailyMoney = BigDecimal.ZERO;

                BigDecimal speMoney = BigDecimal.ZERO;

                BigDecimal dailyFinish = BigDecimal.ZERO;

                BigDecimal speFinish = BigDecimal.ZERO;

                BigDecimal allMoney = BigDecimal.ZERO;

                BigDecimal allFinish= BigDecimal.ZERO;


                if (spe.size()>0){
                    List<BigDecimal> speMoneys = spe.stream().filter(s -> s != null && s.getTotalPrice() != null).map(YearBudgetDetailed::getTotalPrice).collect(Collectors.toList());

                    List<BigDecimal> speFinishs = spe.stream().filter(s -> s != null && s.getImageProgress() != null).map(YearBudgetDetailed::getImageProgress).collect(Collectors.toList());

                    for (BigDecimal speDe:speMoneys){
                        speMoney = speMoney.add(speDe);
                    }

                    for (BigDecimal speFi:speFinishs){
                        speFinish = speFinish.add(speFi);
                    }

                }
                if (daily.size()>0){
                    List<BigDecimal> dailyMoneys = daily.stream().filter(s -> s != null && s.getTotalPrice() != null).map(YearBudgetDetailed::getTotalPrice).collect(Collectors.toList());

                    List<BigDecimal> dailyFinishs = daily.stream().filter(s -> s != null && s.getImageProgress() != null).map(YearBudgetDetailed::getImageProgress).collect(Collectors.toList());
                    for (BigDecimal dailyDe:dailyMoneys){
                        dailyMoney = dailyMoney.add(dailyDe);
                    }

                    allMoney = dailyMoney.add(speMoney);

                    for (BigDecimal dailyFi:dailyFinishs){
                        dailyFinish = dailyFinish.add(dailyFi);
                    }
                }


                allFinish = dailyFinish.add(speFinish);

                vo.setDailyMoney(dailyMoney);
                vo.setDailyFinish(dailyFinish);

                vo.setSpeMoney(speMoney);
                vo.setSpeFinish(speFinish);

                vo.setAllFinish(allFinish);
                vo.setAllMoney(allMoney);

                if (!dailyMoney.equals(BigDecimal.ZERO)&&!dailyFinish.equals(BigDecimal.ZERO)){
                    vo.setDailyRate(dailyFinish.divide(dailyMoney,2,BigDecimal.ROUND_UP));
                }else {
                    vo.setDailyRate(BigDecimal.ZERO);
                }

                if (!speMoney.equals(BigDecimal.ZERO)&&!speFinish.equals(BigDecimal.ZERO)){
                    vo.setSpeRate(speFinish.divide(speMoney,2,BigDecimal.ROUND_UP));
                }else {
                    vo.setSpeRate(BigDecimal.ZERO);
                }

                if (!allFinish.equals(BigDecimal.ZERO)&&!allMoney.equals(BigDecimal.ZERO)){
                    vo.setAllRate(allFinish.divide(allMoney,2,BigDecimal.ROUND_UP));
                }else {
                    vo.setAllRate(BigDecimal.ZERO);
                }
            }else {
                vo.setSpeRate(BigDecimal.ZERO);
                vo.setSpeMoney(BigDecimal.ZERO);
                vo.setSpeFinish(BigDecimal.ZERO);
                vo.setDailyRate(BigDecimal.ZERO);
                vo.setDailyFinish(BigDecimal.ZERO);
                vo.setDailyMoney(BigDecimal.ZERO);
                vo.setAllRate(BigDecimal.ZERO);
                vo.setAllMoney(BigDecimal.ZERO);
                vo.setAllFinish(BigDecimal.ZERO);
            }
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public List<OrderCheckVO> getCheckReport(String year, String orgId) {
        List<OrderCheckVO> vos =  new ArrayList<>();
        QueryWrapper<Road> roadWrapper = new QueryWrapper<>();
        roadWrapper.eq("IS_DELE_","0");
        roadWrapper.like("COMPANY_IDS_",orgId);
        List<Road> roads = roadManager.list(roadWrapper);
        for (Road road : roads){
            List<String> ids = new ArrayList<>();
            ids.add(road.getId());
            OrderCheckVO vo = new OrderCheckVO();
            vo.setRoadName(road.getName());
            QueryWrapper<WorkOrderInformation> orderQueryWrapper = new QueryWrapper<>();
            Map<String, Object> params = new HashMap<>();
            params.put("accDateYear", year);
            params.put("roadSegmentId",ids);
            params.put("ids",ids);
            List<WorkOrderCountVO> mapList = workStatisticDao.countWorkOrder4New(params);
            List<WorkOrderCountVO> userTask1list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask1")).collect(Collectors.toList());
            List<WorkOrderCountVO> userTask2list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask2")).collect(Collectors.toList());
            List<WorkOrderCountVO> endEvent1list = mapList.stream().filter(s -> s.getTaskKey().equals("EndEvent1")).collect(Collectors.toList());
            vo.setFinishCount(endEvent1list.size());
            vo.setConstructionCount(endEvent1list.size()-userTask1list.size()-userTask2list.size());
            if (mapList.size()>0&&endEvent1list.size()>0){
                vo.setFinishRate(new BigDecimal(vo.getFinishCount()).divide(new BigDecimal(mapList.size()),2,BigDecimal.ROUND_UP));
            }else {
                vo.setFinishRate(new BigDecimal(0));
            }
            vos.add(vo);
        }
        return vos;
    }


    @Override
    public List<OrderWorkFinishVO> getWorkFinishReport(String year, String orgId) {
        List<OrderWorkFinishVO> vos =  new ArrayList<>();
        QueryWrapper<Road> roadWrapper = new QueryWrapper<>();
        roadWrapper.eq("IS_DELE_","0");
        roadWrapper.like("COMPANY_IDS_",orgId);
        List<Road> roads = roadManager.list(roadWrapper);
        for (Road road : roads){
            QueryWrapper<WorkOrderInformation> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("IS_DELE_","0");
            orderWrapper.eq("ROAD_SEGMENT_ID_",road.getId());
            orderWrapper.apply("date_format(ISSUE_DATE_,'%Y') = {0}",year);
            List<WorkOrderInformation> allList = this.list(orderWrapper);


            List<String> ids = new ArrayList<>();
            ids.add(road.getId());
            OrderWorkFinishVO vo = new OrderWorkFinishVO();
            vo.setRoadName(road.getName());

            Map<String, Object> params = new HashMap<>();
            params.put("accDateYear", year);
            params.put("roadSegmentId",ids);
            params.put("ids",ids);
            List<WorkOrderCountVO> mapList = workStatisticDao.countWorkOrder4New(params);
            List<WorkOrderCountVO> userTask1list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask1")).collect(Collectors.toList());

            List<WorkOrderCountVO> userTask3list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask3")).collect(Collectors.toList());

            List<WorkOrderCountVO> endEvent1list = mapList.stream().filter(s -> s.getTaskKey().equals("EndEvent1")).collect(Collectors.toList());
            BigDecimal task1Money = new BigDecimal(0);
            if (userTask1list.size()>0){
                List<String> task1 = userTask1list.stream().map(WorkOrderCountVO::getWorkId).collect(Collectors.toList());
                List<Float> worlMoneyF = billOfQuantitiesManager.list(new QueryWrapper<BillOfQuantities>().in("WORK_ORDER_INFORMATION_ID_", task1))
                        .stream().filter(s -> s != null && s.getMoney() != null).map(BillOfQuantities::getMoney).collect(Collectors.toList());

                for (Float aFloat : worlMoneyF) {
                    task1Money = task1Money.add(new BigDecimal(Float.toString(aFloat)));
                }
            }
            BigDecimal task3Money = new BigDecimal(0);
            if (userTask3list.size()>0){
                List<String> task3 = userTask3list.stream().map(WorkOrderCountVO::getWorkId).collect(Collectors.toList());
                List<Float> worlMoneyF = billOfQuantitiesManager.list(new QueryWrapper<BillOfQuantities>().in("WORK_ORDER_INFORMATION_ID_", task3))
                        .stream().filter(s -> s != null && s.getReceiverMoney() != null).map(BillOfQuantities::getReceiverMoney).collect(Collectors.toList());

                for (Float aFloat : worlMoneyF) {
                    task3Money = task3Money.add(new BigDecimal(Float.toString(aFloat)));
                }
            }
            vo.setIssuedMoney(task1Money);
            vo.setIssuedCount(userTask1list.size());
            vo.setWorkCount(userTask3list.size());
            vo.setWorkMoney(task3Money);
            vo.setFinishCount(endEvent1list.size());

            List<WorkOrderInformation> deseasaList = allList.stream().filter(p -> StringUtils.isNotEmpty(p.getDiseaseId())).collect(Collectors.toList());
            vo.setDeseasaCount(deseasaList.size());

            vo.setEseasaFinishCount(deseasaList.stream().filter(p ->p.getStatus().equals("1")).collect(Collectors.toList()).size());
            vos.add(vo);
        }

        return vos;
    }

    @Override
    public List<OrderMoneyVO> getMoneyReport(String year, String orgId) {
        List<OrderMoneyVO> vos =  new ArrayList<>();
        QueryWrapper<Road> roadWrapper = new QueryWrapper<>();
        roadWrapper.eq("IS_DELE_","0");
        roadWrapper.like("COMPANY_IDS_",orgId);
        List<Road> roads = roadManager.list(roadWrapper);
        LocalDateTime now = LocalDateTime.now();
        int month = now.getMonthValue();
        for (Road road : roads){
            BigDecimal finishRate = BigDecimal.ZERO;
            OrderMoneyVO vo = new OrderMoneyVO();
            vo.setRoadName(road.getName());
            QueryWrapper<Contract> contractWrapper = new QueryWrapper<>();
            contractWrapper.eq("ROAD_SEGMENT_ID_",road.getId());
            contractWrapper.eq("IS_DELE_","0");
            contractWrapper.orderByDesc("CREATE_TIME_");
            contractWrapper.last("limit 1");
            Contract contract = contractManager.getOne(contractWrapper);
            if (contract!=null){
                vo.setContractMoney(new BigDecimal(String.valueOf(contract.getContractAmount())));
                vo.setContractName(contract.getName());
            }else {
                vo.setContractMoney(BigDecimal.ZERO);
            }
            //日常养护已用金额
            String monthstr ;
            if (month<10){
                monthstr = "0"+String.valueOf(month);
            }else {
                monthstr = String.valueOf(month);
            }
            List<String> WorkOrderInformationIds = this.list
                    (new QueryWrapper<WorkOrderInformation>().eq("ROAD_SEGMENT_ID_", road.getId()).isNotNull("END_TIME_").
                            apply("date_format(ISSUE_DATE_,'%Y-%m') = '" +year+"-"+monthstr+"'" )).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)));
                }
            }
            vo.setMonthMoney(workOrderMoney);
            //获取金额
            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);

            if(yearBudget!=null){
                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","日常养护");
                YearBudgetDetailed detaileds = yearBudgetDetailedManager.getOne(detailedQueryWrapper);
                if (detaileds!=null){
                    vo.setFinishMoney(detaileds.getImageProgress().multiply(new BigDecimal(10000)));
                    if (!vo.getContractMoney().equals(BigDecimal.ZERO)&&!detaileds.getImageProgress().equals(BigDecimal.ZERO)){
                        finishRate = finishRate.add(vo.getFinishMoney().divide(vo.getContractMoney(),2,BigDecimal.ROUND_UP));
                    }
                }
            }
            vo.setFinishRate(finishRate);
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public List<OrderReportVO> getReport(String year,String orgId) {
        List<OrderReportVO> vos =  new ArrayList<>();
        QueryWrapper<Road> roadWrapper = new QueryWrapper<>();
        roadWrapper.eq("IS_DELE_","0");
        roadWrapper.like("COMPANY_IDS_",orgId);
        List<Road> roads = roadManager.list(roadWrapper);
        for (Road road : roads){
            OrderReportVO vo = new OrderReportVO();
            QueryWrapper<WorkOrderInformation> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("IS_DELE_","0");
            orderWrapper.eq("ROAD_SEGMENT_ID_",road.getId());
            orderWrapper.apply("date_format(ISSUE_DATE_,'%Y') = {0}", year);
            List<WorkOrderInformation> allList = this.list(orderWrapper);
            vo.setOrderCount(allList.size());
            vo.setRoadName(road.getName());
            //获取金额
            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 money = BigDecimal.ZERO;
            if (yearBudget!=null){
                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","日常养护");
                YearBudgetDetailed detaileds = yearBudgetDetailedManager.getOne(detailedQueryWrapper);
                if (detaileds!=null){
                    money = money.add(detaileds.getTotalPrice().multiply(new BigDecimal(10000)));
                }
            }
            vo.setMoney(money);

            if (allList.size()>0){
                List<WorkOrderInformation> finishList = allList.stream().filter(p -> p.getStatus().equals("1")).collect(Collectors.toList());
                vo.setFinishCount(finishList.size());
                List<WorkOrderInformation> runList = allList.stream().filter(p -> p.getStatus().equals("0")).collect(Collectors.toList());
                vo.setRunCount(runList.size());
                if (finishList.size()>0){
                    vo.setFinishRate(new BigDecimal(finishList.size()).divide(new BigDecimal(allList.size()),2,BigDecimal.ROUND_UP));
                }else {
                    vo.setFinishRate(new BigDecimal(0));
                }
                List<WorkOrderInformation> overList = allList.stream().filter(p -> p.getOverdue()==1).collect(Collectors.toList());
                vo.setOverCount(overList.size());
                if (overList.size()>0){
                    vo.setOverRate(new BigDecimal(overList.size()).divide(new BigDecimal(allList.size()),2,BigDecimal.ROUND_UP));
                }else {
                    vo.setOverRate(new BigDecimal(0));
                }
                List<WorkOrderInformation> deseasaList = allList.stream().filter(p -> StringUtils.isNotEmpty(p.getDiseaseId())).collect(Collectors.toList());
                vo.setDeseasaOrderCount(deseasaList.size());
                vo.setUnDeseasaOrderCount(allList.size()-deseasaList.size());
                //日常养护已用金额
                List<String> WorkOrderInformationIds = this.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)));
                    }
                }
                vo.setFinishMoney(workOrderMoney);
                if (!workOrderMoney.equals(BigDecimal.ZERO)&&!vo.getMoney().equals(BigDecimal.ZERO)){
                    vo.setFinishMoneyRate(workOrderMoney.divide(vo.getMoney(),2,BigDecimal.ROUND_UP));
                }else {
                    vo.setFinishMoneyRate(new BigDecimal(0));
                }
            }else {
                vo.setFinishMoneyRate(new BigDecimal(0));
                vo.setOverRate(new BigDecimal(0));
                vo.setFinishRate(new BigDecimal(0));
                vo.setFinishMoney(new BigDecimal(0));
            }
            vos.add(vo);
        }
        return vos;
    }

    @Override
    public PageList<WorkOrderInformation> queryWorkOrderInformation(QueryFilter<WorkOrderInformation> queryFilter) {
        IPage<WorkOrderInformation> result = baseMapper.queryWorkOrderInformation(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public WorkOrderInformation getWorkOrderInformationById(String id) {
        WorkOrderInformation workOrderInformation = baseMapper.selectById(id);
        return workOrderInformation;
    }

    @Override
    public void saveVo(WorkOrderInformationVo vo) {
        WorkOrderInformation workOrderInformation = vo.getWorkOrderInformation();
        //生成唯一编号编号
        Road road = roadManager.get(workOrderInformation.getRoadSegmentId());
        String yhgd = null;
        try {
            yhgd = sysIdentityManager.nextId(road.getSimplicity().toUpperCase(Locale.ROOT)+"yhgd");
        } catch (Exception e) {
            yhgd = sysIdentityManager.nextId("yhgd");
        }
        //通过路段ID查询路段简称，组装成新的工单号
        workOrderInformation.setJobNumber(road.getSimplicity().toUpperCase(Locale.ROOT) + "-" + yhgd);
        this.create(workOrderInformation);
        String workId = workOrderInformation.getId();
        //获取病害ID
        String diseaseId = workOrderInformation.getDiseaseId();
        //修改病害处理状态
        if (StringUtils.isNotEmpty(diseaseId)) {
            //所有病害ID集合ids.split(",")
            List<String> ids = Arrays.asList(diseaseId.split(";"));
            for (String id : ids) {
                Disease disease = this.diseaseManager.getById(id);
                Integer handlingSituation = disease.getHandlingSituation();
                disease.setJobNumber(yhgd);
                //病害超时日期就是要求修复日期
                LocalDate demandFinishTime = workOrderInformation.getDemandFinishTime(); //要求修复时间
        /*        if (null != demandFinishTime) {
                    disease.setDeadline(demandFinishTime.atTime(23, 59, 59)); //超时日期
                    disease.setDeadlineStart(demandFinishTime.plusDays(1).atTime(0, 0, 0, 0));//超时开始时间
                    disease.setDeadlineStatus(0);
                }*/
                if (disease.getHandlingSituation() == null || disease.getHandlingSituation() == 0) {
                    disease.setHandlingSituation(1);
                    disease.setHandledTimeStart(LocalDateTime.now());
                    this.diseaseManager.update(disease);
                }
            }
        }
        //工程量清单(合同内)
        if (null != vo && vo.getBillOfQuantities() != null && vo.getBillOfQuantities().size() > 0) {
            List<BillOfQuantities> billOfQuantities = vo.getBillOfQuantities();
            for (BillOfQuantities billOfQuantity : billOfQuantities) {
                billOfQuantity.setWorkOrderInformationId(workId);
                billOfQuantity.setBillType(1);
            }
            this.billOfQuantitiesManager.saveBatch(billOfQuantities);
        }
        //工程量清单(合同外)
        if (null != vo && vo.getBillOutOfQuantities() != null && vo.getBillOutOfQuantities().size() > 0) {
            List<BillOfQuantities> billOutOfQuantities = vo.getBillOutOfQuantities();
            for (BillOfQuantities billOfQuantity : billOutOfQuantities) {
                billOfQuantity.setWorkOrderInformationId(workId);
                billOfQuantity.setBillType(2);
                billOfQuantity.setSonSubjectName(billOfQuantity.getSubjectName());
            }
            this.billOfQuantitiesManager.saveBatch(billOutOfQuantities);
            //保存到合同外类型管理表
            ArrayList<BillQuantiTypeManag> billQuantiTypeManags = new ArrayList<>();
            billOutOfQuantities.forEach(s->{
                BillQuantiTypeManag billQuantiTypeManag = new BillQuantiTypeManag();
                List<BillQuantiTypeManag> list = billQuantiTypeManagManager.list(new QueryWrapper<BillQuantiTypeManag>().lambda().eq(StringUtils.isNotEmpty(s.getSubjectName()), BillQuantiTypeManag::getProjectName, s.getSubjectName()));
                if (list.size()>0) {
                    billQuantiTypeManag.setId(list.get(0).getId());
                }
                billQuantiTypeManag.setPrice(new BigDecimal(s.getPrice().toString()));
                billQuantiTypeManag.setAmount(new BigDecimal(s.getAmount().toString()));
                billQuantiTypeManag.setRoadSegmentId(road.getId());
                billQuantiTypeManag.setRoadSegmentName(road.getName());
                billQuantiTypeManag.setCompanyId(road.getCompanyId());
                billQuantiTypeManag.setCompanyName(road.getCompanyName());
                billQuantiTypeManag.setProjectName(s.getSubjectName());
                billQuantiTypeManags.add(billQuantiTypeManag);
            });
           if (billQuantiTypeManags.size()>0) {
               billQuantiTypeManagManager.saveOrUpdateBatch(billQuantiTypeManags);
           }
        }
        //删除原来的附件信息
        this.accessoryManager.delAccessoryBySourceId(workOrderInformation.getId());
        // 保存派单附件信息
        List<Accessory> accessoryWorkOrderList = vo.getAccessoriesWorkOrder();
        if (null != accessoryWorkOrderList && accessoryWorkOrderList.size() > 0) {
            //设置附件资源ID
            accessoryWorkOrderList.forEach(s -> {
                s.setSourceId(workOrderInformation.getId());
                s.setGroup("workOrder");
            });
            //派单附件
            this.accessoryManager.saveBatch(accessoryWorkOrderList);
        }
        //1.保存施工前照片
        List<Accessory> accessoryPreList = vo.getAccessoriesPre();
        if (null != accessoryPreList && accessoryPreList.size() > 0) {
            //设置附件资源ID
            accessoryPreList.forEach(s -> {
                s.setSourceId(workOrderInformation.getId());
                s.setGroup("constructionPre");
            });
            //保存施工图片
            this.accessoryManager.saveBatch(accessoryPreList);
        }
        //2.保存施工中照片
        List<Accessory> accessoryUndList = vo.getAccessoriesUnd();
        if (null != accessoryUndList && accessoryUndList.size() > 0) {
            //设置附件资源ID
            accessoryUndList.forEach(s -> {
                s.setSourceId(workOrderInformation.getId());
                s.setGroup("constructionUnd");
            });
            //保存施工图片
            this.accessoryManager.saveBatch(accessoryUndList);
        }
        //3.保存施工后照片
        List<Accessory> accessorySufList = vo.getAccessoriesSuf();
        if (null != accessorySufList && accessorySufList.size() > 0) {
            //设置附件资源ID
            accessorySufList.forEach(s -> {
                s.setSourceId(workOrderInformation.getId());
                s.setGroup("constructionSuf");
            });
            //保存施工图片
            this.accessoryManager.saveBatch(accessorySufList);
        }

    }

    @Override
    public void updateVo(WorkOrderInformationVo vo) {
        WorkOrderInformation workOrderInformation = vo.getWorkOrderInformation();
        this.update(workOrderInformation);
        String workId = workOrderInformation.getId();
        QueryWrapper<BillOfQuantities> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("WORK_ORDER_INFORMATION_ID_", workId);
        this.billOfQuantitiesManager.getBaseMapper().delete(queryWrapper);
        //工程量清单(合同内)
        if (null != vo && vo.getBillOfQuantities() != null && vo.getBillOfQuantities().size() > 0) {
            List<BillOfQuantities> billOfQuantities = vo.getBillOfQuantities();
            for (BillOfQuantities billOfQuantity : billOfQuantities) {
                billOfQuantity.setWorkOrderInformationId(workId);
                billOfQuantity.setBillType(1);
            }
            billOfQuantities = billOfQuantities.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getContractItemId()))), ArrayList::new));
            vo.setBillOfQuantities(billOfQuantities);
            this.billOfQuantitiesManager.saveOrUpdateBatch(billOfQuantities);
        }
        //工程量清单(合同外)
        if (null != vo && vo.getBillOutOfQuantities() != null && vo.getBillOutOfQuantities().size() > 0) {
            List<BillOfQuantities> billOutOfQuantities = vo.getBillOutOfQuantities();
            for (BillOfQuantities billOfQuantity : billOutOfQuantities) {
                billOfQuantity.setWorkOrderInformationId(workId);
                billOfQuantity.setBillType(2);
            }
            this.billOfQuantitiesManager.saveOrUpdateBatch(billOutOfQuantities);
        }
        //删除原来的附件信息
        this.accessoryManager.delAccessoryBySourceId(workOrderInformation.getId());
        // 保存派单附件信息
        List<Accessory> accessoryWorkOrderList = vo.getAccessoriesWorkOrder();
        if (null != accessoryWorkOrderList && accessoryWorkOrderList.size() > 0) {
            //设置附件资源ID
            accessoryWorkOrderList.forEach(s -> {
                s.setSourceId(workOrderInformation.getId());
                s.setGroup("workOrder");
            });
            //派单附件
            this.accessoryManager.saveBatch(accessoryWorkOrderList);
        }
        //1.保存施工前照片
        List<Accessory> accessoryPreList = vo.getAccessoriesPre();
        if (null != accessoryPreList && accessoryPreList.size() > 0) {
            //设置附件资源ID
            accessoryPreList.forEach(s -> {
                s.setSourceId(workOrderInformation.getId());
                s.setGroup("constructionPre");
            });
            //保存施工图片
            this.accessoryManager.saveBatch(accessoryPreList);
        }
        //2.保存施工中照片
        List<Accessory> accessoryUndList = vo.getAccessoriesUnd();
        if (null != accessoryUndList && accessoryUndList.size() > 0) {
            //设置附件资源ID
            accessoryUndList.forEach(s -> {
                s.setSourceId(workOrderInformation.getId());
                s.setGroup("constructionUnd");
            });
            //保存施工图片
            this.accessoryManager.saveBatch(accessoryUndList);
        }
        //3.保存施工后照片
        List<Accessory> accessorySufList = vo.getAccessoriesSuf();
        if (null != accessorySufList && accessorySufList.size() > 0) {
            //设置附件资源ID
            accessorySufList.forEach(s -> {
                s.setSourceId(workOrderInformation.getId());
                s.setGroup("constructionSuf");
            });
            //保存施工图片
            this.accessoryManager.saveBatch(accessorySufList);
        }
    }

    @Override
    public WorkOrderInformationVo getVo(String id) {
        WorkOrderInformationVo orderInformationVo = new WorkOrderInformationVo();
        WorkOrderInformation workOrderInformation = this.getById(id);
        if (null == workOrderInformation) {
            throw new BaseException("工单不存在或已被删除！");
        }
        Road road = this.roadManager.getById(workOrderInformation.getRoadSegmentId());
        workOrderInformation.setRoad(road);
        String diseaseIds = workOrderInformation.getDiseaseId();
        orderInformationVo.setWorkOrderInformation(workOrderInformation);
        if (StringUtils.isNotBlank(diseaseIds)) {
            List<String> detailsIdList = Arrays.asList(diseaseIds.split(";"));
            if (detailsIdList.size() > 0) {
                //根据病害ID查询病害信息
                QueryWrapper<Disease> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("ID_", detailsIdList);
                List<Disease> diseases = this.diseaseManager.getBaseMapper().selectList(queryWrapper);
                if (diseases.size() > 0) {
                    for (Disease disease : diseases) {
                        //根据病害ID查询病害附件
                        QueryWrapper<Accessory> accessoryQueryWrapper = new QueryWrapper<>();
                        accessoryQueryWrapper.eq("SOURCE_ID_", disease.getId());
                        accessoryQueryWrapper.eq("IS_DELE_", "0");
                        List<Accessory> accessories = this.accessoryManager.getBaseMapper().selectList(accessoryQueryWrapper);
                        disease.setAccessories(accessories);
                    }
                    orderInformationVo.setDiseases(diseases);
                }
            }
        } else {
            orderInformationVo.setDiseases(new ArrayList<Disease>(0));
        }
        //工程量清单（合同内）
        QueryWrapper<BillOfQuantities> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("WORK_ORDER_INFORMATION_ID_", id);
        queryWrapper.eq("IS_DELE_", "0");
        queryWrapper.eq("BILL_TYPE_", "1"); // 合同内清单
        List<BillOfQuantities> list = this.billOfQuantitiesManager.getBaseMapper().selectList(queryWrapper);

        ArrayList<BillOfQuantities> billList = new ArrayList<>();


        if(null != list &&  list.size() >0){
            for (BillOfQuantities billOfQuantities : list) {
                BillOfQuantities bill = new BillOfQuantities();
                BeanUtils.copyProperties(billOfQuantities,bill);
                if(null == billOfQuantities.getSonSubjectCode() && !"".equals(billOfQuantities.getSonSubjectCode())){
                    String contractItemId = billOfQuantities.getContractItemId();
                    if(null != contractItemId && !"".equals(contractItemId)){
                        ContractItem contractItem = contractItemManager.get(contractItemId);
                        if(null != contractItem){
                            bill.setSonSubjectCode(contractItem.getSonSubjectCode());
                            bill.setSonSubjectName(contractItem.getSonSubjectName());
                        }
                    }
                }
                billList.add(bill);
            }
        }

        orderInformationVo.setBillOfQuantities(billList);
        // 工程量清单（合同外）
        QueryWrapper<BillOfQuantities> queryBillOutOfQuantitiesWrapper = new QueryWrapper<>();
        queryBillOutOfQuantitiesWrapper.eq("WORK_ORDER_INFORMATION_ID_", workOrderInformation.getId());
        queryBillOutOfQuantitiesWrapper.eq("IS_DELE_", "0");
        queryBillOutOfQuantitiesWrapper.eq("BILL_TYPE_", "2");
        List<BillOfQuantities> outList = this.billOfQuantitiesManager.getBaseMapper().selectList(queryBillOutOfQuantitiesWrapper);
        orderInformationVo.setBillOutOfQuantities(outList);
        //养护合同ID
        String contractId = workOrderInformation.getContractId();
        if (StringUtils.isNotBlank(contractId)) {
            Contract contract = this.contractManager.getById(contractId);
            orderInformationVo.setContract(contract);
        } else {
            orderInformationVo.setContract(new Contract());
        }
        //查询施工照片
        List<Accessory> accessories = accessoryManager.getAccessoryBySourceId(workOrderInformation.getId());
        //1.施工前照片
        List<Accessory> accessoryPreList = new ArrayList<>();
        //2.施工中照片
        List<Accessory> accessoryUndList = new ArrayList<>();
        //3.施工后照片
        List<Accessory> accessorySufList = new ArrayList<>();
        //4.派单附件
        List<Accessory> accessoryWorkOrderList = new ArrayList<>();
        if (null != accessories && accessories.size() > 0) {
            accessories.forEach(s -> {
                String group = s.getGroup();
                if ("constructionPre".equalsIgnoreCase(group)) accessoryPreList.add(s);
                if ("constructionUnd".equalsIgnoreCase(group)) accessoryUndList.add(s);
                if ("constructionSuf".equalsIgnoreCase(group)) accessorySufList.add(s);
                if ("workOrder".equalsIgnoreCase(group)) accessoryWorkOrderList.add(s);
            });
        }
        orderInformationVo.setAccessoriesPre(accessoryPreList);
        orderInformationVo.setAccessoriesUnd(accessoryUndList);
        orderInformationVo.setAccessoriesSuf(accessorySufList);
        orderInformationVo.setAccessoriesWorkOrder(accessoryWorkOrderList);
        return orderInformationVo;
    }

    public static List<OrgVO> getChild(List<OrgVO> allList, String pCode) {
        List<OrgVO> returnList = new ArrayList<>();
        for (OrgVO entity : allList){
            if (pCode.equals(entity.getParentId())) {
                entity.setChirldren(getChild(allList, entity.getId()));
                returnList.add(entity);
            }
        }
        return returnList;
    }

    /**
     * 获取某个父节点下面的所有子节点
     *
     * @param orgList
     * @param parentId
     * @return
     */
    public static List<Org> getOrgChild(List<Org> orgList, String parentId, List<Org> rtnList) {
        for (Org org : orgList) {
            // 遍历出父id等于参数的id，add进子节点集合
            if (parentId.equals(org.getParentId())) {
                // 递归遍历下一级
                getOrgChild(orgList, org.getId(), rtnList);
                rtnList.add(org);
            }
        }
        return rtnList;
    }


    @Override
    public List<Org4AppVO> getWorkOrderCountList4App(String level, String dimension, String date) {
        if ("0".equals(level)){
            dimension = "1419863231459102720";
        }
        Org pOrg = orgDao.get(dimension);
        List<Org4AppVO> lists = new ArrayList<>();
        if (pOrg!=null){
            List<Org> orgList = orgDao.getByParentId(pOrg.getId());
            for (Org org: orgList){
                Org4AppVO fvo = new Org4AppVO();
                BeanUtils.copyProperties(org,fvo);
                lists.add(fvo);
            }
            return this.setCountList4App(lists,date);
        }else {
            return lists;
        }

    }

    @Override
    public Org4AppVO getWorkOrderCount4App(String level,String dimension,String date){
        if ("0".equals(level)){
            dimension = "1419863231459102720";
        }
        Org org = orgDao.get(dimension);
        Org4AppVO fvo = new Org4AppVO();
        BeanUtils.copyProperties(org,fvo);

        return this.setCount4App(fvo,date);

    }

    public List<Org4AppVO> setCountList4App(List<Org4AppVO> list,String date){
        // 获取迭代器
        Iterator<Org4AppVO> it = list.iterator();

        while(it.hasNext()){
            Org4AppVO orgVO = it.next();

            Integer grade = Integer.valueOf(orgVO.getGrade());
            List<String> roadList = new ArrayList<>();

            if (grade<4){
                QueryWrapper<Road> roadQueryWrapper = new QueryWrapper<>();
                roadQueryWrapper.like( "COMPANY_IDS_", orgVO.getId());
                roadList = roadManager.list(roadQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
            }else if (grade==4){
                QueryWrapper<Road> roadByNameQueryWrapper = new QueryWrapper<>();
                roadByNameQueryWrapper.eq("NAME_",orgVO.getName());
                roadList =
                        roadManager.list(roadByNameQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
            }
            if (roadList.size()>0){
                Map<String, Object> params = new HashMap<>();
                params.put("accDateDay",date);
                params.put("roadSegmentId",roadList);
                params.put("ids",roadList);
                List<Map<String, Object>> mapList = workStatisticDao.countWorkOrder(params);
                orgVO.setAllCount(String.valueOf(mapList.size()));
            }else {
                it.remove();

            }

        }


        return list;
    }

    public Org4AppVO setCount4App(Org4AppVO orgVO,String year){

        Integer grade = Integer.valueOf(orgVO.getGrade());
        List<String> roadList = new ArrayList<>();
        if (grade<4){
            QueryWrapper<Road> roadQueryWrapper = new QueryWrapper<>();
            roadQueryWrapper.like( "COMPANY_IDS_", orgVO.getId());
            roadList = roadManager.list(roadQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
        }else if (grade==4){
            QueryWrapper<Road> roadByNameQueryWrapper = new QueryWrapper<>();
            roadByNameQueryWrapper.eq("NAME_",orgVO.getName());
            roadList =
                    roadManager.list(roadByNameQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
        }
        if (roadList.size()>0){
            orgVO = this.dayCountWorkOrder(roadList,orgVO,year);
        }else {
            orgVO.setCheckCount("0");
            orgVO.setAllCount("0");
            orgVO.setConstructionCount("0");
            orgVO.setExamineCount("0");
            orgVO.setFinishCount("0");
            orgVO.setOverdueCount("0");
            orgVO.setDistributionCount("0");
        }

        return orgVO;
    }



    @Override
    public List<OrgVO> getWorkOrderCount(String startDate,String endDate) {
        String orgId ;
        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId())&&!"0".equals(baseContext.getCurrentOrgId())){
            orgId = baseContext.getCurrentOrgId();
        }else {
            orgId = "1419863231459102720";
        }
        List<OrgVO> lists = new ArrayList<>();

        List<Org> rtnList = new ArrayList<Org>();

        QueryWrapper<Org> rgQueryWrapper = new QueryWrapper<>();
        rgQueryWrapper.eq("is_dele_","0");
        List<Org> allList = orgDao.selectList(rgQueryWrapper);

        List<Org> list = getOrgChild(allList, orgId, rtnList);
        for (Org org: list){
            OrgVO fvo = new OrgVO();
            BeanUtils.copyProperties(org,fvo);
            lists.add(fvo);
        }
        lists = getChild(lists,orgId);

        return this.setCount(lists,startDate,endDate);

    }

    public List<OrgVO> setCount(List<OrgVO> list,String startDate,String endDate){

        // 获取迭代器
        Iterator<OrgVO> it = list.iterator();

        while(it.hasNext()){
            OrgVO orgVO = it.next();
            Integer grade = Integer.valueOf(orgVO.getGrade());
            List<String> roadList = new ArrayList<>();
            if (grade<4){
                QueryWrapper<Road> roadQueryWrapper = new QueryWrapper<>();
                roadQueryWrapper.like( "COMPANY_IDS_", orgVO.getId());
                roadList = roadManager.list(roadQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
            }else if (grade==4){
                QueryWrapper<Road> roadByNameQueryWrapper = new QueryWrapper<>();
                roadByNameQueryWrapper.eq("NAME_",orgVO.getName());
                roadList =
                        roadManager.list(roadByNameQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
            }
            if (roadList.size()>0){

                orgVO = this.newCountWorkOrder(roadList,orgVO,startDate,endDate);
            }else {
                it.remove();
            }
            if (orgVO.getChirldren().size()>0&&Integer.valueOf(orgVO.getGrade())<4){
                this.setCount(orgVO.getChirldren(),startDate,endDate);
            }
        }
        return list;
    }

    //日报接口
    public Org4AppVO dayCountWorkOrder(List<String> ids,Org4AppVO orgVO,String date) {
        QueryWrapper<WorkOrderInformation> orderQueryWrapper = new QueryWrapper<>();
        Map<String, Object> params = new HashMap<>();
        params.put("accDateDay",date);
        params.put("roadSegmentId",ids);
        params.put("ids",ids);
        orderQueryWrapper.in("ROAD_SEGMENT_ID_", ids);
        List<Map<String, Object>> mapList = workStatisticDao.countWorkOrder(params);


        //养护站下单[业主]
        long userTask1 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask1")).count();

        //养护单位派单[施工]
        long userTask2 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask2")).count();
        //养护单位填报[施工]
        long userTask3 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask3")).count();
        //收方计量[业主]
        long userTask4 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask4")).count();
        //养护站审核[业主]
        long userTask5 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask5")).count();
        long userTask6 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask6")).count();
        //管理中心确认[业主]
        long userTask7 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask7")).count();
        //完成工单
        long endEvent1 = mapList.stream().filter(s -> s.get("taskKey").equals("EndEvent1")).count();

        //逾期工单  DEMAND_FINISH_TIME_  END_TIME_

        orderQueryWrapper.eq("OVERDUE_", "1");
        orderQueryWrapper.eq("IS_DELE_", "0");
        orderQueryWrapper.apply("date_format(ISSUE_DATE_,'%Y-%m-%d') = {0}", date);
        List<WorkOrderInformation> overList = this.baseMapper.selectList(orderQueryWrapper);



        //未完成工单逾期
        long overdueWorkOrderCountUnFinish = overList.size();

        orgVO.setDistributionCount(String.valueOf(userTask1 + userTask7));
        orgVO.setConstructionCount(String.valueOf(userTask2 + userTask3));
        orgVO.setCheckCount(String.valueOf(userTask4));
        orgVO.setExamineCount(String.valueOf(userTask5+userTask6));
        orgVO.setFinishCount(String.valueOf(endEvent1));
        orgVO.setOverdueCount(String.valueOf( overdueWorkOrderCountUnFinish));
        orgVO.setAllCount(String.valueOf(mapList.size()));
        return orgVO;
    }

    //统计表格
    public OrgVO newCountWorkOrder(List<String> ids,OrgVO orgVO,String startDate,String endDate) {
        QueryWrapper<WorkOrderInformation> orderQueryWrapper = new QueryWrapper<>();
        Map<String, Object> params = new HashMap<>();
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("roadSegmentId",ids);
        params.put("ids",ids);
        orderQueryWrapper.in("ROAD_SEGMENT_ID_", ids);

        List<WorkOrderCountVO> mapList = workStatisticDao.countWorkOrder4New(params);

        List<WorkOrderCountVO> userTask1list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask1")).collect(Collectors.toList());

        List<WorkOrderCountVO> userTask2list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask2")).collect(Collectors.toList());

        List<WorkOrderCountVO> userTask3list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask3")).collect(Collectors.toList());

        List<WorkOrderCountVO> userTask4list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask4")).collect(Collectors.toList());

        List<WorkOrderCountVO> userTask5list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask5")).collect(Collectors.toList());

        List<WorkOrderCountVO> userTask6list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask6")).collect(Collectors.toList());

        List<WorkOrderCountVO> userTask7list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask7")).collect(Collectors.toList());

        List<WorkOrderCountVO> endEvent1list = mapList.stream().filter(s -> s.getTaskKey().equals("EndEvent1")).collect(Collectors.toList());


        //日常养护已用金额

        orgVO.setFinishMoney(workStatisticDao.countWorkOrderFinishMoney(params));


        //养护站下单[业主]
        long userTask1 = userTask1list.size();

        //养护单位派单[施工]
        long userTask2 = userTask2list.size();
        //养护单位填报[施工]
        long userTask3 = userTask3list.size();
        //收方计量[业主]
        long userTask4 = userTask4list.size();
        //养护站审核[业主]
        long userTask5 = userTask5list.size();
        long userTask6 = userTask6list.size();
        //管理中心确认[业主]
        long userTask7 = userTask7list.size();
        //完成工单
        long endEvent1 = endEvent1list.size();

        //逾期工单  DEMAND_FINISH_TIME_  END_TIME_

        orderQueryWrapper.eq("OVERDUE_", "1");
        orderQueryWrapper.eq("IS_DELE_", "0");
        orderQueryWrapper.in("ROAD_SEGMENT_ID_",ids);
        orderQueryWrapper.between("ISSUE_DATE_",startDate,endDate);


        List<WorkOrderInformation> overList = this.baseMapper.selectList(orderQueryWrapper);


        //派单中集合
        List<WorkOrderCountVO> distributionCountList = new ArrayList<>();
        distributionCountList.addAll(userTask7list);
        distributionCountList.addAll(userTask1list);

        int distributionSize = distributionCountList.stream()
                .map(a ->
                        overList.stream()
                                .filter(b -> Objects.nonNull(a.getWorkId())
                                        && Objects.nonNull(b.getId())
                                        && Objects.equals(a.getWorkId(), b.getId()))
                                .findAny()
                                .orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList())
                .size();

        orgVO.setDistributionOverdue(distributionSize);

        //施工中集合

        List<WorkOrderCountVO> constructionCountList = new ArrayList<>();
        constructionCountList.addAll(userTask2list);
        constructionCountList.addAll(userTask3list);

        int constructionSize = constructionCountList.stream()
                .map(a ->
                        overList.stream()
                                .filter(b -> Objects.nonNull(a.getWorkId())
                                        && Objects.nonNull(b.getId())
                                        && Objects.equals(a.getWorkId(), b.getId()))
                                .findAny()
                                .orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList())
                .size();

        orgVO.setConstructionOverdue(constructionSize);

        //审核中集合

        List<WorkOrderCountVO> examineCountList = new ArrayList<>();
        examineCountList.addAll(userTask5list);
        examineCountList.addAll(userTask6list);

        int examineSize = examineCountList.stream()
                .map(a ->
                        overList.stream()
                                .filter(b -> Objects.nonNull(a.getWorkId())
                                        && Objects.nonNull(b.getId())
                                        && Objects.equals(a.getWorkId(), b.getId()))
                                .findAny()
                                .orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList())
                .size();

        orgVO.setExamineOverdue(examineSize);


        int checkSize = userTask4list.stream()
                .map(a ->
                        overList.stream()
                                .filter(b -> Objects.nonNull(a.getWorkId())
                                        && Objects.nonNull(b.getId())
                                        && Objects.equals(a.getWorkId(), b.getId()))
                                .findAny()
                                .orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList())
                .size();
        orgVO.setCheckOverdue(checkSize);

        //未完成工单逾期
        long overdueWorkOrderCountUnFinish = overList.size();

        //派单中
        orgVO.setDistributionCount(String.valueOf(userTask1 + userTask7));
        //施工中
        orgVO.setConstructionCount(String.valueOf(userTask2 + userTask3));
        //验收
        orgVO.setCheckCount(String.valueOf(userTask4));
        //审核中
        orgVO.setExamineCount(String.valueOf(userTask5+userTask6));


        orgVO.setFinishCount(String.valueOf(endEvent1));
        orgVO.setOverdueCount(String.valueOf( overdueWorkOrderCountUnFinish));
        orgVO.setAllCount(String.valueOf(mapList.size()));
        if ("4".equals(orgVO.getGrade()) && mapList.size()>0){
            orgVO.setRoadId(mapList.get(0).getRoadId());
        }

        return orgVO;
    }

    @Override
    public PageList<WorkOrderVo> getWorkOrderVo(QueryFilter queryFilter) {
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        List<String> roadList = new ArrayList<>();
        if (ObjectUtils.isEmpty(map.get("croadSegmentId"))){
            QueryWrapper<Road> roadQueryWrapper = new QueryWrapper<>();
            roadQueryWrapper.like(StringUtils.isNotEmpty(baseContext.getCurrentOrgId()), "COMPANY_IDS_", baseContext.getCurrentOrgId());
            roadList = roadManager.list(roadQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
            queryFilter.addFilter("croadSegmentId", roadList, QueryOP.IN);
        }
        List<QueryField> querys = queryFilter.getQuerys();

        if (null != querys){
            for (QueryField query : querys) {
                String state = query.getProperty();
                if(state.equals("state")){
                    String value = (String) query.getValue();
                    Map<String, Object> paramsf = new HashMap<>();
                    paramsf.put("roadSegmentId",roadList);
                    paramsf.put("ids",roadList);
                    query.setProperty("cid");
                    query.setOperation(QueryOP.IN);
                    query.setRelation(FieldRelation.AND);
                    query.setGroup("ids");


                    if(value.equals("0")){
                        query.setProperty("cstatus");
                        query.setOperation(QueryOP.LIKE);
                        query.setRelation(FieldRelation.AND);
                        query.setGroup("advance");
                        query.setValue("0");
                        break;

                    }
                    if(value.equals("1")){
                        query.setProperty("cstatus");
                        query.setOperation(QueryOP.LIKE);
                        query.setRelation(FieldRelation.AND);
                        query.setGroup("advance");
                        query.setValue("1");
                        break;

                    }

                    //逾期
                    if(value.equals("2")){

                        QueryWrapper<WorkOrderInformation> orderQueryWrapper = new QueryWrapper<>();

                        orderQueryWrapper.eq("OVERDUE_", "1");
                        orderQueryWrapper.eq("IS_DELE_", "0");
                        orderQueryWrapper.in("ROAD_SEGMENT_ID_",roadList);
//                        orderQueryWrapper.apply("date_format(ISSUE_DATE_,'%Y') = {0}", year);
                        List<WorkOrderInformation> overList = this.baseMapper.selectList(orderQueryWrapper);

                        if(null != overList && overList.size() >0){
                            List<String> ids = StreamUtil.toList(overList, WorkOrderInformation::getId);
                            query.setValue(ids);
                        }else {
                            query.setValue("-1");
                        }
                        break;
                    }
                    List<WorkOrderCountVO> mapList = workStatisticDao.countWorkOrder4New(paramsf);


                    List<String> userTask1list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask1")).map(WorkOrderCountVO::getWorkId).collect(Collectors.toList());

                    List<String> userTask2list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask2")).map(WorkOrderCountVO::getWorkId).collect(Collectors.toList());

                    List<String> userTask3list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask3")).map(WorkOrderCountVO::getWorkId).collect(Collectors.toList());

                    List<String> userTask4list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask4")).map(WorkOrderCountVO::getWorkId).collect(Collectors.toList());

                    List<String> userTask6list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask6")).map(WorkOrderCountVO::getWorkId).collect(Collectors.toList());

                    List<String> userTask7list = mapList.stream().filter(s -> s.getTaskKey().equals("UserTask7")).map(WorkOrderCountVO::getWorkId).collect(Collectors.toList());


                    //派单中
                    if(value.equals("3")){
                        List<String> ids = new ArrayList<>();
                        if (null != userTask1list){
                            ids.addAll(userTask1list);
                        }
                        if(null != userTask7list){
                            ids.addAll(userTask7list);
                        }

                        query.setValue(ids);
                        break;
                    }
                    //施工中
                    if(value.equals("4")){
                        List<String> ids = new ArrayList<>();
                        if(null != userTask2list){
                            ids.addAll(userTask2list);
                        }
                        if(null != userTask3list){
                            ids.addAll(userTask3list);
                        }

                        query.setValue(ids);
                        break;
                    }
                    //施工单位验收
                    if(value.equals("5")){
                        List<String> ids = new ArrayList<>();
                        if(null != userTask4list){
                            ids.addAll(userTask4list);
                        }

                        query.setValue(ids);
                        break;
                    }
                    //审核中
                    if(value.equals("6")){
                        List<String> ids = new ArrayList<>();
                        if(null != userTask6list){
                            ids.addAll(userTask6list);
                        }
                        query.setValue(ids);
                        break;
                    }
                    query.setValue("-1");
                }
            }
        }



        IPage<WorkOrderVo> results = this.baseMapper.getWorkOrderVoList(convert2IPage(queryFilter.getPageBean()), map,convert2Wrapper(queryFilter, currentModelClass()));
        for (WorkOrderVo record : results.getRecords()) {
            String contractId = record.getWorkOrderInformation().getContractId();
            Contract contract = contractManager.getById(contractId);
            record.setContract(contract);
            record.getWorkOrderInformation().setTotalMoney
                    (baseMapper.selectSumMoney(record.getWorkOrderInformation().getId()));
        }
        return new PageList<WorkOrderVo>(results);
    }




    @Override
    public PageList<WorkOrderDiseaseVo> getWorkOrder(QueryFilter queryFilter) {
        queryFilter.addFilter("a.is_dele_", "0", QueryOP.EQUAL);
        HashMap map = new HashMap<>();
        Map params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        Object roadId = map.get("roadId");
        IPage<WorkOrderDiseaseVo> results = this.baseMapper.getWorkOrderInformation(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));
        for (WorkOrderDiseaseVo record : results.getRecords()) {
            WorkOrderInformation workOrderInformation = record.getWorkOrderInformation();
            String contractId = workOrderInformation.getContractId();
            Contract contract = contractManager.getById(contractId);
            record.setContract(contract);
            String diseaseId = workOrderInformation.getDiseaseId();
            if (StringUtils.isNotBlank(diseaseId)) {
                List<String> ids = Arrays.asList(diseaseId.split(";"));
                if (ids.size() > 0) {
                    QueryWrapper<Disease> diseaseQueryWrapper = new QueryWrapper<>();
                    diseaseQueryWrapper.in("ID_", ids);
                    diseaseQueryWrapper.eq(roadId != null, "ROAD_ID_", roadId);
                    List<Disease> diseaseList = this.diseaseManager.getBaseMapper().selectList(diseaseQueryWrapper);
                    record.setDiseaseList(diseaseList);
                }
            }
            QueryWrapper<BillOfQuantities> queryBillOfQuantitiesWrapper = new QueryWrapper<>();
            queryBillOfQuantitiesWrapper.eq("WORK_ORDER_INFORMATION_ID_", workOrderInformation.getId());
            queryBillOfQuantitiesWrapper.eq("IS_DELE_", "0");
            queryBillOfQuantitiesWrapper.eq("BILL_TYPE_", "1"); // 合同内清单
            List<BillOfQuantities> billOfQuantitieslist = this.billOfQuantitiesManager.getBaseMapper().selectList(queryBillOfQuantitiesWrapper);
            record.setBillOfQuantities(billOfQuantitieslist);
            QueryWrapper<BillOfQuantities> queryBillOutOfQuantitiesWrapper = new QueryWrapper<>();
            queryBillOutOfQuantitiesWrapper.eq("WORK_ORDER_INFORMATION_ID_", workOrderInformation.getId());
            queryBillOutOfQuantitiesWrapper.eq("IS_DELE_", "0");
            queryBillOutOfQuantitiesWrapper.eq("BILL_TYPE_", "2"); // 合同外清单
            List<BillOfQuantities> billOutOfQuantitieslist = this.billOfQuantitiesManager.getBaseMapper().selectList(queryBillOutOfQuantitiesWrapper);
            record.setBillOutOfQuantities(billOutOfQuantitieslist);
        }
        return new PageList<>(results);
    }

    @Override
    public CompletableFuture<PageList<Map<String, Object>>> getDoneInstList(String currentUserAccout, QueryFilter queryFilter, String status) throws Exception {
        PageList<Map<String, Object>> mapPageList = iFlowManager.getDoneInstList(currentUserAccout, queryFilter, status).get();
        List<Map<String, Object>> rows = mapPageList.getRows();
        if (rows.size() > 0) {
            for (Map<String, Object> row : rows) {
                //procDefKey
                Object procDefKey = row.get("procDefKey");
                if (procDefKey.toString().equals("yhgd")) {
                    //业务主键
                    Object bizKey = row.get("bizKey");
                    if (ObjectUtils.isNotEmpty(bizKey)) {
                        WorkOrderInformation workOrderInformation = this.getById(bizKey.toString());
                        //路段信息
                        Road road = this.roadManager.getById(workOrderInformation.getRoadSegmentId());
                        workOrderInformation.setRoad(road);
                        row.put("workOrderInformation", workOrderInformation);
                    }
                }
            }
        }
        return CompletableFuture.completedFuture(mapPageList);
    }

    @Override
    public String getBizkey(String bpmnInstId) {
        return baseMapper.getBizkey(bpmnInstId);
    }

    @Override
    public Road getRoad(String roadSegmentId) {
        return this.roadManager.getById(roadSegmentId);
    }

    @Override
    public PageList<WorkOrderVo> getWorkOrderVoByBridge(WorkOrderAndBaseIdVo workOrderByBridgeVo) {
        QueryFilter queryFilter = workOrderByBridgeVo.getQueryFilter();
        if (null == queryFilter) queryFilter = QueryFilter.build();
        String bridgeId = workOrderByBridgeVo.getId();
        // 通过桥梁Id查询所有病害信息
        List<String> diseaseIdList = new ArrayList();
        QueryFilter<Disease> queryDiseaseFilter = QueryFilter.build();
        queryDiseaseFilter.addParams("flag", 0);
        PageBean pageBean = queryDiseaseFilter.getPageBean();
        if (null == pageBean) pageBean = new PageBean();
        pageBean.setPageSize(PageBean.WITHOUT_PAGE);
        pageBean.setPage(1);
        queryDiseaseFilter.setPageBean(pageBean);
        queryDiseaseFilter.addFilter("brige_id_", bridgeId, QueryOP.EQUAL);
        // 查询经常检查病害
        PageList<Disease> jsonBridgeDiseaseCheck = diseaseManager.getJsonBridgeDiseaseCheck(queryDiseaseFilter);
        if (null != jsonBridgeDiseaseCheck && null != jsonBridgeDiseaseCheck.getRows() && jsonBridgeDiseaseCheck.getRows().size() > 0) {
            List<Disease> rows = jsonBridgeDiseaseCheck.getRows();
            for (Disease disease : rows) {
                if (null != disease && StringUtils.isNotBlank(disease.getId())) {
                    diseaseIdList.add(disease.getId());
                }
            }
        }
        Map<String, Object> diseaseParams = queryDiseaseFilter.getParams();
        if (null == diseaseParams) diseaseParams = new HashMap<>();
        diseaseParams.put("flag", 1);
        // 查询定期检查病害
        PageList<Disease> jsonBridgeDiseaseCheck1 = diseaseManager.getJsonBridgeDiseaseCheck(queryDiseaseFilter);
        if (null != jsonBridgeDiseaseCheck1 && null != jsonBridgeDiseaseCheck1.getRows() && jsonBridgeDiseaseCheck1.getRows().size() > 0) {
            List<Disease> rows = jsonBridgeDiseaseCheck1.getRows();
            for (Disease disease : rows) {
                if (null != disease && StringUtils.isNotBlank(disease.getId())) {
                    diseaseIdList.add(disease.getId());
                }
            }
        }
        // 如果病害为空则返回空数据
        if (diseaseIdList.size() == 0) {
            PageList<WorkOrderVo> workOrderVoPageList = new PageList<>();
            workOrderVoPageList.setTotal(0);
            workOrderVoPageList.setPageSize(queryFilter.getPageBean().getPageSize());
            workOrderVoPageList.setPage(queryFilter.getPageBean().getPage());
            workOrderVoPageList.setRows(new ArrayList<WorkOrderVo>());
            return workOrderVoPageList;
        }
        // 拼装条件，查询工单信息
        for (String id : diseaseIdList) {
            queryFilter.addFilter("DISEASE_ID_", id, QueryOP.LIKE, FieldRelation.OR, "DISEASE");
        }
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        IPage<WorkOrderVo> results = this.baseMapper.getWorkOrderVo(convert2IPage(queryFilter.getPageBean()),map, convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<WorkOrderVo>(results);

    }

    @Override
    public PageList<WorkOrderVo> getWorkOrderVoByTunnel(WorkOrderAndBaseIdVo workOrderByBridgeVo) {
        QueryFilter queryFilter = workOrderByBridgeVo.getQueryFilter();
        if (null == queryFilter) queryFilter = QueryFilter.build();
        String bridgeId = workOrderByBridgeVo.getId();
        // 通过桥梁Id查询所有病害信息
        List<String> diseaseIdList = new ArrayList();
        QueryFilter<Disease> queryDiseaseFilter = QueryFilter.build();
        queryDiseaseFilter.addParams("flag", 0);
        PageBean pageBean = queryDiseaseFilter.getPageBean();
        if (null == pageBean) pageBean = new PageBean();
        pageBean.setPageSize(PageBean.WITHOUT_PAGE);
        pageBean.setPage(1);
        queryDiseaseFilter.setPageBean(pageBean);
        queryDiseaseFilter.addFilter("TUNNEL_ID_", bridgeId, QueryOP.EQUAL);
        // 查询经常检查病害
        PageList<Disease> jsonBridgeDiseaseCheck = diseaseManager.getJsonTunnelDiseaseCheck(queryDiseaseFilter);
        if (null != jsonBridgeDiseaseCheck && null != jsonBridgeDiseaseCheck.getRows() && jsonBridgeDiseaseCheck.getRows().size() > 0) {
            List<Disease> rows = jsonBridgeDiseaseCheck.getRows();
            for (Disease disease : rows) {
                if (null != disease && StringUtils.isNotBlank(disease.getId())) {
                    diseaseIdList.add(disease.getId());
                }
            }
        }
        Map<String, Object> diseaseParams = queryDiseaseFilter.getParams();
        if (null == diseaseParams) diseaseParams = new HashMap<>();
        diseaseParams.put("flag", 1);
        // 查询定期检查病害
        PageList<Disease> jsonBridgeDiseaseCheck1 = diseaseManager.getJsonTunnelDiseaseCheck(queryDiseaseFilter);
        if (null != jsonBridgeDiseaseCheck1 && null != jsonBridgeDiseaseCheck1.getRows() && jsonBridgeDiseaseCheck1.getRows().size() > 0) {
            List<Disease> rows = jsonBridgeDiseaseCheck1.getRows();
            for (Disease disease : rows) {
                if (null != disease && StringUtils.isNotBlank(disease.getId())) {
                    diseaseIdList.add(disease.getId());
                }
            }
        }
        // 如果病害为空则返回空数据
        if (diseaseIdList.size() == 0) {
            PageList<WorkOrderVo> workOrderVoPageList = new PageList<>();
            workOrderVoPageList.setTotal(0);
            workOrderVoPageList.setPageSize(queryFilter.getPageBean().getPageSize());
            workOrderVoPageList.setPage(queryFilter.getPageBean().getPage());
            workOrderVoPageList.setRows(new ArrayList<WorkOrderVo>());
            return workOrderVoPageList;
        }
        // 拼装条件，查询工单信息
        for (String id : diseaseIdList) {
            queryFilter.addFilter("DISEASE_ID_", id, QueryOP.LIKE, FieldRelation.OR, "DISEASE");
        }
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        IPage<WorkOrderVo> results = this.baseMapper.getWorkOrderVo(convert2IPage(queryFilter.getPageBean()), map,convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<WorkOrderVo>(results);
    }

    @Override
    public PageList<WorkOrderVo> getWorkOrderVoByCulvert(WorkOrderAndBaseIdVo workOrderByBridgeVo) {
        QueryFilter queryFilter = workOrderByBridgeVo.getQueryFilter();
        if (null == queryFilter) queryFilter = QueryFilter.build();
        String bridgeId = workOrderByBridgeVo.getId();
        // 通过桥梁Id查询所有病害信息
        List<String> diseaseIdList = new ArrayList();
        QueryFilter<Disease> queryDiseaseFilter = QueryFilter.build();
        queryDiseaseFilter.addParams("flag", 0);
        PageBean pageBean = queryDiseaseFilter.getPageBean();
        if (null == pageBean) pageBean = new PageBean();
        pageBean.setPageSize(PageBean.WITHOUT_PAGE);
        pageBean.setPage(1);
        queryDiseaseFilter.setPageBean(pageBean);
        queryDiseaseFilter.addFilter("CULVERT_ID_", bridgeId, QueryOP.EQUAL);
        // 查询经常检查病害
        PageList<Disease> jsonBridgeDiseaseCheck = diseaseManager.getJsonCulvertDiseaseCheck(queryDiseaseFilter);
        if (null != jsonBridgeDiseaseCheck && null != jsonBridgeDiseaseCheck.getRows() && jsonBridgeDiseaseCheck.getRows().size() > 0) {
            List<Disease> rows = jsonBridgeDiseaseCheck.getRows();
            for (Disease disease : rows) {
                if (null != disease && StringUtils.isNotBlank(disease.getId())) {
                    diseaseIdList.add(disease.getId());
                }
            }
        }
        Map<String, Object> diseaseParams = queryDiseaseFilter.getParams();
        if (null == diseaseParams) diseaseParams = new HashMap<>();
        diseaseParams.put("flag", 1);
        // 查询定期检查病害
        PageList<Disease> jsonBridgeDiseaseCheck1 = diseaseManager.getJsonCulvertDiseaseCheck(queryDiseaseFilter);
        if (null != jsonBridgeDiseaseCheck1 && null != jsonBridgeDiseaseCheck1.getRows() && jsonBridgeDiseaseCheck1.getRows().size() > 0) {
            List<Disease> rows = jsonBridgeDiseaseCheck1.getRows();
            for (Disease disease : rows) {
                if (null != disease && StringUtils.isNotBlank(disease.getId())) {
                    diseaseIdList.add(disease.getId());
                }
            }
        }
        // 如果病害为空则返回空数据
        if (diseaseIdList.size() == 0) {
            PageList<WorkOrderVo> workOrderVoPageList = new PageList<>();
            workOrderVoPageList.setTotal(0);
            workOrderVoPageList.setPageSize(queryFilter.getPageBean().getPageSize());
            workOrderVoPageList.setPage(queryFilter.getPageBean().getPage());
            workOrderVoPageList.setRows(new ArrayList<WorkOrderVo>());
            return workOrderVoPageList;
        }
        // 拼装条件，查询工单信息
        for (String id : diseaseIdList) {
            queryFilter.addFilter("DISEASE_ID_", id, QueryOP.LIKE, FieldRelation.OR, "DISEASE");
        }
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        IPage<WorkOrderVo> results = this.baseMapper.getWorkOrderVo(convert2IPage(queryFilter.getPageBean()), map,convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<WorkOrderVo>(results);
    }

    @Override
    public PageList<WorkOrderVo> getWorkOrderVoBySideSlope(WorkOrderAndBaseIdVo workOrderByBridgeVo) {
        QueryFilter queryFilter = workOrderByBridgeVo.getQueryFilter();
        if (null == queryFilter) queryFilter = QueryFilter.build();
        String bridgeId = workOrderByBridgeVo.getId();
        // 通过桥梁Id查询所有病害信息
        List<String> diseaseIdList = new ArrayList();
        QueryFilter<Disease> queryDiseaseFilter = QueryFilter.build();
        queryDiseaseFilter.addParams("flag", 0);
        PageBean pageBean = queryDiseaseFilter.getPageBean();
        if (null == pageBean) pageBean = new PageBean();
        pageBean.setPageSize(PageBean.WITHOUT_PAGE);
        pageBean.setPage(1);
        queryDiseaseFilter.setPageBean(pageBean);
        queryDiseaseFilter.addFilter("SIDE_SLOPE_ID_", bridgeId, QueryOP.EQUAL);
        // 查询经常检查病害
        PageList<Disease> jsonBridgeDiseaseCheck = diseaseManager.getJsonSideDiseaseCheck(queryDiseaseFilter);
        if (null != jsonBridgeDiseaseCheck && null != jsonBridgeDiseaseCheck.getRows() && jsonBridgeDiseaseCheck.getRows().size() > 0) {
            List<Disease> rows = jsonBridgeDiseaseCheck.getRows();
            for (Disease disease : rows) {
                if (null != disease && StringUtils.isNotBlank(disease.getId())) {
                    diseaseIdList.add(disease.getId());
                }
            }
        }
        Map<String, Object> diseaseParams = queryDiseaseFilter.getParams();
        if (null == diseaseParams) diseaseParams = new HashMap<>();
        diseaseParams.put("flag", 1);
        // 查询定期检查病害
        PageList<Disease> jsonBridgeDiseaseCheck1 = diseaseManager.getJsonSideDiseaseCheck(queryDiseaseFilter);
        if (null != jsonBridgeDiseaseCheck1 && null != jsonBridgeDiseaseCheck1.getRows() && jsonBridgeDiseaseCheck1.getRows().size() > 0) {
            List<Disease> rows = jsonBridgeDiseaseCheck1.getRows();
            for (Disease disease : rows) {
                if (null != disease && StringUtils.isNotBlank(disease.getId())) {
                    diseaseIdList.add(disease.getId());
                }
            }
        }
        // 如果病害为空则返回空数据
        if (diseaseIdList.size() == 0) {
            PageList<WorkOrderVo> workOrderVoPageList = new PageList<>();
            workOrderVoPageList.setTotal(0);
            workOrderVoPageList.setPageSize(queryFilter.getPageBean().getPageSize());
            workOrderVoPageList.setPage(queryFilter.getPageBean().getPage());
            workOrderVoPageList.setRows(new ArrayList<WorkOrderVo>());
            return workOrderVoPageList;
        }
        // 拼装条件，查询工单信息
        for (String id : diseaseIdList) {
            queryFilter.addFilter("DISEASE_ID_", id, QueryOP.LIKE, FieldRelation.OR, "DISEASE");
        }
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        IPage<WorkOrderVo> results = this.baseMapper.getWorkOrderVo(convert2IPage(queryFilter.getPageBean()),map, convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<WorkOrderVo>(results);
    }

    @Override
    public void exportWorkOrder(String ids, HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(ids)) {
            throw new RuntimeException("请选择对应工单");
        }
        long time = System.currentTimeMillis();
        String fileName = "工单信息" + time;
        File file = new File(fileName);
        if (!file.exists()) {
            file.mkdirs();
        }
        List<String> strings = Arrays.asList(ids.split(","));
        for (String id : strings) {
            WorkOrderInformationVo vo = this.getVo(id);
            //工单信息
            WorkOrderInformation workOrderInformation = vo.getWorkOrderInformation();
            //合同内工程量清单
            List<BillOfQuantities> billOfQuantities = vo.getBillOfQuantities();
            //合同外工程量清单
            List<BillOfQuantities> billOutOfQuantities = vo.getBillOutOfQuantities();
            //所有工程量清单
            List<BillOfQuantities> billOfQuantitiesAll = new ArrayList<>();
            billOfQuantitiesAll.addAll(billOutOfQuantities);
            billOfQuantitiesAll.addAll(billOfQuantities);





            //养护合同
            Contract contract = vo.getContract();
            //工程图片-施工前
            List<Accessory> accessoriesPre = vo.getAccessoriesPre();
            //工程图片-施工中
            List<Accessory> accessoriesUnd = vo.getAccessoriesUnd();
            //工程图片-施工后
            List<Accessory> accessoriesSuf = vo.getAccessoriesSuf();

            //切割后
            List<List<BillOfQuantities>> collect = Stream.iterate(0, f -> f + 1).limit((billOfQuantitiesAll.size() + 5) / 6).parallel().map(a -> billOfQuantitiesAll.stream().skip(a * 6).limit(6).parallel().collect(Collectors.toList())).collect(Collectors.toList());


            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("公路日常养护工程");
            sheet.setColumnWidth(0, 10 * 256);
            sheet.setColumnWidth(1, 30 * 256);
            sheet.setColumnWidth(2, 10 * 256);
            sheet.setColumnWidth(3, 10 * 256);
            sheet.setColumnWidth(4, 15 * 256);
            sheet.setColumnWidth(5, 8 * 256);
            sheet.setColumnWidth(6, 15 * 256);
            sheet.setColumnWidth(7, 8 * 256);
            sheet.setColumnWidth(8, 8 * 256);
            sheet.setColumnWidth(9, 8 * 256);
            sheet.setColumnWidth(10, 8 * 256);

            HSSFCellStyle cellStyle = workbook.createCellStyle();
            HSSFCellStyle cellStyleTitle = workbook.createCellStyle();
            HSSFCellStyle cellStyleLeft = workbook.createCellStyle();
            HSSFCellStyle cellStyleLeftAlign = workbook.createCellStyle();
            HSSFCellStyle cellStyleRight = workbook.createCellStyle();
            HSSFCellStyle cellStyleSmall = workbook.createCellStyle();
            HSSFCellStyle cellStyleNoLine = workbook.createCellStyle();
            HSSFCellStyle cellStyleTitleNoLine = workbook.createCellStyle();
            setExcelStyle(cellStyle, workbook);
            PoiStyleUtil.setExcelStyleNoLine(cellStyleNoLine, workbook);
            PoiStyleUtil.setExcelStyleSmall(cellStyleSmall, workbook);
            PoiStyleUtil.setExcelStyleTitleOne(cellStyleTitle, workbook);
            PoiStyleUtil.setExcelStyleTitleNoLine(cellStyleTitleNoLine, workbook);
            PoiStyleUtil.setExcelStyleLeft(cellStyleLeft, workbook);
            PoiStyleUtil.setExcelStyleRight(cellStyleRight, workbook);
            PoiStyleUtil.setExcelStyleLeftAlign(cellStyleLeftAlign, workbook);


            sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
            //设置横向
            sheet.getPrintSetup().setLandscape(true);


            //路段信息
            Road road = roadManager.getById(workOrderInformation.getRoadSegmentId());
            int num = 0;
            if (collect.size() > 0) {
                for (List<BillOfQuantities> ofQuantities : collect) {
                    HSSFRow row = sheet.createRow(num);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 10));
                    num++;
                    HSSFCell cell = row.createCell(0);
                    cell.setCellValue(road.getCode() + road.getName() + "公路日常养护工程");
                    cell.setCellStyle(cellStyleNoLine);
                    row.createCell(1).setCellStyle(cellStyleNoLine);
                    row.createCell(2).setCellStyle(cellStyleNoLine);
                    row.createCell(3).setCellStyle(cellStyleNoLine);
                    row.createCell(4).setCellStyle(cellStyleNoLine);
                    row.createCell(5).setCellStyle(cellStyleNoLine);
                    row.createCell(6).setCellStyle(cellStyleNoLine);
                    row.createCell(7).setCellStyle(cellStyleNoLine);
                    row.createCell(8).setCellStyle(cellStyleNoLine);
                    row.createCell(9).setCellStyle(cellStyleNoLine);
                    row.createCell(10).setCellStyle(cellStyleNoLine);

                    HSSFRow row1 = sheet.createRow(num);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 10));
                    num++;
                    HSSFCell cell1 = row1.createCell(0);
                    cell1.setCellValue("派工/验收计量单");
                    cell1.setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(1).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(2).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(3).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(4).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(5).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(6).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(7).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(8).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(9).setCellStyle(cellStyleTitleNoLine);
                    row1.createCell(10).setCellStyle(cellStyleTitleNoLine);
                    HSSFRow row2 = sheet.createRow(num);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 10));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));


                    HSSFCell cell2 = row2.createCell(0);
                    cell2.setCellValue("派工编号");
                    cell2.setCellStyle(cellStyle);
                    HSSFCell cell3 = row2.createCell(2);
                    cell3.setCellValue(workOrderInformation.getJobNumber());
                    cell3.setCellStyle(cellStyle);

                    row2.createCell(1).setCellStyle(cellStyle);
                    row2.createCell(3).setCellStyle(cellStyle);

                    row2.createCell(4).setCellStyle(cellStyle);
                    row2.createCell(5).setCellStyle(cellStyle);
                    row2.createCell(6).setCellStyle(cellStyle);
                    row2.createCell(7).setCellStyle(cellStyle);
                    row2.createCell(8).setCellStyle(cellStyle);
                    row2.createCell(9).setCellStyle(cellStyle);
                    row2.createCell(10).setCellStyle(cellStyle);
                    num++;

                    HSSFRow row3 = sheet.createRow(num);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 5));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 10));

                    HSSFCell cell4 = row3.createCell(0);
                    cell4.setCellValue("派       工       方");
                    HSSFCell cell5 = row3.createCell(2);
                    cell5.setCellValue(contract.getFirstParty());
                    HSSFCell cell6 = row3.createCell(6);
                    cell6.setCellValue("承       包       方");
                    HSSFCell cell7 = row3.createCell(7);
                    cell7.setCellValue(contract.getSecondParty());
                    cell4.setCellStyle(cellStyle);
                    cell5.setCellStyle(cellStyle);
                    cell6.setCellStyle(cellStyle);
                    cell7.setCellStyle(cellStyle);
                    row3.createCell(1).setCellStyle(cellStyle);
                    row3.createCell(3).setCellStyle(cellStyle);
                    row3.createCell(4).setCellStyle(cellStyle);
                    row3.createCell(5).setCellStyle(cellStyle);
                    row3.createCell(8).setCellStyle(cellStyle);
                    row3.createCell(9).setCellStyle(cellStyle);
                    row3.createCell(10).setCellStyle(cellStyle);
                    num++;
                    HSSFRow row4 = sheet.createRow(num);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 5));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 10));

                    HSSFCell cell8 = row4.createCell(0);
                    cell8.setCellValue("派   工   原   因   ");
                    HSSFCell cell9 = row4.createCell(2);
                    cell9.setCellValue(workOrderInformation.getTaskContent());
                    HSSFCell cell10 = row4.createCell(6);
                    cell10.setCellValue("桩  号   位   置   ");
                    HSSFCell cell11 = row4.createCell(7);
                    cell11.setCellValue(workOrderInformation.getPosition());
                    cell8.setCellStyle(cellStyle);
                    cell9.setCellStyle(cellStyle);
                    cell10.setCellStyle(cellStyle);
                    cell11.setCellStyle(cellStyle);
                    row4.createCell(1).setCellStyle(cellStyle);
                    row4.createCell(3).setCellStyle(cellStyle);
                    row4.createCell(4).setCellStyle(cellStyle);
                    row4.createCell(5).setCellStyle(cellStyle);
                    row4.createCell(8).setCellStyle(cellStyle);
                    row4.createCell(9).setCellStyle(cellStyle);
                    row4.createCell(10).setCellStyle(cellStyle);
                    num++;
                    HSSFRow row5 = sheet.createRow(num);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 5));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 10));
                    num++;
                    HSSFCell cell12 = row5.createCell(0);
                    cell12.setCellValue("工  作   概   况   ");
                    HSSFCell cell13 = row5.createCell(2);
                    cell13.setCellValue(workOrderInformation.getRemarks());
                    HSSFCell cell14 = row5.createCell(6);
                    cell14.setCellValue("工  期   要   求   ");
                    HSSFCell cell15 = row5.createCell(7);
                    cell15.setCellValue(workOrderInformation.getDemandFinishTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    cell12.setCellStyle(cellStyle);
                    cell13.setCellStyle(cellStyle);
                    cell14.setCellStyle(cellStyle);
                    cell15.setCellStyle(cellStyle);
                    row5.createCell(1).setCellStyle(cellStyle);
                    row5.createCell(3).setCellStyle(cellStyle);
                    row5.createCell(4).setCellStyle(cellStyle);
                    row5.createCell(5).setCellStyle(cellStyle);
                    row5.createCell(8).setCellStyle(cellStyle);
                    row5.createCell(9).setCellStyle(cellStyle);
                    row5.createCell(10).setCellStyle(cellStyle);


                    HSSFRow row7 = sheet.createRow(num);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 5));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 10));
                    num++;
                    HSSFCell cell16 = row7.createCell(0);
                    cell16.setCellValue("派工联");
                    HSSFCell cell17 = row7.createCell(6);
                    cell17.setCellValue("质量要求、验收标准、简图、计算式等");//合并7-8
                    HSSFCell cell18 = row7.createCell(7);
                    cell18.setCellValue("验收、计量单");
                    cell16.setCellStyle(cellStyle);
                    cell17.setCellStyle(cellStyle);
                    cell18.setCellStyle(cellStyle);
                    row7.createCell(1).setCellStyle(cellStyle);
                    row7.createCell(2).setCellStyle(cellStyle);
                    row7.createCell(3).setCellStyle(cellStyle);
                    row7.createCell(4).setCellStyle(cellStyle);
                    row7.createCell(5).setCellStyle(cellStyle);
                    row7.createCell(8).setCellStyle(cellStyle);
                    row7.createCell(9).setCellStyle(cellStyle);
                    row7.createCell(10).setCellStyle(cellStyle);
                    HSSFRow row8 = sheet.createRow(num);
                    sheet.addMergedRegion(new CellRangeAddress(num - 1, num, 6, 6));
                    num++;
                    HSSFCell cell19 = row8.createCell(0);
                    cell19.setCellValue("项次");
                    HSSFCell cell20 = row8.createCell(1);
                    cell20.setCellValue("工作项");
                    HSSFCell cell21 = row8.createCell(2);
                    cell21.setCellValue("单位");
                    HSSFCell cell22 = row8.createCell(3);
                    cell22.setCellValue("数量");
                    HSSFCell cell23 = row8.createCell(4);
                    cell23.setCellValue("单价(元)");
                    HSSFCell cell24 = row8.createCell(5);
                    cell24.setCellValue("合价(元)");
                    HSSFCell cell25 = row8.createCell(7);
                    cell25.setCellValue("质量评价");
                    HSSFCell cell26 = row8.createCell(8);
                    cell26.setCellValue("数量");
                    HSSFCell cell27 = row8.createCell(9);
                    cell27.setCellValue("单价(元)");
                    HSSFCell cell28 = row8.createCell(10);
                    cell28.setCellValue("合价(元)");
                    cell19.setCellStyle(cellStyle);
                    cell20.setCellStyle(cellStyle);
                    cell21.setCellStyle(cellStyle);
                    cell22.setCellStyle(cellStyle);
                    cell23.setCellStyle(cellStyle);
                    cell24.setCellStyle(cellStyle);
                    cell25.setCellStyle(cellStyle);
                    cell26.setCellStyle(cellStyle);
                    cell27.setCellStyle(cellStyle);
                    cell28.setCellStyle(cellStyle);
                    row8.createCell(6).setCellStyle(cellStyle);

                    row.setHeight((short) (32 * 20));
                    row1.setHeight((short) (32 * 20));
                    row2.setHeight((short) (25 * 20));
                    row3.setHeight((short) (22 * 20));
                    row4.setHeight((short) (22 * 20));
                    row5.setHeight((short) (22 * 20));

                    row7.setHeight((short) (22 * 20));
                    row8.setHeight((short) (22 * 20));
                    int itemNumber = 1;
                    for (int i = 0; i < ofQuantities.size(); i++) {
                        HSSFRow row9 = sheet.createRow(num);
                        num++;
                        BillOfQuantities billOfQuantity = ofQuantities.get(i);
                        HSSFCell cell29 = row9.createCell(0);
                        cell29.setCellValue(itemNumber++);
                        HSSFCell cell30 = row9.createCell(1);
                        if (billOfQuantity.getSonSubjectName()!=null &&  !"".equals(billOfQuantity.getSonSubjectName())){
                            cell30.setCellValue(billOfQuantity.getSonSubjectName());
                        }else if (billOfQuantity.getFineSubjectName()!=null &&  !"".equals(billOfQuantity.getFineSubjectName())
                                && (billOfQuantity.getSonSubjectName()==null || "".equals(billOfQuantity.getSonSubjectName()))
                                ){
                            cell30.setCellValue(billOfQuantity.getFineSubjectName());
                        }else {
                            cell30.setCellValue(billOfQuantity.getSubjectName());
                        }

                        HSSFCell cell31 = row9.createCell(2);
                        cell31.setCellValue(billOfQuantity.getSpec());
                        HSSFCell cell32 = row9.createCell(3);
                        cell32.setCellValue(String.format("%.2f",billOfQuantity.getAmount()));
                        HSSFCell cell33 = row9.createCell(4);
                        cell33.setCellValue(String.format("%.2f",billOfQuantity.getPrice()));
                        HSSFCell cell34 = row9.createCell(5);


                        float v = billOfQuantity.getAmount() * billOfQuantity.getPrice();



                        cell34.setCellValue(String.format("%.2f",v));
                        HSSFCell cell35 = row9.createCell(7);
                        cell35.setCellValue("合格");
                        HSSFCell cell36 = row9.createCell(8);
                        cell36.setCellValue(String.format("%.2f",billOfQuantity.getAuditAmount()));
                        HSSFCell cell37 = row9.createCell(9);
                        cell37.setCellValue(String.format("%.2f",billOfQuantity.getAuditPrice()));
                        HSSFCell cell38 = row9.createCell(10);
                        cell38.setCellValue(String.format("%.2f",billOfQuantity.getAuditMoney()));

                        cell29.setCellStyle(cellStyle);
                        cell30.setCellStyle(cellStyle);
                        cell31.setCellStyle(cellStyle);
                        cell32.setCellStyle(cellStyle);
                        cell33.setCellStyle(cellStyle);
                        cell34.setCellStyle(cellStyle);
                        cell35.setCellStyle(cellStyle);
                        cell36.setCellStyle(cellStyle);
                        cell37.setCellStyle(cellStyle);
                        cell38.setCellStyle(cellStyle);
                        HSSFCell cell39 = row9.createCell(6);
                        cell39.setCellValue(workOrderInformation.getConstructionDesc());
                        cell39.setCellStyle(cellStyle);
                        row9.setHeight((short) (20 * 20));


                    }
                    if (ofQuantities.size() < 6) {
                        for (int i = 0; i < 6 - ofQuantities.size(); i++) {
                            HSSFRow row9 = sheet.createRow(num);
                            num++;
                            HSSFCell cell29 = row9.createCell(0);
                            cell29.setCellValue(itemNumber++);
                            HSSFCell cell30 = row9.createCell(1);

                            HSSFCell cell31 = row9.createCell(2);

                            HSSFCell cell32 = row9.createCell(3);

                            HSSFCell cell33 = row9.createCell(4);

                            HSSFCell cell34 = row9.createCell(5);

                            HSSFCell cell35 = row9.createCell(7);

                            HSSFCell cell36 = row9.createCell(8);

                            HSSFCell cell37 = row9.createCell(9);

                            HSSFCell cell38 = row9.createCell(10);

                            cell29.setCellStyle(cellStyle);
                            cell30.setCellStyle(cellStyle);
                            cell31.setCellStyle(cellStyle);
                            cell32.setCellStyle(cellStyle);
                            cell33.setCellStyle(cellStyle);
                            cell34.setCellStyle(cellStyle);
                            cell35.setCellStyle(cellStyle);
                            cell36.setCellStyle(cellStyle);
                            cell37.setCellStyle(cellStyle);
                            cell38.setCellStyle(cellStyle);
                            row9.createCell(6).setCellStyle(cellStyle);
                            row9.setHeight((short) (18 * 20));
                        }
                    }
                    sheet.addMergedRegion(new CellRangeAddress(num - 6, num - 1, 6, 6));
                    HSSFRow row9 = sheet.createRow(num);
                    num++;
                    HSSFCell cell29 = row9.createCell(1);
                    cell29.setCellValue("合计");
                    cell29.setCellStyle(cellStyle);
                    HSSFCell cell30 = row9.createCell(5);
                    double sum = ofQuantities.stream().mapToDouble(BillOfQuantities::getMoney).sum();
                    double sumAuditMoney = ofQuantities.stream().mapToDouble(BillOfQuantities::getAuditMoney).sum();

                    cell30.setCellValue(String.format("%.2f",sum));
                    cell30.setCellStyle(cellStyle);
                    row9.createCell(0).setCellStyle(cellStyle);
                    row9.createCell(2).setCellStyle(cellStyle);
                    row9.createCell(3).setCellStyle(cellStyle);
                    row9.createCell(4).setCellStyle(cellStyle);
                    row9.createCell(6).setCellStyle(cellStyle);
                    row9.createCell(7).setCellStyle(cellStyle);
                    row9.createCell(8).setCellStyle(cellStyle);
                    row9.createCell(9).setCellStyle(cellStyle);
                    HSSFCell cell47 = row9.createCell(10);
                    cell47.setCellStyle(cellStyle);
                    cell47.setCellValue(String.format("%.2f",sumAuditMoney));
                    row9.setHeight((short) (20 * 20));

                    HSSFRow row10 = sheet.createRow(num);
                    HSSFCell cell31 = row10.createCell(0);
                    cell31.setCellValue("管理中心经办人");
                    HSSFCell cell32 = row10.createCell(2);
                    cell31.setCellStyle(cellStyleLeft);
                    cell32.setCellValue(workOrderInformation.getIssuer());
                    HSSFCell cell33 = row10.createCell(4);
                    cell33.setCellValue("承包方经办人");
                    row10.createCell(6).setCellValue(workOrderInformation.getAssignedPersonnel());
                    HSSFCell cell34 = row10.createCell(7);
                    cell34.setCellValue("管理中心经办人");
                    //row10.createCell(8).setCellValue(workOrderInformation.getIssuer());
                    cell34.setCellStyle(cellStyleLeft);
                    HSSFCell cell35 = row10.createCell(9);
                    cell35.setCellValue(workOrderInformation.getMaintenanceStationAudit());
                    row10.createCell(10).setCellStyle(cellStyleRight);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 3));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 4, 5));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 8));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 9, 10));
                    num++;
                    HSSFRow row11 = sheet.createRow(num);

                    HSSFCell cell36 = row11.createCell(0);
                    cell36.setCellValue("管理中心审核人");
                    cell36.setCellStyle(cellStyleLeft);
                    HSSFCell cell37 = row11.createCell(2);
                    cell37.setCellValue(workOrderInformation.getMaintenanceDept());
                    HSSFCell cell38 = row11.createCell(4);
                    cell38.setCellValue("承包方负责人");
                    HSSFCell cell388 = row11.createCell(6);
                    cell388.setCellValue(workOrderInformation.getReceivingPartyReview());
                    HSSFCell cell39 = row11.createCell(7);
                    cell39.setCellValue("管理中心审核人");
                    cell39.setCellStyle(cellStyleLeft);
                    // row11.createCell(8).setCellValue(workOrderInformation.getMaintenanceDept());
                    HSSFCell cell40 = row11.createCell(9);
                    row11.createCell(10).setCellStyle(cellStyleRight);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 3));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 4, 5));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 8));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 9, 10));
                    num++;
                    cell40.setCellValue(workOrderInformation.getMaintenanceDept());
                    HSSFRow row12 = sheet.createRow(num);

                    HSSFCell cell41 = row12.createCell(0);
                    cell41.setCellValue("派工日期");
                    cell41.setCellStyle(cellStyleLeft);
                    HSSFCell cell42 = row12.createCell(2);
                    if (workOrderInformation.getCreateTime() != null) {
                        row12.createCell(2).setCellValue(workOrderInformation.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    }
                    HSSFCell cell43 = row12.createCell(4);
                    cell43.setCellValue("完成日期");
                    HSSFCell cell45 = row12.createCell(6);
                    if (workOrderInformation.getConstructionFinishTime() != null) {
                        cell45.setCellValue(workOrderInformation.getConstructionFinishTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    }
                    HSSFCell cell44 = row12.createCell(7);
                    cell44.setCellValue("验收日期");
                    cell44.setCellStyle(cellStyleLeft);
                    if (workOrderInformation.getEndTime() != null) {
                        row12.createCell(9).setCellValue(workOrderInformation.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    }
                    row12.createCell(10).setCellStyle(cellStyleRight);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 3));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 4, 5));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 8));
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 9, 10));
                    num++;
                    row10.setHeight((short) (28 * 20));
                    row11.setHeight((short) (28 * 20));
                    row12.setHeight((short) (28 * 20));
                    HSSFRow row13 = sheet.createRow(num);

                    HSSFCell cell46 = row13.createCell(0);
                    cell46.setCellValue("附件资料：□技术交底；□施工图；□照片资料；□工程量计算式；□竣工图；□其他");
                    cell46.setCellStyle(cellStyleLeftAlign);
                    row13.createCell(1).setCellStyle(cellStyleLeftAlign);
                    HSSFCell cell48 = row13.createCell(2);

                    cell48.setCellStyle(cellStyleLeftAlign);
                    row13.createCell(3).setCellStyle(cellStyleLeftAlign);
                    row13.createCell(4).setCellStyle(cellStyleLeftAlign);
                    row13.createCell(5).setCellStyle(cellStyleLeftAlign);
                    row13.createCell(6).setCellStyle(cellStyleLeftAlign);
                    row13.createCell(7).setCellStyle(cellStyleLeftAlign);
                    row13.createCell(8).setCellStyle(cellStyleLeftAlign);
                    row13.createCell(9).setCellStyle(cellStyleLeftAlign);
                    row13.createCell(10).setCellStyle(cellStyleLeftAlign);
                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 10));

                    num++;
                    row13.setHeight((short) (20 * 20));

//                    HSSFRow row14 = sheet.createRow(num);
//                    HSSFCell cell47 = row14.createCell(0);
//                    cell47.setCellValue("注：本单作为养护费用结算原始依据。原件一份，签证过程中由管理中心保存，验收签证完成后由计财部保存，同时印发给承包方、管理中心、养护部各一份。");
//                    sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 10));
//                    num++;
//                    cell47.setCellStyle(cellStyleSmall);
//                    row14.createCell(1).setCellStyle(cellStyleSmall);
//                    row14.createCell(2).setCellStyle(cellStyleSmall);
//                    row14.createCell(3).setCellStyle(cellStyleSmall);
//                    row14.createCell(4).setCellStyle(cellStyleSmall);
//                    row14.createCell(5).setCellStyle(cellStyleSmall);
//                    row14.createCell(6).setCellStyle(cellStyleSmall);
//                    row14.createCell(7).setCellStyle(cellStyleSmall);
//                    row14.createCell(8).setCellStyle(cellStyleSmall);
//                    row14.createCell(9).setCellStyle(cellStyleSmall);
//                    row14.createCell(10).setCellStyle(cellStyleSmall);
//                    row14.setHeight((short) (20 * 20));
                }
            } else {
                HSSFRow row = sheet.createRow(num);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 10));
                num++;
                HSSFCell cell = row.createCell(0);
                cell.setCellValue(road.getCode() + road.getName() + "公路日常养护工程");
                cell.setCellStyle(cellStyleNoLine);
                row.createCell(1).setCellStyle(cellStyleNoLine);
                row.createCell(2).setCellStyle(cellStyleNoLine);
                row.createCell(3).setCellStyle(cellStyleNoLine);
                row.createCell(4).setCellStyle(cellStyleNoLine);
                row.createCell(5).setCellStyle(cellStyleNoLine);
                row.createCell(6).setCellStyle(cellStyleNoLine);
                row.createCell(7).setCellStyle(cellStyleNoLine);
                row.createCell(8).setCellStyle(cellStyleNoLine);
                row.createCell(9).setCellStyle(cellStyleNoLine);
                row.createCell(10).setCellStyle(cellStyleNoLine);

                HSSFRow row1 = sheet.createRow(num);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 10));
                num++;
                HSSFCell cell1 = row1.createCell(0);
                cell1.setCellValue("派工/验收计量单");
                cell1.setCellStyle(cellStyleTitleNoLine);
                row1.createCell(1).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(2).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(3).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(4).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(5).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(6).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(7).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(8).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(9).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(10).setCellStyle(cellStyleTitleNoLine);
                HSSFRow row2 = sheet.createRow(num);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 9, 10));
                num++;
                HSSFCell cell2 = row2.createCell(8);
                cell2.setCellValue("编号");
                cell2.setCellStyle(cellStyle);
                row2.createCell(0).setCellStyle(cellStyle);
                row2.createCell(1).setCellStyle(cellStyle);
                row2.createCell(2).setCellStyle(cellStyle);
                row2.createCell(3).setCellStyle(cellStyle);
                row2.createCell(4).setCellStyle(cellStyle);
                row2.createCell(5).setCellStyle(cellStyle);
                row2.createCell(6).setCellStyle(cellStyle);
                row2.createCell(7).setCellStyle(cellStyle);

                row2.createCell(10).setCellStyle(cellStyle);
                HSSFCell cell3 = row2.createCell(9);
                cell3.setCellValue(workOrderInformation.getJobNumber());
                cell3.setCellStyle(cellStyle);
                HSSFRow row3 = sheet.createRow(num);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 5));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 10));
                num++;
                HSSFCell cell4 = row3.createCell(0);
                cell4.setCellValue("派       工       方");
                HSSFCell cell5 = row3.createCell(2);
                cell5.setCellValue(contract.getFirstParty());
                HSSFCell cell6 = row3.createCell(6);
                cell6.setCellValue("承       包       方");
                HSSFCell cell7 = row3.createCell(7);
                cell7.setCellValue(contract.getSecondParty());
                cell4.setCellStyle(cellStyle);
                cell5.setCellStyle(cellStyle);
                cell6.setCellStyle(cellStyle);
                cell7.setCellStyle(cellStyle);
                row3.createCell(1).setCellStyle(cellStyle);
                row3.createCell(3).setCellStyle(cellStyle);
                row3.createCell(4).setCellStyle(cellStyle);
                row3.createCell(5).setCellStyle(cellStyle);
                row3.createCell(8).setCellStyle(cellStyle);
                row3.createCell(9).setCellStyle(cellStyle);
                row3.createCell(10).setCellStyle(cellStyle);

                HSSFRow row4 = sheet.createRow(num);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 5));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 10));
                num++;
                HSSFCell cell8 = row4.createCell(0);
                cell8.setCellValue("派   工   原   因   ");
                HSSFCell cell9 = row4.createCell(2);
                cell9.setCellValue(workOrderInformation.getTaskContent());
                HSSFCell cell10 = row4.createCell(6);
                cell10.setCellValue("桩  号   位   置   ");
                HSSFCell cell11 = row4.createCell(7);
                cell11.setCellValue(workOrderInformation.getPosition());
                cell8.setCellStyle(cellStyle);
                cell9.setCellStyle(cellStyle);
                cell10.setCellStyle(cellStyle);
                cell11.setCellStyle(cellStyle);
                row4.createCell(1).setCellStyle(cellStyle);
                row4.createCell(3).setCellStyle(cellStyle);
                row4.createCell(4).setCellStyle(cellStyle);
                row4.createCell(5).setCellStyle(cellStyle);
                row4.createCell(8).setCellStyle(cellStyle);
                row4.createCell(9).setCellStyle(cellStyle);
                row4.createCell(10).setCellStyle(cellStyle);

                HSSFRow row5 = sheet.createRow(num);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 5));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 10));
                num++;
                HSSFCell cell12 = row5.createCell(0);
                cell12.setCellValue("工  作   概   况   ");
                HSSFCell cell13 = row5.createCell(2);
                cell13.setCellValue(workOrderInformation.getRemarks());
                HSSFCell cell14 = row5.createCell(6);
                cell14.setCellValue("工  期   要   求   ");
                HSSFCell cell15 = row5.createCell(7);
                cell15.setCellValue(workOrderInformation.getDemandFinishTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                cell12.setCellStyle(cellStyle);
                cell13.setCellStyle(cellStyle);
                cell14.setCellStyle(cellStyle);
                cell15.setCellStyle(cellStyle);
                row5.createCell(1).setCellStyle(cellStyle);
                row5.createCell(3).setCellStyle(cellStyle);
                row5.createCell(4).setCellStyle(cellStyle);
                row5.createCell(5).setCellStyle(cellStyle);
                row5.createCell(8).setCellStyle(cellStyle);
                row5.createCell(9).setCellStyle(cellStyle);
                row5.createCell(10).setCellStyle(cellStyle);


                HSSFRow row7 = sheet.createRow(num);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 5));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 10));
                num++;
                HSSFCell cell16 = row7.createCell(0);
                cell16.setCellValue("派工联");
                HSSFCell cell17 = row7.createCell(6);
                cell17.setCellValue("质量要求、验收标准、简图、计算式等");//合并7-8
                HSSFCell cell18 = row7.createCell(7);
                cell18.setCellValue("验收、计量单");
                cell16.setCellStyle(cellStyle);
                cell17.setCellStyle(cellStyle);
                cell18.setCellStyle(cellStyle);
                row7.createCell(1).setCellStyle(cellStyle);
                row7.createCell(2).setCellStyle(cellStyle);
                row7.createCell(3).setCellStyle(cellStyle);
                row7.createCell(4).setCellStyle(cellStyle);
                row7.createCell(5).setCellStyle(cellStyle);
                row7.createCell(8).setCellStyle(cellStyle);
                row7.createCell(9).setCellStyle(cellStyle);
                row7.createCell(10).setCellStyle(cellStyle);
                HSSFRow row8 = sheet.createRow(num);
                sheet.addMergedRegion(new CellRangeAddress(num - 1, num, 6, 6));
                num++;
                HSSFCell cell19 = row8.createCell(0);
                cell19.setCellValue("项次");
                HSSFCell cell20 = row8.createCell(1);
                cell20.setCellValue("工作项");
                HSSFCell cell21 = row8.createCell(2);
                cell21.setCellValue("单位");
                HSSFCell cell22 = row8.createCell(3);
                cell22.setCellValue("数量");
                HSSFCell cell23 = row8.createCell(4);
                cell23.setCellValue("单价(元)");
                HSSFCell cell24 = row8.createCell(5);
                cell24.setCellValue("合价(元)");
                HSSFCell cell25 = row8.createCell(7);
                cell25.setCellValue("质量评价");
                HSSFCell cell26 = row8.createCell(8);
                cell26.setCellValue("数量");
                HSSFCell cell27 = row8.createCell(9);
                cell27.setCellValue("单价(元)");
                HSSFCell cell28 = row8.createCell(10);
                cell28.setCellValue("合价(元)");
                cell19.setCellStyle(cellStyle);
                cell20.setCellStyle(cellStyle);
                cell21.setCellStyle(cellStyle);
                cell22.setCellStyle(cellStyle);
                cell23.setCellStyle(cellStyle);
                cell24.setCellStyle(cellStyle);
                cell25.setCellStyle(cellStyle);
                cell26.setCellStyle(cellStyle);
                cell27.setCellStyle(cellStyle);
                cell28.setCellStyle(cellStyle);
                row8.createCell(6).setCellStyle(cellStyle);

                row.setHeight((short) (32 * 20));
                row1.setHeight((short) (32 * 20));
                row2.setHeight((short) (13 * 20));
                row3.setHeight((short) (22 * 20));
                row4.setHeight((short) (22 * 20));
                row5.setHeight((short) (22 * 20));

                row7.setHeight((short) (22 * 20));
                row8.setHeight((short) (22 * 20));
                int itemNumber = 1;
                for (int i = 0; i < 6; i++) {
                    HSSFRow row9 = sheet.createRow(num);
                    num++;
                    HSSFCell cell29 = row9.createCell(0);
                    cell29.setCellValue(itemNumber++);
                    HSSFCell cell30 = row9.createCell(1);

                    HSSFCell cell31 = row9.createCell(2);

                    HSSFCell cell32 = row9.createCell(3);

                    HSSFCell cell33 = row9.createCell(4);

                    HSSFCell cell34 = row9.createCell(5);

                    HSSFCell cell35 = row9.createCell(7);

                    HSSFCell cell36 = row9.createCell(8);

                    HSSFCell cell37 = row9.createCell(9);

                    HSSFCell cell38 = row9.createCell(10);

                    cell29.setCellStyle(cellStyle);
                    cell30.setCellStyle(cellStyle);
                    cell31.setCellStyle(cellStyle);
                    cell32.setCellStyle(cellStyle);
                    cell33.setCellStyle(cellStyle);
                    cell34.setCellStyle(cellStyle);
                    cell35.setCellStyle(cellStyle);
                    cell36.setCellStyle(cellStyle);
                    cell37.setCellStyle(cellStyle);
                    cell38.setCellStyle(cellStyle);
                    row9.createCell(6).setCellStyle(cellStyle);
                    row9.setHeight((short) (20 * 20));
                }

                sheet.addMergedRegion(new CellRangeAddress(num - 6, num - 1, 6, 6));
                HSSFRow row9 = sheet.createRow(num);
                num++;
                HSSFCell cell29 = row9.createCell(1);
                cell29.setCellValue("合计");
                cell29.setCellStyle(cellStyle);
                HSSFCell cell30 = row9.createCell(5);


                cell30.setCellValue(0);
                cell30.setCellStyle(cellStyle);
                row9.createCell(0).setCellStyle(cellStyle);
                row9.createCell(2).setCellStyle(cellStyle);
                row9.createCell(3).setCellStyle(cellStyle);
                row9.createCell(4).setCellStyle(cellStyle);
                row9.createCell(6).setCellStyle(cellStyle);
                row9.createCell(7).setCellStyle(cellStyle);
                row9.createCell(8).setCellStyle(cellStyle);
                row9.createCell(9).setCellStyle(cellStyle);
                row9.createCell(10).setCellStyle(cellStyle);
                row9.setHeight((short) (20 * 20));

                HSSFRow row10 = sheet.createRow(num);

                HSSFCell cell31 = row10.createCell(0);
                cell31.setCellValue("管理中心经办人");
                HSSFCell cell32 = row10.createCell(2);
                cell31.setCellStyle(cellStyleLeft);
                cell32.setCellValue(workOrderInformation.getIssuer());
                HSSFCell cell33 = row10.createCell(4);
                cell33.setCellValue("承包方经办人");
                row10.createCell(6).setCellValue(workOrderInformation.getAssignedPersonnel());
                HSSFCell cell34 = row10.createCell(7);
                cell34.setCellValue("管理中心经办人");
                //row10.createCell(8).setCellValue(workOrderInformation.getIssuer());
                cell34.setCellStyle(cellStyleLeft);
                HSSFCell cell35 = row10.createCell(9);
                cell35.setCellValue(workOrderInformation.getIssuer());
                row10.createCell(10).setCellStyle(cellStyleRight);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 3));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 4, 5));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 8));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 9, 10));
                num++;
                HSSFRow row11 = sheet.createRow(num);

                HSSFCell cell36 = row11.createCell(0);
                cell36.setCellValue("管理中心审核人");
                cell36.setCellStyle(cellStyleLeft);
                HSSFCell cell37 = row11.createCell(2);
                cell37.setCellValue(workOrderInformation.getMaintenanceDept());
                HSSFCell cell38 = row11.createCell(4);
                cell38.setCellValue("承包方负责人");
                HSSFCell cell388 = row11.createCell(6);
                cell388.setCellValue(workOrderInformation.getReceivingPartyReview());
                HSSFCell cell39 = row11.createCell(7);
                cell39.setCellValue("管理中心审核人");
                cell39.setCellStyle(cellStyleLeft);
                // row11.createCell(8).setCellValue(workOrderInformation.getMaintenanceDept());
                HSSFCell cell40 = row11.createCell(9);
                row11.createCell(10).setCellStyle(cellStyleRight);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 3));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 4, 5));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 8));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 9, 10));
                num++;
                cell40.setCellValue(workOrderInformation.getMaintenanceDept());
                HSSFRow row12 = sheet.createRow(num);

                HSSFCell cell41 = row12.createCell(0);
                cell41.setCellValue("派工日期");
                cell41.setCellStyle(cellStyleLeft);
                HSSFCell cell42 = row12.createCell(2);
                if (workOrderInformation.getCreateTime() != null) {
                    cell42.setCellValue(workOrderInformation.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                HSSFCell cell43 = row12.createCell(4);
                cell43.setCellValue("完成日期");
                HSSFCell cell45 = row12.createCell(6);
                if (workOrderInformation.getConstructionFinishTime() != null) {
                    cell45.setCellValue(workOrderInformation.getConstructionFinishTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                HSSFCell cell44 = row12.createCell(7);
                cell44.setCellValue("验收日期");
                cell44.setCellStyle(cellStyleLeft);
                if (workOrderInformation.getEndTime() != null) {
                    row12.createCell(9).setCellValue(workOrderInformation.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                row12.createCell(10).setCellStyle(cellStyleRight);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 1));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 3));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 4, 5));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 7, 8));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 9, 10));
                num++;
                row10.setHeight((short) (28 * 20));
                row11.setHeight((short) (28 * 20));
                row12.setHeight((short) (28 * 20));
                HSSFRow row13 = sheet.createRow(num);

                HSSFCell cell46 = row13.createCell(0);
                cell46.setCellValue("附件资料：□技术交底；□施工图；□照片资料；□工程量计算式；□竣工图；□其他");
                cell46.setCellStyle(cellStyleLeftAlign);
                row13.createCell(1).setCellStyle(cellStyleLeftAlign);
                HSSFCell cell48 = row13.createCell(2);
                //cell48.setCellValue("□技术交底；□施工图；□照片资料；□工程量计算式；□竣工图；□其他");
                cell48.setCellStyle(cellStyleLeftAlign);
                row13.createCell(3).setCellStyle(cellStyleLeftAlign);
                row13.createCell(4).setCellStyle(cellStyleLeftAlign);
                row13.createCell(5).setCellStyle(cellStyleLeftAlign);
                row13.createCell(6).setCellStyle(cellStyleLeftAlign);
                row13.createCell(7).setCellStyle(cellStyleLeftAlign);
                row13.createCell(8).setCellStyle(cellStyleLeftAlign);
                row13.createCell(9).setCellStyle(cellStyleLeftAlign);
                row13.createCell(10).setCellStyle(cellStyleLeftAlign);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 10));
                //sheet.addMergedRegion(new CellRangeAddress(num, num, 2, 10));
                num++;
                row13.setHeight((short) (20 * 20));

//                HSSFRow row14 = sheet.createRow(num);
//                HSSFCell cell47 = row14.createCell(0);
//                cell47.setCellValue("注：本单作为养护费用结算原始依据。原件一份，签证过程中由管理中心保存，验收签证完成后由计财部保存，同时印发给承包方、管理中心、养护部各一份。");
//                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 10));
//                num++;
//                cell47.setCellStyle(cellStyleSmall);
//                row14.createCell(1).setCellStyle(cellStyleSmall);
//                row14.createCell(2).setCellStyle(cellStyleSmall);
//                row14.createCell(3).setCellStyle(cellStyleSmall);
//                row14.createCell(4).setCellStyle(cellStyleSmall);
//                row14.createCell(5).setCellStyle(cellStyleSmall);
//                row14.createCell(6).setCellStyle(cellStyleSmall);
//                row14.createCell(7).setCellStyle(cellStyleSmall);
//                row14.createCell(8).setCellStyle(cellStyleSmall);
//                row14.createCell(9).setCellStyle(cellStyleSmall);
//                row14.createCell(10).setCellStyle(cellStyleSmall);
//                row14.setHeight((short) (20 * 20));
            }


            HSSFWorkbook workbookPhotos = new HSSFWorkbook();
            HSSFSheet sheetPhotos = workbookPhotos.createSheet("派单、验收计量单附件资料");
            HSSFPatriarch patriarch = sheetPhotos.createDrawingPatriarch();

            HSSFCellStyle cellStylePhotos = workbookPhotos.createCellStyle();
            HSSFCellStyle cellStylePhotoT = workbookPhotos.createCellStyle();
            HSSFCellStyle cellStyleTitlePhotos = workbookPhotos.createCellStyle();
            HSSFCellStyle cellStyleTitlePhotosNoLine = workbookPhotos.createCellStyle();
            sheetPhotos.setColumnWidth(0, 20 * 256);
            sheetPhotos.setColumnWidth(1, 22 * 256);
            sheetPhotos.setColumnWidth(2, 20 * 256);
            sheetPhotos.setColumnWidth(3, 22 * 256);

            PoiStyleUtil.setExcelStylePhotos(cellStylePhotos, workbookPhotos);
            setExcelStyle(cellStylePhotoT, workbookPhotos);

            PoiStyleUtil.setExcelStylePhotos(cellStyleTitlePhotos, workbookPhotos);
            PoiStyleUtil.setExcelStylePhotosOnLine(cellStyleTitlePhotosNoLine, workbookPhotos);
            sheetPhotos.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
            HSSFRow row20 = sheetPhotos.createRow(0);
            HSSFCell cell66 = row20.createCell(0);
            cell66.setCellValue(road.getCode() + road.getName() + "公路日常养护工程");
            cell66.setCellStyle(cellStyleTitlePhotosNoLine);
            row20.createCell(1).setCellStyle(cellStyleTitlePhotosNoLine);
            row20.createCell(2).setCellStyle(cellStyleTitlePhotosNoLine);
            row20.createCell(3).setCellStyle(cellStyleTitlePhotosNoLine);
            HSSFRow row15 = sheetPhotos.createRow(1);
            HSSFCell cell51 = row15.createCell(0);
            cell51.setCellValue("派工/验收计量资料");
            cell51.setCellStyle(cellStyleTitlePhotosNoLine);
            row15.createCell(1).setCellStyle(cellStyleTitlePhotosNoLine);
            row15.createCell(2).setCellStyle(cellStyleTitlePhotosNoLine);
            row15.createCell(3).setCellStyle(cellStyleTitlePhotosNoLine);


            HSSFRow row16 = sheetPhotos.createRow(2);
            HSSFCell cell52 = row16.createCell(0);
            cell52.setCellValue("派工方");
            cell52.setCellStyle(cellStylePhotos);
            HSSFCell cell53 = row16.createCell(1);
            cell53.setCellValue(contract.getFirstParty());
            cell53.setCellStyle(cellStylePhotoT);
            HSSFCell cell54 = row16.createCell(2);
            cell54.setCellValue("承包方");
            cell54.setCellStyle(cellStylePhotos);
            HSSFCell cell55 = row16.createCell(3);
            cell55.setCellStyle(cellStylePhotoT);
            cell55.setCellValue(contract.getSecondParty());
            HSSFRow row17 = sheetPhotos.createRow(3);
            HSSFCell cell49 = row17.createCell(0);
            cell49.setCellValue("施工桩号位置");
            cell49.setCellStyle(cellStylePhotoT);
            HSSFCell cell65 = row17.createCell(1);
            cell65.setCellValue(workOrderInformation.getPosition());
            cell65.setCellStyle(cellStylePhotoT);
            HSSFCell cell1 = row17.createCell(2);
            cell1.setCellStyle(cellStylePhotos);
            cell1.setCellValue("派  工  编  号");
            HSSFCell cell2 = row17.createCell(3);
            cell2.setCellStyle(cellStylePhotoT);
            cell2.setCellValue(workOrderInformation.getJobNumber());
            HSSFRow row18 = sheetPhotos.createRow(4);
            HSSFCell cell50 = row18.createCell(0);

            cell50.setCellValue("工作概况");
            cell50.setCellStyle(cellStylePhotos);
            HSSFCell cell64 = row18.createCell(1);
            cell64.setCellValue(workOrderInformation.getRemarks());
            cell64.setCellStyle(cellStylePhotos);
            row18.createCell(2).setCellStyle(cellStylePhotos);
            row18.createCell(3).setCellStyle(cellStylePhotos);
            HSSFRow row19 = sheetPhotos.createRow(5);
            HSSFCell cell60 = row19.createCell(0);
            cell60.setCellValue("施工前照片");
            cell60.setCellStyle(cellStylePhotos);
            HSSFCell cell63 = row19.createCell(2);
            row19.createCell(1).setCellStyle(cellStylePhotos);
            cell63.setCellValue("拍摄时间");
            cell63.setCellStyle(cellStylePhotos);
            sheetPhotos.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
            sheetPhotos.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));
            sheetPhotos.addMergedRegion(new CellRangeAddress(4, 4, 1, 3));
            sheetPhotos.addMergedRegion(new CellRangeAddress(5, 5, 0, 1));

            row15.setHeight((short) (20 * 20));
            row16.setHeight((short) (32 * 20));
            row17.setHeight((short) (20 * 20));
            row18.setHeight((short) (64 * 20));
            row19.setHeight((short) (20 * 20));
            row20.setHeight((short) (20 * 20));
            HSSFCell cell = row19.createCell(3);
            cell.setCellStyle(cellStylePhotos);
            HSSFRow rowPhoto24 = sheetPhotos.createRow(6);
            rowPhoto24.setHeight((short) (150 * 20));
            if (accessoriesPre.size() > 0) {
                cell.setCellValue(accessoriesPre.get(0).getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                for (int i = 0; i < accessoriesPre.size(); i++) {
                    InputStream fileStream = MinioUtil.getMinioFile("yhxt", accessoriesPre.get(i).getUrl(), false);
                    if (fileStream == null) continue;
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    int len = 1024;
                    byte tmp[] = new byte[len];
                    int j;
                    while ((j = fileStream.read(tmp, 0, len)) > 0) {
                        output.write(tmp, 0, j);
                    }
                    if (i == 0) {
                        HSSFClientAnchor anchor = new HSSFClientAnchor(66, 10, 1000, 0, (short) 0, 6, (short) 1, 6);
                        HSSFPicture picture = patriarch.createPicture(anchor, workbookPhotos.addPicture(output.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
                        picture.resize(1, 1);

                    }
                    if (i == 1) {
                        HSSFClientAnchor anchor2 = new HSSFClientAnchor(66, 10, 1000, 0, (short) 2, 6, (short) 3, 6);
                        patriarch.createPicture(anchor2, workbookPhotos.addPicture(output.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)).resize(1, 1);
                    }
                    if (i == 1) {
                        break;
                    }
                }
                rowPhoto24.createCell(0).setCellStyle(cellStyleTitlePhotos);
                rowPhoto24.createCell(1).setCellStyle(cellStyleTitlePhotos);
                rowPhoto24.createCell(2).setCellStyle(cellStyleTitlePhotos);
                rowPhoto24.createCell(3).setCellStyle(cellStyleTitlePhotos);
            }
            sheetPhotos.addMergedRegion(new CellRangeAddress(6, 6, 0, 1));
            sheetPhotos.addMergedRegion(new CellRangeAddress(6, 6, 2, 3));

            HSSFRow rowPhoto6 = sheetPhotos.createRow(7);
            HSSFCell cell58 = rowPhoto6.createCell(0);
            cell58.setCellValue("施工中照片");
            cell58.setCellStyle(cellStylePhotos);
            rowPhoto6.createCell(1).setCellStyle(cellStylePhotos);
            HSSFCell cell59 = rowPhoto6.createCell(2);

            cell59.setCellValue("拍摄时间");
            cell59.setCellStyle(cellStylePhotos);
            cell59.setCellStyle(cellStylePhotos);
            HSSFCell cell61 = rowPhoto6.createCell(3);
            cell61.setCellStyle(cellStylePhotos);
            HSSFRow rowPhoto23 = sheetPhotos.createRow(8);
            rowPhoto23.setHeight((short) (150 * 20));
            sheetPhotos.addMergedRegion(new CellRangeAddress(7, 7, 0, 1));
            if (accessoriesUnd.size() > 0) {
                cell61.setCellValue(accessoriesUnd.get(0).getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

                for (int i = 0; i < accessoriesUnd.size(); i++) {
                    InputStream fileStream = MinioUtil.getMinioFile("yhxt", accessoriesUnd.get(i).getUrl(), false);
                    if (fileStream == null) continue;
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    int len = 1024;
                    byte tmp[] = new byte[len];
                    int j;
                    while ((j = fileStream.read(tmp, 0, len)) > 0) {
                        output.write(tmp, 0, j);
                    }
                    if (i == 0) {
                        HSSFClientAnchor anchor = new HSSFClientAnchor(66, 10, 1000, 0, (short) 0, 8, (short) 1, 8);
                        patriarch.createPicture(anchor, workbookPhotos.addPicture(output.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)).resize(1, 1);
                    }
                    if (i == 1) {
                        HSSFClientAnchor anchor2 = new HSSFClientAnchor(66, 10, 1000, 0, (short) 2, 8, (short) 3, 8);
                        patriarch.createPicture(anchor2, workbookPhotos.addPicture(output.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)).resize(1, 1);
                    }
                    if (i == 1) {
                        break;
                    }
                }
                rowPhoto23.createCell(0).setCellStyle(cellStyleTitlePhotos);
                rowPhoto23.createCell(1).setCellStyle(cellStyleTitlePhotos);
                rowPhoto23.createCell(2).setCellStyle(cellStyleTitlePhotos);
                rowPhoto23.createCell(3).setCellStyle(cellStyleTitlePhotos);

            }
            sheetPhotos.addMergedRegion(new CellRangeAddress(8, 8, 0, 1));
            sheetPhotos.addMergedRegion(new CellRangeAddress(8, 8, 2, 3));

            HSSFRow rowPhoto4 = sheetPhotos.createRow(9);
            HSSFCell cell56 = rowPhoto4.createCell(0);
            cell56.setCellValue("施工后照片");
            cell56.setCellStyle(cellStylePhotos);
            rowPhoto4.createCell(1).setCellStyle(cellStylePhotos);
            HSSFCell cell57 = rowPhoto4.createCell(2);
            cell57.setCellValue("拍摄时间");
            cell57.setCellStyle(cellStylePhotos);
            HSSFCell cell62 = rowPhoto4.createCell(3);
            cell62.setCellStyle(cellStylePhotos);
            sheetPhotos.addMergedRegion(new CellRangeAddress(9, 9, 0, 1));
            HSSFRow rowPhoto22 = sheetPhotos.createRow(10);
            rowPhoto22.setHeight((short) (150 * 20));
            if (accessoriesSuf.size() > 0) {
                cell62.setCellValue(accessoriesSuf.get(0).getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                for (int i = 0; i < accessoriesSuf.size(); i++) {
                    InputStream fileStream = MinioUtil.getMinioFile("yhxt", accessoriesSuf.get(i).getUrl(), false);
                    if (fileStream == null) continue;
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    int len = 1024;
                    byte tmp[] = new byte[len];
                    int j;
                    while ((j = fileStream.read(tmp, 0, len)) > 0) {
                        output.write(tmp, 0, j);
                    }
                    if (i == 0) {
                        HSSFClientAnchor anchor = new HSSFClientAnchor(66, 10, 1000, 0, (short) 0, 10, (short) 1, 10);
                        patriarch.createPicture(anchor, workbookPhotos.addPicture(output.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)).resize(1, 1);
                    }
                    if (i == 1) {
                        HSSFClientAnchor anchor2 = new HSSFClientAnchor(66, 10, 1000, 0, (short) 2, 10, (short) 3, 10);
                        patriarch.createPicture(anchor2, workbookPhotos.addPicture(output.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)).resize(1, 1);
                    }
                    if (i == 1) {
                        break;
                    }
                }
                rowPhoto22.createCell(0).setCellStyle(cellStyleTitlePhotos);
                rowPhoto22.createCell(1).setCellStyle(cellStyleTitlePhotos);
                rowPhoto22.createCell(2).setCellStyle(cellStyleTitlePhotos);
                rowPhoto22.createCell(3).setCellStyle(cellStyleTitlePhotos);

            }
            sheetPhotos.addMergedRegion(new CellRangeAddress(10, 10, 0, 1));
            sheetPhotos.addMergedRegion(new CellRangeAddress(10, 10, 2, 3));
            HSSFRow row21 = sheetPhotos.createRow(11);
            HSSFCell cell67 = row21.createCell(0);
            cell67.setCellValue("承包方经办人");
            HSSFCell cell68 = row21.createCell(2);
            HSSFCell cell69 = row21.createCell(1);
            HSSFCell cell70 = row21.createCell(3);
            cell68.setCellValue("管理中心经办人");
            cell67.setCellStyle(cellStylePhotos);
            cell69.setCellStyle(cellStylePhotos);
            cell69.setCellValue(workOrderInformation.getAssignedPersonnel());
            cell70.setCellValue(workOrderInformation.getIssuer());
            cell68.setCellStyle(cellStylePhotos);
            cell70.setCellStyle(cellStylePhotos);
            row21.setHeight((short) (20 * 20));
            try {
                OutputStream os = new FileOutputStream(file + "/" + workOrderInformation.getJobNumber() + "-Photo" + ".xls");
                workbookPhotos.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("导出列表失败！");
            }

            try {
                OutputStream os = new FileOutputStream(file + "/" + workOrderInformation.getJobNumber() + ".xls");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("导出列表失败！");
            }


        }
        PoiStyleUtil.zip(fileName, true);
        String zip = fileName + ".zip";

        HttpUtil.downLoadFile(response, zip, zip);
        // 删除导出的文件
        FileUtil.deleteFile(zip);

    }

    /**
     * 按照时间导出已办工单
     * @param
     * @param response
     */
    @Override
    public void exportWorkOrdersConstruction(String startTime, String endTime, String contractId, String type, HttpServletResponse response) throws Exception {

            if (StringUtils.isEmpty(contractId)) {
                throw new RuntimeException("请选择对应合同");
            }
            long time = System.currentTimeMillis();
            String fileName = "工单信息" + time;
            File file = new File(fileName);
            if (!file.exists()) {
                file.mkdirs();
            }
            Contract contract = contractManager.getById(contractId);
            QueryWrapper<WorkOrderInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("END_TIME_", startTime);
            queryWrapper.le("END_TIME_", endTime);
            queryWrapper.eq("CONTRACT_ID_", contract.getId());
            queryWrapper.eq("ROAD_SEGMENT_ID_", contract.getRoadSegmentId());



            List<WorkOrderInformation> workOrderInformationList = baseMapper.selectList(queryWrapper);
            if(null == workOrderInformationList || workOrderInformationList.isEmpty()){

                throw new RuntimeException("未找到对应工单信息，请重新选择条件");
            }

            queryWrapper.clear();
            List<String> orderIds = workOrderInformationList.stream().map(WorkOrderInformation::getId).collect(Collectors.toList());


            QueryFilter filter = QueryFilter.build();
            PageBean pageBean = new PageBean();
            pageBean.setPage(1);
            pageBean.setPageSize(-1);


            filter.setPageBean(pageBean);


            filter.addFilter("wfInst.biz_key_", orderIds, QueryOP.IN, FieldRelation.AND);

            filter.addFilter("type_id_", "1425741173624016896", QueryOP.IN, FieldRelation.AND);
            PageList<Map<String, Object>> mapPageList = iFlowManager.getDoneInstList(baseContext.getCurrentUserAccout(), filter, null).get();


        List<Map<String, Object>> rows = mapPageList.getRows();


        ArrayList<String> ids = new ArrayList<>();

        if (rows.size() > 0) {
            for (Map<String, Object> row : rows) {
                //procDefKey
                Object procDefKey = row.get("procDefKey");
                if (procDefKey.toString().equals("yhgd")) {
                    //业务主键
                    Object bizKey = row.get("bizKey");
                    if (ObjectUtils.isNotEmpty(bizKey)) {

                        ids.add(bizKey.toString());
                    }
                }
            }
        }

        if(null == ids || ids.isEmpty()){

            throw new RuntimeException("未找到对应工单信息，请重新选择条件");
        }

        List<WorkOrderInformation> workOrderInformations = baseMapper.selectBatchIds(ids);

        if(null == workOrderInformations || workOrderInformations.isEmpty()){

            throw new RuntimeException("未找到对应工单信息，请重新选择条件");
        }


        Road road = roadManager.getById(contract.getRoadSegmentId());

        HSSFWorkbook workbook = getExportSheets(endTime, contract, workOrderInformations, road);


        try {
            OutputStream os = new FileOutputStream(file + "/" + road.getName() + "季度结算明细表" + ".xls");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败！");
        }


        PoiStyleUtil.zip(fileName, true);
        String zip = fileName + ".zip";

        HttpUtil.downLoadFile(response, zip, zip);
        // 删除导出的文件
        FileUtil.deleteFile(zip);




    }


    /**
     * 按照时间导出设置导出格式
     * @param endTime
     * @param contract
     * @param workOrderInformations
     * @param road
     * @return
     * @throws ParseException
     */
    private HSSFWorkbook getExportSheets(String endTime, Contract contract, List<WorkOrderInformation> workOrderInformations, Road road) throws ParseException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFCellStyle cellStyleOne = workbook.createCellStyle();
        HSSFCellStyle cellStyleTwo = workbook.createCellStyle();
        HSSFCellStyle cellStyleTitle = workbook.createCellStyle();
        HSSFCellStyle cellStyleNoLine = workbook.createCellStyle();
        HSSFCellStyle cellStyleTitleNoLine = workbook.createCellStyle();
        HSSFCellStyle cellStyleTitleNoLineSmall = workbook.createCellStyle();
        setExcelStyle(cellStyle, workbook);
        PoiStyleUtil.setExcelStyleOne(cellStyleOne, workbook);
        PoiStyleUtil.setExcelStyleTwo(cellStyleTwo, workbook);
        PoiStyleUtil.setExcelStyleTitle(cellStyleTitle, workbook);
        PoiStyleUtil.setExcelStyleTitleNoLine(cellStyleTitleNoLine, workbook);
        PoiStyleUtil.cellStyleTitleNoLineSmall(cellStyleTitleNoLineSmall, workbook);
        PoiStyleUtil.setExcelStyleNoLine(cellStyleNoLine, workbook);
        HSSFSheet sheet = workbook.createSheet("季度结算明细表");

        sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
        //设置横向
        sheet.getPrintSetup().setLandscape(true);
        sheet.setColumnWidth(0, 25 * 256);
        sheet.setColumnWidth(1, 25 * 256);
        sheet.setColumnWidth(2, 15 * 256);
        sheet.setColumnWidth(3, 10 * 256);
        sheet.setColumnWidth(4, 10 * 256);
        sheet.setColumnWidth(5, 15 * 256);
        sheet.setColumnWidth(6, 10 * 256);
        sheet.setColumnWidth(7, 15 * 256);

        List<BillOfQuantitiesVo> billOfQuantitiesVos = new ArrayList<>();
        for (WorkOrderInformation workOrderInformation : workOrderInformations) {

            WorkOrderInformationVo vo = this.getVo(workOrderInformation.getId());

            //合同内工程量清单
            List<BillOfQuantities> billOfQuantities = vo.getBillOfQuantities();
            //合同外工程量清单
            List<BillOfQuantities> billOutOfQuantities = vo.getBillOutOfQuantities();
            billOfQuantities.forEach(s -> {
                BillOfQuantitiesVo bill = new BillOfQuantitiesVo();
                BillOfQuantitiesVo billOfQuantitiesVo = bill.getVo(s);
                billOfQuantitiesVo.setJobNumber(workOrderInformation.getJobNumber());
                billOfQuantitiesVo.setPosition(workOrderInformation.getPosition());
                billOfQuantitiesVos.add(billOfQuantitiesVo);
            });

            billOutOfQuantities.forEach(s -> {
                BillOfQuantitiesVo bill = new BillOfQuantitiesVo();
                BillOfQuantitiesVo billOfQuantitiesVo = bill.getVo(s);
                billOfQuantitiesVo.setJobNumber(workOrderInformation.getJobNumber());
                billOfQuantitiesVo.setPosition(workOrderInformation.getPosition());
                billOfQuantitiesVos.add(billOfQuantitiesVo);
            });

        }
        List<BillOfQuantitiesVo> billOfQuantitiesVoList = billOfQuantitiesVos.stream().sorted(Comparator.comparing(BillOfQuantitiesVo::getJobNumber)).collect(Collectors.toList());

        List<List<BillOfQuantitiesVo>> collect = Stream.iterate(0, f -> f + 1).limit((billOfQuantitiesVoList.size() + 13) / 14).parallel().map(a -> billOfQuantitiesVoList.stream().skip(a * 14).limit(14).parallel().collect(Collectors.toList())).collect(Collectors.toList());
        int num = 0;
        if (collect.size() > 0) {
            for (List<BillOfQuantitiesVo> vos : collect) {
                HSSFRow row = sheet.createRow(num);
                HSSFCell cell = row.createCell(0);
                cell.setCellValue(road.getName() + "季度结算明细表");
                cell.setCellStyle(cellStyleTitleNoLineSmall);
                row.createCell(1).setCellStyle(cellStyleTitleNoLineSmall);
                row.createCell(2).setCellStyle(cellStyleTitleNoLineSmall);
                row.createCell(3).setCellStyle(cellStyleTitleNoLineSmall);
                row.createCell(4).setCellStyle(cellStyleTitleNoLineSmall);
                row.createCell(5).setCellStyle(cellStyleTitleNoLineSmall);
                row.createCell(6).setCellStyle(cellStyleTitleNoLineSmall);
                row.createCell(7).setCellStyle(cellStyleTitleNoLineSmall);

                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 7));
                num++;
                HSSFRow row1 = sheet.createRow(num);
                HSSFCell cell1 = row1.createCell(0);
                String yearWork = endTime.split("-")[0];
                Date date = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
                cell1.setCellStyle(cellStyleTitleNoLine);
                row1.createCell(1).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(2).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(3).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(4).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(5).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(6).setCellStyle(cellStyleTitleNoLine);
                row1.createCell(7).setCellStyle(cellStyleTitleNoLine);
                sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 7));
                int season = this.getSeason(date);
                String quarter = "";
                switch (season) {
                    case 1:
                        quarter = "一";
                        break;
                    case 2:
                        quarter = "二";
                        break;
                    case 3:
                        quarter = "三";
                        break;
                    case 4:
                        quarter = "四";
                        break;
                    default:
                        quarter = "一";
                        break;
                }
                cell1.setCellValue(yearWork + "年第" + quarter + "季度结算明细表");
                num++;
                HSSFRow row2 = sheet.createRow(2);
                HSSFCell cell2 = row2.createCell(0);
                cell2.setCellValue("派    工   方：");
                cell2.setCellStyle(cellStyleNoLine);
                HSSFCell cell3 = row2.createCell(1);
                cell3.setCellValue(contract.getFirstParty());
                cell3.setCellStyle(cellStyleNoLine);
                row2.createCell(2).setCellStyle(cellStyleNoLine);
                HSSFCell cell4 = row2.createCell(3);
                cell4.setCellValue("承      包     方：");
                cell4.setCellStyle(cellStyleNoLine);

                HSSFCell cell5 = row2.createCell(5);
                cell5.setCellValue(contract.getSecondParty());
                cell5.setCellStyle(cellStyleNoLine);
                row2.createCell(4).setCellStyle(cellStyleNoLine);
                row2.createCell(6).setCellStyle(cellStyleNoLine);
                row2.createCell(7).setCellStyle(cellStyleNoLine);

                sheet.addMergedRegion(new CellRangeAddress(num, num, 5, 7));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 3, 4));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 1, 2));
                num++;
                HSSFRow row3 = sheet.createRow(num);

                HSSFCell cell6 = row3.createCell(0);
                cell6.setCellValue("合   同   名   称：");
                cell6.setCellStyle(cellStyleNoLine);
                HSSFCell cell7 = row3.createCell(1);
                cell7.setCellValue(contract.getName());
                cell7.setCellStyle(cellStyleNoLine);
                row3.createCell(2).setCellStyle(cellStyleNoLine);
                HSSFCell cell8 = row3.createCell(3);
                cell8.setCellValue("合   同   编   号：");
                cell8.setCellStyle(cellStyleNoLine);

                HSSFCell cell9 = row3.createCell(5);
                cell9.setCellStyle(cellStyleNoLine);
                row3.createCell(4).setCellStyle(cellStyleNoLine);
                row3.createCell(6).setCellStyle(cellStyleNoLine);
                row3.createCell(7).setCellStyle(cellStyleNoLine);
                cell9.setCellValue(contract.getUniqueNumber());
                sheet.addMergedRegion(new CellRangeAddress(num, num, 5, 7));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 3, 4));
                sheet.addMergedRegion(new CellRangeAddress(num, num, 1, 2));
                num++;
                HSSFRow row4 = sheet.createRow(num);
                HSSFCell cell10 = row4.createCell(0);
                HSSFCell cell11 = row4.createCell(1);
                HSSFCell cell12 = row4.createCell(2);
                HSSFCell cell13 = row4.createCell(3);
                HSSFCell cell14 = row4.createCell(4);
                HSSFCell cell15 = row4.createCell(5);
                HSSFCell cell16 = row4.createCell(6);
                HSSFCell cell17 = row4.createCell(7);
                cell10.setCellStyle(cellStyle);
                cell11.setCellStyle(cellStyle);
                cell12.setCellStyle(cellStyle);
                cell13.setCellStyle(cellStyle);
                cell14.setCellStyle(cellStyle);
                cell15.setCellStyle(cellStyle);
                cell16.setCellStyle(cellStyle);
                cell17.setCellStyle(cellStyle);


                cell10.setCellValue("派工编号");
                cell11.setCellValue("工作项");
                cell12.setCellValue("桩号");
                cell13.setCellValue("单位");
                cell14.setCellValue("数量");
                cell15.setCellValue("单价");
                cell16.setCellValue("合价");
                cell17.setCellValue("备注");

                row.setHeight((short) (15 * 20));
                row1.setHeight((short) (20 * 20));
                row2.setHeight((short) (32 * 20));
                row3.setHeight((short) (32 * 20));
                row4.setHeight((short) (15 * 20));
                num++;

                Map<String, List<BillOfQuantitiesVo>> listMap = vos.stream().collect(Collectors.groupingBy(BillOfQuantitiesVo::getJobNumber));
                for (Map.Entry<String, List<BillOfQuantitiesVo>> entry : listMap.entrySet()) {
                    List<BillOfQuantitiesVo> value = entry.getValue();
                    int itemNumber = num;
                    System.out.println(itemNumber);
                    for (BillOfQuantitiesVo billOfQuantitiesVo : value) {
                        HSSFRow row5 = sheet.createRow(num);
                        HSSFCell cell18 = row5.createCell(0);
                        HSSFCell cell19 = row5.createCell(1);
                        HSSFCell cell20 = row5.createCell(2);
                        HSSFCell cell21 = row5.createCell(3);
                        HSSFCell cell22 = row5.createCell(4);
                        HSSFCell cell23 = row5.createCell(5);
                        HSSFCell cell24 = row5.createCell(6);
                        HSSFCell cell25 = row5.createCell(7);

                        cell18.setCellStyle(cellStyle);
                        cell19.setCellStyle(cellStyle);
                        cell20.setCellStyle(cellStyle);
                        cell21.setCellStyle(cellStyle);
                        cell22.setCellStyle(cellStyle);
                        cell23.setCellStyle(cellStyle);
                        cell24.setCellStyle(cellStyle);
                        cell25.setCellStyle(cellStyle);
                        cell18.setCellValue(billOfQuantitiesVo.getJobNumber());
                        if (billOfQuantitiesVo.getSonSubjectName() != null) {
                            cell19.setCellValue(billOfQuantitiesVo.getFineSubjectName() + "、" + billOfQuantitiesVo.getSonSubjectName());
                        } else {
                            cell19.setCellValue(billOfQuantitiesVo.getFineSubjectName());
                        }
                        if (billOfQuantitiesVo.getPosition() != null)
                            cell20.setCellValue(billOfQuantitiesVo.getPosition());
                        if (billOfQuantitiesVo.getSpec() != null)
                            cell21.setCellValue(billOfQuantitiesVo.getSpec());
                        if (billOfQuantitiesVo.getAuditAmount() != null)
                            cell22.setCellValue(billOfQuantitiesVo.getAuditAmount());
                        if (billOfQuantitiesVo.getAuditPrice() != null)
                            cell23.setCellValue(billOfQuantitiesVo.getAuditPrice());
                        if (billOfQuantitiesVo.getAuditMoney() != null)
                            cell24.setCellValue(billOfQuantitiesVo.getAuditMoney());
                        cell25.setCellValue("");
                        row5.setHeight((short) (19 * 20));
                        num++;
                    }

                    if (num - itemNumber > 1) {
                        sheet.addMergedRegion(new CellRangeAddress(itemNumber, num - 1, 0, 0));
                        sheet.addMergedRegion(new CellRangeAddress(itemNumber, num - 1, 2, 2));
                        sheet.addMergedRegion(new CellRangeAddress(itemNumber, num - 1, 7, 7));
                    }


                }
                if (vos.size() < 14) {
                    for (int i = 0; i < 14 - vos.size(); i++) {
                        HSSFRow row5 = sheet.createRow(num);
                        HSSFCell cell18 = row5.createCell(0);
                        HSSFCell cell19 = row5.createCell(1);
                        HSSFCell cell20 = row5.createCell(2);
                        HSSFCell cell21 = row5.createCell(3);
                        HSSFCell cell22 = row5.createCell(4);
                        HSSFCell cell23 = row5.createCell(5);
                        HSSFCell cell24 = row5.createCell(6);
                        HSSFCell cell25 = row5.createCell(7);

                        cell18.setCellStyle(cellStyle);
                        cell19.setCellStyle(cellStyle);
                        cell20.setCellStyle(cellStyle);
                        cell21.setCellStyle(cellStyle);
                        cell22.setCellStyle(cellStyle);
                        cell23.setCellStyle(cellStyle);
                        cell24.setCellStyle(cellStyle);
                        cell25.setCellStyle(cellStyle);
                        row5.setHeight((short) (19 * 20));
                        num++;
                    }
                }
                HSSFRow row9 = sheet.createRow(num);
                HSSFCell cell18 = row9.createCell(0);
                cell18.setCellValue("管理中心经办人");
                HSSFCell cell19 = row9.createCell(1);

                HSSFCell cell20 = row9.createCell(2);
                cell20.setCellValue("日期");
                HSSFCell cell21 = row9.createCell(3);

                HSSFCell cell22 = row9.createCell(4);
                cell22.setCellValue("管理中心审核人");
                HSSFCell cell23 = row9.createCell(5);
                HSSFCell cell24 = row9.createCell(6);
                HSSFCell cell25 = row9.createCell(7);
                cell24.setCellValue("日期");

                num++;
                HSSFRow row10 = sheet.createRow(num);
                HSSFCell cell27 = row10.createCell(0);
                cell27.setCellValue("管理中心负责人");
                HSSFCell cell28 = row10.createCell(1);

                HSSFCell cell29 = row10.createCell(2);
                cell29.setCellValue("日期");
                HSSFCell cell30 = row10.createCell(3);

                HSSFCell cell31 = row10.createCell(4);
                cell31.setCellValue("养护部审核人");
                HSSFCell cell32 = row10.createCell(5);
                HSSFCell cell33 = row10.createCell(6);
                HSSFCell cell34 = row10.createCell(7);
                cell33.setCellValue("日期");
                num++;

                row9.setHeight((short) (32 * 20));
                row10.setHeight((short) (32 * 20));
            }
        } else {
            HSSFRow row = sheet.createRow(num);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue(road.getName() + "季度结算明细表");
            cell.setCellStyle(cellStyleTitleNoLine);
            row.createCell(1).setCellStyle(cellStyleTitleNoLine);
            row.createCell(2).setCellStyle(cellStyleTitleNoLine);
            row.createCell(3).setCellStyle(cellStyleTitleNoLine);
            row.createCell(4).setCellStyle(cellStyleTitleNoLine);
            row.createCell(5).setCellStyle(cellStyleTitleNoLine);
            row.createCell(6).setCellStyle(cellStyleTitleNoLine);
            row.createCell(7).setCellStyle(cellStyleTitleNoLine);

            sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 7));
            num++;
            HSSFRow row1 = sheet.createRow(num);
            HSSFCell cell1 = row1.createCell(0);
            String yearWork = endTime.split("-")[0];
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
            cell1.setCellStyle(cellStyleTitleNoLine);
            row1.createCell(1).setCellStyle(cellStyleTitleNoLine);
            row1.createCell(2).setCellStyle(cellStyleTitleNoLine);
            row1.createCell(3).setCellStyle(cellStyleTitleNoLine);
            row1.createCell(4).setCellStyle(cellStyleTitleNoLine);
            row1.createCell(5).setCellStyle(cellStyleTitleNoLine);
            row1.createCell(6).setCellStyle(cellStyleTitleNoLine);
            row1.createCell(7).setCellStyle(cellStyleTitleNoLine);
            sheet.addMergedRegion(new CellRangeAddress(num, num, 0, 7));
            int season = this.getSeason(date);
            String quarter = "";
            switch (season) {
                case 1:
                    quarter = "一";
                    break;
                case 2:
                    quarter = "二";
                    break;
                case 3:
                    quarter = "三";
                    break;
                case 4:
                    quarter = "四";
                    break;
                default:
                    quarter = "一";
                    break;
            }
            cell1.setCellValue(yearWork + "年第" + quarter + "季度结算明细表");
            num++;
            HSSFRow row2 = sheet.createRow(2);
            HSSFCell cell2 = row2.createCell(0);
            cell2.setCellValue("派    工   方：");
            cell2.setCellStyle(cellStyleNoLine);
            HSSFCell cell3 = row2.createCell(1);
            cell3.setCellValue(contract.getFirstParty());
            cell3.setCellStyle(cellStyleNoLine);
            row2.createCell(2).setCellStyle(cellStyleNoLine);
            HSSFCell cell4 = row2.createCell(3);
            cell4.setCellValue("承      包     方：");
            cell4.setCellStyle(cellStyleNoLine);

            HSSFCell cell5 = row2.createCell(5);
            cell5.setCellValue(contract.getSecondParty());
            cell5.setCellStyle(cellStyleNoLine);
            row2.createCell(4).setCellStyle(cellStyleNoLine);
            row2.createCell(6).setCellStyle(cellStyleNoLine);
            row2.createCell(7).setCellStyle(cellStyleNoLine);

            sheet.addMergedRegion(new CellRangeAddress(num, num, 5, 7));
            sheet.addMergedRegion(new CellRangeAddress(num, num, 3, 4));
            sheet.addMergedRegion(new CellRangeAddress(num, num, 1, 2));
            num++;
            HSSFRow row3 = sheet.createRow(num);

            HSSFCell cell6 = row3.createCell(0);
            cell6.setCellValue("合   同   名   称：");
            cell6.setCellStyle(cellStyleNoLine);
            HSSFCell cell7 = row3.createCell(1);
            cell7.setCellValue(contract.getName());
            cell7.setCellStyle(cellStyleNoLine);
            row3.createCell(2).setCellStyle(cellStyleNoLine);
            HSSFCell cell8 = row3.createCell(3);
            cell8.setCellValue("合   同   编   号：");
            cell8.setCellStyle(cellStyleNoLine);

            HSSFCell cell9 = row3.createCell(5);
            cell9.setCellStyle(cellStyleNoLine);
            row3.createCell(4).setCellStyle(cellStyleNoLine);
            row3.createCell(6).setCellStyle(cellStyleNoLine);
            row3.createCell(7).setCellStyle(cellStyleNoLine);
            cell9.setCellValue(contract.getUniqueNumber());
            sheet.addMergedRegion(new CellRangeAddress(num, num, 5, 7));
            sheet.addMergedRegion(new CellRangeAddress(num, num, 3, 4));
            sheet.addMergedRegion(new CellRangeAddress(num, num, 1, 2));
            num++;
            HSSFRow row4 = sheet.createRow(num);
            HSSFCell cell10 = row4.createCell(0);
            HSSFCell cell11 = row4.createCell(1);
            HSSFCell cell12 = row4.createCell(2);
            HSSFCell cell13 = row4.createCell(3);
            HSSFCell cell14 = row4.createCell(4);
            HSSFCell cell15 = row4.createCell(5);
            HSSFCell cell16 = row4.createCell(6);
            HSSFCell cell17 = row4.createCell(7);
            cell10.setCellStyle(cellStyle);
            cell11.setCellStyle(cellStyle);
            cell12.setCellStyle(cellStyle);
            cell13.setCellStyle(cellStyle);
            cell14.setCellStyle(cellStyle);
            cell15.setCellStyle(cellStyle);
            cell16.setCellStyle(cellStyle);
            cell17.setCellStyle(cellStyle);


            cell10.setCellValue("派工编号");
            cell11.setCellValue("工作项");
            cell12.setCellValue("桩号");
            cell13.setCellValue("单位");
            cell14.setCellValue("数量");
            cell15.setCellValue("单价");
            cell16.setCellValue("合价");
            cell17.setCellValue("备注");

            row.setHeight((short) (15 * 20));
            row1.setHeight((short) (20 * 20));
            row2.setHeight((short) (32 * 20));
            row3.setHeight((short) (32 * 20));
            row4.setHeight((short) (15 * 20));
            num++;

            for (int i = 0; i < 14; i++) {
                HSSFRow row5 = sheet.createRow(num);
                HSSFCell cell18 = row5.createCell(0);
                HSSFCell cell19 = row5.createCell(1);
                HSSFCell cell20 = row5.createCell(2);
                HSSFCell cell21 = row5.createCell(3);
                HSSFCell cell22 = row5.createCell(4);
                HSSFCell cell23 = row5.createCell(5);
                HSSFCell cell24 = row5.createCell(6);
                HSSFCell cell25 = row5.createCell(7);

                cell18.setCellStyle(cellStyle);
                cell19.setCellStyle(cellStyle);
                cell20.setCellStyle(cellStyle);
                cell21.setCellStyle(cellStyle);
                cell22.setCellStyle(cellStyle);
                cell23.setCellStyle(cellStyle);
                cell24.setCellStyle(cellStyle);
                cell25.setCellStyle(cellStyle);
                row5.setHeight((short) (19 * 20));
                num++;
            }
            HSSFRow row9 = sheet.createRow(num);
            HSSFCell cell18 = row9.createCell(0);
            cell18.setCellValue("管理中心经办人");
            HSSFCell cell19 = row9.createCell(1);

            HSSFCell cell20 = row9.createCell(2);
            cell20.setCellValue("日期");
            HSSFCell cell21 = row9.createCell(3);

            HSSFCell cell22 = row9.createCell(4);
            cell22.setCellValue("管理中心审核人");
            HSSFCell cell23 = row9.createCell(5);
            HSSFCell cell24 = row9.createCell(6);
            HSSFCell cell25 = row9.createCell(7);
            cell24.setCellValue("日期");

            num++;
            HSSFRow row10 = sheet.createRow(num);
            HSSFCell cell27 = row10.createCell(0);
            cell27.setCellValue("管理中心负责人");
            HSSFCell cell28 = row10.createCell(1);

            HSSFCell cell29 = row10.createCell(2);
            cell29.setCellValue("日期");
            HSSFCell cell30 = row10.createCell(3);

            HSSFCell cell31 = row10.createCell(4);
            cell31.setCellValue("养护部审核人");
            HSSFCell cell32 = row10.createCell(5);
            HSSFCell cell33 = row10.createCell(6);
            HSSFCell cell34 = row10.createCell(7);
            cell33.setCellValue("日期");
            num++;

            row9.setHeight((short) (32 * 20));
            row10.setHeight((short) (32 * 20));
        }
        return workbook;
    }


    /**
     * 按照时间导出工单
     * @param
     * @param response
     */
    @Override
    public void exportWorkOrders(String startTime, String endTime, String contractId, String type, HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(contractId)) {
                throw new RuntimeException("请选择对应合同");
            }
            long time = System.currentTimeMillis();
            String fileName = "工单信息" + time;
            File file = new File(fileName);
            if (!file.exists()) {
                file.mkdirs();
            }
            Contract contract = contractManager.getById(contractId);
            QueryWrapper<WorkOrderInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("END_TIME_", startTime);
            queryWrapper.le("END_TIME_", endTime);
            queryWrapper.eq("CONTRACT_ID_", contract.getId());
            queryWrapper.eq("ROAD_SEGMENT_ID_", contract.getRoadSegmentId());
            List<WorkOrderInformation> workOrderInformations = baseMapper.selectList(queryWrapper);
            Road road = roadManager.getById(contract.getRoadSegmentId());

            HSSFWorkbook workbook = getExportSheets(endTime, contract, workOrderInformations, road);


            try {
                OutputStream os = new FileOutputStream(file + "/" + road.getName() + "季度结算明细表" + ".xls");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("导出失败！");
            }
            PoiStyleUtil.zip(fileName, true);
            String zip = fileName + ".zip";

            HttpUtil.downLoadFile(response, zip, zip);
            // 删除导出的文件
            FileUtil.deleteFile(zip);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败");
        }
    }

    @Override
    public List<User> getPrincipal(String userId) {
        String currentOrgId = ContextUtil.getCurrentOrgId(userId);
        QueryWrapper<OrgUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ORG_ID_", currentOrgId);
        List<OrgUser> orgUserList = orgUserManager.list(queryWrapper);

        String[] userIds = orgUserList.stream().map(OrgUser::getUserId).toArray(String[]::new);
        List<User> listUser = new ArrayList<>();
        if (userIds.length > 0) {
            QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.in("ID_", userIds);
            listUser = userManager.list(queryWrapper1);
        }
        if (listUser.size() < 0) {
            throw new RuntimeException("未找到承包方负责人");
        }
        return listUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleWorkOrderInformation(String ids) {
        // 获取当前登录人id
        String userId = baseContext.getCurrentUserId();

        if (StringUtils.isEmpty(ids)) {
            throw new RuntimeException("选择需要删除的工单");
        }
        try {
            List<String> idLList = Arrays.asList(ids.split(","));
            for (String id : idLList) {
                List<DefaultBpmProcessInstance> listBpmProInst = this.baseMapper.selectBpmProInst(id);
                if (listBpmProInst.size() > 0) {
                    for (DefaultBpmProcessInstance defaultBpmProcessInstance : listBpmProInst) {
                        //非创建人不允许删除(不包括admin)
                        IUser user= ContextUtil.getCurrentUser();

                        boolean admin = user.isAdmin();
                        if(!admin){
                            if ((!userId.equals(defaultBpmProcessInstance.getCreateBy()))){
                                return false;
                            }
                        }

                        List<DefaultBpmTask> defaultBpmTaskList = this.baseMapper.selectDefaultBpmTask(defaultBpmProcessInstance.getId());
                        for (DefaultBpmTask defaultBpmTask : defaultBpmTaskList) {
                            if (defaultBpmTask != null) {
                                //只允许删除前三节点
                                if ("UserTask7".equals(defaultBpmTask.getNodeId()) || "UserTask1".equals(defaultBpmTask.getNodeId())
                                        ||"UserTask2".equals(defaultBpmTask.getNodeId())) {
                                    this.deleteById(id);
                                    bpmProcessInstanceDao.deleteById(defaultBpmProcessInstance.getId());
                                    this.deleteById(defaultBpmTask.getId());
                                } else {
                                    return false;
                                }
                            }
                        }

                    }
                }else {
                    this.deleteById(id);
                }



            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id){
        WorkOrderInformation workOrderInformation = this.getById(id);
        if(null != workOrderInformation){
            workOrderInformation.setIsDele("1");
            workOrderInformation.setUpdateTime(LocalDateTime.now());

            this.update(workOrderInformation);
        }

    }


    @Override
    public List<WorkOrderInformation> listFinishWork(String rodeSegmentId, String first, String last) {
        return baseMapper.listFinishWork(rodeSegmentId, first, last);
    }

    @Override
    public List<WorkOrderInformation> listWorkAll(String rodeSegmentId, String first, String last) {
        return baseMapper.listWorkAll(rodeSegmentId, first, last);

    }

    @Override
    public List<WorkOrderInformation> getWorkOrderContract(String contractId, WorkOrderParamVo param) {
        List<WorkOrderInformation> list = this.list(new LambdaQueryWrapper<WorkOrderInformation>().eq(WorkOrderInformation::getContractId, contractId)
                .ge(param.getStartTime() != null, WorkOrderInformation::getIssueDate, param.getStartTime())
                .le(param.getEndTime() != null, WorkOrderInformation::getIssueDate, param.getEndTime()));
        return list;
 /*       if (list.size() > 0) {
            List<String> collect = list.stream().map(WorkOrderInformation::getId).collect(Collectors.toList());
            List<BillOfQuantities> billOfQuantitiesList = billOfQuantitiesManager.list(new LambdaQueryWrapper<BillOfQuantities>().eq(BillOfQuantities::getBillType, "1").in(BillOfQuantities::getWorkOrderInformationId, collect));
            return billOfQuantitiesList;
        } else {
            return new ArrayList<BillOfQuantities>();
        }*/
    }

    //判断季度
    public int getSeason(Date date) {

        int season = 0;

        Calendar c = Calendar.getInstance();

        c.setTime(date);

        int month = c.get(Calendar.MONTH);

        switch (month) {

            case Calendar.JANUARY:

            case Calendar.FEBRUARY:

            case Calendar.MARCH:

                season = 1;

                break;

            case Calendar.APRIL:

            case Calendar.MAY:

            case Calendar.JUNE:

                season = 2;

                break;

            case Calendar.JULY:

            case Calendar.AUGUST:

            case Calendar.SEPTEMBER:

                season = 3;

                break;

            case Calendar.OCTOBER:

            case Calendar.NOVEMBER:

            case Calendar.DECEMBER:

                season = 4;

                break;

            default:

                break;

        }

        return season;

    }


    /**
     * 获取养护资金执行情况报表
     * @param
     * @param
     * @return
     */
    @Override
    public PageList<OrderCashVo> getOrderCashReport(QueryFilter<YearBudget> queryFilter) {

        queryFilter.addFilter("IS_DELE_", "0", QueryOP.EQUAL);
        PageList<YearBudget> pageList = yearBudgetManager.queryYearBuget(queryFilter);

        PageList page = new PageList<OrderCashVo>();
        BeanUtils.copyProperties(pageList,page);

        List<YearBudget> rows = pageList.getRows();
        if(null == rows || rows.size() == 0){
            return page;
        }

        List<OrderCashVo> cashVos = new ArrayList<>();


        List<String> pids = StreamUtil.toList(rows,YearBudget::getId);


        //批量查询渲染
        QueryWrapper<YearBudgetDetailed> wrapper = new QueryWrapper<>();
        wrapper.in("YEAR_BUDGET_ID_",pids);
        wrapper.eq("IS_DELE_",0);
        List<YearBudgetDetailed> detailedList = yearBudgetDetailedManager.list(wrapper);
        Map<String, List<YearBudgetDetailed>> detailMap = detailedList.stream().collect(Collectors.groupingBy(YearBudgetDetailed::getYearBudgetId));


        for (YearBudget entity : rows) {

            OrderCashVo orderCashVo = new OrderCashVo();

            orderCashVo.setCompanyName(entity.getCompanyName());
            orderCashVo.setRoadName(entity.getRoadSegmentName());
//            OrderCashVo.setAscriptionYear(entity.getAscriptionYear());
            //合计
            orderCashVo.setFundTotal(entity.getBudgetSum());
            //执行合计
            orderCashVo.setFundTotalAbort(entity.getAlreadyCount());
            //完成年度百分比合计
            if(entity.getAlreadyCount().compareTo(BigDecimal.ZERO)!=0 && entity.getBudgetSum().compareTo(BigDecimal.ZERO)!=0){
                BigDecimal percentageTotal = entity.getAlreadyCount().divide(entity.getBudgetSum(), 2, BigDecimal.ROUND_HALF_DOWN);
                orderCashVo.setPercentageTotal(percentageTotal+"%");
            }else {
                orderCashVo.setPercentageTotal(BigDecimal.ZERO+"%");
            }


            //日常和专项

            List<YearBudgetDetailed> list = detailMap.get(entity.getId());
            if(null == list || list.isEmpty()){
                orderCashVo.setFundDaily(BigDecimal.ZERO);
                orderCashVo.setFundSpecial(BigDecimal.ZERO);
            }else {
                BigDecimal fundDailyAbort = new BigDecimal(0);
                BigDecimal fundDaily = new BigDecimal(0);
                BigDecimal fundSpecialAbort = new BigDecimal(0);
                BigDecimal fundSpecial = new BigDecimal(0);

                for (YearBudgetDetailed budgetDetailed : list) {
                    //日常养护
                    if(null ==budgetDetailed.getImageProgress()){
                        budgetDetailed.setImageProgress(BigDecimal.ZERO);
                    }
                    if(null ==budgetDetailed.getTotalPrice()){
                        budgetDetailed.setTotalPrice(BigDecimal.ZERO);
                    }

                    if("RCJF".equals(budgetDetailed.getBudgetType())){
                        fundDailyAbort=fundDailyAbort.add(budgetDetailed.getImageProgress());
                        fundDaily=fundDaily.add(budgetDetailed.getTotalPrice());
                    }else {
                        //专项养护
                        fundSpecialAbort=fundDailyAbort.add(budgetDetailed.getImageProgress());
                        fundSpecial=fundDaily.add(budgetDetailed.getTotalPrice());
                    }
                }
                //日常养护已用
                orderCashVo.setFundDailyAbort(fundDailyAbort);

                orderCashVo.setFundDaily(fundDaily);
                //专项养护已用
                orderCashVo.setFundSpecialAbort(fundSpecialAbort);
                orderCashVo.setFundSpecial(fundSpecial);

                //完成年度百分比-日常
                if(fundDailyAbort.compareTo(BigDecimal.ZERO)!=0 && fundDaily.compareTo(BigDecimal.ZERO)!=0){
                    BigDecimal percentageDaily = fundDailyAbort.divide(entity.getBudgetSum(), 2, BigDecimal.ROUND_HALF_DOWN);
                    orderCashVo.setPercentageDaily(percentageDaily+"%");
                }else {
                    orderCashVo.setPercentageDaily(BigDecimal.ZERO+"%");
                }

                //完成年度百分比-专项
                if(fundSpecialAbort.compareTo(BigDecimal.ZERO)!=0 && fundSpecial.compareTo(BigDecimal.ZERO)!=0){
                    BigDecimal percentageSpecial =fundSpecialAbort.divide(fundSpecial, 2, BigDecimal.ROUND_HALF_DOWN);
                    orderCashVo.setPercentageSpecial(percentageSpecial+"%");
                }else {
                    orderCashVo.setPercentageSpecial(BigDecimal.ZERO+"%");
                }
            }

            cashVos.add(orderCashVo);
        }
        page.setRows(cashVos);

         return page;
    }


    @Resource
    BizProjectBeginApplyForManager bizProjectBeginApplyForManager;
    @Resource
    MeasurementPaymentManager measurementPaymentManager;


    @Override
    public PageList<OrderSpecialCashVo> getOrderSpecialCashReport(QueryFilter<BizEngineeringProject> queryFilter) {


        queryFilter.addFilter("is_dele_","0", QueryOP.EQUAL);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(baseContext.getCurrentOrgId()) ){
            permissionUtils.addPermission(queryFilter);
        }
        PageBean pageBean = queryFilter.getPageBean();
        pageBean.setPageSize(PageBean.WITHOUT_PAGE);
        pageBean.setPage(1);
        queryFilter.setPageBean(pageBean);
        PageList<BizEngineeringProject> pageList = bizEngineeringProjectManager.queryBizEngineeringProject(queryFilter);
        PageList<OrderSpecialCashVo> page = new PageList<>();
        BeanUtils.copyProperties(pageList,page);

        List<BizEngineeringProject> rows = pageList.getRows();

        if(null == rows || rows.size() == 0){
            return page;
        }
        ArrayList<OrderSpecialCashVo> cashVos = new ArrayList<>();


        List<String> projectIds = StreamUtil.toList(rows, BizEngineeringProject::getId);





        //开工时间 批量查询
        QueryWrapper<BizProjectBeginApplyFor> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("PROJECT_ID_",projectIds);
        queryWrapper.eq("IS_DELE_",0);

        List<BizProjectBeginApplyFor> applyForList = bizProjectBeginApplyForManager.list(queryWrapper);




        Map<String, List<BizProjectBeginApplyFor>> projectApplyMap = null;

        if(null != applyForList && !applyForList.isEmpty()){
            projectApplyMap = applyForList.stream().collect(Collectors.groupingBy(BizProjectBeginApplyFor::getProjectId));

        }
        QueryWrapper<MeasurementPayment> paymentQueryWrapper = new QueryWrapper<>();
        paymentQueryWrapper.in("PROJECT_ID_",projectIds);
        paymentQueryWrapper.eq("IS_DELE_",0);

        List<MeasurementPayment> measurementPayments = measurementPaymentManager.list(paymentQueryWrapper);


        Map<String, List<MeasurementPayment>> measurementPaymentMap = null;
        if(null != measurementPayments && !measurementPayments.isEmpty()){
            measurementPaymentMap = measurementPayments.stream().collect(Collectors.groupingBy(MeasurementPayment::getProjectId));

        }




        for (BizEngineeringProject row : rows) {


            OrderSpecialCashVo cashVo = new OrderSpecialCashVo();

            cashVo.setCompanyName(row.getCompanyName());
            cashVo.setRoadName(row.getRoadSegmentName());
            cashVo.setProjectName(row.getProjectName());
            cashVo.setProjectYear(row.getProjectYear());
            if(null != projectApplyMap){
                List<BizProjectBeginApplyFor> applys = projectApplyMap.get(row.getId());
                if(null != applys && !applys.isEmpty()){
                    BizProjectBeginApplyFor applyFor = applys.get(0);
                    cashVo.setStartTime(applyFor.getStartupTime().toString());
                    if(null != applyFor.getActualCompleteTime()){
                        cashVo.setDeliverTime(applyFor.getActualCompleteTime().toString());
                    }else {
                        cashVo.setDeliverTime(applyFor.getExpectedCompleteTime().toString());
                    }


                }
            }
            if(row.getStartupFlag() == 0){
                cashVo.setStartTime("未开工");
                cashVo.setDeliverTime(null);
            }



            if(null != measurementPaymentMap){
                List<MeasurementPayment> payments = measurementPaymentMap.get(row.getId());
                if(null != payments  && payments.size() >0){
                    BigDecimal paymentsMoney = payments.stream().filter(e -> null != e.getPaymentCashs()).map(MeasurementPayment::getPaymentCashs).reduce(BigDecimal.ZERO, BigDecimal::add);

                    BigDecimal projectMoney = row.getProjectMoney();

                    if(paymentsMoney.compareTo(BigDecimal.ZERO) !=0 && null != projectMoney && projectMoney.compareTo(BigDecimal.ZERO) !=0){

                        BigDecimal scale = paymentsMoney.divide(projectMoney, 4, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100));


                        cashVo.setPercentageMeasurement(scale+"%");

                    }else {
                        cashVo.setPercentageMeasurement(0+"%");
                    }
                }

            }else {
                cashVo.setPercentageMeasurement(0+"%");
            }
            //TODO 预算金额
//            cashVo.setAnnualBudgetCash();


            cashVo.setConstructUnit(row.getConstructUnit());
            cashVo.setConstructUnitPersonLiable(row.getConstructUnitPersonLiable());

            cashVo.setContractCash(row.getProjectMoney());

//            cashVo.setConstructLocation();
//            cashVo.setConstructType();
//            cashVo.setConstructUnitPersonTel();

            cashVo.setWorkProgress(row.getWorkProgress());




            cashVos.add(cashVo);
        }

        return page;
    }


    @Override
    public void orderItemCountReportExport(QueryFilter<WorkOrderInformation> queryFilter, HttpServletResponse response) throws IOException {
        PageList<OrderItemCountVo> orderItemCountVoPageList = orderItemCountReport(queryFilter);
        List<OrderItemCountVo> lists = orderItemCountVoPageList.getRows();
        if (null == lists || lists.isEmpty()) {
            throw new RuntimeException("暂无数据导出！");
        }

        long time = System.currentTimeMillis();
        String fileName = "日常养护工单科目统计报表" + time;
        File file = new File(fileName);
        if (!file.exists()) {
            file.mkdirs();
        }


        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("日常养护工单科目统计报表");
        sheet.setColumnWidth(0, 15 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 15 * 256);
        sheet.setColumnWidth(3, 15 * 256);
        sheet.setColumnWidth(4, 15 * 256);
        sheet.setColumnWidth(5, 15 * 256);
        sheet.setColumnWidth(6, 15 * 256);
        sheet.setColumnWidth(7, 15 * 256);
        sheet.setColumnWidth(8, 15 * 256);
        sheet.setColumnWidth(9, 8 * 256);
        sheet.setColumnWidth(10, 8 * 256);



        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFCellStyle cellStyleTitle = workbook.createCellStyle();
        HSSFCellStyle cellStyleLeft = workbook.createCellStyle();
        HSSFCellStyle cellStyleLeftAlign = workbook.createCellStyle();
        HSSFCellStyle cellStyleRight = workbook.createCellStyle();
        HSSFCellStyle cellStyleSmall = workbook.createCellStyle();
        HSSFCellStyle cellStyleNoLine = workbook.createCellStyle();
        HSSFCellStyle cellStyleTitleNoLine = workbook.createCellStyle();
        setExcelStyle(cellStyle, workbook);
        PoiStyleUtil.setExcelStyleNoLine(cellStyleNoLine, workbook);
        PoiStyleUtil.setExcelStyleSmall(cellStyleSmall, workbook);
        PoiStyleUtil.setExcelStyleTitleOne(cellStyleTitle, workbook);
        PoiStyleUtil.setExcelStyleTitleNoLine(cellStyleTitleNoLine, workbook);
        PoiStyleUtil.setExcelStyleLeft(cellStyleLeft, workbook);
        PoiStyleUtil.setExcelStyleRight(cellStyleRight, workbook);
        PoiStyleUtil.setExcelStyleLeftAlign(cellStyleLeftAlign, workbook);



        HSSFRow row = sheet.createRow(0);
//        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));


        HSSFCell cell = row.createCell(0);
        cell.setCellValue("日常养护工单科目统计报表");



        cell.setCellStyle(cellStyleNoLine);
        row.createCell(1).setCellStyle(cellStyleNoLine);
        row.createCell(2).setCellStyle(cellStyleNoLine);
        row.createCell(3).setCellStyle(cellStyleNoLine);
        row.createCell(4).setCellStyle(cellStyleNoLine);
        row.createCell(5).setCellStyle(cellStyleNoLine);
        row.createCell(6).setCellStyle(cellStyleNoLine);
        row.createCell(7).setCellStyle(cellStyleNoLine);
        row.createCell(8).setCellStyle(cellStyleNoLine);
        row.createCell(9).setCellStyle(cellStyleNoLine);
        row.createCell(10).setCellStyle(cellStyleNoLine);

        HSSFCellStyle cellStyleTitleNoLineSmall = workbook.createCellStyle();

        PoiStyleUtil.cellStyleTitleNoLineSmall(cellStyleTitleNoLineSmall, workbook);


        HSSFCell cell01 = row.createCell(0);
        cell01.setCellStyle(cellStyleTitleNoLineSmall);
        cell01.setCellValue("路段");

        HSSFCell cell02 = row.createCell(1);
        cell02.setCellValue("成本科目");
        cell02.setCellStyle(cellStyleTitleNoLineSmall);

        HSSFCell cell03 = row.createCell(2);
        cell03.setCellStyle(cellStyleTitleNoLineSmall);
        cell03.setCellValue("已完成");

        HSSFCell cell04 = row.createCell(3);
        cell04.setCellStyle(cellStyleTitleNoLineSmall);
        cell04.setCellValue("施工中");

        HSSFCell cell05 = row.createCell(4);
        cell05.setCellStyle(cellStyleTitleNoLineSmall);
        cell05.setCellValue("已逾期");

        HSSFCell cell06 = row.createCell(5);
        cell06.setCellStyle(cellStyleTitleNoLineSmall);
        cell06.setCellValue("合同金额");

        HSSFCell cell07 = row.createCell(6);
        cell07.setCellStyle(cellStyleTitleNoLineSmall);
        cell07.setCellValue("完成金额");

        HSSFCell cell08 = row.createCell(7);
        cell08.setCellStyle(cellStyleTitleNoLineSmall);
        cell08.setCellValue("执行率");



//        sheet.addMergedRegion(new CellRangeAddress(0 - 1, 0, 6, 6));



        int num =0;
        for (OrderItemCountVo vo : lists) {
            num++;
            HSSFRow row1= sheet.createRow(num);

            HSSFCell cell1 = row1.createCell(0);
            cell1.setCellValue("路段");
            HSSFCell cell2 = row1.createCell(1);
            cell2.setCellValue("成本科目");
            HSSFCell cell3 = row1.createCell(2);
            cell3.setCellValue("已完成");
            HSSFCell cell4 = row1.createCell(3);
            cell4.setCellValue("施工中");
            HSSFCell cell5 = row1.createCell(4);
            cell5.setCellValue("已逾期");
            HSSFCell cell6 = row1.createCell(5);
            cell6.setCellValue("合同金额");
            HSSFCell cell7 = row1.createCell(6);
            cell7.setCellValue("完成金额");

            HSSFCell cell8 = row1.createCell(7);
            cell8.setCellValue("执行率");


            cell1.setCellValue(vo.getRoadName());
            cell2.setCellValue(vo.getItemName());
            cell3.setCellValue(vo.getFinishCount().toString());
            cell4.setCellValue(vo.getConstructionCount().toString());
            cell5.setCellValue(vo.getOverdueCount().toString());
            cell6.setCellValue(vo.getContractMoney().toString());
            cell7.setCellValue(vo.getFinishMoney().toString());
            cell8.setCellValue(vo.getImplementationRate());


        }

        try {
            OutputStream os = new FileOutputStream(file + "/" + "日常养护工单科目统计报表" + ".xls");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出列表失败！");
        }

        PoiStyleUtil.zip(fileName, true);
        String zip = fileName + ".zip";

        HttpUtil.downLoadFile(response, zip, zip);
        // 删除导出的文件
        FileUtil.deleteFile(zip);

    }



//        List<QueryField> querys = queryFilter.getQuerys();
//
//        Workbook workbook = null;
//
//        try {
//            ServletOutputStream outputStream = response.getOutputStream();
//
//            workbook = ExcelExportUtil.exportExcel(new ExportParams( "养护工单科目统计报表",   "养护工单科目统计报表"), OrderItemCountVo.class, rows);
//
//            String fileName = "养护工单科目统计报表" + System.currentTimeMillis() + ".xls";
//
//            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
//
//            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//            response.setContentType("application/x-download");
//            response.setCharacterEncoding("UTF-8");
//            response.addHeader("Pargam", "no-cache");
//            response.addHeader("Cache-Control", "no-cache");
//            response.flushBuffer();
//            workbook.write(outputStream);
//            outputStream.flush();
//        } catch (IOException e) {
//            throw new RuntimeException("导出文件失败,请重试");
//        }
//







    /**
     * 养护资金导出
     * @param queryFilter
     * @param response
     */
    @Override
    public void exportOrderCashReport(QueryFilter<YearBudget> queryFilter, HttpServletResponse response) {

            PageList<OrderCashVo> cashReport = getOrderCashReport(queryFilter);
            List<OrderCashVo> rows = cashReport.getRows();

            if (null == rows || rows.isEmpty()) {
                throw new RuntimeException("暂无数据导出！");
            }
            Integer year = rows.get(0).getAscriptionYear();
            Workbook workbook = null;
            int count = 0;
            try {
                ServletOutputStream outputStream = response.getOutputStream();

                long q2 = System.currentTimeMillis();
                workbook = ExcelExportUtil.exportExcel(new ExportParams( year +"年度养护资金执行情况",  year +"年度养护资金执行情况"), OrderCashVo.class, rows);

                String fileName = year + "年度养护资金执行情况" + System.currentTimeMillis() + ".xls";

                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.setContentType("application/x-download");
                response.setCharacterEncoding("UTF-8");
                response.addHeader("Pargam", "no-cache");
                response.addHeader("Cache-Control", "no-cache");
                response.flushBuffer();
                workbook.write(outputStream);
                outputStream.flush();
            } catch (IOException e) {
                throw new RuntimeException("导出文件失败,请重试");
            }
    }


    /**
     * 获取工单科目统计报表
     * @return
     */
    @Override
    public PageList<OrderItemCountVo> orderItemCountReport(QueryFilter<WorkOrderInformation> queryFilter) {

        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }

        List<String> roadList = new ArrayList<>();



        if (ObjectUtils.isEmpty(map.get("croadSegmentId"))){
            QueryWrapper<Road> roadQueryWrapper = new QueryWrapper<>();
            roadQueryWrapper.like(StringUtils.isNotEmpty(baseContext.getCurrentOrgId()), "COMPANY_IDS_", baseContext.getCurrentOrgId());
            roadList = roadManager.list(roadQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
            queryFilter.addFilter("croadSegmentId", roadList, QueryOP.IN);
        }

        List<QueryField> querys = queryFilter.getQuerys();


        for (QueryField query : querys) {
            if(query.getProperty().equals("croadSegmentId")){
                query.setProperty("a.ROAD_SEGMENT_ID_");
            }

            if(query.getProperty().equals("cissueDate")){
                query.setProperty("a.ISSUE_DATE_");
            }
            if(query.getProperty().equals("companyId")){
                query.setProperty("road.COMPANY_ID");
                query.setOperation(QueryOP.IN);

            }
        }



        IPage<OrderItemCountVo> result =workOrderInformationDao.orderItemCountReport(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()));

        List<OrderItemCountVo> records = result.getRecords();

        for (OrderItemCountVo record : records) {
            BigDecimal finishMoney = record.getFinishMoney();

            BigDecimal contractMoney = record.getContractMoney();

            BigDecimal divide = finishMoney.divide(contractMoney, BigDecimal.ROUND_HALF_UP,4);

            BigDecimal multiply = divide.multiply(BigDecimal.valueOf(100)).setScale(2);


            record.setImplementationRate(multiply+"%");
        }


        return new PageList<>(result);
    }





    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(String id, Integer state) {
        User currentUser = ContextUtil.getCurrentUser();
        WorkOrderInformationVo vo = this.getVo(id);
        WorkOrderInformation workOrderInformation = vo.getWorkOrderInformation();
        workOrderInformation.setApproveState(state);
        workOrderInformation.setUpdateBy(currentUser.getId());
        this.update(workOrderInformation);
        //作废需要减去金额
        if(state == 0){
            //计算已用金额
            Double zf = 0.0;
            List<BillOfQuantities> billOfQuantities = vo.getBillOfQuantities();
            for(BillOfQuantities billOfQuantitie : billOfQuantities){
                Float auditMoney = billOfQuantitie.getTaxMoney();
                if (auditMoney!=null){
                    zf = ArithUtil.add(zf, auditMoney);
                }
            }
            //修改预算使用金额

            if(zf > 0){
                String roadSegmentId = workOrderInformation.getRoadSegmentId();
                QueryFilter<YearBudget> queryFilter = QueryFilter.build();
                queryFilter.addFilter("ASCRIPTION_YEAR_", workOrderInformation.getEndTime().getYear(), QueryOP.EQUAL);
                queryFilter.addFilter("ROAD_SEGMENT_ID_", roadSegmentId, QueryOP.EQUAL);
                queryFilter.addFilter("IS_DELE_", "0", QueryOP.EQUAL);
                List<YearBudget> yearBudgetList = yearBudgetManager.queryNoPage(queryFilter);
                if(null != yearBudgetList && yearBudgetList.size() > 0){
                    for (YearBudget yearBudget : yearBudgetList){
                        //计算形象金额
                        QueryWrapper<YearBudgetDetailed> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("YEAR_BUDGET_ID_",yearBudget.getId());
                        queryWrapper.eq("IS_DELE_","0");
                        queryWrapper.eq("EXPENDITURE_TYPE_","FXCBXZC");
                        queryWrapper.eq("BUDGET_TYPE_","RCJF");
                        queryWrapper.eq("BUDGET_ITEM_","RCYH");
                        queryWrapper.eq("BUDGET_CONTENT","日常养护");
                        List<YearBudgetDetailed> detaileds = yearBudgetDetailedManager.list(queryWrapper);
                        for (YearBudgetDetailed detailed:detaileds){
                            BigDecimal imageProgress = detailed.getImageProgress();
                            if (imageProgress==null){
                                imageProgress=new BigDecimal(0);
                            }
                            BigDecimal bigDecimal = imageProgress.subtract(BigDecimal.valueOf(zf/10000));
                            detailed.setImageProgress(bigDecimal);
                            yearBudgetDetailedManager.update(detailed);
                        }

                        yearBudget.setAlreadyCount(yearBudgetDetailedDao.sumImageProgress(yearBudget.getId()));
                        yearBudgetManager.updateById(yearBudget);
                    }
                }
            }
            //不通过需要发送消息提醒管理中心处理人，记录由谁审核，什么时间审核未通过
            String maintenanceDeptId = workOrderInformation.getMaintenanceDeptId();
            User receiverUser = userManager.getById(maintenanceDeptId);
            LocalDate now = LocalDate.now();
            String msg= "<p>消息提醒：<br/>您的养护工单-工单号【"+workOrderInformation.getJobNumber()+"】在"+now+"已经被驳回，请重新发起养护工单!</p>";

            JmsMessage jmsMessage = new JmsMessage();
            jmsMessage.setContent(msg);
            jmsMessage.setType("inner");
            jmsMessage.setTypeKey("bpmnTaskTrans");
            jmsMessage.setSubject("驳回提醒");

            //发送人
            JmsActor sender = new JmsActor();
            sender.setId(currentUser.getId());
            sender.setAccount(currentUser.getAccount());
            sender.setName(currentUser.getFullname());
            sender.setEmail(currentUser.getEmail());
            sender.setMobile(currentUser.getMobile());
            sender.setWeixin(currentUser.getWeixin());
            sender.setClientId(currentUser.getClientId());
            sender.setClientToken(currentUser.getClientToken());
            jmsMessage.setSender(sender);

            //接收人
            JmsActor receiver = new JmsActor();
            receiver.setId(maintenanceDeptId);
            receiver.setAccount(receiverUser.getAccount());
            receiver.setName(receiverUser.getFullname());
            receiver.setEmail(receiverUser.getEmail());
            receiver.setMobile(receiverUser.getMobile());
            receiver.setWeixin(receiverUser.getWeixin());
            receiver.setClientId(receiverUser.getClientId());
            receiver.setClientToken(receiverUser.getClientToken());



            List<JmsActor> receivers= Arrays.asList(receiver);
            jmsMessage.setReceivers(receivers);

            JmsHandler jmsHandler = innerHandler;
            jmsHandler.send(jmsMessage);
        }
    }



    /**
     * 重大专项导出
     * @param queryFilter
     * @param response
     */
    @Override
    public void exportOrderSpecialCashReport(QueryFilter<BizEngineeringProject> queryFilter, HttpServletResponse response) {
        PageList<OrderSpecialCashVo> specialCashReport = getOrderSpecialCashReport(queryFilter);
        List<OrderSpecialCashVo> rows = specialCashReport.getRows();

        if (null == rows || rows.isEmpty()) {
            throw new RuntimeException("暂无数据导出！");
        }
        String year = rows.get(0).getProjectYear();
        Workbook workbook = null;
        try {
            ServletOutputStream outputStream = response.getOutputStream();

            workbook = ExcelExportUtil.exportExcel(new ExportParams("重大养护专项情况统计表", "重大养护专项情况统计表"), OrderSpecialCashVo.class, rows);

            String fileName = year + "重大养护专项情况统计表" + System.currentTimeMillis() + ".xls";

            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/x-download");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            response.flushBuffer();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException("导出文件失败,请重试");
        }
    }
}
