package com.ruoyi.project.service.impl;

import com.ruoyi.project.domain.DeptProofreadStatsVo;
import com.ruoyi.project.domain.TrsResultsStatsSimpleVo;
import com.ruoyi.project.mapper.TrsResultsLogStatsSimpleMapper;
import com.ruoyi.project.service.ITrsResultsStatsSimpleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TrsResultsStatsSimpleServiceImpl implements ITrsResultsStatsSimpleService {

    @Autowired
    private TrsResultsLogStatsSimpleMapper trsResultsLogStatsSimpleMapper;

    @Override
    public TrsResultsStatsSimpleVo getStats(Date beginTime, Date endTime) {
        TrsResultsStatsSimpleVo vo = new TrsResultsStatsSimpleVo();

        vo.setStartTime(beginTime);
        vo.setEndTime(endTime);

        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", beginTime);
        params.put("endTime", endTime);

        // 1. 总体活跃程度
        Map<String, Object> totalStats = trsResultsLogStatsSimpleMapper.selectTotalStats(params);
        if (totalStats != null) {
            vo.setTotalLogCount(getIntegerValue(totalStats.get("totalLogCount")));
            vo.setTotalWordCount(getIntegerValue(totalStats.get("totalWordCount")));
            vo.setActiveUserCount(getIntegerValue(totalStats.get("activeUserCount")));
            vo.setActiveDeptCount(getIntegerValue(totalStats.get("activeDeptCount")));
        }

        // 2. 各盟市/部门活跃账号（按内蒙古自治区直接下级部门统计）
        List<Map<String, Object>> deptStats = trsResultsLogStatsSimpleMapper.selectDeptStats(params);
        List<TrsResultsStatsSimpleVo.DeptStatsVo> deptStatsList = new ArrayList<>();

        for (Map<String, Object> dept : deptStats) {
            TrsResultsStatsSimpleVo.DeptStatsVo deptVo = new TrsResultsStatsSimpleVo.DeptStatsVo();
            deptVo.setDeptId(getLongValue(dept.get("deptId")));
            deptVo.setDeptName((String) dept.get("deptName"));
            deptVo.setUserCount(getIntegerValue(dept.get("userCount")));
            deptVo.setLogCount(getIntegerValue(dept.get("logCount")));
            deptVo.setWordCount(getIntegerValue(dept.get("wordCount")));

            // 获取部门下的活跃用户
            Map<String, Object> userParams = new HashMap<>(params);
            userParams.put("rootDeptId", deptVo.getDeptId());

            List<Map<String, Object>> userStats = trsResultsLogStatsSimpleMapper.selectDeptActiveUsers(userParams);
            List<TrsResultsStatsSimpleVo.UserActiveVo> userList = new ArrayList<>();

            for (Map<String, Object> user : userStats) {
                TrsResultsStatsSimpleVo.UserActiveVo userVo = new TrsResultsStatsSimpleVo.UserActiveVo();
                userVo.setUserId(getLongValue(user.get("userId")));
                userVo.setUserName((String) user.get("userName"));
                userVo.setLoginName((String) user.get("loginName"));
                userVo.setLogCount(getIntegerValue(user.get("logCount")));
                userVo.setWordCount(getIntegerValue(user.get("wordCount")));
                userList.add(userVo);
            }
            deptVo.setActiveUsers(userList);
            deptStatsList.add(deptVo);
        }
        vo.setDeptStatsList(deptStatsList);

        // 3. 自定义词增加排行
        /*List<Map<String, Object>> customWordStats = trsResultsLogStatsSimpleMapper.selectCustomWordRank(params);
        List<TrsResultsStatsSimpleVo.CustomWordRankVo> customWordList = new ArrayList<>();

        for (Map<String, Object> item : customWordStats) {
            TrsResultsStatsSimpleVo.CustomWordRankVo rankVo = new TrsResultsStatsSimpleVo.CustomWordRankVo();
            rankVo.setType((String) item.get("type"));
            rankVo.setId(getLongValue(item.get("id")));
            rankVo.setName((String) item.get("name"));
            rankVo.setLoginName((String) item.get("loginName"));
            rankVo.setDeptName((String) item.get("deptName"));
            rankVo.setAddCount(getIntegerValue(item.get("addCount")));
            customWordList.add(rankVo);
        }
        vo.setCustomWordRank(customWordList);*/

        // 4. 错误类型占比
        List<Map<String, Object>> errorTypeStats = trsResultsLogStatsSimpleMapper.selectErrorTypeRatio(params);
        List<TrsResultsStatsSimpleVo.ErrorTypeVo> errorTypeList = new ArrayList<>();
        Long total = 0L;
        for (Map<String, Object> item : errorTypeStats) {
            Long count = getLongValue(item.get("count"));
            total += count;
        }

        for (Map<String, Object> item : errorTypeStats) {
            TrsResultsStatsSimpleVo.ErrorTypeVo errorVo = new TrsResultsStatsSimpleVo.ErrorTypeVo();
            errorVo.setErrorType((String) item.get("errorType"));
            Long count = getLongValue(item.get("count"));
            errorVo.setCount(count);
            errorVo.setPercentage(total > 0 ? (double) Math.round((double) count / total * 100 * 10) / 10 : 0);
            errorTypeList.add(errorVo);
        }
        vo.setErrorTypeRatio(errorTypeList);

        // 5. 趋势数据
        /*List<Map<String, Object>> trendStats = trsResultsLogStatsSimpleMapper.selectTrendData(params);
        List<TrsResultsStatsSimpleVo.TrendDataVo> trendList = new ArrayList<>();
        for (Map<String, Object> item : trendStats) {
            TrsResultsStatsSimpleVo.TrendDataVo trendVo = new TrsResultsStatsSimpleVo.TrendDataVo();
            trendVo.setDate((String) item.get("date"));
            trendVo.setLogCount(getIntegerValue(item.get("logCount")));
            trendVo.setWordCount(getIntegerValue(item.get("wordCount")));
            trendVo.setUserCount(getIntegerValue(item.get("userCount")));
            trendList.add(trendVo);
        }
        vo.setTrendData(trendList);*/

        return vo;
    }

    @Override
    public TrsResultsStatsSimpleVo getLast30DaysStats() {
        Calendar calendar = Calendar.getInstance();
        Date endTime = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -30);
        Date beginTime = calendar.getTime();

        return getStats(beginTime, endTime);
    }

    @Override
    public List<TrsResultsStatsSimpleVo.UserActiveVo> getDeptUsers(Long deptId, Date beginTime, Date endTime) {
        Map<String, Object> params = new HashMap<>();
        params.put("rootDeptId", deptId);
        params.put("beginTime", beginTime);
        params.put("endTime", endTime);

        List<Map<String, Object>> userStats = trsResultsLogStatsSimpleMapper.selectDeptActiveUsers(params);
        List<TrsResultsStatsSimpleVo.UserActiveVo> userList = new ArrayList<>();

        for (Map<String, Object> user : userStats) {
            TrsResultsStatsSimpleVo.UserActiveVo userVo = new TrsResultsStatsSimpleVo.UserActiveVo();
            userVo.setUserId(getLongValue(user.get("userId")));
            userVo.setUserName((String) user.get("userName"));
            userVo.setLoginName((String) user.get("loginName"));
            userVo.setLogCount(getIntegerValue(user.get("logCount")));
            userVo.setWordCount(getIntegerValue(user.get("wordCount")));
            userList.add(userVo);
        }

        return userList;
    }

    @Override
    public List<DeptProofreadStatsVo> getDeptProofreadStats(Date beginTime, Date endTime) {
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", beginTime);
        params.put("endTime", endTime);

        return trsResultsLogStatsSimpleMapper.selectDeptProofreadStats(params);
    }

    /**
     * 安全地获取Long值
     */
    private Long getLongValue(Object obj) {
        if (obj == null) {
            return 0L;
        }
        if (obj instanceof Long) {
            return (Long) obj;
        }
        if (obj instanceof Integer) {
            return ((Integer) obj).longValue();
        }
        if (obj instanceof String) {
            try {
                return Long.parseLong((String) obj);
            } catch (NumberFormatException e) {
                return 0L;
            }
        }
        return 0L;
    }

    /**
     * 安全地获取Integer值
     */
    private Integer getIntegerValue(Object obj) {
        if (obj == null) {
            return 0;
        }
        if (obj instanceof Integer) {
            return (Integer) obj;
        }
        if (obj instanceof Long) {
            return ((Long) obj).intValue();
        }
        if (obj instanceof String) {
            try {
                return Integer.parseInt((String) obj);
            } catch (NumberFormatException e) {
                return 0;
            }
        }
        return 0;
    }
}