package org.dromara.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.domain.SenEvents;
import org.dromara.mapper.SenEventsMapper;
import org.springframework.stereotype.Service;
import org.dromara.domain.bo.SenEventsReportBo;
import org.dromara.domain.vo.SenEventsReportVo;
import org.dromara.domain.SenEventsReport;
import org.dromara.mapper.SenEventsReportMapper;
import org.dromara.service.ISenEventsReportService;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 推送记录Service业务层处理
 *
 * @author luogang
 * @date 2024-09-19
 */
@RequiredArgsConstructor
@Service
public class SenEventsReportServiceImpl implements ISenEventsReportService {

    private final SenEventsReportMapper baseMapper;
    private final SenEventsMapper senEventsMapper;

    /**
     * 查询推送记录
     *
     * @param id 主键
     * @return 推送记录
     */
    @Override
    public SenEventsReportVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询推送记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 推送记录分页列表
     */
    @Override
    public TableDataInfo<SenEventsReportVo> queryPageList(SenEventsReportBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SenEventsReport> lqw = buildQueryWrapper(bo);
        Page<SenEventsReportVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的推送记录列表
     *
     * @param bo 查询条件
     * @return 推送记录列表
     */
    @Override
    public List<SenEventsReportVo> queryList(SenEventsReportBo bo) {
        LambdaQueryWrapper<SenEventsReport> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SenEventsReport> buildQueryWrapper(SenEventsReportBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SenEventsReport> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getReportPlatform()), SenEventsReport::getReportPlatform, bo.getReportPlatform());
        lqw.eq(bo.getPointId() != null, SenEventsReport::getPointId, bo.getPointId());
        lqw.like(StringUtils.isNotBlank(bo.getPointName()), SenEventsReport::getPointName, bo.getPointName());
        lqw.like(StringUtils.isNotBlank(bo.getEventName()), SenEventsReport::getEventName, bo.getEventName());
        lqw.eq(StringUtils.isNotBlank(bo.getDataContent()), SenEventsReport::getDataContent, bo.getDataContent());
        lqw.eq(StringUtils.isNotBlank(bo.getDataType()), SenEventsReport::getDataType, bo.getDataType());
        lqw.eq(StringUtils.isNotBlank(bo.getReportStatus()), SenEventsReport::getReportStatus, bo.getReportStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getReportDesc()), SenEventsReport::getReportDesc, bo.getReportDesc());
        lqw.eq(bo.getRetryNum() != null, SenEventsReport::getRetryNum, bo.getRetryNum());
        return lqw;
    }

    /**
     * 新增推送记录
     *
     * @param bo 推送记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SenEventsReportBo bo) {
        SenEventsReport add = MapstructUtils.convert(bo, SenEventsReport.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改推送记录
     *
     * @param bo 推送记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SenEventsReportBo bo) {
        SenEventsReport update = MapstructUtils.convert(bo, SenEventsReport.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SenEventsReport entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除推送记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
    /**
     * 批量重试失败推送记录
     * @param ids 主键集合
     */
    @Override
    public void againReport(Collection<Long> ids) {
        for (Long id : ids) {
            SenEventsReport senEventsReport = baseMapper.selectById(id);
            senEventsReport.setRetryNum(senEventsReport.getRetryNum() + 1);
            senEventsReport.setReportStatus("0");
            baseMapper.updateById(senEventsReport);
        }
    }
    public void reportEvents() {
        // 查询未上报的数据
        LambdaQueryWrapper<SenEvents> queryWrapper = new LambdaQueryWrapper<>();
        // 获取当天的起始时间（00:00:00）
        LocalDateTime dayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        // 获取当天的结束时间（23:59:59）
        LocalDateTime dayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        // 设置查询条件，查询当天的数据
        queryWrapper.ge(SenEvents::getCreateTime, dayStart)
                .le(SenEvents::getCreateTime, dayEnd);
        List<SenEvents> unreportedEvents = senEventsMapper.selectList(queryWrapper);
        for (SenEvents event : unreportedEvents) {
            // 检查是否已经上报过
            LambdaQueryWrapper<SenEventsReport> reportQueryWrapper = new LambdaQueryWrapper<>();
            reportQueryWrapper.eq(SenEventsReport::getEventId, event.getId());
            SenEventsReport existingReport = baseMapper.selectOne(reportQueryWrapper);
            if (existingReport == null) {
                // 上报数据
                String reportPlatform = "examplePlatform"; // 示例平台名
                String dataContent = "{}"; // 将SenEvent对象转换为JSON字符串
                SenEventsReport newReport = new SenEventsReport();
                newReport.setReportPlatform(reportPlatform);
                newReport.setPointId(event.getPointId());
                newReport.setPointName(event.getPointName());
                newReport.setEventId(event.getId());
                newReport.setEventName(event.getEventName());
                newReport.setDataContent(dataContent);
                newReport.setDataType("application/json");
                newReport.setReportStatus("0"); // 假设0表示成功
                newReport.setReportDesc("上报成功");
                newReport.setRetryNum(0);
                newReport.setCreateBy(1L);
                newReport.setCreateTime(new Date());
                baseMapper.insert(newReport);
            }
        }
    }
}
