package com.easyproject.system.service.home.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coze.openapi.client.common.pagination.PageResp;
import com.coze.openapi.client.dataset.ListDatasetReq;
import com.coze.openapi.client.dataset.model.Dataset;
import com.coze.openapi.service.service.CozeAPI;
import com.easyproject.common.core.domain.AjaxResult;
import com.easyproject.common.utils.coze.ChatAiForCozeUtils;
import com.easyproject.service.domain.coze.CozeTokenSet;
import com.easyproject.service.domain.coze.CozeWorkspacesSet;
import com.easyproject.service.domain.log.ClientOperLog;
import com.easyproject.service.mapper.aichat.BotConversationChatMapper;
import com.easyproject.service.mapper.aichat.BotConversationMapper;
import com.easyproject.service.mapper.coze.CozeWorkspacesSetMapper;
import com.easyproject.service.mapper.log.ClientOperLogMapper;
import com.easyproject.service.service.ICozeJwtService;
import com.easyproject.system.domain.vo.KnowledgeListVo;
import com.easyproject.system.domain.vo.home.PageViewTotalVo;
import com.easyproject.system.domain.vo.home.TotalInfoVo;
import com.easyproject.system.service.home.IIndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * 方法说明: 首页数据统计
 * @param
 * @return
 * @author java-101
 * @date 2025-04-11 12:39:00
 */
@Slf4j
@Service
public class IndexServiceImpl implements IIndexService {

    @Resource
    private CozeWorkspacesSetMapper cozeWorkspacesSetMapper;
    @Resource
    private BotConversationMapper botConversationMapper;
    @Resource
    private BotConversationChatMapper botConversationChatMapper;
    @Resource
    private ClientOperLogMapper clientOperLogMapper;
    @Resource
    private ICozeJwtService cozeJwtService;

    /**
     * 方法说明:  获取近N天的日期
     * @param
     * @return ['2024-04-26', '2023-04-27', '2023-04-28', '2023-04-29', '2023-04-30', '2023-04-31', '2023-05-01']
     * @author java-101
     * @date 2025-04-11 14:35:49
     */
    private String[] getDayDate(int num) {
        // 获取当前日期
        Date currentDate = DateUtil.date();

        // 创建一个数组来存储近七天的日期
        Date[] datesArray = new Date[num];
        String[] datesArrayStr = new String[num];

        // 添加近七天的日期到数组中
        for (int i = 0; i < num; i++) {
            datesArray[i] = DateUtil.offsetDay(currentDate, -i);
            datesArrayStr[i] = DateUtil.format(datesArray[i], "yyyy-MM-dd");
        }
        return datesArrayStr;
    }

    /**
     * 方法说明: 首页-顶部统计
     * @param
     * @return
     * @author java-101
     * @date 2025-04-11 12:42:23
     */
    @Override
    public AjaxResult getTotalInfo() {
        int sessionTotalNum = 0; // 会话统计-累计会话数
        int sessionTodayNum = 0; // 会话统计-今日新增
        int chatTotalNum = 0; // 对话统计-累计对话数
        int chatTodayNum = 0; // 对话统计-今日新增

        //查询对话相关-本地
        sessionTotalNum = botConversationMapper.selectConversationNum(2);
        sessionTodayNum = botConversationMapper.selectConversationNum(1);

        chatTotalNum = botConversationChatMapper.selectConversationChatNum(2);
        chatTodayNum = botConversationChatMapper.selectConversationChatNum(1);

        //查询知识库相关-coze
        TotalInfoVo vo = getTotalInfoVo();
        vo.setSessionTotalNum(sessionTotalNum);
        vo.setSessionTodayNum(sessionTodayNum);
        vo.setChatTotalNum(chatTotalNum);
        vo.setChatTodayNum(chatTodayNum);
        return AjaxResult.success(vo);
    }

    /**
     * 方法说明:  查询知识库相关-coze
     * @param
     * @return
     * @author java-101
     * @date 2025-04-11 14:34:30
     */
    private TotalInfoVo getTotalInfoVo() {
        TotalInfoVo totalInfoVo = new TotalInfoVo();
        totalInfoVo.setKnowledgeTotalNum(0);
        totalInfoVo.setKnowledgeTodayNum(0);
        totalInfoVo.setKnowledgeFileTotalNum(0);
        // 查询系统token 使用JWT方式获取token（永久授权）
        CozeTokenSet tokenSet = cozeJwtService.getCozeTokenSetForToken();
        if(ObjectUtil.isEmpty(tokenSet)){
            return totalInfoVo;
        }

        //查询有效空间
        CozeWorkspacesSet workspacesSet = cozeWorkspacesSetMapper.selectOne(Wrappers.<CozeWorkspacesSet>lambdaQuery().eq(CozeWorkspacesSet::getStatus,1).orderByDesc(CozeWorkspacesSet::getId).last("limit 1"));
        if(ObjectUtil.isEmpty(workspacesSet)){

            return totalInfoVo;
        }
        String spaceID = workspacesSet.getSpacesId();

        List<KnowledgeListVo> voList = null;

        //初始化客户端
        CozeAPI coze = ChatAiForCozeUtils.getCozeClient(tokenSet.getPersonToken());
        ListDatasetReq req = ListDatasetReq.builder()
                .spaceID(spaceID)
                .name(null)
                .formatType(null)
                .pageSize(300)
                .pageNum(1)
                .build();

        // 使用迭代器自动获取下一页
        PageResp<Dataset> datasets = coze.datasets().list(req);
        totalInfoVo.setKnowledgeTotalNum(datasets.getTotal());
        int knowledgeTodayNum = 0;//今日新增知识库
        int knowledgeFileTotalNum = 0;//知识库文件数量
        for (Dataset item : datasets.getItems()) {
            //利用hutool工具 将秒级时间戳转为时间，和当前时间比较，判断是否为今日创建的
            DateTime createTime = DateUtil.date(item.getCreateTime()*1000);
            if(DateUtil.isSameDay(createTime,new Date())){
                knowledgeTodayNum = knowledgeTodayNum + 1;
            }
            knowledgeFileTotalNum = knowledgeFileTotalNum + item.getFileList().size();
        }
        totalInfoVo.setKnowledgeTodayNum(knowledgeTodayNum);
        totalInfoVo.setKnowledgeFileTotalNum(knowledgeFileTotalNum);
        return totalInfoVo;
    }

    /**
     * 方法说明: 首页-查询访问量（近15天）
     * @param
     * @return
     * @author java-101
     * @date 2025-04-11 12:42:39
     */
    @Override
    public AjaxResult getPageViewTotalList() {
        PageViewTotalVo vo = new PageViewTotalVo();

        String[] dateArray = getDayDate(15);
        Arrays.sort(dateArray);

        //访问量
        Long[] pvData = new Long[dateArray.length];

        if (ObjectUtil.isNotEmpty(dateArray)) {
            for (int i = 0; i < dateArray.length; i++) {
                String item = dateArray[i];
                //查询用户端操作日志表数据
                long count = clientOperLogMapper.selectCount(Wrappers.<ClientOperLog>lambdaQuery().apply("date_format(oper_time,'%Y-%m-%d') = {0}", item));
                pvData[i] = count;
            }
        }

        vo.setDateTimeData(dateArray);
        vo.setPvData(pvData);

        return AjaxResult.success(vo);
    }
}
