package com.hys.app.mapper.datasync;

import com.hys.app.framework.database.WebPage;
import com.hys.app.framework.database.mybatisplus.base.BaseMapperX;
import com.hys.app.model.datasync.dos.MessagePushDO;
import com.hys.app.model.datasync.dto.MessagePushQueryParams;
import com.hys.app.model.datasync.enums.MessagePushStatusEnum;

import java.util.List;

/**
 * 消息推送的Mapper
 *
 * @author 张崧
 * @since 2023-12-18 16:24:10
 */
public interface MessagePushMapper extends BaseMapperX<MessagePushDO> {

    default WebPage<MessagePushDO> selectPage(MessagePushQueryParams params) {
        return lambdaQuery()
                .eqIfPresent(MessagePushDO::getTargetSystem, params.getTargetSystem())
                .eqIfPresent(MessagePushDO::getBusinessType, params.getBusinessType())
                .likeIfPresent(MessagePushDO::getSummary, params.getSummary())
                .likeIfPresent(MessagePushDO::getContent, params.getContent())
                .betweenIfPresent(MessagePushDO::getProduceTime, params.getProduceTime())
                .eqIfPresent(MessagePushDO::getStatus, params.getStatus())
                .likeIfPresent(MessagePushDO::getRemark, params.getRemark())
                .orderByDesc(MessagePushDO::getId)
                .page(params);
    }

    default List<MessagePushDO> selectWaitPushList(Long lastId, int limit, int maxRetryCount){
        return lambdaQuery()
                // 查询推送失败的
                .in(MessagePushDO::getStatus, MessagePushStatusEnum.Fail)
                // 失败次数达到一定次数不再推送
                .lt(MessagePushDO::getFailCount, maxRetryCount)
                .gt(MessagePushDO::getId, lastId)
                .last("limit " + limit)
                .list();
    }

    default void updateStatus(Long id, MessagePushStatusEnum status, String remark){
        lambdaUpdate()
                .set(MessagePushDO::getStatus, status)
                .set(MessagePushDO::getRemark, remark)
                // 如果是失败，失败次数+1
                .setSql(status == MessagePushStatusEnum.Fail, "fail_count = fail_count + 1")
                .eq(MessagePushDO::getId, id)
                .update();
    }
}

