package com.yida.data.system.service;

import com.yida.data.common.core.entity.system.Log;
import com.yida.data.system.dto.ListLogDTO;
import com.yida.data.system.repository.LogEsRepository;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 日志操作es数据service层
 *
 * @author ZYJ
 * @date 2021/1/15
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LogService {

    private final LogEsRepository logEsRepository;

    /**
     * 保存操作日志数据到es
     *
     * @param systemLogInfoList 操作日志数据集合
     * @author ZYJ
     * @date 2021/1/18 13:48
     */
    public void saveLogList(List<Log> systemLogInfoList) {
        try {
            logEsRepository.saveAll(systemLogInfoList);
            log.info("logList insert es success! count:{}", systemLogInfoList.size());
        } catch (Exception e) {
            log.error("logList insert es failed!", e);
        }
    }

    /**
     * 查询日志列表数据
     *
     * @return core.operation.log.domain.LogResult<java.util.List < core.operation.log.domain.SystemLogInfo>>
     * @author ZYJ
     * @date 2021/1/18 14:32
     */
    @SuppressWarnings("deprecation")
    public Page<Log> findLogPageList(ListLogDTO dto) {
        //封装分页数据
        Pageable pageable = PageRequest.of(dto.getPageNum() - 1, dto.getPageSize());
        //封装查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
            .withPageable(pageable)
            .withSort(SortBuilders.fieldSort("createDate").order(SortOrder.DESC));

        //日志类型
        String logType = dto.getLogType();
        if (StringUtils.isNotBlank(logType)) {
            queryBuilder.withQuery(QueryBuilders.matchQuery("logType", logType));
        }
        //操作模块
        String module = dto.getModule();
        if (StringUtils.isNotBlank(module)) {
            queryBuilder.withQuery(QueryBuilders.matchQuery("module", module));
        }
        //操作方法
        String method = dto.getMethod();
        if (StringUtils.isNotBlank(method)) {
            queryBuilder.withQuery(QueryBuilders.matchQuery("method", method));
        }

        //操作参数
        String operateParams = dto.getOperateParams();
        if (StringUtils.isNotBlank(operateParams)) {
            queryBuilder.withQuery(QueryBuilders.matchQuery("operateParams", operateParams));
        }
        //操作开始时间
        LocalDateTime startTime = dto.getStartTime();
        //操作结束时间
        LocalDateTime endTime = dto.getEndTime();
        if (Optional.ofNullable(startTime).isPresent()) {
            queryBuilder.withQuery(QueryBuilders.rangeQuery("createDate").gte(startTime.toInstant(
                ZoneOffset.of("+8")
            ).toEpochMilli()).lte(endTime.toInstant(
                ZoneOffset.of("+8")
            ).toEpochMilli()));
        }
        //查询列表数据
        return logEsRepository.search(queryBuilder.build());
    }
}
