package com.tofly.gpsboot.service.es.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.es.PdaDeviceUpload;
import com.tofly.gpsboot.common.system.WorkStateEnum;
import com.tofly.es.dto.EsQueryDto;
import com.tofly.gpsboot.mapper.es.PdaDeviceUploadRepository;
import com.tofly.gpsboot.service.es.IPdaDeviceService;

import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.gpsboot.util.EsQueryUtil;
import com.tofly.gpsboot.util.EsSaveInfoUtil;
import lombok.extern.slf4j.Slf4j;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.*;

import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import org.springframework.data.elasticsearch.core.ResultsExtractor;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 *
 * @author BZ-DJJ
 */
@Service("PdaDeviceService")
@Slf4j
public class PdaDeviceServiceImpl implements IPdaDeviceService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private PdaDeviceUploadRepository pdaDeviceUploadRepository;
    @Autowired
    private EsSaveInfoUtil esSaveInfoUtil;

    @Override
    public Boolean savePdaDeviceInfo(PdaDeviceUpload pdaDeviceUpload) {
        if (null == pdaDeviceUpload.getWorkState()){
            pdaDeviceUpload.setWorkState(WorkStateEnum.WORK_STATE_WORKING.getCode());
        }
        pdaDeviceUpload.setUserId(SecurityUtils.getUserId());
        pdaDeviceUpload.setUserName(SecurityUtils.getUser().getRealName());
        pdaDeviceUpload.setDeptId(SecurityUtils.getUserDeptId());
        pdaDeviceUpload.setDeptName(SecurityUtils.getUser().getDepartemntName());
        if(null == pdaDeviceUpload.getUploadTime()){
            pdaDeviceUpload.setUploadTime(Date8Util.getCurrentDate());
        }
        pdaDeviceUploadRepository.save(pdaDeviceUpload);
        esSaveInfoUtil.checkInsertEsInfo(pdaDeviceUploadRepository.getIndex());

        return true;
    }

    @Override
    public Boolean updatePdaDeviceInfo(PdaDeviceUpload pdaDeviceUpload) {
        return pdaDeviceUploadRepository.update(pdaDeviceUpload);
    }

    @Override
    public PdaDeviceUpload getByIdPdaDeviceInfo(String id) {
        return pdaDeviceUploadRepository.findById(id).get();
    }

    @Override
    public Boolean removeByIdPdaDeviceInfo(String id) {
        pdaDeviceUploadRepository.deleteById(id);
        return true;
    }

    @Override
    public Page<List<PdaDeviceUpload>> getPageGpsInfo(Page page, EsQueryDto dto) {
        PdaDeviceUpload pdaDeviceUpload = new PdaDeviceUpload();
        QueryBuilder[] queryBuilders = EsQueryUtil.putQUery(page, dto);
        return pdaDeviceUploadRepository.getPage(pdaDeviceUpload, page, queryBuilders);
    }

    @Override
    public Page<List<PdaDeviceUpload>> getAllPage(Page page, EsQueryDto dto) {
        PdaDeviceUpload pdaDeviceUpload = new PdaDeviceUpload();
        QueryBuilder[] queryBuilders = EsQueryUtil.putQUery(page, dto);
        return pdaDeviceUploadRepository.getAllPage(pdaDeviceUpload,page,
                esSaveInfoUtil.DyMonth(pdaDeviceUploadRepository.getIndex()),elasticsearchTemplate,queryBuilders);
    }

    @Override
    public List<PdaDeviceUpload> getAll(EsQueryDto dto) {
        PdaDeviceUpload pdaDeviceUpload = new PdaDeviceUpload();
        Page page = new Page();
        page.setSize(10000);
        QueryBuilder[] queryBuilders = EsQueryUtil.putQUery(page, dto);
        return pdaDeviceUploadRepository.getAll(pdaDeviceUpload,page,
                esSaveInfoUtil.DyMonth(pdaDeviceUploadRepository.getIndex()),elasticsearchTemplate,queryBuilders);
    }

    @Override
    public List<PdaDeviceUpload> getNowUserInfoList(List<Long> userIdList, Date startTime, Date endTime) {
        EsQueryDto dto = new EsQueryDto();
        dto.setStartDate(startTime);
        dto.setEndDate(endTime);
        // 按照时间排序用户分组
        Map<Long, List<PdaDeviceUpload>> listMap = this.getAll(dto).stream().filter(u->userIdList.contains(u.getUserId())).sorted(Comparator.comparing(PdaDeviceUpload::getUploadTime).reversed()).collect(Collectors.groupingBy(PdaDeviceUpload::getUserId, Collectors.toList()));
        List<PdaDeviceUpload> result = new ArrayList<>();
        listMap.forEach((k,v) ->{
            result.add(v.get(0));
        });
        return result;
    }


    @Override
    public List<Map<String, Object>> getExportData(String dto, String templateFlag) {
        //传过来的是json字符串，也是就最后要导出的结果，所以需要进行转换
        PdaDeviceUpload pdaDeviceUpload = new PdaDeviceUpload();
        Page page = new Page();
        page.setSize(10000);
        EsQueryDto esQueryDto = new EsQueryDto();
        if(!StringUtils.isEmpty(dto)){
            esQueryDto = JSONObject.parseObject(JSON.toJSONString(dto), EsQueryDto.class);
        }
        QueryBuilder[] queryBuilders = EsQueryUtil.putQUery(page, esQueryDto);
        List records = pdaDeviceUploadRepository.getPage(pdaDeviceUpload, page, queryBuilders).getRecords();
        List<Map<String, Object>> returnMap = new ArrayList<>();
        Map<String, Object> parentMap = new HashMap<>(12);
        parentMap.put("list", records);
        returnMap.add(parentMap);
        return returnMap;
    }

    @Override
    public Boolean excelDataStorage(List<Object> dataList) {
        return null;
    }
}
