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.CollectionUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.message.model.KwmMessage;
import com.sckw.message.model.KwmMessageUser;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.redis.utils.RedissonUtils;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.SckwMessage;
import com.sckw.stream.model.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @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) {
        log.info("SckwMessageHandler:{}", JSON.toJSONString(sckwMessage));
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(getKey(sckwMessage.getRequestId()), 10L, RedisConstant.CONSUMER_REQUEST_VALID_TIME))) {
            log.info("重复message消息：{}，不处理", sckwMessage.getRequestId());
            return;
        }
        List<UserInfo> userInfos = sckwMessage.getUserInfos();
        if (CollectionUtils.isEmpty(userInfos)) {
            log.error("message消息处理用户信息为空，不处理");
            return;
        }
        //构建message对象
        MessageEnum messageEnum = sckwMessage.getMessageEnum();
        Long createBy = sckwMessage.getCreateBy();
        String content = StringUtils.replaceTextVar(messageEnum.getContent(), sckwMessage.getParams());
        KwmMessage kwmMessage = KwmMessage.builder()
                .category(messageEnum.getCategory())
                .type(messageEnum.getType())
                .title(messageEnum.getTitle())
                .content(content)
                .clientType(messageEnum.getPushType())
                .url(Objects.isNull(sckwMessage.getMsgUrls()) ? null : JSON.toJSONString(sckwMessage.getMsgUrls()))
                .params(Objects.isNull(sckwMessage.getParams()) ? null : JSON.toJSONString(sckwMessage.getParams()))
                .build();
        kwmMessage.setCreateBy(createBy);
        kwmMessage.setUpdateBy(createBy);
        Long msgId = kwmMessageService.insert(kwmMessage);
        //多个用户id，构建多个KwmMessageUser对象保存
        List<KwmMessageUser> messageUsers = Lists.newArrayList();
        userInfos.forEach(e -> {
            KwmMessageUser messageUser = KwmMessageUser.builder()
                    .userId(e.getUserId())
                    .entId(e.getEntId())
                    .msgId(msgId)
                    .build();
            messageUser.setCreateBy(createBy);
            messageUser.setUpdateBy(createBy);
            messageUsers.add(messageUser);
        });
        kwmMessageUserService.batchSave(messageUsers);
    }

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