package cn.axzo.msg.center.inside.notices.service.impl.v3.msg;

import cn.axzo.msg.center.common.utils.PlaceholderResolver;
import cn.axzo.msg.center.domain.entity.MessageRecordV3;
import cn.axzo.msg.center.inside.notices.config.MessageSystemConfig;
import cn.axzo.msg.center.message.domain.dto.MessageTemplateDTO;
import cn.axzo.msg.center.message.domain.dto.MessageTemplateRouterDTO;
import cn.axzo.msg.center.message.domain.vo.GeneralMessagePushVO;
import cn.axzo.msg.center.service.dto.MessageCardContentItemDTO;
import cn.axzo.msg.center.utils.MessageCardUtil;
import cn.axzo.msg.center.utils.MessageRouterUtil;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 从 {@link cn.axzo.msg.center.message.service.impl.GeneralMessageServiceImpl} 拷贝进行更改
 *
 * @author yanglin
 */
@Component
@RequiredArgsConstructor
public class MessageTemplateParser {

    private final MessageSystemConfig messageSystemConfig;
    private final MessageRouterUtil messageRouterUtil;

    GeneralMessagePushVO parse(MessageRecordV3 message, MessageTemplateDTO template) {
        // 对应模板的路由列表
        MessageTemplateRouterDTO msgTemplateRouter = template.getMsgTemplateRouter();
        // 解析路由地址
        msgTemplateRouter = messageRouterUtil.parseAndConcatRouteUrl(template, msgTemplateRouter, message.getRouterParams());
        // 获取模板卡片信息
        List<MessageCardContentItemDTO> rawCardContentItems = template.getMsgCardContentItems();
        List<MessageCardContentItemDTO> cardContentItems = rawCardContentItems;
        if (CollectionUtils.isNotEmpty(rawCardContentItems) && Objects.nonNull(message.getBizExtParams())
                && !message.getBizExtParams().isEmpty()) {
            // 克隆，避免修改入参
            cardContentItems = cardContentItems.stream()
                    .map(MessageCardContentItemDTO::deepClone)
                    .collect(Collectors.toList());
            cardContentItems.forEach(e -> {
                String value = PlaceholderResolver.getDefaultResolver()
                        .resolveByMap(e.getValue(), message.getBizExtParams());
                e.setValue(value);
            });
        }
        return parseRouterAndCard(message, template.getIcon(), messageSystemConfig.getOrgIcon(), msgTemplateRouter, cardContentItems);
    }

    private GeneralMessagePushVO parseRouterAndCard(MessageRecordV3 message, String templateIcon, String orgIcon,
                                                    MessageTemplateRouterDTO msgTemplateRouter,
                                                    List<MessageCardContentItemDTO> cardContentItems) {
        GeneralMessagePushVO.CardButton cardDetailButton = GeneralMessagePushVO.parseDetailButton(msgTemplateRouter);
        List<GeneralMessagePushVO.CardButton> cardButtons = GeneralMessagePushVO.parseCardButtons(msgTemplateRouter);
        List<MessageCardContentItemDTO> cardItems = MessageCardUtil.filterParsedCardItemsByValues(cardContentItems);
        List<GeneralMessagePushVO.CardExtensionItem> cardExtension = CollectionUtils.isEmpty(cardItems) ? Collections.emptyList() :
                cardItems.stream()
                        .map(GeneralMessagePushVO.CardExtensionItem::from)
                        .collect(Collectors.toList());
        List<GeneralMessagePushVO.Subtitle> subtitles = Collections.emptyList();
        GeneralMessagePushVO.Subtitle subtitleOp = parseSubtitle(message, orgIcon);
        if (subtitleOp != null) {
            subtitles = Lists.newArrayList(subtitleOp);
        }
        return GeneralMessagePushVO.builder()
                // 这个identityCode应该意义不大
                .identityCode(message.getIdentityCode())
                .templateCode(message.getTemplateCode())
                .cardBannerUrl(templateIcon)
                .cardTitle(message.getTitle())
                .cardDetailButton(cardDetailButton)
                .subtitles(subtitles)
                .cardContent(message.getContent())
                .cardExtension(cardExtension)
                .cardButtons(cardButtons)
                .bizCode(message.getBizCode())
                // 因为是异常发送, send time不太准确
                .sendTimestamp(message.getCreateAt().getTime())
                .build();
    }

    private GeneralMessagePushVO.Subtitle parseSubtitle(MessageRecordV3 message, String orgIcon) {
        if (StringUtils.isBlank(message.getSubtitle())) {
            return null;
        }
        return GeneralMessagePushVO.Subtitle.builder()
                .title(message.getSubtitle())
                .iconUrl(orgIcon)
                .build();
    }
}
