package org.jk.rag.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import org.jk.common.core.domain.model.LoginUser;
import org.jk.common.core.utils.MapstructUtils;
import org.jk.common.core.utils.StringUtils;
import org.jk.common.mybatis.core.page.TableDataInfo;
import org.jk.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jk.common.satoken.utils.LoginHelper;
import org.jk.rag.domain.EvaluationTask;
import org.jk.rag.domain.SysUserOnlineLog;
import org.jk.rag.domain.bo.SysUserOnlineLogBo;
import org.jk.rag.domain.dto.ConversationReqDTO;
import org.jk.rag.domain.dto.OverviewAppDTO;
import org.jk.rag.domain.dto.OverviewAppDetailDTO;
import org.jk.rag.domain.dto.OverviewKnowledgeDTO;
import org.jk.rag.domain.entity.JkApplication;
import org.jk.rag.domain.entity.JkApplicationResult;
import org.jk.rag.domain.vo.SysUserOnlineLogVo;
import org.jk.rag.mapper.JkApplicationMapper;
import org.jk.rag.mapper.SysUserOnlineLogMapper;
import org.jk.rag.service.ISysUserOnlineLogService;
import org.jk.rag.utils.MonthTimeUtils;
import org.jk.system.service.ISysLogininforService;
import org.springframework.stereotype.Service;

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

/**
 * 在线人数记录Service业务层处理
 *
 * @author Lion Li
 * @date 2026-01-22
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserOnlineLogServiceImpl implements ISysUserOnlineLogService {

    private final SysUserOnlineLogMapper baseMapper;

    private final JkApplicationMapper jkApplicationMapper;

    private final ISysLogininforService logininforService;

    /**
     * 查询在线人数记录
     *
     * @param id 主键
     * @return 在线人数记录
     */
    @Override
    public SysUserOnlineLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询在线人数记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 在线人数记录分页列表
     */
    @Override
    public TableDataInfo<SysUserOnlineLogVo> queryPageList(SysUserOnlineLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserOnlineLog> lqw = buildQueryWrapper(bo);
        Page<SysUserOnlineLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的在线人数记录列表
     *
     * @param bo 查询条件
     * @return 在线人数记录列表
     */
    @Override
    public List<SysUserOnlineLogVo> queryList(SysUserOnlineLogBo bo) {
        LambdaQueryWrapper<SysUserOnlineLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserOnlineLog> buildQueryWrapper(SysUserOnlineLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserOnlineLog> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserOnlineLog::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getOnlineNum()), SysUserOnlineLog::getOnlineNum, bo.getOnlineNum());
        return lqw;
    }

    /**
     * 新增在线人数记录
     *
     * @param bo 在线人数记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysUserOnlineLogBo bo) {
        SysUserOnlineLog add = MapstructUtils.convert(bo, SysUserOnlineLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改在线人数记录
     *
     * @param bo 在线人数记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysUserOnlineLogBo bo) {
        SysUserOnlineLog update = MapstructUtils.convert(bo, SysUserOnlineLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserOnlineLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除在线人数记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<SysUserOnlineLogVo> queryThirtyDayData() {
        List<SysUserOnlineLogVo> result = baseMapper.queryThirtyDayData();
        SysUserOnlineLogVo today = new SysUserOnlineLogVo();
        Date todayStart = MonthTimeUtils.getTodayStartAsDate();
        Date todayEnd = MonthTimeUtils.getTodayEndAsDate();
        today.setOnlineNum(String.valueOf(logininforService.queryCountByTime(todayStart,todayEnd)));
        today.setCreateTime(new Date());
        result.add(today);
        return result;
    }

    @Override
    public List<SysUserOnlineLogVo> queryTwelveMonthData() {
        List<SysUserOnlineLogVo> result = new ArrayList<>();
        result = baseMapper.queryTwelveMonthData();
        return result;
    }

    @Override
    public List<ConversationReqDTO> queryThirtyDayConversationData() {
        return baseMapper.queryThirtyDayConversationData();
    }

    @Override
    public List<ConversationReqDTO> queryTwelveMonthConversationData() {
        return baseMapper.queryTwelveMonthConversationData();
    }

    @Override
    public List<ConversationReqDTO> queryThirtyDayConversationDetailData() {
        return baseMapper.queryThirtyDayConversationDetailData();
    }

    @Override
    public List<ConversationReqDTO> queryTwelveMonthConversationDetailData() {
        return baseMapper.queryTwelveMonthConversationDetailData();
    }

    @Override
    public List<OverviewAppDTO> queryOverviewAppData() {
        List<OverviewAppDTO> resultList = new ArrayList<>();
        PageQuery pageQuery = new PageQuery(5,1);
        JkApplication jkApplication = new JkApplication();
        //管理员 获取所有项目
        Map<String,Object> userParams = getUserParams();
        if(userParams != null){
            jkApplication.setParams(userParams);
        }
        jkApplication.setFlag("0");
        jkApplication.setApprover(String.valueOf(LoginHelper.getUserId()));
        Page<JkApplicationResult> appList = jkApplicationMapper.selectApplicationPageList(jkApplication,pageQuery.build());
//        List<JkApplicationResult> distinctRecords = appList.getRecords().stream()
//            // 核心：通过toMap去重，收集器放在collect中，而非filter
//            .collect(Collectors.collectingAndThen(
//                Collectors.toMap(
//                    JkApplicationResult::getAppId, // 关键：实体的【唯一标识字段】，替换成你的实际唯一字段
//                    Function.identity(),        // 保留原实体对象
//                    (oldObj, newObj) -> oldObj  // 重复时保留【首次出现】的对象（去重核心）
//                ),
//                map -> map.values().stream().collect(Collectors.toList()) // 转成List，保持顺序
//            ));

        for(JkApplicationResult jkApplicationResult :appList.getRecords()) {
            OverviewAppDTO overviewAppDTO = new OverviewAppDTO();
            overviewAppDTO.setAppId(jkApplicationResult.getAppId());
            overviewAppDTO.setAppName(jkApplicationResult.getName());
            int appCount = baseMapper.queryAppCountData(jkApplicationResult.getAppId());
            Long costTime = baseMapper.queryAppCostTime(jkApplicationResult.getAppId());
            overviewAppDTO.setCostTime(costTime);
            overviewAppDTO.setTotalNum(appCount);
            Integer outputCount = baseMapper.queryAppOutputTokenData(jkApplicationResult.getAppId());
            Integer inputCount = baseMapper.queryAppInputTokenData(jkApplicationResult.getAppId());
            overviewAppDTO.setOutputTokenCount(outputCount);
            overviewAppDTO.setInputTokenCount(inputCount);
            resultList.add(overviewAppDTO);
        }
        return resultList;
    }

    @Override
    public TableDataInfo<OverviewAppDetailDTO> queryOverviewAppDetailData(PageQuery pageQuery) {
        List<OverviewAppDetailDTO> resultList = new ArrayList<>();
        JkApplication jkApplication = new JkApplication();
        //管理员 获取所有项目
        Map<String,Object> userParams = getUserParams();
        if(userParams != null){
            jkApplication.setParams(userParams);
        }
        jkApplication.setFlag("0");
        jkApplication.setApprover(String.valueOf(LoginHelper.getUserId()));
        Page<JkApplicationResult> appList = jkApplicationMapper.selectApplicationPageList(jkApplication,pageQuery.build());
        Page<OverviewAppDetailDTO> rePage = new Page<>();
        for(JkApplicationResult jkApplicationResult :appList.getRecords()) {
            OverviewAppDetailDTO overviewAppDTO = new OverviewAppDetailDTO();
            overviewAppDTO.setAppId(jkApplicationResult.getAppId());
            overviewAppDTO.setAppName(jkApplicationResult.getName());
            int appCount = baseMapper.queryAppCountData(jkApplicationResult.getAppId());
            Long costTime = baseMapper.queryAppCostTime(jkApplicationResult.getAppId());
            overviewAppDTO.setCostTime(costTime);
            overviewAppDTO.setTotalNum(appCount);
            EvaluationTask evaluationTask = baseMapper.queryAppTaskTime(jkApplicationResult.getAppId());
            if(evaluationTask != null) {
                overviewAppDTO.setAnswerLoyalty(evaluationTask.getAnswerLoyalty());
                overviewAppDTO.setContextRecall(evaluationTask.getContextRecall());
                overviewAppDTO.setAnswerRelevance(evaluationTask.getAnswerRelevance());
                overviewAppDTO.setContextRelevance(evaluationTask.getContextRelevance());
                overviewAppDTO.setCorrectAnswer(evaluationTask.getCorrectAnswer());
                overviewAppDTO.setNoiseSensitivity(evaluationTask.getNoiseSensitivity());
            }

            resultList.add(overviewAppDTO);
        }
        rePage.setTotal(appList.getTotal());
        rePage.setRecords(resultList);
        return TableDataInfo.build(rePage);
    }

    @Override
    public TableDataInfo<OverviewKnowledgeDTO> queryOverviewKnowledgeData(PageQuery pageQuery) {
        Page<OverviewKnowledgeDTO> page = baseMapper.queryKnowledgeData(pageQuery.build());
        return TableDataInfo.build(page);
    }

    private Map<String,Object> getUserParams() {
        //管理员 获取所有项目

        LoginUser user =  null;
        if(StpUtil.isLogin()){
            user = LoginHelper.getLoginUser();
        }
        Map<String,Object> userParams = null;
        if(user != null){
            userParams = new HashMap<>();

            userParams.put("userType",user.getUserType());
            userParams.put("userId",user.getUserId());
            userParams.put("tenantId",user.getTenantId());
            if(LoginHelper.isSuperAdmin() || LoginHelper.isTenantAdmin()) {
                userParams.put("isAdmin", true);
            } else {
                userParams.put("isAdmin", false);
            }
        }
        return userParams;
    }
}
