package cn.axzo.msg.center.message.service.todo.manage.event;

import cn.axzo.msg.center.dal.TodoBusinessDao;
import cn.axzo.msg.center.dal.TodoBusinesses;
import cn.axzo.msg.center.domain.entity.Todo;
import cn.axzo.msg.center.domain.entity.TodoBusiness;
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.dto.MessageTemplateRouterDTO.MessageRouteDetailDTO;
import cn.axzo.msg.center.message.domain.dto.MessageTemplateRouterDTO.MessageRouterConfigDTO;
import cn.axzo.msg.center.message.service.todo.manage.TodoExt;
import cn.axzo.msg.center.message.service.youmeng.YoumengPush;
import cn.axzo.msg.center.message.service.youmeng.YoumengPush.PushNavigation;
import cn.axzo.msg.center.message.service.youmeng.YoumengTemplateClient;
import cn.axzo.msg.center.utils.MessageRouterUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yanglin
 */
@Slf4j
@Component
@RequiredArgsConstructor
class TodoPushSender implements ApplicationListener<NewTodoEvent> {

    private final YoumengTemplateClient youmengTemplateClient;
    private final MessageRouterUtil messageRouterUtil;
    private final TodoBusinessDao todoBusinessDao;

    @Override
    public void onApplicationEvent(@NotNull NewTodoEvent event) {
        log.info("Prepare sending todo push. event={}", event);
        ArrayList<YoumengPush> pushes = new ArrayList<>();
        for (Todo todo : event.getTodos()) {
            YoumengPush push = new YoumengPush();
            push.setTitle(todo.getTitle());
            push.setContent(todo.getContent());
            push.setReceiverPersonId(todo.getExecutorPersonId());
            push.setReceiverOuId(todo.getOuId());
            push.setNavigations(determineNavigations(event.getTemplate(), todo));
            pushes.add(push);
        }
        youmengTemplateClient.asyncSend(event.getTemplate().getId(), pushes);
    }

    private List<PushNavigation> determineNavigations(MessageTemplateDTO template, Todo todo) {
        if (template.getMsgTemplateRouter() == null)
            return Collections.emptyList();
        MessageRouteDetailDTO detail = template.getMsgTemplateRouter().getRouteDetail();
        if (detail == null)
            return Collections.emptyList();
        List<MessageRouterConfigDTO> routerConfigs = detail.getRouterConfigs();
        if (CollectionUtils.isEmpty(routerConfigs))
            return Collections.emptyList();
        JSONObject routerParam = todo.getRouterParams();
        if (routerParam == null) {
            routerParam = new JSONObject();
        }
        TodoBusinesses businesses = todoBusinessDao.getBusinesses(todo);
        TodoBusiness business = businesses.findBusiness(todo).orElse(null);
        Map<String, Object> ctx = new HashMap<>();
        ctx.put("business", business);
        ctx.put("todo", todo);
        routerParam.put(TodoExt.CTX, ctx);
        MessageTemplateRouterDTO router = messageRouterUtil.parseAndConcatRouteUrl(
                template, template.getMsgTemplateRouter(), routerParam);
        if (router == null)
            return Collections.emptyList();
        ArrayList<PushNavigation> navigations = new ArrayList<>();
        for (MessageRouterConfigDTO routerCfg : router.getRouteDetail().getRouterConfigs()) {
            String url = template.isCardJumpToBiz() ? routerCfg.getUrl() : "";
            navigations.add(new PushNavigation(routerCfg.getTerminalType(), url));
        }
        return navigations;
    }
}