package com.fs.fastGpt.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.annotation.DataSource;
import com.fs.common.core.domain.entity.SysDictData;
import com.fs.common.enums.DataSourceType;
import com.fs.common.utils.DateUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyService;
import com.fs.fastGpt.domain.FastGptEventTokenLog;
import com.fs.fastGpt.domain.FastGptRole;
import com.fs.fastGpt.domain.FastgptEventLogTotal;
import com.fs.fastGpt.mapper.FastgptEventLogTotalMapper;
import com.fs.fastGpt.service.IFastGptRoleService;
import com.fs.fastGpt.service.IFastgptEventLogTotalService;
import com.fs.fastGpt.vo.FastgptEventLogTotalVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.fs.common.utils.DictUtils.getDictCache;

/**
 * ai事件埋点统计Service业务层处理
 * 
 * @author fs
 * @date 2025-06-26
 */
@Service
public class FastgptEventLogTotalServiceImpl extends ServiceImpl<FastgptEventLogTotalMapper, FastgptEventLogTotal> implements IFastgptEventLogTotalService {

    @Autowired
    FastgptEventLogTotalMapper fastgptEventLogTotalMapper;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IFastGptRoleService fastGptRoleService;
    /**
     * 查询ai事件埋点统计
     * 
     * @param id ai事件埋点统计主键
     * @return ai事件埋点统计
     */
    @Override
    public FastgptEventLogTotal selectFastgptEventLogTotalById(Long id)
    {
        return baseMapper.selectFastgptEventLogTotalById(id);
    }

    /**
     * 查询ai事件埋点统计列表
     * 
     * @param fastgptEventLogTotal ai事件埋点统计
     * @return ai事件埋点统计
     */
    @Override
    public List<FastgptEventLogTotal> selectFastgptEventLogTotalList(FastgptEventLogTotal fastgptEventLogTotal)
    {
        return baseMapper.selectFastgptEventLogTotalList(fastgptEventLogTotal);
    }

    /**
     * 新增ai事件埋点统计
     * 
     * @param fastgptEventLogTotal ai事件埋点统计
     * @return 结果
     */
    @Override
    public int insertFastgptEventLogTotal(FastgptEventLogTotal fastgptEventLogTotal)
    {
        return baseMapper.insertFastgptEventLogTotal(fastgptEventLogTotal);
    }

    /**
     * 修改ai事件埋点统计
     * 
     * @param fastgptEventLogTotal ai事件埋点统计
     * @return 结果
     */
    @Override
    public int updateFastgptEventLogTotal(FastgptEventLogTotal fastgptEventLogTotal)
    {
        return baseMapper.updateFastgptEventLogTotal(fastgptEventLogTotal);
    }

    /**
     * 批量删除ai事件埋点统计
     * 
     * @param ids 需要删除的ai事件埋点统计主键
     * @return 结果
     */
    @Override
    public int deleteFastgptEventLogTotalByIds(Long[] ids)
    {
        return baseMapper.deleteFastgptEventLogTotalByIds(ids);
    }

    /**
     * 删除ai事件埋点统计信息
     * 
     * @param id ai事件埋点统计主键
     * @return 结果
     */
    @Override
    public int deleteFastgptEventLogTotalById(Long id)
    {
        return baseMapper.deleteFastgptEventLogTotalById(id);
    }

    @Override
    public List<FastgptEventLogTotal> selectFastgptEventLogTotalInfoList(FastgptEventLogTotal logTotal) {
        return fastgptEventLogTotalMapper.selectFastgptEventLogTotalInfoList(logTotal);
    }

    @Override
    public FastgptEventLogTotal selectFastgptEventLogTotalByRoleIdAndType(FastgptEventLogTotal total) {
        return fastgptEventLogTotalMapper.selectFastgptEventLogTotalByRoleIdAndType(total);
    }

    @Override
    public FastgptEventLogTotal selectFastgptEventTokenLogTotalByRoleIdAndType(FastGptEventTokenLog tokenLog) {
        return fastgptEventLogTotalMapper.selectFastgptEventTokenLogTotalByRoleIdAndType(tokenLog);
    }

    @Override
    public FastgptEventLogTotalVo totalFastgptEventLog(List<FastgptEventLogTotalVo> list) {
        FastgptEventLogTotalVo totalVo = new FastgptEventLogTotalVo();
        totalVo.setRoleName("总计");
        Map<Integer, Long> totalMap = new HashMap<>();
        if(list != null && !list.isEmpty()){
            list.forEach(m -> {
                m.getTypeCountMap().forEach((k,v) -> {
                    if(totalMap.containsKey(k)){
                        totalMap.put(k, totalMap.get(k) + v);
                    }else{
                        totalMap.put(k, v);
                    }
                });
            });
            totalVo.setTypeCountMap(totalMap);
            return totalVo;
        }else{
            return null;
        }
    }

    @Override
    public List<FastgptEventLogTotalVo> selectFastgptEventLogTotalVoInfoList(FastgptEventLogTotalVo fastgptEventLogTotal) {
        if(fastgptEventLogTotal.getBeginTime() == null || fastgptEventLogTotal.getEndTime() == null){
            fastgptEventLogTotal.setBeginTime(DateUtil.offsetDay(DateUtil.parse(DateUtils.getDate()), -10).toDateStr());
            fastgptEventLogTotal.setEndTime(DateUtils.getDate());
        }
        String appKey = fastgptEventLogTotal.getAppKey();
        if(appKey != null){
            List<String> roleIds = fastGptRoleService.selectFastGptRoleRoleIdsByAppKey(appKey);
            if(roleIds != null && !roleIds.isEmpty()){
                fastgptEventLogTotal.setRoleIds(roleIds);
                fastgptEventLogTotal.setRoleId(null);
            }else{
                fastgptEventLogTotal.setRoleId(0L);
            }
        }

        if(fastgptEventLogTotal.getUserIds() != null && !fastgptEventLogTotal.getUserIds().isEmpty()){
            List<String> userIds = fastgptEventLogTotal.getUserIds();
            String result = String.join(",", userIds);
            List<CompanyUser> companyUserList = companyService.selectCompanyListByIds(result);
            String qwUserIds = companyUserList.stream()
                    .map(CompanyUser::getQwUserId)
                    .filter(Objects::nonNull) // 过滤掉 null 的 qwUserId
                    .flatMap(userId -> Arrays.stream(userId.split(","))) // 安全 split
                    .map(String::trim)
                    .distinct() // 去重
                    .collect(Collectors.joining(",")); // 收集为逗号分隔的字符串
            fastgptEventLogTotal.setQwUserIds(qwUserIds);
        }
        List<FastgptEventLogTotal> totalList = fastgptEventLogTotalMapper.selectFastgptEventLogTotalVoInfoList(fastgptEventLogTotal);
        List<SysDictData> dictCache = getDictCache("sys_fastgpt_event_log_type");
        if(dictCache == null){
            return null;
        }
        List<FastgptEventLogTotalVo> totalVoList = new ArrayList<>();
        List<Integer> typeList = new ArrayList<>();
        dictCache.forEach(n -> typeList.add(Integer.parseInt(n.getDictValue())));
        if(totalList != null && !totalList.isEmpty()){
            Map<String, List<FastgptEventLogTotal>> groupedByDateStr = totalList.stream()
                    .collect(Collectors.groupingBy(FastgptEventLogTotal::getStatTime));

            List<Long> roleIds = totalList.stream().map(FastgptEventLogTotal::getRoleId).collect(Collectors.toList());
            List<FastGptRole> fastGptRoles = fastGptRoleService.selectFastGptRoleByRoleIds(roleIds);

            for (String date : groupedByDateStr.keySet()) {
                List<FastgptEventLogTotal> list = groupedByDateStr.get(date);
                Map<Long, List<FastgptEventLogTotal>> roleIdGrouped = list.stream()
                        .collect(Collectors.groupingBy(FastgptEventLogTotal::getRoleId));
                for (Long roleId : roleIdGrouped.keySet()) {
                    List<FastgptEventLogTotal> logTotalList = roleIdGrouped.get(roleId);
                    FastgptEventLogTotalVo eventLogTotalVo = new FastgptEventLogTotalVo();
                    eventLogTotalVo.setRoleId(roleId);
                    eventLogTotalVo.setStatTime(date);
                    List<Integer> types = logTotalList.stream().map(FastgptEventLogTotal::getType).collect(Collectors.toList());
                    typeList.forEach(m -> logTotalList.forEach(n ->{
                        if(types.contains(m)){
                            if(eventLogTotalVo.getTypeCountMap() == null){
                                Map<Integer, Long> map = new HashMap<>();
                                map.put(n.getType(), n.getCount());
                                eventLogTotalVo.setTypeCountMap(map);
                            }else{
                                Map<Integer, Long> countMap = eventLogTotalVo.getTypeCountMap();
                                countMap.put(n.getType(), n.getCount());
                                eventLogTotalVo.setTypeCountMap(countMap);
                            }
                        }else{
                            if(eventLogTotalVo.getTypeCountMap() == null){
                                Map<Integer, Long> map = new HashMap<>();
                                map.put(m, 0L);
                                eventLogTotalVo.setTypeCountMap(map);
                            }else{
                                Map<Integer, Long> countMap = eventLogTotalVo.getTypeCountMap();
                                countMap.put(m, 0L);
                                eventLogTotalVo.setTypeCountMap(countMap);
                            }
                        }
                    }));
                    for (FastGptRole fastGptRole : fastGptRoles) {
                        if(Objects.equals(fastGptRole.getRoleId(), eventLogTotalVo.getRoleId())){
                            eventLogTotalVo.setRoleName(fastGptRole.getRoleName());
                        }
                    }

                    totalVoList.add(eventLogTotalVo);
                }
            }
            totalVoList.sort(Comparator.comparing(FastgptEventLogTotalVo::getStatTime).thenComparing(FastgptEventLogTotalVo::getRoleId).reversed());
            return totalVoList;
        }else{
            return null;
        }
    }

    @Override
    public List<FastGptEventTokenLog> selectFastgptEventTokenLogTotalList(FastGptEventTokenLog fastGptEventTokenLog) {
        return fastgptEventLogTotalMapper.selectFastgptEventTokenLogTotalList(fastGptEventTokenLog);
    }



    public static List<String> generateDateStrings(String startDateStr, int days) {
        List<String> dateList = new ArrayList<>();
        for (int i = 0; i < days; i++) {
            String dateStr = DateUtil.offsetDay(DateUtil.parse(startDateStr), i).toDateStr();
            dateList.add(dateStr);
        }
        return dateList;
    }

    /**
     * 批量新增ai事件埋点统计
     *
     * @param fastgptEventLogTotalList ai事件埋点统计列表
     * @return 结果
     */
    @Override
    public int insertFastgptEventLogTotalBatch(List<FastgptEventLogTotal> fastgptEventLogTotalList) {
        return baseMapper.insertFastgptEventLogTotalBatch(fastgptEventLogTotalList);
    }

    /**
     * 批量修改ai事件埋点统计
     *
     * @param fastgptEventLogTotalList ai事件埋点统计列表
     * @return 结果
     */
    @Override
    public int updateFastgptEventLogTotalBatch(List<FastgptEventLogTotal> fastgptEventLogTotalList) {
        return baseMapper.updateFastgptEventLogTotalBatch(fastgptEventLogTotalList);
    }

    @Override
    public List<FastgptEventLogTotalVo> selectFastgptEventLogTotalListByStatTime(String dateTime) {
        return fastgptEventLogTotalMapper.selectFastgptEventLogTotalListByStatTime(dateTime);
    }


}
