package com.gree.mall.manager.logic.workorder;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.es.OrderBaseEs;
import com.gree.mall.manager.bean.es.OrderBaseEsDate;
import com.gree.mall.manager.bean.es.SettlementOrderEs;
import com.gree.mall.manager.bean.listvo.param.WorkOrderZfireParam;
import com.gree.mall.manager.bean.listvo.workorder.OrderBaseVO;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.MaterialExamineStatusEnum;
import com.gree.mall.manager.enums.OrderStatusEnum;
import com.gree.mall.manager.enums.workorder.OrderTypeEnum;
import com.gree.mall.manager.es.OrderBaseEsRepository;
import com.gree.mall.manager.es.SettlementOrderEsRepository;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.PgOrderBase;
import com.gree.mall.manager.plus.entity.PgOrderFlag;
import com.gree.mall.manager.plus.entity.SettlementOrder;
import com.gree.mall.manager.plus.entity.WorkerOrder;
import com.gree.mall.manager.plus.service.PgOrderBaseService;
import com.gree.mall.manager.plus.service.SettlementOrderService;
import com.gree.mall.manager.plus.service.WorkerOrderService;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.zfire.bean.QueryParamBean;
import io.micrometer.core.instrument.search.Search;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderBaseEsLogic {


    private final OrderFlagLogic orderFlagLogic;

    private final WorkerOrderService workerOrderService;

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    private final CommonLogic commonLogic;
    private final OrderBaseEsRepository orderBaseEsRepository;
    private final PgOrderBaseService pgOrderBaseService;
    private final SettlementOrderService settlementOrderService;
    private final SettlementOrderEsRepository settlementOrderEsRepository;

    public IPage<OrderBaseVO> orderBaseEsList(WorkOrderZfireParam zfireParamBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        BoolQueryBuilder queryBuilder1 = QueryBuilders.boolQuery();
        this.montage(queryBuilder1,zfireParamBean);

        if (CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds())) {
            queryBuilder1.must(
                    QueryBuilders.boolQuery().should(QueryBuilders.termsQuery("create_websit_id", adminUser.getAdminWebsitIds()))
                    .should(QueryBuilders.termsQuery("websit_id", adminUser.getAdminWebsitIds()))
                    );

        }

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

        if (zfireParamBean.getIsWait() != null && zfireParamBean.getIsWait()){
            List<String> collect = workerOrderService.lambdaQuery()
                    .eq(WorkerOrder::getPayStatus, "WAIT")
                    .ne(WorkerOrder::getWorkerOrderId, "").select(WorkerOrder::getWorkerOrderId)
                    .list().stream().map(WorkerOrder::getWorkerOrderId).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(collect))
                return new Page<>();

            orderBaseId.addAll(collect);


        }

        if (!CollectionUtils.isEmpty(orderBaseId)){
            queryBuilder1.must(QueryBuilders.termsQuery("id",orderBaseId));
        }



        NativeSearchQuery build = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder1)
                .withSort(SortBuilders.fieldSort("create_time").order(SortOrder.DESC))
                .withPageable(PageRequest.of(zfireParamBean.getPageNum() -1, zfireParamBean.getPageSize()))
                .build();

        build.setTrackTotalHits(true);


        SearchHits<OrderBaseEs> orderBaseEsSearchHits = elasticsearchRestTemplate.search(build, OrderBaseEs.class);
        SearchPage<OrderBaseEs> searchHits = SearchHitSupport.searchPageFor(orderBaseEsSearchHits, build.getPageable());


        List<OrderBaseEs> orderBaseEs = new ArrayList<>();
        for (SearchHit<OrderBaseEs> searchHit : searchHits.getContent()) {
            orderBaseEs.add(searchHit.getContent());
        }

        IPage<OrderBaseVO> page = new Page<>();
        page.setTotal(searchHits.getSearchHits().getTotalHits());
        page.setCurrent(zfireParamBean.getPageNum());
        page.setSize(zfireParamBean.getPageSize());
        page.setRecords(BeanUtil.copyToList(orderBaseEs,OrderBaseVO.class));
        //服务单标识
        if (zfireParamBean.getPageSize() != -1 && page.getTotal() > 0) {
            List<String> orderBaseIds = page.getRecords()
                    .stream()
                    .map(OrderBaseVO::getId)
                    .collect(Collectors.toList());
            Map<String, List<PgOrderFlag>> mapList = orderFlagLogic.list(orderBaseIds);

            List<WorkerOrder> workerOrderList = workerOrderService.lambdaQuery().in(WorkerOrder::getWorkerOrderId, orderBaseIds)
                    .eq(WorkerOrder::getPayStatus, MaterialExamineStatusEnum.PAID.getKey())
                    .select(WorkerOrder::getWorkerOrderId, WorkerOrder::getTotalAmount).list();

            for (OrderBaseVO orderBaseVO : page.getRecords()) {
                orderBaseVO.setOrderFlags(mapList.get(orderBaseVO.getId()));

                List<WorkerOrder> workerOrders = workerOrderList.stream()
                        .filter(item -> item.getWorkerOrderId().equals(orderBaseVO.getId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(workerOrderList)) {
                    BigDecimal bigDecimal = workerOrders.stream().map(WorkerOrder::getTotalAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
                    orderBaseVO.setWorkerPrice(bigDecimal);
                }

            }
        }
        return page;
    }



    private void montage(BoolQueryBuilder queryBuilder, WorkOrderZfireParam workOrderZfireParam) {

        List<QueryParamBean> params = workOrderZfireParam.getParams();
        if (params == null || params.size() == 0) {
            return;
        }

        List<QueryBuilder> should = queryBuilder.should();
        for (QueryParamBean paramBean : params) {
            if (paramBean.getValue() == null)
                continue;

            String param = "";
            if (paramBean.getParam().split("\\.").length > 1){
                param = paramBean.getParam().split("\\.")[1];
            }else {
                param = paramBean.getParam();
            }
            if (paramBean.getValue() instanceof ArrayList) {
                List<String> values = (List<String>) paramBean.getValue();
                if (values != null && values.size() > 0) {
                    List<String> join = new ArrayList<>();
                    for (String s : values) {
                        join.add(s);
                    }

                    queryBuilder.must(QueryBuilders.termsQuery(param,join));
                    continue;
                }
            } else {
                String value = "";
                if (paramBean.getValue() instanceof Boolean) {
                    value = paramBean.getValue().toString();
                } else {
                    value = paramBean.getValue().toString();
                }
                if (StringUtils.isBlank(value))
                    continue;

                if (param.equals("order_status") && value.equals("DYY")
                ){

                    queryBuilder.mustNot(QueryBuilders.existsQuery("appointment_time"));
                    queryBuilder.mustNot(QueryBuilders.termsQuery("order_status", "YWG", "GCSZX", "WDWG", "YWGO", "YQX", "FWZT", "YCGB",
                                    "FWQX", "FL", "YJS", "LRCD", "DSHPG", "CJ", "YPD", "DXSPD", "DZBPG", "DWDSPGP", "DXSSPGP", "DTJXSSPGP", "DZBSPGP"));

                    continue;
                }

                if (param.equals("order_status")
                        &&  value.equals("YCD")
                ){
                    queryBuilder.must(QueryBuilders.termQuery("is_exception",true));
                    queryBuilder.mustNot(QueryBuilders.termsQuery("order_status", "YWG", "YWGO", "YJS"));
                    continue;
                }

                if (param.equals("order_status")
                        && value.equals("DJD")
                ){

                    queryBuilder.must(QueryBuilders.boolQuery()
                            .mustNot(QueryBuilders.termsQuery("order_status","YQX", "FWQX", "FL", "FWZT", "YCGB"))
                            .must(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("is_meet", false))
                                    .should(QueryBuilders.termsQuery("order_status", "DJD"))));
                    continue;
                }


                if (param.equals("order_status")
                        && value.equals("PJSQZ")
                ){
                    queryBuilder.must(QueryBuilders.termQuery("parts_apply_status","ING"));
                    continue;
                }

                if (param.equals("order_status")
                        && value.equals("PJYDH")
                ){
                    queryBuilder.must(QueryBuilders.termQuery("parts_apply_status","END"));
                    continue;
                }


                if (param.equals("order_status")
                        && value.equals("PJYQX")
                ){
                    queryBuilder.must(QueryBuilders.termQuery("parts_apply_status","CANCEL"));
                    continue;
                }

                if (StringUtils.equals(paramBean.getCompare(), "like")) {
                    queryBuilder.must(QueryBuilders.wildcardQuery(param,"*"+value+"*"));
                    continue;
                }

                if (value.equals("true") || value.equals("false")) {

                    queryBuilder.must(QueryBuilders.termQuery(param,value.equals("true")?true:false));
                    continue;
                } else {
                    if (paramBean.getCompare().equals(">=")){

                        queryBuilder.must(QueryBuilders.rangeQuery(param).gte(value));
                        continue;
                    }
                    if (paramBean.getCompare().equals("<=")){
                        queryBuilder.must(QueryBuilders.rangeQuery(param).lte(value));
                        continue;
                    }
                    queryBuilder.must(QueryBuilders.termQuery(param,value));
                    continue;
                }
            }
        }


    }

        public static String replaceValue(String value) {
            return value.replaceAll("'", "").replaceAll("\"", "")
                    .replaceAll(" or ", "").replaceAll(" union ", "");
        }


    public void test() {
  /*      boolean a = elasticsearchRestTemplate.indexOps(OrderBaseEs.class).delete();
        IndexOperations indexOperations1 = elasticsearchRestTemplate.indexOps(OrderBaseEsDate.class);
        if (!indexOperations1.exists()) {
            indexOperations1.create();
            Document document = indexOperations1.createMapping();
            indexOperations1.putMapping(document);
        }*/
        /*
        List<PgOrderBase> list = pgOrderBaseService.lambdaQuery().list();*/

       // List<OrderBaseEsDate> orderBaseEsDates = BeanUtil.copyToList(list, OrderBaseEsDate.class);
  /*      for (PgOrderBase pgOrderBase : list) {
            OrderBaseEs orderBaseEs = BeanUtil.toBean(pgOrderBase, OrderBaseEs.class);

            orderBaseEs.setDispatchTime(pgOrderBase.getDispatchTime() != null? DateUtil.format(pgOrderBase.getDispatchTime(),"yyyy-MM-dd HH:mm:ss"):null);
            orderBaseEs.setWorkerReceTime(pgOrderBase.getWorkerReceTime() != null? DateUtil.format(pgOrderBase.getWorkerReceTime(),"yyyy-MM-dd HH:mm:ss"):null);
            orderBaseEs.setDispatchWebsitTime(pgOrderBase.getDispatchWebsitTime() != null? DateUtil.format(pgOrderBase.getDispatchWebsitTime(),"yyyy-MM-dd HH:mm:ss"):null);

            orderBaseEs.setLastOperatorTime(pgOrderBase.getLastOperatorTime() != null? DateUtil.format(pgOrderBase.getLastOperatorTime(),"yyyy-MM-dd HH:mm:ss"):null);
            orderBaseEs.setAppointmentTime(pgOrderBase.getAppo() != null? DateUtil.format(pgOrderBase.getLastOperatorTime(),"yyyy-MM-dd HH:mm:ss"):null);

            orderBaseEsList.add(orderBaseEs);
        }*/

      // orderBaseEsRepository.saveAll(orderBaseEsDates);

 /*       boolean a = elasticsearchRestTemplate.indexOps(SettlementOrderEs.class).delete();
        IndexOperations indexOperations1 = elasticsearchRestTemplate.indexOps(SettlementOrderEs.class);
        if (!indexOperations1.exists()) {
            indexOperations1.create();
            Document document = indexOperations1.createMapping();
            indexOperations1.putMapping(document);
        }
*/
    }

    public List<Map<String, Object>> countStatus(String startTime, String endTime, String orderSmallType, String orderSmallTypeText) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        List<Map<String, Object>> maps = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds())) {
            List<QueryBuilder> should = queryBuilder.should();
            should.add(QueryBuilders.termsQuery("create_websit_id", adminUser.getAdminWebsitIds()));
            should.add(QueryBuilders.termsQuery("websit_id", adminUser.getAdminWebsitIds()));
        }

        if (!StringUtil.isEmpty(orderSmallTypeText))
            queryBuilder.must(QueryBuilders.termsQuery("order_small_type_text",orderSmallTypeText));


        //待预约
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("DYY", QueryBuilders.boolQuery()
                        .mustNot(QueryBuilders.existsQuery("appointment_time"))
                        .mustNot(QueryBuilders.termsQuery("order_status", "YWG", "GCSZX", "WDWG", "YWGO", "YQX", "FWZT", "YCGB",
                                "FWQX", "FL", "YJS", "LRCD", "DSHPG", "CJ", "YPD", "DXSPD", "DZBPG", "DWDSPGP", "DXSSPGP", "DTJXSSPGP", "DZBSPGP"))
                        .must(QueryBuilders.rangeQuery("create_time")
                                .gte(startTime)
                                .lte(endTime)
                        ))))
                .build();
        SearchHits response = elasticsearchRestTemplate.search(searchQuery, OrderBaseEs.class);

        HashMap<String, Object> dyy = new HashMap<>();
        dyy.put("total",this.getWorkerOrderCountResult(response.getAggregations(),"DYY"));
        dyy.put("orderStatus","DYY");

        maps.add(dyy);


        //待抢单
        NativeSearchQuery searchQueryDqd = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("DQD", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("order_status","DQD")))))
                .build();
        SearchHits responsedqd = elasticsearchRestTemplate.search(searchQueryDqd, OrderBaseEs.class);

        HashMap<String, Object> dqd = new HashMap<>();
        dqd.put("total",this.getWorkerOrderCountResult(responsedqd.getAggregations(),"DQD"));
        dqd.put("orderStatus","DQD");

        maps.add(dqd);


        //待商户派工
        NativeSearchQuery searchQueryDshpg = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("DSHPG", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termsQuery("order_status","DSHPG","CJ","YPD","DXSPD","DZBPG","DWDSPGP","DXSSPGP",
                                "DTJXSSPGP","DZBSPGP","DFZXPD","DFZXSPGP")))))
                .build();
        SearchHits responseDshpg = elasticsearchRestTemplate.search(searchQueryDshpg, OrderBaseEs.class);

        HashMap<String, Object> dshpg = new HashMap<>();
        dshpg.put("total",this.getWorkerOrderCountResult(responseDshpg.getAggregations(),"DSHPG"));
        dshpg.put("orderStatus","DSHPG");

        maps.add(dshpg);


        //待网点派工
        NativeSearchQuery searchQueryDwdpg = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("DWDPG", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termsQuery("order_status","DWDPG","DWDPD")))))
                .build();
        SearchHits responseDwdpg = elasticsearchRestTemplate.search(searchQueryDwdpg, OrderBaseEs.class);

        HashMap<String, Object> DWDPG = new HashMap<>();
        DWDPG.put("total",this.getWorkerOrderCountResult(responseDwdpg.getAggregations(),"DWDPG"));
        DWDPG.put("orderStatus","DWDPG");
        maps.add(DWDPG);


        //待接单
        NativeSearchQuery searchQueryDJD = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("DJD", QueryBuilders.boolQuery()
                        .mustNot(QueryBuilders.termsQuery("order_status","YQX", "FWQX", "FL", "FWZT", "YCGB"))
                        .must(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("is_meet", false))
                        .should(QueryBuilders.termsQuery("order_status", "DJD")))
                        )))
                .build();
        SearchHits responseDJD = elasticsearchRestTemplate.search(searchQueryDJD, OrderBaseEs.class);

        HashMap<String, Object> DJD = new HashMap<>();
        DJD.put("total",this.getWorkerOrderCountResult(responseDJD.getAggregations(),"DJD"));
        DJD.put("orderStatus","DJD");

        maps.add(DJD);

        //服务中
        NativeSearchQuery searchQueryfwz = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("FWZ", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termsQuery("order_status","FWZ","GCSZT","BFWG",
                                "DSM","YZP","WDBH", "XSBH","TJXSBH","ZBBH","FZXBH")))))
                .build();
        SearchHits responseFWZ = elasticsearchRestTemplate.search(searchQueryfwz, OrderBaseEs.class);

        HashMap<String, Object> FWZ = new HashMap<>();
        FWZ.put("total",this.getWorkerOrderCountResult(responseFWZ.getAggregations(),"FWZ"));
        FWZ.put("orderStatus","FWZ");

        maps.add(FWZ);


        //异常单
        NativeSearchQuery searchQueryYCD = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("YCD", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("is_exception",true))
                        .mustNot(QueryBuilders.termsQuery("order_status", "YWG", "YWGO", "YJS")))))
                .build();
        SearchHits responseYCD = elasticsearchRestTemplate.search(searchQueryYCD, OrderBaseEs.class);

        HashMap<String, Object> YCD = new HashMap<>();
        YCD.put("total",this.getWorkerOrderCountResult(responseYCD.getAggregations(),"YCD"));
        YCD.put("orderStatus","YCD");

        maps.add(YCD);

        //已完工待结算
        NativeSearchQuery searchQueryYWGDJS = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("YWG", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termsQuery("order_status","YWG","GCSZX","WDWG","YWGO")))))
                .build();
        SearchHits responseYWG = elasticsearchRestTemplate.search(searchQueryYWGDJS, OrderBaseEs.class);

        HashMap<String, Object> YWG = new HashMap<>();
        YWG.put("total",this.getWorkerOrderCountResult(responseYWG.getAggregations(),"YWG"));
        YWG.put("orderStatus","YWG");

        maps.add(YWG);


        //已结算
        NativeSearchQuery searchQueryYJS= new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("YJS", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termsQuery("order_status","YJS","LRCD")))))
                .build();
        SearchHits responseYJS = elasticsearchRestTemplate.search(searchQueryYJS, OrderBaseEs.class);

        HashMap<String, Object> YJS = new HashMap<>();
        YJS.put("total",this.getWorkerOrderCountResult(responseYJS.getAggregations(),"YJS"));
        YJS.put("orderStatus","YJS");

        maps.add(YJS);

        //已取消
        NativeSearchQuery searchQueryYQX = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("YQX", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termsQuery("order_status","YQX","FWZT","YCGB","FWQX","FL")))))
                .build();
        SearchHits responseYQX = elasticsearchRestTemplate.search(searchQueryYQX, OrderBaseEs.class);

        HashMap<String, Object> YQX = new HashMap<>();
        YQX.put("total",this.getWorkerOrderCountResult(responseYQX.getAggregations(),"YQX"));
        YQX.put("orderStatus","YQX");

        maps.add(YQX);


        //配件申请中
        NativeSearchQuery searchQueryPJSQZ = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("PJSQZ", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("parts_apply_status","ING")))))
                .build();
        SearchHits responsePJSQZ = elasticsearchRestTemplate.search(searchQueryPJSQZ, OrderBaseEs.class);

        HashMap<String, Object> PJSQZ = new HashMap<>();
        PJSQZ.put("total",this.getWorkerOrderCountResult(responsePJSQZ.getAggregations(),"PJSQZ"));
        PJSQZ.put("orderStatus","PJSQZ");

        maps.add(PJSQZ);


        //配件已到货
        NativeSearchQuery searchQueryPJYDH = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("PJYDH", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("parts_apply_status","END")))))
                .build();
        SearchHits responsePJYDH = elasticsearchRestTemplate.search(searchQueryPJYDH, OrderBaseEs.class);

        HashMap<String, Object> PJYDH = new HashMap<>();
        PJYDH.put("total",this.getWorkerOrderCountResult(responsePJYDH.getAggregations(),"PJYDH"));
        PJYDH.put("orderStatus","PJYDH");

        maps.add(PJYDH);


        //配件已取消
        NativeSearchQuery searchQueryPJYQX = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(PageRequest.of(1, 1))
                .addAggregation(this.getAggs(AggregationBuilders.filter("PJYQX", QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("parts_apply_status","CANCEL")))))
                .build();
        SearchHits responsePJYQX = elasticsearchRestTemplate.search(searchQueryPJYQX, OrderBaseEs.class);

        HashMap<String, Object> PJYQX = new HashMap<>();
        PJYQX.put("total",this.getWorkerOrderCountResult(responsePJYQX.getAggregations(),"PJYQX"));
        PJYQX.put("orderStatus","PJYQX");

        maps.add(PJYQX);

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

        HashMap<String, Object> DZF = new HashMap<>();
        List<String> collect = workerOrderService.lambdaQuery()
                .eq(WorkerOrder::getPayStatus, "WAIT")
                .ne(WorkerOrder::getWorkerOrderId, "").select(WorkerOrder::getWorkerOrderId)
                .list().stream().map(WorkerOrder::getWorkerOrderId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {

            orderBaseId.addAll(collect);
            //待支付
            NativeSearchQuery searchQueryDZF = new NativeSearchQueryBuilder()
                    .withQuery(queryBuilder)
                    .withPageable(PageRequest.of(1, 1))
                    .addAggregation(this.getAggs(AggregationBuilders.filter("DZF", QueryBuilders.boolQuery()
                            .must(QueryBuilders.termsQuery("id",orderBaseId))
                    )))
                    .build();
            SearchHits responseDZF = elasticsearchRestTemplate.search(searchQueryDZF, OrderBaseEs.class);
            DZF.put("total",this.getWorkerOrderCountResult(responseDZF.getAggregations(),"DZF"));
            DZF.put("orderStatus","DZF");

            maps.add(DZF);

        }

        return maps;
    }

    public AbstractAggregationBuilder<?> getAggs(FilterAggregationBuilder filter) {
        return filter.subAggregation(AggregationBuilders.sum("total_mac_sum").field("total_num"))
                .subAggregation(AggregationBuilders.terms("order_type_group").field("order_type")
                        .subAggregation(AggregationBuilders.sum("mac_sum").field("total_num")));
    }
    private long getWorkerOrderCountResult(Aggregations aggregations, String name) {
        StringBuffer sb = new StringBuffer();
        ParsedFilter parsedFilter = aggregations.get(name);
        //总服务单数
        long totalOrderNums = parsedFilter.getDocCount();

        return totalOrderNums;
    }

    public void esSync() {

        List<PgOrderBase> list = pgOrderBaseService.lambdaQuery()
                .gt(PgOrderBase::getUpdateTime,DateUtil.offsetMinute(new Date(),-5))
                .list();

        List<OrderBaseEsDate> orderBaseEsDates = BeanUtil.copyToList(list, OrderBaseEsDate.class);


        orderBaseEsRepository.saveAll(orderBaseEsDates);
    }

    public void esSync1() {
        List<SettlementOrder> list = settlementOrderService.lambdaQuery()
                .gt(SettlementOrder::getUpdateTime, DateUtil.offsetMinute(new Date(), -5))
                .list();

        List<SettlementOrderEs> orderBaseEsDates = BeanUtil.copyToList(list, SettlementOrderEs.class);


        settlementOrderEsRepository.saveAll(orderBaseEsDates);
    }

    public void del() {
    }
}
