package cn.axzo.msg.center.event.outer;

import cn.axzo.framework.rocketmq.Event;
import cn.axzo.framework.rocketmq.EventConsumer;
import cn.axzo.framework.rocketmq.EventHandler;
import cn.axzo.msg.center.api.request.MsgBody4Guest;
import cn.axzo.msg.center.dal.MessageRecordV3Dao;
import cn.axzo.msg.center.domain.entity.MessageBaseTemplate;
import cn.axzo.msg.center.domain.entity.MessageRecordV3;
import cn.axzo.msg.center.domain.enums.NativeTypeEnum;
import cn.axzo.msg.center.event.payload.MessageHistoryUpdatedPayload;
import cn.axzo.msg.center.inside.notices.service.IYouMengMessageService;
import cn.axzo.msg.center.inside.notices.service.impl.v3.msg.TemplateMessage;
import cn.axzo.msg.center.message.domain.dto.MessageTemplateDTO;
import cn.axzo.msg.center.message.service.MessageTemplateNewService;
import cn.axzo.msg.center.service.enums.TerminalTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
public class PushYouMengMessageHandler implements EventHandler, InitializingBean {

    @Autowired
    private EventConsumer eventConsumer;
    @Autowired
    private MessageRecordV3Dao messageRecordV3Dao;
    @Autowired
    private MessageTemplateNewService messageTemplateNewService;
    @Autowired
    private IYouMengMessageService youMengMessageService;

    /**
     * 按照这个顺序解析routerType
     */
    private static final List<TerminalTypeEnum> ROUTER_TYPE_SORTED = Lists.newArrayList(
            TerminalTypeEnum.IOS,
            TerminalTypeEnum.ANDROID,
            TerminalTypeEnum.WEB_VIEW,
            TerminalTypeEnum.MINI_PROGRAM,
            TerminalTypeEnum.WECHAT_MINI_PROGRAM);

    /**
     * 按照这个顺序解析IOS的url
     */
    private static final List<TerminalTypeEnum> IOS_URL_SORTED = Lists.newArrayList(
            TerminalTypeEnum.IOS,
            TerminalTypeEnum.WEB_VIEW,
            TerminalTypeEnum.MINI_PROGRAM,
            TerminalTypeEnum.WECHAT_MINI_PROGRAM);

    /**
     * 按照这个顺序解析ANDROID的url
     */
    private static final List<TerminalTypeEnum> ANDROID_URL_SORTED = Lists.newArrayList(
            TerminalTypeEnum.ANDROID,
            TerminalTypeEnum.WEB_VIEW,
            TerminalTypeEnum.MINI_PROGRAM,
            TerminalTypeEnum.WECHAT_MINI_PROGRAM);


    @Override
    public void onEvent(Event event, EventConsumer.Context context) {
        log.info("begin push-handler rocketmq event: {}", event);
        MessageHistoryUpdatedPayload payload = event.normalizedData(MessageHistoryUpdatedPayload.class);
        if (Objects.isNull(payload) || StringUtils.isBlank(payload.getNewMessageHistory().getBizId())) {
            return;
        }

        if (!payload.getNewMessageHistory().getBizId().startsWith(TemplateMessage.BIZ_ID_PREFIX)) {
            log.info("push-handler 非msg-center的消息");
            return;
        }

        if (!payload.isSuccess()) {
            log.info("push-handler is not success");
            return;
        }

        Long imMessageTaskId = payload.getNewMessageHistory().getImMessageTaskId();
        Optional<MessageRecordV3> messageRecordV3s = messageRecordV3Dao.lambdaQuery()
                .eq(MessageRecordV3::getImMsgId, String.valueOf(imMessageTaskId))
                .list()
                .stream()
                .findFirst();
        if (!messageRecordV3s.isPresent()) {
            log.info("push-handler, 非当前业务的im消息");
            return;
        }

        MessageRecordV3 messageRecordV3 = messageRecordV3s.get();
        Optional<MessageTemplateDTO> messageTemplateDTO = messageTemplateNewService.queryEnableTemplateByCode(messageRecordV3.getTemplateCode());
        if (!messageTemplateDTO.isPresent()) {
            log.info("push-handler, 模板code:{},不存在", messageRecordV3.getTemplateCode());
            return;
        }

        if (messageTemplateDTO.get().getPushData() == null) {
            log.info("push-handler, 模板code:{},未配置push信息", messageRecordV3.getTemplateCode());
            return;
        }

        MessageBaseTemplate.PushData pushData = messageTemplateDTO.get().getPushData().toJavaObject(MessageBaseTemplate.PushData.class);

        if (BooleanUtils.isNotTrue(pushData.isSwitchOn())) {
            log.info("push-handler, 模板code:{},push开关未打开", messageRecordV3.getTemplateCode());
            return;
        }
        MessageHistoryUpdatedPayload.MessageHistory newMessageHistory = payload.getNewMessageHistory();
        MessageHistoryUpdatedPayload.MessageBody messageBody = newMessageHistory.resolveMessageBody();
        youMengMessageService.sendPushMessage(MsgBody4Guest.builder()
                .ty(0)
                .f("0")
                .appClient(newMessageHistory.getAppType())
                .m(messageRecordV3.getContent())
                .m3(newMessageHistory.getReceivePersonId())
                .m2(resolveM2(messageBody, pushData))
                // 为了兼容老版本，保证老版本的工人端能收到push，所以新的push都alias都是person
                .t("not_identity" + newMessageHistory.getReceivePersonId())
                .ouId(newMessageHistory.getReceiveOuId())
                .pushType(pushData.getType())
                .build());

        log.info("end push-handler rocketmq event: {}", event);
    }

    private String resolveM2(MessageHistoryUpdatedPayload.MessageBody messageBody,
                             MessageBaseTemplate.PushData pushData) {
        JSONObject jsonObject = new JSONObject()
                .fluentPut("t", messageBody.getMsgHeader())
                .fluentPut("type", 0);
        if (StringUtils.isNotBlank(pushData.getVoiceFile())) {
            jsonObject.fluentPut("audio", pushData.getVoiceFile());
        }

        MessageHistoryUpdatedPayload.CardDetailButton cardDetailButton = messageBody.resolveMsgBody().getCardDetailButton();
        if (cardDetailButton != null && CollectionUtils.isNotEmpty(cardDetailButton.getActionPaths())) {
            resolveRouter(jsonObject, cardDetailButton.getActionPaths());
        }
        return jsonObject.toJSONString();
    }

    /**
     *
     * @param jsonObject
     * @param actionPaths
     */
    public void resolveRouter(JSONObject jsonObject, List<MessageHistoryUpdatedPayload.ActionPath> actionPaths) {

        Map<TerminalTypeEnum, MessageHistoryUpdatedPayload.ActionPath> actionPathMap = actionPaths.stream()
                .collect(Collectors.toMap(MessageHistoryUpdatedPayload.ActionPath::getPlatform, Function.identity()));
        Optional<MessageHistoryUpdatedPayload.ActionPath> routerType = ROUTER_TYPE_SORTED.stream()
                .map(actionPathMap::get)
                .filter(Objects::nonNull)
                .findFirst();
        routerType.ifPresent(actionPath -> jsonObject.fluentPut("rt", NativeTypeEnum.getByCode(actionPath.getPlatform().getCode()).getMessage()));

        Optional<MessageHistoryUpdatedPayload.ActionPath> ios = IOS_URL_SORTED.stream()
                .map(actionPathMap::get)
                .filter(Objects::nonNull)
                .findFirst();
        // IOS的跳转URL
        ios.ifPresent(actionPath -> jsonObject.fluentPut("ir", actionPath.getUrl()));

        Optional<MessageHistoryUpdatedPayload.ActionPath> android = ANDROID_URL_SORTED.stream()
                .map(actionPathMap::get)
                .filter(Objects::nonNull)
                .findFirst();
        // ANDROID的跳转URL
        android.ifPresent(actionPath -> jsonObject.fluentPut("ar", actionPath.getUrl()));

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        eventConsumer.registerHandler(EventTypeEnum.MESSAGE_HISTORY_UPDATED.getEventCode(), this);
    }
}
