package cn.axzo.msg.center.message.controller;

import cn.axzo.msg.center.dal.MessageBaseTemplateDao;
import cn.axzo.msg.center.dal.MessageRouteDetailDao;
import cn.axzo.msg.center.dal.MessageRouterConfigDao;
import cn.axzo.msg.center.dal.MessageTemplateRouterDao;
import cn.axzo.msg.center.dal.PendingMessageRecordDao;
import cn.axzo.msg.center.domain.entity.MessageBaseTemplate;
import cn.axzo.msg.center.domain.entity.MessageRouteDetail;
import cn.axzo.msg.center.domain.entity.MessageRouterConfig;
import cn.axzo.msg.center.domain.entity.MessageTemplateRouter;
import cn.axzo.msg.center.domain.entity.PendingMessageRecord;
import cn.axzo.msg.center.message.service.PendingMessageDataInitService;
import cn.axzo.msg.center.service.admin.MessageAdminConsoleClient;
import cn.axzo.msg.center.service.enums.BizCategoryEnum;
import cn.axzo.msg.center.service.enums.BizDetailShowStrategyEnum;
import cn.axzo.msg.center.service.enums.MessageCategoryEnum;
import cn.azxo.framework.common.model.CommonResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * msg-center
 *
 * @author zuoqinbo
 * @version V1.0
 * @date 2023/11/17 14:03
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class MessageAdminController implements MessageAdminConsoleClient {

    private final PendingMessageDataInitService pendingMessageDataInitService;
    private final MessageTemplateRouterDao messageTemplateRouterDao;
    private final MessageRouteDetailDao messageRouteDetailDao;
    private final MessageRouterConfigDao messageRouterConfigDao;
    private final MessageBaseTemplateDao messageBaseTemplateDao;
    private final PendingMessageRecordDao pendingMessageRecordDao;

    @Override
    public CommonResponse<Void> transformPendingMessageRecord(Integer diffDays, Long minRecordId) {
        pendingMessageDataInitService.transformPendingMessageRecord(diffDays, minRecordId);
        return CommonResponse.success();
    }

    @PostMapping(value = "/admin/console/template/category/adjust", produces = {MediaType.APPLICATION_JSON_VALUE})
    public CommonResponse<Void> adjustTemplateCategory(@RequestParam Long id) {
        if (Objects.isNull(id)) {
            return CommonResponse.success();
        }
        messageBaseTemplateDao.lambdaUpdate()
                .eq(MessageBaseTemplate::getId, id)
                .set(MessageBaseTemplate::getMsgCategory, MessageCategoryEnum.APPROVAL_PENDING_MESSAGE)
                .update();
        pendingMessageRecordDao.lambdaUpdate()
                .eq(PendingMessageRecord::getBizCategory, BizCategoryEnum.FLOW)
                .lt(PendingMessageRecord::getCreateAt, new Date(1700411318));
        return CommonResponse.success();
    }

    @PostMapping(value = "/admin/console/template/init-router", produces = {MediaType.APPLICATION_JSON_VALUE})
    @Transactional(rollbackFor = Exception.class)
    public CommonResponse<Void> initTemplateRouter() {
        List<MessageTemplateRouter> routers = messageTemplateRouterDao.lambdaQuery()
                .eq(MessageTemplateRouter::getIsDelete, 0)
                .list();
        Set<String> templates = messageRouteDetailDao.lambdaQuery()
                .select(MessageRouteDetail::getTemplateCode)
                .list().stream()
                .map(MessageRouteDetail::getTemplateCode)
                .collect(Collectors.toSet());
        routers = routers.stream().filter(e -> !templates.contains(e.getTemplateCode())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(routers)) {
            batchSave(routers);
        }
        return CommonResponse.success();
    }

    private void batchSave(List<MessageTemplateRouter> routers) {
        Map<String, List<MessageTemplateRouter>> map = routers.stream()
                .collect(Collectors.groupingBy(MessageTemplateRouter::getTemplateCode));
        List<MessageRouteDetail> routeDetails = map.values().stream()
                .map(e -> convertRouteDetail(e.get(0)))
                .collect(Collectors.toList());
        List<MessageRouterConfig> routerConfigs = routers.stream()
                .map(this::convertRouterConfig)
                .collect(Collectors.toList());
        messageRouteDetailDao.saveBatch(routeDetails);
        messageRouterConfigDao.saveBatch(routerConfigs);
    }

    private MessageRouteDetail convertRouteDetail(MessageTemplateRouter router) {
        return MessageRouteDetail.builder()
                .templateCode(router.getTemplateCode())
                .name(router.getName())
                .showStrategy(BizDetailShowStrategyEnum.JUMP_TO)
                .build();
    }

    private MessageRouterConfig convertRouterConfig(MessageTemplateRouter router) {
        return MessageRouterConfig.builder()
                .routerCode(router.getTemplateCode())
                .url(router.getUrl())
                .terminalType(router.getTerminalType())
                .build();
    }
}
