package com.ruoyi.project.business.service.impl;

import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.business.domain.dto.TtAssessResultDto;
import com.ruoyi.project.business.domain.train.TtAssessResult;
import com.ruoyi.project.business.domain.train.TtTrainTarget;
import com.ruoyi.project.business.domain.vo.train.TtTrainTargetVo;
import com.ruoyi.project.business.enums.train.TrainAssessCompleteFlagEnum;
import com.ruoyi.project.business.mapper.TtTrainTargetMapper;
import com.ruoyi.project.business.service.ITtTrainTargetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.business.mapper.TtAssessResultMapper;
import com.ruoyi.project.business.service.ITtAssessResultService;

/**
 * 答卷Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-04
 */
@Service
public class TtAssessResultServiceImpl implements ITtAssessResultService {
    @Autowired
    private TtAssessResultMapper ttAssessResultMapper;
    @Autowired
    private TtTrainTargetMapper ttTrainTargetMapper;

    /**
     * 查询答卷
     *
     * @param id 答卷主键
     * @return 答卷
     */
    @Override
    public TtAssessResult selectTtAssessResultById(Long id) {
        return ttAssessResultMapper.selectTtAssessResultById(id);
    }

    /**
     * 查询答卷列表
     *
     * @param ttAssessResult 答卷
     * @return 答卷
     */
    @Override
    public List<TtAssessResult> selectTtAssessResultList(TtAssessResult ttAssessResult) {
        return ttAssessResultMapper.selectTtAssessResultList(ttAssessResult);
    }

    /**
     * 新增答卷
     *
     * @param ttAssessResultDto 答卷
     * @return 结果
     */
    @Override
    public int insertTtAssessResult(TtAssessResultDto ttAssessResultDto) {
        // 获取登录人
        Long loginUserId = SecurityUtils.getLoginUser().getUserId();

        // 插入前先删除上一次填写的试卷（如果有上一次的话）
        // 获取试题idList
        List<Long> questionIds = new ArrayList<>();
        for (TtAssessResult ttAssessResult : ttAssessResultDto.getTtAssessResults()) {
            questionIds.add(ttAssessResult.getTestPaperDetailId());
        }
        QueryWrapper<TtAssessResult> qw = new QueryWrapper<>();
        qw.eq("train_target_id", loginUserId);
        qw.in("test_paper_detail_id", questionIds);
        ttAssessResultMapper.delete(qw);

        List<TtAssessResult> ttAssessResultList = ttAssessResultDto.getTtAssessResults();
        ttAssessResultList.forEach(item -> {
            item.setTrainTargetId(loginUserId);
            item.setDelFlag("0");
            // 设置创建者创建时间，更新这更新时间
            item.setCreateBy(loginUserId.toString());
            item.setCreateTime(DateUtils.getNowDate());
            item.setUpdateBy(loginUserId.toString());
            item.setUpdateTime(DateUtils.getNowDate());
        });
        ttAssessResultMapper.insertTtAssessResultBatch(ttAssessResultList);

        // 获取考核id
        QueryWrapper<TtTrainTarget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("train_id", ttAssessResultDto.getTrainId());
        queryWrapper.eq("target_person_id", loginUserId);
        TtTrainTarget targetUpdateInfo = new TtTrainTarget();

        // 判断考核是否通过
        // 获取总分
        Long totalScore = 0L;
        for (TtAssessResult ttAssessResult : ttAssessResultList) {
            totalScore += ttAssessResult.getScore();
        }
        // 如果得分大于通过分数，设置考核结果为已通过，否则为未通过
        if(totalScore >= ttAssessResultDto.getPassScore()){
            targetUpdateInfo.setAssessCompleteFlag(TrainAssessCompleteFlagEnum.PASS.getCode());
        }else {
            targetUpdateInfo.setAssessCompleteFlag(TrainAssessCompleteFlagEnum.NOT_PASS.getCode());
        }
        targetUpdateInfo.setTotalScore(totalScore);
        return  ttTrainTargetMapper.update(targetUpdateInfo,queryWrapper);
    }

    /**
     * 修改答卷
     *
     * @param ttAssessResult 答卷
     * @return 结果
     */
    @Override
    public int updateTtAssessResult(TtAssessResult ttAssessResult) {
        ttAssessResult.setUpdateTime(DateUtils.getNowDate());
        return ttAssessResultMapper.updateTtAssessResult(ttAssessResult);
    }

    /**
     * 批量删除答卷
     *
     * @param ids 需要删除的答卷主键
     * @return 结果
     */
    @Override
    public int deleteTtAssessResultByIds(Long[] ids) {
        return ttAssessResultMapper.deleteTtAssessResultByIds(ids);
    }

    /**
     * 删除答卷信息
     *
     * @param id 答卷主键
     * @return 结果
     */
    @Override
    public int deleteTtAssessResultById(Long id) {
        return ttAssessResultMapper.deleteTtAssessResultById(id);
    }
}
