package cn.com.poc.expose.aggregate.impl;

import cn.com.poc.common.utils.DateUtils;
import cn.com.poc.data_analyze.constants.DataAnalyzeChannelEnum;
import cn.com.poc.data_analyze.constants.DataAnalyzeTimeDimensionEnum;
import cn.com.poc.data_analyze.constants.DataAnalyzeTimeRangeEnum;
import cn.com.poc.data_analyze.domain.*;
import cn.com.poc.data_analyze.entity.*;
import cn.com.poc.data_analyze.query.*;
import cn.com.poc.data_analyze.service.BizDataAnalyzeDialogueRecordService;
import cn.com.poc.data_analyze.service.BizDataAnalyzePointRecordService;
import cn.com.poc.expose.aggregate.AgentDataAnalyzeService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author alex.yao
 * @date 2024/12/11
 */
@Service
public class AgentDataAnalyzeServiceImpl implements AgentDataAnalyzeService {
    @Resource
    private BizDataAnalyzePointRecordService bizDataAnalyzePointRecordService;

    @Resource
    private BizDataAnalyzeDialogueRecordService bizDataAnalyzeDialogueRecordService;


    @Override
    public List<AgentDataAnalyzeGeneralEntity> getGeneralUsageData(String agentId, List<String> channel) {
        List<AgentDataAnalyzeGeneralEntity> result = new ArrayList<>();
        // 积分使用情况
        PointsUsageQueryCondition condition = new PointsUsageQueryCondition();
        condition.setRelationId(agentId);
        condition.setChannels(channel);
        List<PointsUsageQueryItem> pointsUsageQueryItems = bizDataAnalyzePointRecordService.pointsUsageQuery(condition, null);

        // 对话情况
        AgentUsageQueryCondition agentUsageQueryCondition = new AgentUsageQueryCondition();
        agentUsageQueryCondition.setChannels(channel);
        agentUsageQueryCondition.setRelationId(agentId);
        List<AgentUsageQueryItem> agentUsageQueryItems = bizDataAnalyzeDialogueRecordService.agentUsageQuery(agentUsageQueryCondition, null);

        //1. 构造今天数据
        buildGeneralData(DataAnalyzeTimeDimensionEnum.today, pointsUsageQueryItems, agentUsageQueryItems, result);
        //2. 构造本周数据
        buildGeneralData(DataAnalyzeTimeDimensionEnum.week, pointsUsageQueryItems, agentUsageQueryItems, result);
        //3. 构造本月数据
        buildGeneralData(DataAnalyzeTimeDimensionEnum.month, pointsUsageQueryItems, agentUsageQueryItems, result);
        return result;
    }

    @Override
    public List<ChannelUsersCountEntity> getChannelUserCount(String agentId, List<String> channel) {
        List<ChannelUsersCountEntity> result = new ArrayList<>();
        //1. 获取本周的日期范围
        Date currDateTime = DateUtils.getCurrDateTime();
        //2. 获取本周第二周前的日期范围
        Date secondDateTime = DateUtils.addDays(currDateTime, -7);
        //3. 获取本周第三周前的日期范围
        Date threeDateTime = DateUtils.addDays(secondDateTime, -7);
        //4. 获取本周第四周前的日期范围
        Date fourDateTime = DateUtils.addDays(threeDateTime, -7);

        channelUserConvert(agentId, channel, fourDateTime, result);
        channelUserConvert(agentId, channel, threeDateTime, result);
        channelUserConvert(agentId, channel, secondDateTime, result);
        channelUserConvert(agentId, channel, currDateTime, result);
        return result;
    }

    @Override
    public List<ChannelUsageCountEntity> getSendMessageCount(String agentId, List<String> channel) {
        List<ChannelUsageCountEntity> result = new ArrayList<>();
        ChannelUsageCountQueryCondition condition = new ChannelUsageCountQueryCondition();
        condition.setRelationId(agentId);
        condition.setChannels(channel);
        List<ChannelUsageCountQueryItem> channelUsageCountQueryItems = bizDataAnalyzeDialogueRecordService.channelUsageCountQuery(condition, null);
        for (ChannelUsageCountQueryItem item : channelUsageCountQueryItems) {
            ChannelUsageCountEntity channelUsageCountEntity = new ChannelUsageCountEntity();
            channelUsageCountEntity.setChannel(item.getChannel());
            channelUsageCountEntity.setCount(item.getUsageCount());
            result.add(channelUsageCountEntity);
        }
        return result;
    }

    @Override
    public List<ChannelPointCountEntity> getPointUsageCount(String agentId, List<String> channel) {
        List<ChannelPointCountEntity> result = new ArrayList<>();
        ChannelPointsCountQueryCondition condition = new ChannelPointsCountQueryCondition();
        condition.setChannels(channel);
        condition.setRelationId(agentId);
        List<ChannelPointsCountQueryItem> channelPointsCountQueryItems = bizDataAnalyzePointRecordService.channelPointsCountQuery(condition, null);
        for (ChannelPointsCountQueryItem item : channelPointsCountQueryItems) {
            ChannelPointCountEntity channelPointCountEntity = new ChannelPointCountEntity();
            channelPointCountEntity.setChannel(item.getChannel());
            channelPointCountEntity.setCount(item.getTotalPoints());
            result.add(channelPointCountEntity);
        }
        return result;
    }

    @Override
    public List<AgentDataAnalyzeTrendEntity> getAgentDataTrend(String agentId, List<String> channel, DataAnalyzeTimeRange timeRange) {
        TimeRange timeRangeResult = DataAnalyzeTimeRangeEnum.calculateTimeRange(timeRange);
        String endTime = timeRangeResult.getEndTime();
        String startTime = timeRangeResult.getStartTime();
        AgentDataTrendQueryCondition agentDataTrendQueryCondition = new AgentDataTrendQueryCondition();
        agentDataTrendQueryCondition.setStartDate(startTime);
        agentDataTrendQueryCondition.setEndDate(endTime);
        agentDataTrendQueryCondition.setRelationId(agentId);
        agentDataTrendQueryCondition.setChannels(channel);
        List<AgentDataAnalyzeTrendEntity> result = new ArrayList<>();
        List<AgentDataTrendQueryItem> agentDataTrendQueryItems = bizDataAnalyzeDialogueRecordService.agentDataTrendQuery(agentDataTrendQueryCondition, null);
        if (CollectionUtils.isNotEmpty(agentDataTrendQueryItems)) {
            for (AgentDataTrendQueryItem item : agentDataTrendQueryItems) {
                AgentDataAnalyzeTrendEntity agentDataAnalyzeTrendEntity = new AgentDataAnalyzeTrendEntity();
                agentDataAnalyzeTrendEntity.setDate(item.getDialogueDate());
                agentDataAnalyzeTrendEntity.setUsersCount(item.getMemberCount());
                agentDataAnalyzeTrendEntity.setUsageCount(item.getUsageCount());
                agentDataAnalyzeTrendEntity.setTotalPoints(item.getTotalPoints());
                result.add(agentDataAnalyzeTrendEntity);
            }
        }
        return result;
    }


    @Override
    public List<AgentDataAnalyzeApiChannelEntity> getAgentApiChannelPointCount(String agentId, DataAnalyzeTimeRange timeRange) {
        TimeRange timeRangeResult = DataAnalyzeTimeRangeEnum.calculateTimeRange(timeRange);
        String endTime = timeRangeResult.getEndTime();
        String startTime = timeRangeResult.getStartTime();
        List<String> channels = new ArrayList<String>() {{
            add(DataAnalyzeChannelEnum.api.getChannel());
        }};
        DataAnalyzePointRecordQueryCondition condition = new DataAnalyzePointRecordQueryCondition();
        condition.setRelationId(agentId);
        condition.setChannels(channels);
        condition.setStartDate(startTime);
        condition.setEndDate(endTime);
        List<DataAnalyzePointRecordQueryItem> dataAnalyzePointRecordQueryItems = bizDataAnalyzePointRecordService.dataAnalyzePointRecordQuery(condition, null);
        List<AgentDataAnalyzeApiChannelEntity> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dataAnalyzePointRecordQueryItems)) {
            for (DataAnalyzePointRecordQueryItem item : dataAnalyzePointRecordQueryItems) {
                AgentDataAnalyzeApiChannelEntity agentDataAnalyzeApiChannelEntity = new AgentDataAnalyzeApiChannelEntity();
                agentDataAnalyzeApiChannelEntity.setDateTime(DateUtils.formatDate(item.getDatetime(), DateUtils.yyyy_MM_dd_HH_mm_ss));
                agentDataAnalyzeApiChannelEntity.setCount(item.getPointNum());
                result.add(agentDataAnalyzeApiChannelEntity);
            }
        }
        return result;
    }

    private static void buildGeneralData(DataAnalyzeTimeDimensionEnum dataAnalyzeTimeDimensionEnum, List<PointsUsageQueryItem> pointsUsageQueryItems, List<AgentUsageQueryItem> agentUsageQueryItems, List<AgentDataAnalyzeGeneralEntity> result) {
        DataAnalyzeInfo dataAnalyzeInfo = new DataAnalyzeInfo();
        //积分
        DataAnalyze pointsCount = new DataAnalyze();
        setPointsDataAnalyze(pointsUsageQueryItems, pointsCount, dataAnalyzeTimeDimensionEnum);
        dataAnalyzeInfo.setPointsCount(pointsCount);
        //使用人数
        DataAnalyze usersCount = new DataAnalyze();
        setUserCountDataAnalyze(usersCount, agentUsageQueryItems, dataAnalyzeTimeDimensionEnum);
        dataAnalyzeInfo.setUsersCount(usersCount);
        //使用量
        DataAnalyze usageCount = new DataAnalyze();
        setUsageDataAnalyze(usageCount, agentUsageQueryItems, dataAnalyzeTimeDimensionEnum);
        dataAnalyzeInfo.setUsageCount(usageCount);

        AgentDataAnalyzeGeneralEntity agentDataAnalyzeGeneralEntity = new AgentDataAnalyzeGeneralEntity();
        agentDataAnalyzeGeneralEntity.setTimeDimension(dataAnalyzeTimeDimensionEnum.name());
        agentDataAnalyzeGeneralEntity.setDataAnalyzeInfo(dataAnalyzeInfo);
        result.add(agentDataAnalyzeGeneralEntity);
    }


    private static void setUsageDataAnalyze(DataAnalyze dataAnalyze, List<AgentUsageQueryItem> agentUsageQueryItems, DataAnalyzeTimeDimensionEnum dimension) {
        if (dataAnalyze == null) {
            dataAnalyze = new DataAnalyze();
        }
        double num = 0D;
        short fluctuate = 0;
        if (CollectionUtils.isNotEmpty(agentUsageQueryItems)) {
            if (DataAnalyzeTimeDimensionEnum.today.equals(dimension)) {
                num = agentUsageQueryItems.get(0).getTodayDialogue();
                fluctuate = (short) (agentUsageQueryItems.get(0).getTodayDialogue() < agentUsageQueryItems.get(0).getYesterdayDialogue() ? -1 : 1);
            } else if (DataAnalyzeTimeDimensionEnum.week.equals(dimension)) {
                num = agentUsageQueryItems.get(0).getWeekDialogue();
                fluctuate = (short) (agentUsageQueryItems.get(0).getWeekDialogue() < agentUsageQueryItems.get(0).getLastWeekDialogue() ? -1 : 1);
            } else if (DataAnalyzeTimeDimensionEnum.month.equals(dimension)) {
                num = agentUsageQueryItems.get(0).getMonthDialogue();
                fluctuate = (short) (agentUsageQueryItems.get(0).getMonthDialogue() < agentUsageQueryItems.get(0).getLastMonthDialogue() ? -1 : 1);
            }
        }
        dataAnalyze.setNum(num);
        dataAnalyze.setFluctuate(fluctuate);
    }

    private static void setUserCountDataAnalyze(DataAnalyze dataAnalyze, List<AgentUsageQueryItem> agentUsageQueryItems, DataAnalyzeTimeDimensionEnum dimension) {
        if (dataAnalyze == null) {
            dataAnalyze = new DataAnalyze();
        }
        double num = 0D;
        short fluctuate = 0;
        if (CollectionUtils.isNotEmpty(agentUsageQueryItems)) {
            if (DataAnalyzeTimeDimensionEnum.today.equals(dimension)) {
                num = agentUsageQueryItems.get(0).getTodayDialogueMember();
                fluctuate = (short) (agentUsageQueryItems.get(0).getTodayDialogueMember() < agentUsageQueryItems.get(0).getYesterdayDialogueMember() ? -1 : 1);
            } else if (DataAnalyzeTimeDimensionEnum.week.equals(dimension)) {
                num = agentUsageQueryItems.get(0).getWeekDialogueMember();
                fluctuate = (short) (agentUsageQueryItems.get(0).getWeekDialogueMember() < agentUsageQueryItems.get(0).getLastWeekDialogueMember() ? -1 : 1);
            } else if (DataAnalyzeTimeDimensionEnum.month.equals(dimension)) {
                num = agentUsageQueryItems.get(0).getMonthDialogueMember();
                fluctuate = (short) (agentUsageQueryItems.get(0).getMonthDialogueMember() < agentUsageQueryItems.get(0).getLastMonthDialogueMember() ? -1 : 1);
            }
        }
        dataAnalyze.setNum(num);
        dataAnalyze.setFluctuate(fluctuate);
    }

    private static void setPointsDataAnalyze(List<PointsUsageQueryItem> pointsUsageQueryItems, DataAnalyze dataAnalyze, DataAnalyzeTimeDimensionEnum dimension) {
        if (dataAnalyze == null) {
            dataAnalyze = new DataAnalyze();
        }
        double num = 0D;
        short fluctuate = 0;
        if (CollectionUtils.isNotEmpty(pointsUsageQueryItems)) {
            if (DataAnalyzeTimeDimensionEnum.today.equals(dimension)) {
                num = pointsUsageQueryItems.get(0).getTodayTotalPoints();
                fluctuate = (short) (pointsUsageQueryItems.get(0).getTodayTotalPoints() < pointsUsageQueryItems.get(0).getYesterdayTotalPoints() ? -1 : 1);
            } else if (DataAnalyzeTimeDimensionEnum.week.equals(dimension)) {
                num = pointsUsageQueryItems.get(0).getWeekTotalPoints();
                fluctuate = (short) (pointsUsageQueryItems.get(0).getWeekTotalPoints() < pointsUsageQueryItems.get(0).getLastWeekTotalPoints() ? -1 : 1);
            } else if (DataAnalyzeTimeDimensionEnum.month.equals(dimension)) {
                num = pointsUsageQueryItems.get(0).getMonthTotalPoints();
                fluctuate = (short) (pointsUsageQueryItems.get(0).getMonthTotalPoints() < pointsUsageQueryItems.get(0).getLastMonthTotalPoints() ? -1 : 1);
            }
        }
        dataAnalyze.setNum(num);
        dataAnalyze.setFluctuate(fluctuate);
    }


    private void channelUserConvert(String agentId, List<String> channel, Date currDateTime, List<ChannelUsersCountEntity> result) {
        Date thisWeekBegin = DateUtils.getWeekBegin2(currDateTime);
        Date thisWeekEnd = DateUtils.addDays(DateUtils.getWeekEnd2(currDateTime), -1);
        ChannelUserCountQueryCondition thisWeekCondition = new ChannelUserCountQueryCondition();
        thisWeekCondition.setStartDate(DateUtils.formatDate(thisWeekBegin, DateUtils.yyyy_MM_dd_HH_mm_ss));
        thisWeekCondition.setEndDate(DateUtils.formatDate(thisWeekEnd, DateUtils.yyyy_MM_dd_HH_mm_ss));
        thisWeekCondition.setRelationId(agentId);
        thisWeekCondition.setChannels(channel);
        List<ChannelUserCountQueryItem> thisWeekItems = bizDataAnalyzeDialogueRecordService.channelUserCountQuery(thisWeekCondition, null);

        List<ChannelDataCount> channelDataCountList = new ArrayList<>();
        for (ChannelUserCountQueryItem thisWeekItem : thisWeekItems) {
            ChannelDataCount channelDataCount = new ChannelDataCount();
            channelDataCount.setChannel(thisWeekItem.getChannel());
            channelDataCount.setCount(thisWeekItem.getMemberCount());
            channelDataCountList.add(channelDataCount);
        }

        ChannelUsersCountEntity countEntity = new ChannelUsersCountEntity();
        countEntity.setDate(DateUtils.formatDate(thisWeekBegin, DateUtils.yyyy_MM_dd) + "_" + DateUtils.formatDate(thisWeekEnd, DateUtils.yyyy_MM_dd));
        countEntity.setChannelDataCount(channelDataCountList);
        result.add(countEntity);
    }
}
