package com.zehong.system.service.impl.train;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.domain.model.LoginUser;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.system.domain.form.TStaffForm;
import com.zehong.system.domain.train.*;
import com.zehong.system.domain.vo.UserCourseVo;
import com.zehong.system.mapper.train.TTrainCourseMapper;
import com.zehong.system.mapper.train.TTrainCourseTopicMapper;
import com.zehong.system.mapper.train.TTrainPlanMapper;
import com.zehong.system.mapper.train.TTrainUserCourseMapper;
import com.zehong.system.service.train.ITTrainCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 培训课程Service业务层处理
 *
 * @author zehong
 * @date 2022-09-19
 */
@Service
public class TTrainCourseServiceImpl implements ITTrainCourseService
{
    @Autowired
    private TTrainCourseMapper tTrainCourseMapper;
    @Autowired
    private TTrainPlanMapper tTrainPlanMapper;
    @Autowired
    private TTrainUserCourseMapper tTrainUserCourseMapper;
    @Autowired
    private TTrainCourseTopicMapper tTrainCourseTopicMapper;

    /**
     * 查询培训课程
     *
     * @param courseId 培训课程ID
     * @return 培训课程
     */
    @Override
    public TTrainCourse selectTTrainCourseById(Long courseId)
    {
        return tTrainCourseMapper.selectTTrainCourseById(courseId);
    }

    /**
     * 发布培训课程
     * @return
     */
    @Override
    @Transactional
    public Integer selectTTrainCourseRelease(Long courseId){
         TTrainCourse course = tTrainCourseMapper.selectTTrainCourseById(courseId);
         if(course==null){
             return 0;
         }
         List<String> userIds = tTrainPlanMapper.selectAlluserByplanId(course.getCourseType());
         //异常数据
         if(userIds==null||userIds.size()==0){
             return 0;
         }
        //查询考试详情
        TTrainCourse tTrainCourse1 = tTrainCourseMapper.selectTTrainCourseById(courseId);
        for (int i=0;i<userIds.size();i++){
            /** 手机端消息新封装类 */
            TNews tNews=new TNews();
            /**设置所属模块*/
            tNews.setModule(Integer.valueOf(tTrainCourse1.getDataKind()));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String myDate = simpleDateFormat.format(tTrainCourse1.getTestEndTime());
            if ("0".equals(tTrainCourse1.getDataKind())){
                /**设置消息内容*/
                tNews.setMessageContent("培训课程："+tTrainCourse1.getCourseName()+",已发布，请于"+myDate+"前进行学习");
            }else {
                SecurityUtils.getUsername();
                tNews.setMessageContent("您有一场新的试卷考试");
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser user = loginUser.getUser();
            Long userId = user.getUserId();
            /** 发布人ID*/
            tNews.setPublisherId(userId);
            /** 接收人id*/
            tNews.setRecipientId(Integer.valueOf(userIds.get(i)));
            /** 所属模块id*/
            tNews.setModuleId(courseId);
            tNews.setReleaseTime(new DateTime());
            /**
             * 消息添加
             */
            tTrainCourseMapper.insertNews(tNews);
        }

         tTrainCourseMapper.insertUserCourse(courseId,userIds,course.getPersonnelType());
         course.setStatus(1);
         course.setReleaseTime(new Date());
         return tTrainCourseMapper.updateTTrainCourse(course);
    }
    /**
     * 查询培训课程列表
     *
     * @param tTrainCourse 培训课程
     * @return 培训课程
     */
    @Override
    public List<TTrainCourse> selectTTrainCourseList(TTrainCourse tTrainCourse)
    {
        return tTrainCourseMapper.selectTTrainCourseList(tTrainCourse);
    }

    /**
     * 新增培训课程
     *
     * @param tTrainCourse 培训课程
     * @return 结果
     */
    @Override
    public Long insertTTrainCourse(TTrainCourse tTrainCourse)
    {
        if(tTrainCourse.getDuration()!=null){//分钟转化秒
            tTrainCourse.setDuration(tTrainCourse.getDuration()*60);
        }
        if(tTrainCourse.getCourseType()!=null){
            TTrainPlan p = tTrainPlanMapper.selectTTrainPlanById(tTrainCourse.getCourseType());
            if(p!=null){
                tTrainCourse.setPersonnelType(p.getPersonnelType());
            }
        }
        tTrainCourse.setCreateTime(DateUtils.getNowDate());
        tTrainCourseMapper.insertTTrainCourse(tTrainCourse);
        return tTrainCourse.getCourseId();
    }

    /**
     * 修改培训课程
     *
     * @param tTrainCourse 培训课程
     * @return 结果
     */
    @Override
    public int updateTTrainCourse(TTrainCourse tTrainCourse)
    {
        if(tTrainCourse.getDuration()!=null){//分钟转化秒
            tTrainCourse.setDuration(tTrainCourse.getDuration()*60);
        }
        return tTrainCourseMapper.updateTTrainCourse(tTrainCourse);
    }
    @Override
    public int updateTTrainUserCourse(TTrainUserCourse tTrainUserCourse)
    {
        //判断有没有考试
        if(tTrainUserCourse.getTrainState()==1){
            List<TTrainCourseTopic> topicList = tTrainCourseTopicMapper.selectCourseTopicList(tTrainUserCourse.getCourseId());
            if(topicList.size()==0){
                tTrainUserCourse.setState(2);
            }
        }

        return tTrainUserCourseMapper.updateTTrainUserCourse(tTrainUserCourse);
    }


    /**
     * 批量删除培训课程
     *
     * @param courseIds 需要删除的培训课程ID
     * @return 结果
     */
    @Override
    public int deleteTTrainCourseByIds(Long[] courseIds)
    {
        return tTrainCourseMapper.deleteTTrainCourseByIds(courseIds);
    }

    /**
     * 删除培训课程信息
     *
     * @param courseId 培训课程ID
     * @return 结果
     */
    @Override
    public int deleteTTrainCourseById(Long courseId)
    {
        return tTrainCourseMapper.deleteTTrainCourseById(courseId);
    }

    /**
     * 用户课程表
     * @return
     */
    @Override
    public List<UserCourseVo> userCourseList(Long userId,Integer type){
        List<UserCourseVo> list = tTrainCourseMapper.userCourseList(userId,type,1);
        for (UserCourseVo v :list){
            if(v.getTestEndTime()!=null&&v.getTestEndTime().getTime()<new Date().getTime()&&v.getState()!=2){
                v.setState(3);
            }
            if(v.getTestStartTime()!=null&&v.getTestStartTime().getTime()>new Date().getTime()){
                v.setState(4);
            }
        }

        for (int i=0;i<list.size();i++){
            int totalScore=0;
            Long courseId = list.get(i).getCourseId();
            //查询课程下面的题
            List<TTrainCourseTopic> tTrainCourseTopics = tTrainCourseTopicMapper.selectCourseTopicList(courseId);

                for (int t = 0; t < tTrainCourseTopics.size(); t++) {
                    if (StringUtils.isEmpty(String.valueOf(tTrainCourseTopics.get(t).getTopicType()))) {
                        if (tTrainCourseTopics.get(t).getTopicType() == 1) {
                            totalScore = totalScore + list.get(i).getSingleChoiceScore();
                        } else if (tTrainCourseTopics.get(t).getTopicType() == 2) {
                            totalScore = totalScore + list.get(i).getMultipleChoiceScore();
                        } else if (tTrainCourseTopics.get(t).getTopicType() == 3) {
                            totalScore = totalScore + list.get(i).getJudgmentScore();
                        }
                    }
                }

            list.get(i).setTotalScore(totalScore);
        }
        return list;
    }

    @Override
    public List<UserCourseVo> userCourseLists(TStaffForm tStaff) {
        List<UserCourseVo> list = tTrainCourseMapper.userCourseLists(tStaff);
        for (UserCourseVo v :list){
            if(v.getTestEndTime()!=null&&v.getTestEndTime().getTime()<new Date().getTime()){
                v.setState(3);
            }
            if(v.getTestStartTime()!=null&&v.getTestStartTime().getTime()>new Date().getTime()){
                v.setState(4);
            }
        }

        for (int i=0;i<list.size();i++){
            int totalScore=0;
            Long courseId = list.get(i).getCourseId();
            //查询课程下面的题
            List<TTrainCourseTopic> tTrainCourseTopics = tTrainCourseTopicMapper.selectCourseTopicList(courseId);

            for (int t = 0; t < tTrainCourseTopics.size(); t++) {
                if (StringUtils.isEmpty(String.valueOf(tTrainCourseTopics.get(t).getTopicType()))) {
                    if (tTrainCourseTopics.get(t).getTopicType() == 1) {
                        totalScore = totalScore + list.get(i).getSingleChoiceScore();
                    } else if (tTrainCourseTopics.get(t).getTopicType() == 2) {
                        totalScore = totalScore + list.get(i).getMultipleChoiceScore();
                    } else if (tTrainCourseTopics.get(t).getTopicType() == 3) {
                        totalScore = totalScore + list.get(i).getJudgmentScore();
                    }
                }
            }

            list.get(i).setTotalScore(totalScore);
        }
        return list;
    }

    /**
     * 承包商课程表
     * @return
     */
    @Override
    public List<UserCourseVo> youkeCourseList(Long userId,Integer type){
        List<UserCourseVo> list = tTrainCourseMapper.userCourseList(userId,type,2);
        return list;
    }
    /**
     * 考试判断
     * @param userCourseId
     * @param answers
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> examination (Long userCourseId,Integer[][] answers){
        //查询用户课程信息
        TTrainUserCourse userCourse = tTrainUserCourseMapper.selectTTrainUserCourseById(userCourseId);
        TTrainCourseTopic topic = new TTrainCourseTopic();
        /**添加所属课程id*/
        topic.setCourseId(userCourse.getCourseId());
        /**查询培训课程题库列表*/
        List<TTrainCourseTopic> list = tTrainCourseTopicMapper.selectTTrainCourseTopicList(topic);
        /**查询培训课程*/
        TTrainCourse c = tTrainCourseMapper.selectTTrainCourseById(userCourse.getCourseId());
        /**获取各个题目类型多少分*/
        //多选题分数
        Integer multipleChoiceScore = c.getMultipleChoiceScore();
        //单选题分数
        Integer singleChoiceScore = c.getSingleChoiceScore();
        //判断题分数
        Integer judgmentScore = c.getJudgmentScore();
        //答题合格分数
        Integer qualifiedNum = c.getQualifiedNum();
        //已获得分数
        int num = 0;
        /**
         * 大循环 共有多少答案   此循环最后只算出 得了多少分
         */
        for (int i=0;i<answers.length;i++){
            /**答题是否正确  0 不正确  1正确*/
            int PassedNot =0;
           /*题目答案*/
            String answer = list.get(i).getAnswer();
           //答案转换成数组
            Integer[] integers = JSON.parseObject(answer, Integer[].class);
            /**判断所选答案是否与正确答案长度相等*/
            if (integers.length==answers[i].length){
                boolean  adopt=true;
                for (int n=0;n<integers.length;n++){
                        if (integers[n]!=answers[i][n]){
                            adopt=false;
                            break;
                        }
                    }
                if (adopt){
                    /** 1单选  2多选   3判断*/
                    if (list.get(i).getTopicType()==1){
                        num=num+singleChoiceScore;
                    }else if (list.get(i).getTopicType()==2){
                        num=num+multipleChoiceScore;
                    }else if (list.get(i).getTopicType()==3){
                        num=num+judgmentScore;
                    }
                }
            }

            /**
             * 小循环 循环出每次的答案
             */
//            for (int s=0;s<answers[i].length;s++){
//                System.out.println("所选答案"+answers[i][s]);
//            }

        }


//        for(Integer i=0;i<answers.length;i++){
//            String demosub = list.get(i).getAnswer().substring(1,list.get(i).getAnswer().length()-1);
//            if(Integer.parseInt(answers[i])==demosub){
//                num++;
//            }
//        }
        /**已获得分数*/
        userCourse.setExaminationResult(num);
        /**生成日期*/
        userCourse.setExaminationTime(new Date());
        /**判断已获得分数  是否通过  1未通过 2已通过*/
        if(num>=qualifiedNum){
            userCourse.setState(2);
        }else {
            userCourse.setState(1);
        }
        tTrainUserCourseMapper.updateTTrainUserCourse(userCourse);
        Map<String,Object> map = new HashMap<>();
        map.put("answer",num);  //得分分数
        map.put("qualifiedNum",c.getQualifiedNum());  //答题合格分数
        map.put("topicNum",list.size()); //题目数据
        return map;
    }

    /**
     * 考试发布
     * @param tTrainCourse 考试实体
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int testPublish( TTrainCourse tTrainCourse){
        //查询考试人员信息
        TTrainCourse course = tTrainCourseMapper.selectTTrainCourseById(tTrainCourse.getCourseId());
        if(course==null){
            return 0;
        }
        //新增考试人员
        List<JSONObject> personList = JSONObject.parseArray(course.getTestPersons(),JSONObject.class);

        List<String> persons = personList.stream().map(item ->String.valueOf(item.get("peoPleId"))).collect(Collectors.toList());
        //查询考试详情
        TTrainCourse tTrainCourse1 = tTrainCourseMapper.selectTTrainCourseById(tTrainCourse.getCourseId());
        for (int i=0;i<persons.size();i++){
            /** 手机端消息新封装类 */
            TNews tNews=new TNews();
            /**设置所属模块*/
            tNews.setModule(Integer.valueOf(tTrainCourse1.getDataKind()));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String myDate = simpleDateFormat.format(tTrainCourse1.getTestEndTime());
            if ("0".equals(tTrainCourse1.getDataKind())){
                /**设置消息内容*/
                tNews.setMessageContent("培训课程："+tTrainCourse1.getCourseName()+"已发布，请于"+myDate+"前进行学习");
            }else {
                tNews.setMessageContent("考试："+tTrainCourse1.getCourseName()+"已发布，请于"+myDate+"前进行学习");
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser user = loginUser.getUser();
            Long userId = user.getUserId();
            /** 发布人ID*/
            tNews.setPublisherId(userId);
            /** 接收人id*/
            tNews.setRecipientId(Integer.valueOf(persons.get(i)));
            /** 所属模块id*/
            tNews.setModuleId(tTrainCourse.getCourseId());
            tNews.setReleaseTime(new DateTime());
            /**
             * 消息添加
             */
            tTrainCourseMapper.insertNews(tNews);
        }

        tTrainCourseMapper.insertUserCourse(tTrainCourse.getCourseId(),persons,tTrainCourse.getPersonnelType());
        tTrainCourse.setStatus(1);
        tTrainCourse.setReleaseTime(new Date());
        return tTrainCourseMapper.updateTTrainCourse(tTrainCourse);
    }

    /**
     * 考试统计接口
     * @param statisticsTrainCourse 统计实体
     * @return List<StatisticsTrainCourse>
     */
    @Override
    public List<StatisticsTrainCourse> statisticsTrainCourse(StatisticsTrainCourse statisticsTrainCourse){
        return tTrainCourseMapper.statisticsTrainCourse(statisticsTrainCourse);
    }

    /**
     * 根据考试查询人员考试详情
     * @param courseId 考试id
     * @return List<TTrainUserCourse>
     */
    @Override
    public List<TTrainUserCourse> testPersonDetailByCourseId(Long courseId){
        return tTrainUserCourseMapper.testPersonDetailByCourseId(courseId);
    }

    /**
     * 导出所有考试详细数据项
     * @param courseId
     * @return
     */
    @Override
    public List<TTrainUserCourse> examDetails(Long courseId) {
        return tTrainUserCourseMapper.examDetails(courseId);
    }

    @Override
    public TTrainUserCourse getUserCourse(Long userCourseId){
        TTrainUserCourse userCourse = tTrainUserCourseMapper.selectTTrainUserCourseById(userCourseId);
        TTrainCourse v = tTrainCourseMapper.selectTTrainCourseById(userCourse.getCourseId());
        if(v.getTestEndTime()!=null&&v.getTestEndTime().getTime()<new Date().getTime()&&userCourse.getState()!=2){
            userCourse.setState(3);
        }
        return userCourse;
    }


    /**
     * 手机端  最新消息查询
     * @param recipientId
     * @return
     */
    @Override
    public TNews selectLatestNews(Long recipientId) {
        return tTrainCourseMapper.selectLatestNews(recipientId);
    }

    /**
     * 手机端 查询历史消息
     * @param recipientId
     * @return
     */
    @Override
    public List<TNews> historicalMessages(Long recipientId) {
        return tTrainCourseMapper.historicalMessages(recipientId);
    }

    /**
     * 修改消息状态为已读
     * @param newsId
     * @return
     */
    @Override
    public int updateReadStatus(Long newsId) {
        return tTrainCourseMapper.updateReadStatus(newsId);
    }


}
