package org.framework.lazy.cloud.network.heartbeat.server.standalone.application.impl;

import jakarta.annotation.Resource;
import org.framework.lazy.cloud.network.heartbeat.server.properties.ServerNodeProperties;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.LazyVisitorPortFlowApplication;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.assembler.VisitorPortFlowDTOAssembler;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.assembler.VisitorPortPerDayFlowDTOAssembler;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.command.visitor.flow.*;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.command.visitor.port.per.day.flow.LazyVisitorPortPerDayFlowStoryCommand;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.dto.LazyVisitorFlowDTO;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.application.dto.LazyVisitorPortFlowDTO;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.visitor.flow.LazyVisitorPortFlow;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.visitor.flow.LazyVisitorPortFlowRepository;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.visitor.port.per.day.flow.LazyVisitorPortPerDayFlow;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.visitor.port.per.day.flow.LazyVisitorPortPerDayFlowRepository;

import org.wu.framework.core.utils.ObjectUtils;
import org.wu.framework.database.lazy.web.plus.stereotype.LazyApplication;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyApplicationImpl;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * describe 访客端流量
 *
 * @author Jia wei Wu
 * @date 2024/01/24 05:19 下午
 * @see DefaultDDDLazyApplicationImpl
 **/
@LazyApplication
public class LazyVisitorPortFlowApplicationImpl implements LazyVisitorPortFlowApplication {

    @Resource
    LazyVisitorPortFlowRepository lazyVisitorPortFlowRepository;

    @Resource
    LazyVisitorPortPerDayFlowRepository lazyVisitorPortPerDayFlowRepository;
    @Resource
    ServerNodeProperties serverNodeProperties;

    /**
     * describe 新增访客端流量
     *
     * @param lazyVisitorPortFlowStoryCommand 新增访客端流量
     * @return {@link Result<   LazyVisitorPortFlow   >} 访客端流量新增后领域对象
     * @author Jia wei Wu
     * @date 2024/01/24 05:19 下午
     **/

    @Override
    public Result<LazyVisitorPortFlow> story(LazyVisitorPortFlowStoryCommand lazyVisitorPortFlowStoryCommand) {
        LazyVisitorPortFlow lazyVisitorPortFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(lazyVisitorPortFlowStoryCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyVisitorPortFlow.setServerId(serverId);
        return lazyVisitorPortFlowRepository.story(lazyVisitorPortFlow);
    }

    /**
     * 流量增长存储
     * 访客 ID 访客 端口必须
     *
     * @param lazyVisitorPortFlowStoryCommand
     * @return
     */
    @Override
    public Result<LazyVisitorPortFlow> flowIncreaseStory(LazyVisitorPortFlowStoryCommand lazyVisitorPortFlowStoryCommand) {
        String clientId = lazyVisitorPortFlowStoryCommand.getClientId();
        Integer visitorPort = lazyVisitorPortFlowStoryCommand.getVisitorPort();
        String serverId = serverNodeProperties.getNodeId();
        lazyVisitorPortFlowStoryCommand.setServerId(serverId);

        Integer realOutFlow = ObjectUtils.isEmpty(lazyVisitorPortFlowStoryCommand.getOutFlow()) ? 0 : lazyVisitorPortFlowStoryCommand.getOutFlow();
        Integer realInFlow = ObjectUtils.isEmpty(lazyVisitorPortFlowStoryCommand.getInFlow()) ? 0 : lazyVisitorPortFlowStoryCommand.getInFlow();
        // 查询是否存在已有流量 而后进行统计汇总
        LazyVisitorPortFlow findOneLazyVisitorPortFlowQuery = new LazyVisitorPortFlow();
        findOneLazyVisitorPortFlowQuery.setClientId(clientId);
        findOneLazyVisitorPortFlowQuery.setVisitorPort(visitorPort);

        findOneLazyVisitorPortFlowQuery.setServerId(serverId);
        lazyVisitorPortFlowRepository.findOne(findOneLazyVisitorPortFlowQuery).accept(existVisitorFlow -> {
            Integer inFlow = existVisitorFlow.getInFlow();
            Integer outFlow = existVisitorFlow.getOutFlow();
            if (!ObjectUtils.isEmpty(inFlow)) {
                lazyVisitorPortFlowStoryCommand.setInFlow(realInFlow + inFlow);
            }
            if (!ObjectUtils.isEmpty(outFlow)) {
                lazyVisitorPortFlowStoryCommand.setOutFlow(realOutFlow + outFlow);
            }
        });
        LazyVisitorPortFlow lazyVisitorPortFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(lazyVisitorPortFlowStoryCommand);
        lazyVisitorPortFlowRepository.story(lazyVisitorPortFlow);

        // 日流量统计
        LazyVisitorPortPerDayFlowStoryCommand lazyVisitorPortPerDayFlowStoryCommand = new LazyVisitorPortPerDayFlowStoryCommand();
        lazyVisitorPortPerDayFlowStoryCommand.setClientId(clientId);
        lazyVisitorPortPerDayFlowStoryCommand.setVisitorPort(visitorPort);
        lazyVisitorPortPerDayFlowStoryCommand.setDay(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        lazyVisitorPortPerDayFlowStoryCommand.setOutFlow(realOutFlow);
        lazyVisitorPortPerDayFlowStoryCommand.setInFlow(realInFlow);
        lazyVisitorPortPerDayFlowStoryCommand.setServerId(serverId);

        LazyVisitorPortPerDayFlow findOneLazyVisitorPortPerDayFlowQuery = new LazyVisitorPortPerDayFlow();
        findOneLazyVisitorPortPerDayFlowQuery.setClientId(clientId);
        findOneLazyVisitorPortPerDayFlowQuery.setVisitorPort(visitorPort);
        findOneLazyVisitorPortPerDayFlowQuery.setDay(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        findOneLazyVisitorPortPerDayFlowQuery.setServerId(serverId);

        lazyVisitorPortPerDayFlowRepository.findOne(findOneLazyVisitorPortPerDayFlowQuery).accept(existVisitorPortPerDayFlow -> {
            Integer inFlow = existVisitorPortPerDayFlow.getInFlow();
            Integer outFlow = existVisitorPortPerDayFlow.getOutFlow();
            if (!ObjectUtils.isEmpty(inFlow)) {
                lazyVisitorPortPerDayFlowStoryCommand.setInFlow(realInFlow + inFlow);
            }
            if (!ObjectUtils.isEmpty(outFlow)) {
                lazyVisitorPortPerDayFlowStoryCommand.setOutFlow(realOutFlow + outFlow);
            }
        });
        LazyVisitorPortPerDayFlow lazyVisitorPortPerDayFlow = VisitorPortPerDayFlowDTOAssembler.INSTANCE.toVisitorPortPerDayFlow(lazyVisitorPortPerDayFlowStoryCommand);
        lazyVisitorPortPerDayFlowRepository.story(lazyVisitorPortPerDayFlow);

        return ResultFactory.successOf();

    }

    /**
     * describe 批量新增访客端流量
     *
     * @param lazyVisitorPortFlowStoryCommandList 批量新增访客端流量
     * @return {@link Result<List<  LazyVisitorPortFlow  >>} 访客端流量新增后领域对象集合
     * @author Jia wei Wu
     * @date 2024/01/24 05:19 下午
     **/

    @Override
    public Result<List<LazyVisitorPortFlow>> batchStory(List<LazyVisitorPortFlowStoryCommand> lazyVisitorPortFlowStoryCommandList) {
        List<LazyVisitorPortFlow> lazyVisitorPortFlowList = lazyVisitorPortFlowStoryCommandList
                .stream()
                .map(visitorPortFlowStoryCommand -> {
                            LazyVisitorPortFlow visitorFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(visitorPortFlowStoryCommand);
                            String serverId = serverNodeProperties.getNodeId();
                            visitorFlow.setServerId(serverId);
                            return visitorFlow;
                        }

                )
                .collect(Collectors.toList());
        return lazyVisitorPortFlowRepository.batchStory(lazyVisitorPortFlowList);
    }

    /**
     * describe 更新访客端流量
     *
     * @param lazyVisitorPortFlowUpdateCommand 更新访客端流量
     * @return {@link Result<  LazyVisitorPortFlow  >} 访客端流量领域对象
     * @author Jia wei Wu
     * @date 2024/01/24 05:19 下午
     **/

    @Override
    public Result<LazyVisitorPortFlow> updateOne(LazyVisitorPortFlowUpdateCommand lazyVisitorPortFlowUpdateCommand) {
        LazyVisitorPortFlow lazyVisitorPortFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(lazyVisitorPortFlowUpdateCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyVisitorPortFlow.setServerId(serverId);
        return lazyVisitorPortFlowRepository.story(lazyVisitorPortFlow);
    }

    /**
     * describe 查询单个访客端流量
     *
     * @param lazyVisitorPortFlowQueryOneCommand 查询单个访客端流量
     * @return {@link Result<   LazyVisitorFlowDTO   >} 访客端流量DTO对象
     * @author Jia wei Wu
     * @date 2024/01/24 05:19 下午
     **/

    @Override
    public Result<LazyVisitorPortFlowDTO> findOne(LazyVisitorPortFlowQueryOneCommand lazyVisitorPortFlowQueryOneCommand) {
        LazyVisitorPortFlow lazyVisitorPortFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(lazyVisitorPortFlowQueryOneCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyVisitorPortFlow.setServerId(serverId);
        return lazyVisitorPortFlowRepository.findOne(lazyVisitorPortFlow).convert(VisitorPortFlowDTOAssembler.INSTANCE::fromVisitorFlow);
    }

    /**
     * describe 查询多个访客端流量
     *
     * @param visitorFlowQueryListCommand 查询多个访客端流量
     * @return {@link Result<List<  LazyVisitorFlowDTO  >>} 访客端流量DTO对象
     * @author Jia wei Wu
     * @date 2024/01/24 05:19 下午
     **/

    @Override
    public Result<List<LazyVisitorPortFlowDTO>> findList(LazyVisitorPortFlowQueryListCommand visitorFlowQueryListCommand) {
        LazyVisitorPortFlow lazyVisitorPortFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(visitorFlowQueryListCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyVisitorPortFlow.setServerId(serverId);
        return lazyVisitorPortFlowRepository.findList(lazyVisitorPortFlow).convert(visitorFlows -> visitorFlows.stream().map(VisitorPortFlowDTOAssembler.INSTANCE::fromVisitorFlow).collect(Collectors.toList()));
    }

    /**
     * describe 分页查询多个访客端流量
     *
     * @param lazyVisitorPortFlowQueryListCommand 分页查询多个访客端流量
     * @return {@link Result<LazyPage<  LazyVisitorPortFlowDTO  >>} 分页访客端流量DTO对象
     * @author Jia wei Wu
     * @date 2024/01/24 05:19 下午
     **/

    @Override
    public Result<LazyPage<LazyVisitorPortFlowDTO>> findPage(int size, int current, LazyVisitorPortFlowQueryListCommand lazyVisitorPortFlowQueryListCommand) {
        LazyVisitorPortFlow lazyVisitorPortFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(lazyVisitorPortFlowQueryListCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyVisitorPortFlow.setServerId(serverId);
        return lazyVisitorPortFlowRepository.findPage(size, current, lazyVisitorPortFlow).convert(page -> page.convert(VisitorPortFlowDTOAssembler.INSTANCE::fromVisitorFlow));
    }

    /**
     * describe 删除访客端流量
     *
     * @param lazyVisitorPortFlowRemoveCommand 删除访客端流量
     * @return {@link Result<  LazyVisitorPortFlow  >} 访客端流量
     * @author Jia wei Wu
     * @date 2024/01/24 05:19 下午
     **/

    @Override
    public Result<LazyVisitorPortFlow> remove(LazyVisitorPortFlowRemoveCommand lazyVisitorPortFlowRemoveCommand) {
        LazyVisitorPortFlow lazyVisitorPortFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(lazyVisitorPortFlowRemoveCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyVisitorPortFlow.setServerId(serverId);
        return lazyVisitorPortFlowRepository.remove(lazyVisitorPortFlow);
    }

    /**
     * 根据客户端查询流量
     *
     * @param size                                分页大小
     * @param current                             分页
     * @param lazyVisitorPortFlowQueryListCommand 查询条件
     * @return {@link Result<LazyPage<  LazyVisitorFlowDTO  >>} 分页访客端流量DTO对象
     */
    @Override
    public Result<LazyPage<LazyVisitorFlowDTO>> findClientFlowPage(int size, int current, LazyVisitorPortFlowQueryListCommand lazyVisitorPortFlowQueryListCommand) {
        LazyVisitorPortFlow lazyVisitorPortFlow = VisitorPortFlowDTOAssembler.INSTANCE.toVisitorFlow(lazyVisitorPortFlowQueryListCommand);
        String serverId = serverNodeProperties.getNodeId();
        lazyVisitorPortFlow.setServerId(serverId);
        return lazyVisitorPortFlowRepository.findPageGroupByClientId(size, current, lazyVisitorPortFlow).convert(visitorPortFlowLazyPage -> {
            List<String> clientIdList = visitorPortFlowLazyPage
                    .getRecords()
                    .stream()
                    .map(LazyVisitorPortFlow::getClientId)
                    .toList();
            List<LazyVisitorPortFlow> lazyVisitorPortFlowList = lazyVisitorPortFlowRepository.findListByClientIds(clientIdList, serverId);


            // 根据客户端进行分组

            List<LazyVisitorPortFlowDTO> lazyVisitorPortFlowDTOList = lazyVisitorPortFlowList.stream().map(VisitorPortFlowDTOAssembler.INSTANCE::fromVisitorFlow).toList();


            Map<String/*客户端ID*/, List<LazyVisitorPortFlowDTO>> client_port_flow_map = lazyVisitorPortFlowDTOList.stream().collect(Collectors.groupingBy(LazyVisitorPortFlowDTO::getClientId));

            Map<String/*客户端ID*/, Integer/*客户端进口流量*/> client_in_flow = lazyVisitorPortFlowDTOList.stream()
                    .collect(
                            Collectors.groupingBy(LazyVisitorPortFlowDTO::getClientId,
                                    Collectors.summingInt(LazyVisitorPortFlowDTO::getInFlowSize)));

            Map<String/*客户端ID*/, Integer/*客户端出口流量*/> client_out_flow = lazyVisitorPortFlowDTOList.stream()
                    .collect(
                            Collectors.groupingBy(LazyVisitorPortFlowDTO::getClientId,
                                    Collectors.summingInt(LazyVisitorPortFlowDTO::getOutFlowSize)));

            return visitorPortFlowLazyPage.convert(visitorPortFlow1 -> {
                String clientId = visitorPortFlow1.getClientId();
                LazyVisitorFlowDTO lazyVisitorFlowDTO = new LazyVisitorFlowDTO();
                lazyVisitorFlowDTO.setClientId(clientId);
                lazyVisitorFlowDTO.setInFlow(client_in_flow.getOrDefault(clientId, 0));
                lazyVisitorFlowDTO.setOutFlow(client_out_flow.getOrDefault(clientId, 0));
                lazyVisitorFlowDTO.setLazyVisitorPortFlowDTOList(client_port_flow_map.getOrDefault(clientId, new ArrayList<>()));
                return lazyVisitorFlowDTO;
            });
        });
    }
}