package org.xyzh.study.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.common.dto.study.TbLearningTask;
import org.xyzh.common.dto.study.TbTaskUser;
import org.xyzh.common.dto.study.TbTaskItem;
import org.xyzh.common.vo.TaskItemVO;
import org.xyzh.common.vo.TaskVO;
import org.xyzh.study.mapper.LearningTaskMapper;
import org.xyzh.study.mapper.TaskUserMapper;
import org.xyzh.system.utils.LoginUtil;
import org.xyzh.study.mapper.TaskItemMapper;
import org.xyzh.api.study.task.LearningTaskService;
import org.xyzh.common.core.enums.TaskItemType;

/**
 * @description 学习任务服务实现类
 * @filename SCLearningTaskServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-15
 */
@Service
public class SCLearningTaskServiceImpl implements LearningTaskService {

    private static final Logger logger = LoggerFactory.getLogger(SCLearningTaskServiceImpl.class);

    @Autowired
    private LearningTaskMapper learningTaskMapper;

    @Autowired
    private TaskUserMapper taskUserMapper;

    @Autowired
    private TaskItemMapper taskItemMapper;

    @Override
    public ResultDomain<TbTaskItem> addTaskCourse(TbTaskItem taskItem) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ResultDomain<TbTaskItem> addTaskResource(TbTaskItem taskItem) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ResultDomain<TbTaskUser> addTaskUser(String taskID, List<String> userIDs) {
        ResultDomain<TbTaskUser> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("请先登录");
            return resultDomain;
        }
        List<TbTaskUser> taskUsers = new ArrayList<>();
        for (String userID : userIDs) {
            TbTaskUser taskUser = new TbTaskUser();
            taskUser.setID(IDUtils.generateID());
            taskUser.setTaskID(taskID);
            taskUser.setUserID(userID);
            taskUser.setCreator(user.getID());
            taskUser.setCreateTime(new Date());
            taskUsers.add(taskUser);
        }
        int result = taskUserMapper.batchInsertTaskUsers(taskUsers);
        if (result > 0) {
            resultDomain.success("添加任务用户成功", taskUsers);
            return resultDomain;
        } else {
            resultDomain.fail("添加任务用户失败");
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbTaskUser> batchAddTaskUsers(String taskID, List<String> userIDs, String deptID) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ResultDomain<TbLearningTask> getTaskPage(TbLearningTask filter, PageParam pageParam) {
        ResultDomain<TbLearningTask> resultDomain = new ResultDomain<>();
        List<TbLearningTask> taskList = learningTaskMapper.selectLearningTasksPage(filter, pageParam);
        long total = learningTaskMapper.countLearningTasks(filter);
        pageParam.setTotalElements(total);
        pageParam.setTotalPages((int) Math.ceil((double) total / pageParam.getPageSize()));
        PageDomain<TbLearningTask> pageDomain = new PageDomain<>();
        pageDomain.setDataList(taskList);
        pageDomain.setPageParam(pageParam);
        resultDomain.success("获取任务列表分页成功", pageDomain);
        return resultDomain;
    }

    @Override
    public ResultDomain<TbLearningTask> getUserTaskPage(TaskItemVO filter, PageParam pageParam) {
        ResultDomain<TbLearningTask> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("请先登录");
            return resultDomain;
        }
        filter.setUserID(user.getID());
        List<TbLearningTask> taskList = learningTaskMapper.selectUserLearningTasksPage(filter, pageParam);
        long total = learningTaskMapper.countLearningTasks(filter);
        pageParam.setTotalElements(total);
        pageParam.setTotalPages((int) Math.ceil((double) total / pageParam.getPageSize()));
        PageDomain<TbLearningTask> pageDomain = new PageDomain<>();
        pageDomain.setDataList(taskList);
        pageDomain.setPageParam(pageParam);
        resultDomain.success("获取任务列表分页成功", pageDomain);
        return resultDomain;
    }

    @Override
    public ResultDomain<TaskVO> createTask(TaskVO taskVO) {
        ResultDomain<TaskVO> resultDomain = new ResultDomain<>();
        TbSysUser currentUser = LoginUtil.getCurrentUser();
        String taskID = IDUtils.generateID();
        Date now = new Date();
        // 创建任务
        TbLearningTask learningTask = taskVO.getLearningTask();
        learningTask.setCreator(currentUser.getID());
        learningTask.setID(IDUtils.generateID());
        learningTask.setTaskID(taskID);
        learningTask.setCreateTime(now);
        learningTaskMapper.insertLearningTask(learningTask);
        
        // 绑定任务项（课程和资源）
        List<TbTaskItem> taskItems = new ArrayList<>();
        
        // 转换课程为任务项
        List<TbTaskItem> taskCourses = taskVO.toTaskCourses();
        taskCourses.forEach(item -> {
            item.setTaskID(taskID);
            item.setItemType(TaskItemType.COURSE.getValue());
            item.setCreator(currentUser.getID());
            item.setCreateTime(now);
        });
        taskItems.addAll(taskCourses);
        
        // 转换资源为任务项
        List<TbTaskItem> taskResources = taskVO.toTaskResources();
        taskResources.forEach(item -> {
            item.setTaskID(taskID);
            item.setItemType(TaskItemType.RESOURCE.getValue());
            item.setCreator(currentUser.getID());
            item.setCreateTime(now);
        });
        taskItems.addAll(taskResources);
        
        // 批量插入任务项
        if (!taskItems.isEmpty()) {
            taskItemMapper.batchInsertTaskItems(taskItems);
        }
        
        // 绑定用户
        List<TbTaskUser> taskUsers = taskVO.toTaskUsers();
        taskUsers.forEach(item -> {
            item.setTaskID(taskID);
            item.setCreator(currentUser.getID());
            item.setCreateTime(now);
        });
        taskUserMapper.batchInsertTaskUsers(taskUsers);

        resultDomain.success("创建任务成功", taskVO);
        return resultDomain;
    }

    @Override
    public ResultDomain<TaskVO> updateTask(TaskVO taskVO) {
        ResultDomain<TaskVO> resultDomain = new ResultDomain<>();
        
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("请先登录");
            return resultDomain;
        }
        
        TbLearningTask task = taskVO.getLearningTask();
        String taskID = task.getTaskID();
        
        if (taskID == null || taskID.isEmpty()) {
            resultDomain.fail("任务ID不能为空");
            return resultDomain;
        }
        
        Date now = new Date();
        
        // 1. 更新任务基本信息
        task.setUpdater(user.getID());
        task.setUpdateTime(now);
        learningTaskMapper.updateLearningTask(task);
        
        // 2. 处理任务项关联（课程和资源）
        List<TaskItemVO> newCourseItems = taskVO.getTaskCourses();
        List<TaskItemVO> newResourceItems = taskVO.getTaskResources();
        if (newCourseItems == null) {
            newCourseItems = new ArrayList<>();
        }
        if (newResourceItems == null) {
            newResourceItems = new ArrayList<>();
        }
        
        // 获取现有的所有任务项
        List<TbTaskItem> existingItems = taskItemMapper.selectByTaskId(taskID);
        
        // 分离课程和资源
        List<TbTaskItem> existingCourses = existingItems.stream()
                .filter(item -> item.getItemType().equals(TaskItemType.COURSE.getValue()))
                .collect(Collectors.toList());
        List<TbTaskItem> existingResources = existingItems.stream()
                .filter(item -> item.getItemType().equals(TaskItemType.RESOURCE.getValue()))
                .collect(Collectors.toList());
        
        Map<String, TbTaskItem> existingCourseMap = existingCourses.stream()
                .collect(Collectors.toMap(TbTaskItem::getItemID, item -> item));
        Map<String, TbTaskItem> existingResourceMap = existingResources.stream()
                .collect(Collectors.toMap(TbTaskItem::getItemID, item -> item));
        
        Set<String> newCourseIDs = new HashSet<>();
        Set<String> newResourceIDs = new HashSet<>();
        List<TbTaskItem> itemsToInsert = new ArrayList<>();
        
        // 处理新的课程关联
        for (TaskItemVO item : newCourseItems) {
            String courseID = item.getCourseID();
            if (courseID == null || courseID.isEmpty()) {
                continue;
            }
            newCourseIDs.add(courseID);
            
            if (!existingCourseMap.containsKey(courseID)) {
                TbTaskItem taskItem = new TbTaskItem();
                taskItem.setID(IDUtils.generateID());
                taskItem.setTaskID(taskID);
                taskItem.setItemType(TaskItemType.COURSE.getValue());
                taskItem.setItemID(courseID);
                taskItem.setRequired(item.getRequired());
                taskItem.setOrderNum(item.getOrderNum());
                taskItem.setCreator(user.getID());
                taskItem.setCreateTime(now);
                itemsToInsert.add(taskItem);
            }
        }
        
        // 处理新的资源关联
        for (TaskItemVO item : newResourceItems) {
            String resourceID = item.getResourceID();
            if (resourceID == null || resourceID.isEmpty()) {
                continue;
            }
            newResourceIDs.add(resourceID);
            
            if (!existingResourceMap.containsKey(resourceID)) {
                TbTaskItem taskItem = new TbTaskItem();
                taskItem.setID(IDUtils.generateID());
                taskItem.setTaskID(taskID);
                taskItem.setItemType(TaskItemType.RESOURCE.getValue());
                taskItem.setItemID(resourceID);
                taskItem.setRequired(item.getRequired());
                taskItem.setOrderNum(item.getOrderNum());
                taskItem.setCreator(user.getID());
                taskItem.setCreateTime(now);
                itemsToInsert.add(taskItem);
            }
        }
        
        // 找出要删除的任务项
        List<String> itemIDsToDelete = new ArrayList<>();
        existingCourseMap.values().stream()
                .filter(item -> !newCourseIDs.contains(item.getItemID()))
                .forEach(item -> itemIDsToDelete.add(item.getID()));
        existingResourceMap.values().stream()
                .filter(item -> !newResourceIDs.contains(item.getItemID()))
                .forEach(item -> itemIDsToDelete.add(item.getID()));
        
        if (!itemIDsToDelete.isEmpty()) {
            taskItemMapper.batchDeleteTaskItems(itemIDsToDelete);
        }
        
        if (!itemsToInsert.isEmpty()) {
            taskItemMapper.batchInsertTaskItems(itemsToInsert);
        }
        
        // 3. 处理任务用户关联
        List<TaskItemVO> newUserItems = taskVO.getTaskUsers();
        if (newUserItems == null) {
            newUserItems = new ArrayList<>();
        }
        
        // 获取现有的用户关联
        List<TbTaskUser> existingUsers = taskUserMapper.selectByTaskId(taskID);
        Map<String, TbTaskUser> existingUserMap = existingUsers.stream()
                .collect(Collectors.toMap(TbTaskUser::getUserID, taskUser -> taskUser));
        
        Set<String> newUserIDs = new HashSet<>();
        List<TbTaskUser> usersToInsert = new ArrayList<>();
        
        // 处理新的用户关联
        for (TaskItemVO item : newUserItems) {
            String userID = item.getUserID();
            if (userID == null || userID.isEmpty()) {
                continue;
            }
            
            newUserIDs.add(userID);
            
            // 如果不存在，则新增
            if (!existingUserMap.containsKey(userID)) {
                TbTaskUser taskUser = new TbTaskUser();
                taskUser.setID(IDUtils.generateID());
                taskUser.setTaskID(taskID);
                taskUser.setUserID(userID);
                taskUser.setCreator(user.getID());
                taskUser.setCreateTime(now);
                usersToInsert.add(taskUser);
            }
        }
        
        // 找出要删除的用户关联
        List<String> userIDsToDelete = existingUserMap.values().stream()
                .filter(taskUser -> !newUserIDs.contains(taskUser.getUserID()))
                .map(TbTaskUser::getID)
                .collect(Collectors.toList());
        
        if (!userIDsToDelete.isEmpty()) {
            taskUserMapper.batchDeleteTaskUsers(taskID, userIDsToDelete);
        }
        
        if (!usersToInsert.isEmpty()) {
            taskUserMapper.batchInsertTaskUsers(usersToInsert);
        }
        
        resultDomain.success("更新任务成功", taskVO);
        return resultDomain;
    }

    @Override
    public ResultDomain<Boolean> deleteTask(String taskID) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ResultDomain<TaskVO> getTaskById(String taskID) {
        ResultDomain<TaskVO> resultDomain = new ResultDomain<>();
        TaskVO taskVO = new TaskVO();
        TbLearningTask task = learningTaskMapper.selectByTaskId(taskID);
        if (task == null) {
            resultDomain.fail("任务不存在");
            return resultDomain;
        }
        
        // 获取所有任务项
        List<TaskItemVO> allTaskItems = taskItemMapper.selectTaskItemVOByTaskId(taskID);
        
        // 一次循环完成分离和统计
        List<TaskItemVO> taskCourses = new ArrayList<>();
        List<TaskItemVO> taskResources = new ArrayList<>();
        int completedTaskNum = 0;
        int learningTaskNum = 0;
        int notStartTaskNum = 0;
        
        for (TaskItemVO item : allTaskItems) {
            // 分离课程和资源
            if (item.getItemType() != null) {
                if (item.getItemType().equals(TaskItemType.COURSE.getValue())) {
                    taskCourses.add(item);
                } else if (item.getItemType().equals(TaskItemType.RESOURCE.getValue())) {
                    taskResources.add(item);
                }
            }
            
            // 统计状态
            Integer status = item.getStatus();
            if (status != null) {
                if (status == 2) {
                    completedTaskNum++;
                } else if (status == 1) {
                    learningTaskNum++;
                } else if (status == 0) {
                    notStartTaskNum++;
                }
            }
        }

        taskVO.setCompletedTaskNum(completedTaskNum);
        taskVO.setLearningTaskNum(learningTaskNum);
        taskVO.setNotStartTaskNum(notStartTaskNum);
        
        List<TaskItemVO> taskUsers = taskUserMapper.selectTaskItemByTaskId(taskID);
        taskVO.setLearningTask(task);
        taskVO.setTaskCourses(taskCourses);
        taskVO.setTaskResources(taskResources);
        taskVO.setTaskUsers(taskUsers);

        taskVO.setTotalTaskNum(allTaskItems.size());

 

        resultDomain.success("获取任务详情成功", taskVO);
        return resultDomain;
    }


    @Override
    public ResultDomain<TaskVO> getTaskUser(String taskID) {
        ResultDomain<TaskVO> resultDomain = new ResultDomain<>();
        TaskVO taskVO = new TaskVO();
        TbLearningTask task = learningTaskMapper.selectByTaskId(taskID);
        if (task == null) {
            resultDomain.fail("任务不存在");
            return resultDomain;
        }
        
        // 获取所有任务项
        List<TaskItemVO> allTaskItems = taskItemMapper.selectTaskItemVOByTaskId(taskID);
        
        // 一次循环完成分离和统计
        List<TaskItemVO> taskCourses = new ArrayList<>();
        List<TaskItemVO> taskResources = new ArrayList<>();
        int completedTaskNum = 0;
        int learningTaskNum = 0;
        int notStartTaskNum = 0;
        
        for (TaskItemVO item : allTaskItems) {
            // 分离课程和资源
            if (item.getItemType() != null) {
                if (item.getItemType().equals(TaskItemType.COURSE.getValue())) {
                    taskCourses.add(item);
                } else if (item.getItemType().equals(TaskItemType.RESOURCE.getValue())) {
                    taskResources.add(item);
                }
            }
            
            // 统计状态
            Integer status = item.getStatus();
            if (status != null) {
                if (status == 2) {
                    completedTaskNum++;
                } else if (status == 1) {
                    learningTaskNum++;
                } else if (status == 0) {
                    notStartTaskNum++;
                }
            }
        }

        taskVO.setCompletedTaskNum(completedTaskNum);
        taskVO.setLearningTaskNum(learningTaskNum);
        taskVO.setNotStartTaskNum(notStartTaskNum);
        
        List<TaskItemVO> taskUsers = taskUserMapper.selectUserTaskItem(taskID, LoginUtil.getCurrentUser().getID());
        taskVO.setLearningTask(task);
        taskVO.setTaskCourses(taskCourses);
        taskVO.setTaskResources(taskResources);
        taskVO.setTaskUsers(taskUsers);

        taskVO.setTotalTaskNum(allTaskItems.size());

 

        resultDomain.success("获取任务详情成功", taskVO);
        return resultDomain;
    }


    @Override
    public ResultDomain<TbTaskItem> getTaskCourses(String taskID) {
        ResultDomain<TbTaskItem> resultDomain = new ResultDomain<>();
        List<TbTaskItem> taskCourses = taskItemMapper.selectByTaskIdAndType(taskID, TaskItemType.COURSE.getValue());
        resultDomain.success("获取任务课程列表成功", taskCourses);
        return resultDomain;
    }

    @Override
    public ResultDomain<TbLearningTask> getTaskList(TbLearningTask filter) {
        ResultDomain<TbLearningTask> resultDomain = new ResultDomain<>();
        List<TbLearningTask> taskList = learningTaskMapper.selectLearningTasks(filter);
        resultDomain.success("获取任务列表成功", taskList);
        return resultDomain;
    }

    @Override
    public ResultDomain<TbTaskItem> getTaskResources(String taskID) {
        ResultDomain<TbTaskItem> resultDomain = new ResultDomain<>();
        List<TbTaskItem> taskResources = taskItemMapper.selectByTaskIdAndType(taskID, TaskItemType.RESOURCE.getValue());
        resultDomain.success("获取任务资源列表成功", taskResources);
        return resultDomain;
    }

    @Override
    public ResultDomain<TaskItemVO> getTaskUsers(String taskID) {
        ResultDomain<TaskItemVO> resultDomain = new ResultDomain<>();
        List<TaskItemVO> taskUsers = taskUserMapper.selectTaskItemByTaskId(taskID);
        resultDomain.success("获取任务用户列表成功", taskUsers);
        return resultDomain;
    }

    @Override
    public ResultDomain<Boolean> removeTaskCourse(String taskID, String courseID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        TbTaskItem taskItem = taskItemMapper.selectByTaskIdAndItemId(taskID, courseID, TaskItemType.COURSE.getValue());
        if (taskItem != null) {
            taskItemMapper.deleteTaskItem(taskItem);
            resultDomain.success("移除任务课程成功", true);
        } else {
            resultDomain.fail("任务课程不存在");
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<Boolean> removeTaskResource(String taskID, String resourceID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        TbTaskItem taskItem = taskItemMapper.selectByTaskIdAndItemId(taskID, resourceID, TaskItemType.RESOURCE.getValue());
        if (taskItem != null) {
            taskItemMapper.deleteTaskItem(taskItem);
            resultDomain.success("移除任务资源成功", true);
        } else {
            resultDomain.fail("任务资源不存在");
        }
        return resultDomain;
    }

    @Override
    public ResultDomain<Boolean> removeTaskUser(String taskID, List<String> userIDs) {

        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("请先登录");
            return resultDomain;
        }
        int result = taskUserMapper.batchDeleteTaskUsers(taskID, userIDs);
        if (result > 0) {
            resultDomain.success("移除任务用户成功", true);
            return resultDomain;
        } else {
            resultDomain.fail("移除任务用户失败");
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbLearningTask> updateTaskStatus(String taskID, Integer status) {
        ResultDomain<TbLearningTask> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("请先登录");
            return resultDomain;
        }
        TbLearningTask task = new TbLearningTask();
        task.setUpdater(user.getID());
        task.setUpdateTime(new Date());
        task.setTaskID(taskID);
        task.setStatus(status);
        int result = learningTaskMapper.updateLearningTask(task);
        if (result > 0) {
            resultDomain.success("更新任务状态成功", task);
            return resultDomain;
        } else {
            resultDomain.fail("更新任务状态失败");
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbTaskUser> updateTaskUserStatus(String taskID, String userID, Integer status,
            BigDecimal progress) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ResultDomain<TaskVO> getUserProgress(String userID) {
        ResultDomain<TaskVO> resultDomain = new ResultDomain<>();
        TaskVO taskVO = new TaskVO();
        
        TbTaskUser fliter = new TbTaskUser();
        fliter.setUserID(userID);
        // 获取用户所有任务关联
        List<TbTaskUser> taskUsers = taskUserMapper.selectTaskUsers(fliter);
        taskVO.setCompletedTaskNum((int) taskUsers.stream().filter(item -> item.getStatus() == 2).count());
        taskVO.setLearningTaskNum((int) taskUsers.stream().filter(item -> item.getStatus() == 1).count());
        taskVO.setNotStartTaskNum((int) taskUsers.stream().filter(item -> item.getStatus() == 0).count());
        taskVO.setTotalTaskNum(taskUsers.size());
        resultDomain.success("获取用户整体学习进度成功", taskVO);
        return resultDomain;
    }
}
