package com.yida.data.attendance.service.impl;

import com.yida.data.attendance.dto.ListErrorRecordDTO;
import com.yida.data.attendance.repository.ErrorRecordMsgRepository;
import com.yida.data.attendance.service.ErrorRecordMsgService;
import com.yida.data.common.core.entity.ErrorRecordMsg;
import com.yida.data.common.core.utils.FebsUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * 通行记录错误信息es处理service
 *
 * @author ZYJ
 * @date 2023/11/1 16:08
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class ErrorRecordMsgServiceImpl implements ErrorRecordMsgService {

    private final ErrorRecordMsgRepository errorRecordMsgRepository;

    @Override
    public void saveMsg(ErrorRecordMsg errorRecordMsg) {
        errorRecordMsgRepository.save(errorRecordMsg);
    }

    @Override
    public Page<ErrorRecordMsg> listErrorRecord(ListErrorRecordDTO dto) {
        // 封装分页数据
        Pageable pageable = PageRequest.of(dto.getPageNum() - 1, dto.getPageSize());
        // 封装查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                .withPageable(pageable)
                // 查询当前学校信息
                .withQuery(QueryBuilders.termQuery("schoolId", FebsUtil.getDeptId()))
                .withSort(SortBuilders.fieldSort("createDate").order(SortOrder.DESC));
        // 姓名
        String name = dto.getName();
        if (StringUtils.isNotBlank(name)) {
            queryBuilder.withQuery(QueryBuilders.matchQuery("msg", name));
        }
        // 操作开始时间
        LocalDateTime startTime = dto.getStartDateTime();
        // 操作结束时间
        LocalDateTime endTime = dto.getEndDateTime();
        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 errorRecordMsgRepository.search(queryBuilder.build());
    }

    @Override
    public void batchDeleteErrorRecord(String[] recordIds) {
        for (String id : recordIds) {
            if (errorRecordMsgRepository.existsById(id)) {
                errorRecordMsgRepository.deleteById(id);
            } else {
                log.error("记录id不存在: {}", id);
            }
        }
    }
}
