package cn.axzo.msg.center.dal;

import cn.axzo.msg.center.api.enums.MsgStateV3Enum;
import cn.axzo.msg.center.dal.mapper.MessageRecordV3Mapper;
import cn.axzo.msg.center.domain.entity.MessageRecordV3;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Date;

/**
 * @author yanglin
 */
@Slf4j
@Component
public class MessageRecordV3Dao extends ServiceImpl<MessageRecordV3Mapper, MessageRecordV3> {

    public void setSendSuccess(Collection<Long> messageIds, @Nullable String imMsgId) {
        if (CollectionUtils.isEmpty(messageIds))
            return;
        lambdaUpdate()
                .eq(MessageRecordV3::getState, MsgStateV3Enum.UNSENT)
                .in(MessageRecordV3::getId, messageIds)
                .set(MessageRecordV3::getState, MsgStateV3Enum.SEND_SUCCESS)
                .set(MessageRecordV3::getUpdateAt, new Date())
                .set(MessageRecordV3::getSendTime, new Date())
                .set(StringUtils.isNotBlank(imMsgId), MessageRecordV3::getImMsgId, imMsgId)
                .update();
    }

    public void setSendSuccess(Long messageId, @Nullable String imMsgId) {
        lambdaUpdate()
                .eq(MessageRecordV3::getState, MsgStateV3Enum.UNSENT)
                .eq(MessageRecordV3::getId, messageId)
                .set(MessageRecordV3::getState, MsgStateV3Enum.SEND_SUCCESS)
                .set(MessageRecordV3::getUpdateAt, new Date())
                .set(MessageRecordV3::getSendTime, new Date())
                .set(StringUtils.isNotBlank(imMsgId), MessageRecordV3::getImMsgId, imMsgId)
                .update();
    }

    public void batchSetSendFailed(Collection<Long> messageIds, String cause) {
        if (CollectionUtils.isEmpty(messageIds)) {
            return;
        }
        lambdaUpdate()
                .eq(MessageRecordV3::getState, MsgStateV3Enum.UNSENT)
                .in(MessageRecordV3::getId, messageIds)
                .set(MessageRecordV3::getState, MsgStateV3Enum.SEND_FAILED)
                .set(MessageRecordV3::getUpdateAt, new Date())
                .set(MessageRecordV3::getSendTime, new Date())
                .set(MessageRecordV3::getFailCause, cause)
                .update();
    }
}