package cn.axzo.msg.center.message.domain.vo;

import cn.axzo.msg.center.domain.entity.GeneralMessageRecord;
import cn.axzo.msg.center.message.domain.dto.MessageTemplateRouterDTO;
import cn.axzo.msg.center.service.dto.MessageCardContentItemDTO;
import cn.axzo.msg.center.service.enums.ButtonStyleEnum;
import cn.axzo.msg.center.service.enums.RouterCategoryEnum;
import cn.axzo.msg.center.service.enums.TerminalTypeEnum;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author cold_blade
 * @date 2023/10/19
 * @version 1.0
 */
@Setter
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class GeneralMessagePushVO implements Serializable {

    private static final long serialVersionUID = -9017550674630922381L;

    /**
     * 消息的唯一标识
     */
    private String identityCode;
    /**
     * 模板编码
     */
    private String templateCode;
    /**
     * 顶部图片 - 模板icon地址
     */
    private String cardBannerUrl;
    /**
     * 卡片标题标题 - 消息标题
     */
    private String cardTitle;
    /**
     * 详情按钮
     */
    private CardButton cardDetailButton;
    /**
     * 副标题 - 消息所属组织信息
     */
    private List<Subtitle> subtitles;
    /**
     * 消息内容
     */
    private String cardContent;
    /**
     * 卡片信息
     */
    private List<CardExtensionItem> cardExtension;
    /**
     * 按钮操作区域
     */
    private List<CardButton> cardButtons;
    /**
     * 业务编码
     */
    private String bizCode;
    /**
     * 消息发送时间戳
     */
    private Long sendTimestamp;

    public static GeneralMessagePushVO from(GeneralMessageRecord record, String templateIcon, String orgIcon,
                                            MessageTemplateRouterDTO msgTemplateRouter,
                                            List<MessageCardContentItemDTO> cardContentItems) {
        CardButton cardDetailButton = parseDetailButton(msgTemplateRouter);
        List<CardButton> cardButtons = parseCardButtons(msgTemplateRouter);
        List<CardExtensionItem> cardExtension = CollectionUtils.isEmpty(cardContentItems) ? Collections.emptyList() :
                cardContentItems.stream()
                        .map(CardExtensionItem::from)
                        .filter(i -> StringUtils.isNotBlank(i.getDetail()) && !"null".equals(i.getDetail()))
                        .collect(Collectors.toList());
        List<Subtitle> subtitles = Collections.emptyList();
        Optional<Subtitle> subtitleOp = Subtitle.from(record, orgIcon);
        if (subtitleOp.isPresent()) {
            subtitles = Lists.newArrayList(subtitleOp.get());
        }
        return GeneralMessagePushVO.builder()
                .identityCode(record.getIdentityCode())
                .templateCode(record.getTemplateCode())
                .cardBannerUrl(templateIcon)
                .cardTitle(record.getTitle())
                .cardDetailButton(cardDetailButton)
                .subtitles(subtitles)
                .cardContent(record.getContent())
                .cardExtension(cardExtension)
                .cardButtons(cardButtons)
                .bizCode(record.getBizCode())
                .sendTimestamp(record.getCreateAt().getTime())
                .build();
    }

    public static CardButton parseDetailButton(MessageTemplateRouterDTO msgTemplateRouter) {
        if (Objects.isNull(msgTemplateRouter) || Objects.isNull(msgTemplateRouter.getRouteDetail())) {
            return null;
        }
        return CardButton.from(msgTemplateRouter.getRouteDetail());
    }

    public static List<CardButton> parseCardButtons(MessageTemplateRouterDTO msgTemplateRouter) {
        if (Objects.isNull(msgTemplateRouter)
                || CollectionUtils.isEmpty(msgTemplateRouter.getRouteButtons())) {
            return Collections.emptyList();
        }
        return msgTemplateRouter.getRouteButtons().stream()
                .map(CardButton::from)
                .filter(b -> BooleanUtils.isTrue(b.isOverCard))
                .collect(Collectors.toList());
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    @Setter
    @Getter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Subtitle {

        /**
         * 图标 - 对应消息所属组织的图标
         */
        private String iconUrl;
        /**
         * 标题 - 对应消息所属组织的名称
         */
        private String title;

        public static Optional<Subtitle> from(GeneralMessageRecord record, String orgIcon) {
            if (StringUtils.isBlank(record.getOrgName())) {
                return Optional.empty();
            }
            return Optional.of(Subtitle.builder()
                    .title(record.getOrgName())
                    .iconUrl(orgIcon)
                    .build());
        }

        @Override
        public String toString() {
            return JSON.toJSONString(this);
        }
    }

    @Setter
    @Getter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class CardButton {

        /**
         * 按钮标题
         */
        private String title;
        /**
         * 按钮操作类型: JUMP - 页面跳转, ACTION - 接口调用
         */
        private String action;
        /**
         * 按钮样式 - 是否高亮
         */
        private Boolean isHighlight;
        /**
         * 按钮样式 - 是否按钮显示在卡片
         */
        private Boolean isOverCard;
        /**
         * 按钮点击后的跳转地址
         */
        private List<ButtonAction> actionPaths;

        static CardButton from(MessageTemplateRouterDTO.MessageRouteDetailDTO routeDetail) {
            return CardButton.builder()
                    .title(routeDetail.getName())
                    .action(RouterCategoryEnum.JUMP.name())
                    .isHighlight(false)
                    .actionPaths(routeDetail.getRouterConfigs().stream()
                            .map(e -> new ButtonAction(e.getTerminalType().name(), e.getUrl()))
                            .collect(Collectors.toList())
                    ).build();
        }

        static CardButton from(MessageTemplateRouterDTO.MessageRouteButtonDTO routerButton) {
            List<ButtonStyleEnum> buttonStyles = Objects.isNull(routerButton.getStyle()) ? Collections.emptyList() :
                    JSON.parseArray(routerButton.getStyle().toJSONString(), ButtonStyleEnum.class);
            if (RouterCategoryEnum.ACTION.equals(routerButton.getCategory())) {
                return CardButton.builder()
                        .title(routerButton.getName())
                        .action(routerButton.getCategory().name())
                        .isHighlight(buttonStyles.stream().anyMatch(ButtonStyleEnum.HIGH_LIGHT::equals))
                        .isOverCard(buttonStyles.stream().anyMatch(ButtonStyleEnum.OVER_CARD::equals))
                        .actionPaths(Lists.newArrayList(
                                new ButtonAction(TerminalTypeEnum.WEB_VIEW.name(), routerButton.getApiUrl())))
                        .build();
            }
            return CardButton.builder()
                    .title(routerButton.getName())
                    .action(routerButton.getCategory().name())
                    .isHighlight(buttonStyles.stream().anyMatch(ButtonStyleEnum.HIGH_LIGHT::equals))
                    .isOverCard(buttonStyles.stream().anyMatch(ButtonStyleEnum.OVER_CARD::equals))
                    .actionPaths(routerButton.getRouterConfigs().stream()
                            .map(e -> new ButtonAction(e.getTerminalType().name(), e.getUrl()))
                            .collect(Collectors.toList())
                    ).build();
        }

        @Getter
        @AllArgsConstructor
        static class ButtonAction {

            /**
             * 平台
             */
            private String platform;
            /**
             * 跳转地址
             */
            private String url;
        }
    }

    @Setter
    @Getter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class CardExtensionItem {

        private String title;

        private String detail;

        public static CardExtensionItem from(MessageCardContentItemDTO cardContentItem) {
            return CardExtensionItem.builder()
                    .title(cardContentItem.getLabel())
                    .detail(cardContentItem.getValue())
                    .build();
        }

        @Override
        public String toString() {
            return JSON.toJSONString(this);
        }
    }
}
