package org.xyzh.study.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

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.enums.TaskItemType;
import org.xyzh.common.dto.study.TbLearningRecord;
import org.xyzh.common.dto.study.TbTaskItem;
import org.xyzh.common.dto.study.TbTaskUser;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.vo.TaskItemVO;
import org.xyzh.api.study.record.LearningRecordService;
import org.xyzh.study.mapper.LearningRecordMapper;
import org.xyzh.study.mapper.TaskItemMapper;
import org.xyzh.study.mapper.TaskUserMapper;
import org.xyzh.system.utils.LoginUtil;

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

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

    @Autowired
    private LearningRecordMapper learningRecordMapper;

    @Autowired
    private TaskItemMapper taskItemMapper;

    @Autowired
    private TaskUserMapper taskUserMapper;

    @Override
    public ResultDomain<TbLearningRecord> insertLearningRecord(TbLearningRecord learningRecord) {
        ResultDomain<TbLearningRecord> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
          resultDomain.fail("请先登录");
          return resultDomain;
        }
        learningRecord.setUserID(user.getID());
        learningRecord.setCreateTime(new Date());
        if (learningRecord.getResourceType() == null) {
          resultDomain.fail("资源类型不能为空");
          return resultDomain;
        }
        if (learningRecord.getResourceType() == 1 && learningRecord.getResourceID() == null) {
          resultDomain.fail("资源ID不能为空");
          return resultDomain;
        }
        if (learningRecord.getResourceType() == 2 && (learningRecord.getCourseID() == null || learningRecord.getChapterID() == null || learningRecord.getNodeID() == null)) {
          resultDomain.fail("课程信息不能为空");
          return resultDomain;
        }
        List<TbLearningRecord> records = learningRecordMapper.selectLearningRecords(learningRecord);
        if (records.size() > 0) {
          resultDomain.fail("学习记录已存在");
          return resultDomain;
        }
        List<TaskItemVO> allTaskItems = taskItemMapper.selectTaskItemVOByTaskIdAndUserId(learningRecord.getTaskID(), user.getID());
        if (allTaskItems == null || allTaskItems.isEmpty()) {
          TbTaskUser taskUser = new TbTaskUser();
          taskUser.setTaskID(learningRecord.getTaskID());
          taskUser.setUserID(user.getID());
          taskUser.setProgress(new BigDecimal(0));
          taskUser.setUpdater(user.getID());
          
          // 全部完成
          taskUser.setStatus(1);
          taskUser.setUpdateTime(new Date());
          taskUserMapper.updateTaskUser(taskUser);
        }
        
        int result = learningRecordMapper.insertLearningRecord(learningRecord);
        if (result > 0) {
          resultDomain.success("创建学习记录成功", learningRecord);
          return resultDomain;
        } else {
          resultDomain.fail("创建学习记录失败");
          return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbLearningRecord> updateLearningRecord(TbLearningRecord learningRecord) {
        ResultDomain<TbLearningRecord> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
          resultDomain.fail("请先登录");
          return resultDomain;
        }
        learningRecord.setUpdater(user.getID());

        int result = learningRecordMapper.updateLearningRecord(learningRecord);
        if (result > 0) {
          resultDomain.success("更新学习记录成功", learningRecord);
          return resultDomain;
        } else {
          resultDomain.fail("更新学习记录失败");
          return resultDomain;
        }
    }

    @Override
    public ResultDomain<Boolean> deleteLearningRecord(String recordID) {
      ResultDomain<Boolean> resultDomain = new ResultDomain<>();
      int result = learningRecordMapper.deleteLearningRecord(recordID);
      if (result > 0) {
        resultDomain.success("删除学习记录成功", true);
        return resultDomain;
      } else {
        resultDomain.fail("删除学习记录失败");
        return resultDomain;
      }
    }


    @Override
    public ResultDomain<TbLearningRecord> getLearningRecord(TbLearningRecord learningRecord) {
      ResultDomain<TbLearningRecord> resultDomain = new ResultDomain<>();
      List<TbLearningRecord> records = learningRecordMapper.selectLearningRecords(learningRecord);
      resultDomain.success("获取学习记录成功", records);
      return resultDomain;
    }
    

    @Override
    public ResultDomain<TbLearningRecord> getCourseLearningRecord(TbLearningRecord learningRecord) {
      ResultDomain<TbLearningRecord> resultDomain = new ResultDomain<>();

      if (learningRecord.getCourseID() == null) {
        resultDomain.fail("课程ID不能为空");
        return resultDomain;
      }
      learningRecord.setResourceType(2);
      List<TbLearningRecord> records = learningRecordMapper.selectLearningRecords(learningRecord);
      resultDomain.success("获取学习记录成功", records);
      return resultDomain;
    }

    @Override
    public ResultDomain<TbLearningRecord> getResourceLearningRecords(TbLearningRecord learningRecord) {
      ResultDomain<TbLearningRecord> resultDomain = new ResultDomain<>();
      TbSysUser user = LoginUtil.getCurrentUser();
      if (user == null) {
        resultDomain.fail("请先登录");
        return resultDomain;
      }
      learningRecord.setUserID(user.getID());
      if (learningRecord.getResourceID() == null) {
        resultDomain.fail("资源ID不能为空");
        return resultDomain;
      }
      learningRecord.setResourceType(1);
      List<TbLearningRecord> records = learningRecordMapper.selectLearningRecords(learningRecord);
      resultDomain.success("获取学习记录成功", records);
      return resultDomain;
    }

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

    @Override
    public ResultDomain<TbLearningRecord> getUserLearningProgress(String userID, Integer resourceType,
        String resourceID) {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public ResultDomain<TbLearningRecord> getUserLearningStatistics(String userID, Integer resourceType) {
      // TODO Auto-generated method stub
      return null;
    }


    @Override
    public ResultDomain<TbLearningRecord> markLearningComplete(TbLearningRecord learningRecord) {
      ResultDomain<TbLearningRecord> resultDomain = new ResultDomain<>();
      TbSysUser user = LoginUtil.getCurrentUser();
      if (user == null) {
        resultDomain.fail("请先登录");
        return resultDomain;
      }
      learningRecord.setUpdater(user.getID());
      learningRecord.setCompleteTime(new Date());
      learningRecord.setIsComplete(true);
      int result = learningRecordMapper.updateLearningRecord(learningRecord);
      if (result > 0) {
        // 检查是否完成了该任务的所有任务项
        String taskId = learningRecord.getTaskID();
        String userId = user.getID();
        if (taskId != null && !taskId.isEmpty()) {
          checkAndUpdateTaskCompletion(taskId, userId);
        }
        
        resultDomain.success("标记学习完成成功", learningRecord);
        return resultDomain;
      } else {
        resultDomain.fail("标记学习完成失败");
        return resultDomain;
      }
    }

    /**
     * @description 检查并更新任务完成状态
     * @param taskId 任务ID
     * @param userId 用户ID
     * @author yslg
     * @since 2025-10-24
     */
    private void checkAndUpdateTaskCompletion(String taskId, String userId) {
      try {
        // 获取该任务下所有任务项（包含该用户的学习状态）
        List<TaskItemVO> allTaskItems = taskItemMapper.selectTaskItemVOByTaskIdAndUserId(taskId, userId);
        if (allTaskItems == null || allTaskItems.isEmpty()) {
          return;
        }
        
        // 检查是否所有必须的任务项都已完成（status = 2）
        boolean allCompleted = true;
        int totalRequired = 0;
        int completedRequired = 0;
        
        for (TaskItemVO item : allTaskItems) {
          if (item.getRequired() != null && item.getRequired()) {
            totalRequired++;
            if (item.getStatus() != null && item.getStatus() == 2) {
              completedRequired++;
            } else {
              allCompleted = false;
            }
          }
        }
        if (!allCompleted) {
          return;
        }
        
        // 计算总进度
        BigDecimal progressPercent = BigDecimal.valueOf(100);
        
        // 更新 task_user 状态
        TbTaskUser taskUser = new TbTaskUser();
        taskUser.setTaskID(taskId);
        taskUser.setUserID(userId);
        taskUser.setProgress(progressPercent);
        taskUser.setUpdater(userId);
        
        // 全部完成
        taskUser.setStatus(2);
        taskUser.setCompleteTime(new Date());
        taskUserMapper.updateTaskUser(taskUser);
        logger.info("更新任务用户状态成功 - taskId: {}, userId: {}, status: {}, progress: {}",
            taskId, userId, taskUser.getStatus(), progressPercent);
      } catch (Exception e) {
        logger.error("检查并更新任务完成状态失败 - taskId: {}, userId: {}", taskId, userId, e);
      }
    }


    

    
}
