package org.jk.rag.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.jk.common.core.domain.model.LoginUser;
import org.jk.common.core.utils.DateUtils;
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.DialogLog;
import org.jk.rag.domain.bo.DialogLogBo;
import org.jk.rag.domain.dto.OverviewTopDTO;
import org.jk.rag.domain.entity.JkApplication;
import org.jk.rag.domain.entity.JkApplicationResult;
import org.jk.rag.domain.vo.DialogLogVo;
import org.jk.rag.mapper.DialogLogMapper;
import org.jk.rag.mapper.JkApplicationMapper;
import org.jk.rag.service.IDialogLogService;
import org.jk.rag.utils.MonthTimeUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author Lion Li
 * @date 2026-01-20
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DialogLogServiceImpl implements IDialogLogService {

    private final DialogLogMapper baseMapper;

    private final JkApplicationMapper jkApplicationMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 主键
     * @return 【请填写功能名称】
     */
    @Override
    public DialogLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询【请填写功能名称】列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 【请填写功能名称】分页列表
     */
    @Override
    public TableDataInfo<DialogLogVo> queryPageList(DialogLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DialogLog> lqw = buildQueryWrapper(bo);
        Page<DialogLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的【请填写功能名称】列表
     *
     * @param bo 查询条件
     * @return 【请填写功能名称】列表
     */
    @Override
    public List<DialogLogVo> queryList(DialogLogBo bo) {
        LambdaQueryWrapper<DialogLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(DialogLogBo bo) {
        DialogLog add = MapstructUtils.convert(bo, DialogLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(DialogLogBo bo) {
        DialogLog update = MapstructUtils.convert(bo, DialogLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DialogLog 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 OverviewTopDTO queryByTime() {
        OverviewTopDTO dto = new OverviewTopDTO();
        //获取当月数据
        PageQuery pageQuery = new PageQuery(100,1);
        JkApplication jkApplication = new JkApplication();
        //管理员 获取所有项目
        Map<String,Object> userParams = getUserParams();
        if(userParams != null){
            jkApplication.setParams(userParams);
        }
        Page<JkApplicationResult> appList = jkApplicationMapper.selectApplicationPageList(jkApplication,pageQuery.build());
        List<String> appIdList = new ArrayList<>();
        appIdList = appList.getRecords().stream()
            .map(JkApplicationResult::getAppId)
            .filter(Objects::nonNull)
            .distinct() // 去重
            .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(appIdList)) {
            return dto;
        }
        LocalDateTime nowStart = MonthTimeUtils.getCurrentMonthStart();
        LocalDateTime nowEnd = MonthTimeUtils.getCurrentMonthEnd();
        LambdaQueryWrapper<DialogLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(DialogLog::getCreateTime,nowStart,nowEnd);
        if(appIdList.size() > 0) {
            wrapper.in(DialogLog::getAppId,appIdList);
        }

        List<DialogLogVo> nowList = baseMapper.selectVoList(wrapper);
        //获取上月月数据
        LocalDateTime beforStart = MonthTimeUtils.getLastMonthStart();
        LocalDateTime beforEnd = MonthTimeUtils.getLastMonthEnd();
        LambdaQueryWrapper<DialogLog> lastWrapper = new LambdaQueryWrapper<>();
        lastWrapper.between(DialogLog::getCreateTime,beforStart,beforEnd);
        if(appIdList.size() > 0) {
            lastWrapper.in(DialogLog::getAppId,appIdList);
        }
        List<DialogLogVo> lastList = baseMapper.selectVoList(lastWrapper);
        dto.setTotalNum(nowList.size());
        dto.setBjNum(nowList.size()-lastList.size());
        //筛选成功接口次数
        List<DialogLogVo> filtered0List = nowList.stream()
            // 过滤条件：flg == 1（注意判空，避免空指针）
            .filter(vo -> vo != null && "0".equals(vo.getStatus()))
            // 收集为新的 List
            .collect(Collectors.toList());
        Double successRate = nowList.isEmpty()
            ? 0.00
            : (double) Math.round((double) filtered0List.size() / nowList.size() * 100) / 100.0;
        dto.setSuccessRate(successRate);
        // 1. 获取当天的开始时间：yyyy-MM-dd 00:00:00
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        // 2. 获取当天的结束时间：yyyy-MM-dd 23:59:59.999
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        // 3. 转换为Date类型（适配你的实体类Date字段）
        Date startDate = Date.from(todayStart.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(todayEnd.atZone(ZoneId.systemDefault()).toInstant());
        LambdaQueryWrapper<DialogLog> todayWrapper = new LambdaQueryWrapper<>();
        todayWrapper.ge(DialogLog::getCreateTime, startDate)
            .le(DialogLog::getCreateTime, endDate);
        if(appIdList.size() > 0) {
            todayWrapper.in(DialogLog::getAppId,appIdList);
        }
        List<DialogLogVo> todayList = baseMapper.selectVoList(todayWrapper);
        dto.setTodayNum(todayList.size());
        //获取昨天数据
        Date yesterdayStart = MonthTimeUtils.getYesterdayStartAsDate();
        Date yesterdayEnd = MonthTimeUtils.getYesterdayEndAsDate();
        LambdaQueryWrapper<DialogLog> yesterdayWrapper = new LambdaQueryWrapper<>();
        yesterdayWrapper.between(DialogLog::getCreateTime,yesterdayStart,yesterdayEnd);
        if(appIdList.size() > 0) {
            yesterdayWrapper.in(DialogLog::getAppId,appIdList);
        }
        List<DialogLogVo> yesterdayList = baseMapper.selectVoList(yesterdayWrapper);
        dto.setBjYNum(todayList.size()-yesterdayList.size());
        return dto;
    }

    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;
    }
}
