package com.sckw.message.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.sckw.core.utils.StringUtils;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.message.model.KwmMessage;
import com.sckw.message.model.KwmMessageUser;
import com.sckw.redis.utils.RedissonUtils;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.SckwMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @desc: message消息处理service
 * @author: yzc
 * @date: 2023-06-09 11:01
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SckwMessageHandlerService {

    private final KwmMessageService kwmMessageService;
    private final KwmMessageUserService kwmMessageUserService;


    /**
     * @desc: message消息处理
     * @author: yzc
     * @date: 2023-06-09 15:33
     * @Param sckwMessage:
     * @return: void
     */
    @Transactional(rollbackFor = Exception.class)
    public void handler(SckwMessage sckwMessage) {
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(getKey(sckwMessage.getRequestId()), 10L, RedisConstant.CONSUMER_REQUEST_VALID_TIME))) {
            log.info("重复message消息：{}，不处理", sckwMessage.getRequestId());
            return;
        }
        String userIds = sckwMessage.getUserIds();
        if (StringUtils.isBlank(userIds)) {
            log.error("message消息处理用户id为空，不处理");
            return;
        }
        //构建message对象
        MessageEnum messageEnum = sckwMessage.getMessageEnum();
        KwmMessage kwmMessage = KwmMessage.builder().category(messageEnum.getCategory()).type(messageEnum.getType()).title(messageEnum.getTitle())
                .content(messageEnum.getContent()).clientType(messageEnum.getPushType()).url(sckwMessage.getMsgUrl())
                .params(JSON.toJSONString(sckwMessage.getParams())).build();
        kwmMessage.setCreateBy(sckwMessage.getCreateBy());
        kwmMessage.setUpdateBy(sckwMessage.getCreateBy());
        Long msgId = kwmMessageService.insert(kwmMessage);
        //多个用户id，构建多个KwmMessageUser对象保存
        List<String> userIdList = Arrays.asList(userIds.split(","));
        List<KwmMessageUser> messageUsers = Lists.newArrayList();
        userIdList.forEach(e -> {
            KwmMessageUser messageUser = KwmMessageUser.builder().userId(Long.valueOf(e)).msgId(msgId).build();
            messageUser.setCreateBy(sckwMessage.getCreateBy());
            messageUser.setUpdateBy(sckwMessage.getCreateBy());
            messageUsers.add(messageUser);
        });
        kwmMessageUserService.batchSave(messageUsers);
    }

    public static String getKey(String requestId) {
        return String.format(RedisConstant.MESSAGE_CONSUMER_REQUEST_KEY, requestId);
    }
}
