package com.cirle.scientific.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.cirle.scientific.dao.*;
import com.cirle.scientific.dto.course.CourseAppDetailsDTO;
import com.cirle.scientific.dto.course.CourseAppListDTO;
import com.cirle.scientific.dto.questiondetail.QkjQuestionDetailAppDTO;
import com.cirle.scientific.po.*;
import com.cirle.scientific.pojo.BizCodeEnum;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.CourseAppService;
import com.cirle.scientific.service.QuestionAnswerAppService;
import com.cirle.scientific.service.QuestionnaireService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class CourseAppServiceImpl implements CourseAppService {
    private final QkjTqcourseAppDao qkjTqcourseAppDao;
    private final QkjStudyRecordAppDao qkjStudyRecordAppDao;
    private final QkjMemberAppDao qkjMemberAppDao;
    private final QkjTqcourseCommentsAppDao qkjTqcourseCommentsAppDao;
    private final QkjExaminationAppDao qkjExaminationAppDao;
    private final QuestionnaireService questionnaireService;
    private final QuestionAnswerAppService questionAnswerAppService;

    @Override
    public List<CourseAppListDTO> getCourseList(String memCard, Integer type) {
        List<QkjTqcourseApp> qkjTqcourseApps = qkjTqcourseAppDao.findByTypeAndStatus(type, 1);
        List<CourseAppListDTO> resultList = qkjTqcourseApps.stream()
                .map(e -> BeanUtil.copyProperties(e, CourseAppListDTO.class))
                .sorted(Comparator.comparing(CourseAppListDTO::getSortNum))
                .collect(Collectors.toList());
        if (StringUtils.isBlank(memCard)) {
            return resultList;
        }
        List<QkjStudyRecordApp> recordApps = qkjStudyRecordAppDao.findByMemCardAndType(memCard, type);
        log.info("getCourseList recordApps:{}", recordApps);
        if (CollectionUtil.isEmpty(recordApps)) {
            return resultList;
        }
        Map<Long, Integer> objIdToStatusMap = recordApps.stream().collect(Collectors.toMap(QkjStudyRecordApp::getObjId, QkjStudyRecordApp::getStudyAccomplish, (v1, v2) -> v1));


        resultList.forEach(e -> {
            e.setFinishCourse(objIdToStatusMap.getOrDefault(e.getId(), 0));
        });
        log.info("getCourseList resultList:{}", resultList);
        return resultList;
    }

    @Override
    public CourseAppDetailsDTO getCourseDetails(Long id, String memCard) {
        log.info("getCourseDetails id:{} memCard:{}", id, memCard);
        QkjTqcourseApp qkjTqcourseApp = qkjTqcourseAppDao.findById(id).orElse(null);
        CourseAppDetailsDTO courseAppDetailsDTO = BeanUtil.copyProperties(qkjTqcourseApp, CourseAppDetailsDTO.class);
        log.info("getCourseDetails id:{} memCard:{} courseAppDetailsDTO:{}", id, memCard, courseAppDetailsDTO);
        if (StringUtils.isBlank(memCard)) {
            log.info("getCourseDetails memCard is null id:{} memCard:{}", id, memCard);
            return courseAppDetailsDTO;
        }
        QkjStudyRecordApp recordApp = qkjStudyRecordAppDao.findByMemCardAndTypeAndObjId(memCard, courseAppDetailsDTO.getType(), id);
        log.info("getCourseDetails id:{} memCard:{} recordApp:{}", id, memCard, recordApp);
        if (Objects.isNull(recordApp)) {
            log.info("getCourseDetails recordApp is null id:{} memCard:{}", id, memCard);
            return courseAppDetailsDTO;
        }
        courseAppDetailsDTO.setDuration(recordApp.getDuration());
        courseAppDetailsDTO.setCurrentTime(recordApp.getPresentTime());
        courseAppDetailsDTO.setStudyAccomplish(recordApp.getStudyAccomplish());
        log.info("getCourseDetails id:{} memCard:{} courseAppDetailsDTO:{}", id, memCard, courseAppDetailsDTO);
        return courseAppDetailsDTO;
    }

    @Override
    public List<QkjTqcourseCommentsApp> getComment(Long id) {
        return qkjTqcourseCommentsAppDao.findCommentsByCourseId(id);
    }

    @Override
    public QkjStudyRecordApp saveStudyRecord(String memCard, Long objId, Integer studyAccomplish, Integer objType) {
        QkjStudyRecordApp studyRecordApp = qkjStudyRecordAppDao.findByMemCardAndTypeAndId(memCard, objType, objId);

        if (Objects.isNull(studyRecordApp)) {
            QkjStudyRecordApp qkjStudyRecordApp = new QkjStudyRecordApp();
            qkjStudyRecordApp.setMemCard(memCard);
            qkjStudyRecordApp.setObjType(objType);
            qkjStudyRecordApp.setObjId(objId);
            qkjStudyRecordApp.setStudyAccomplish(0);
            studyRecordApp = qkjStudyRecordAppDao.save(qkjStudyRecordApp);
        } else {
            studyRecordApp.setStudyAccomplish(studyAccomplish);
            qkjStudyRecordAppDao.save(studyRecordApp);
        }
        return studyRecordApp;
    }

    @Override
    public QkjStudyRecordApp saveRecordProgress(String memCard, Long objId, Integer objType, Integer duration, Integer currentTime) {
        QkjStudyRecordApp studyRecordApp = qkjStudyRecordAppDao.findByMemCardAndTypeAndId(memCard, objType, objId);

        if (Objects.isNull(studyRecordApp)) {
            QkjStudyRecordApp qkjStudyRecordApp = new QkjStudyRecordApp();
            qkjStudyRecordApp.setMemCard(memCard);
            qkjStudyRecordApp.setObjType(objType);
            qkjStudyRecordApp.setObjId(objId);
            qkjStudyRecordApp.setDuration(duration);
            qkjStudyRecordApp.setPresentTime(currentTime);
            qkjStudyRecordApp.setStudyAccomplish(0);
            studyRecordApp = qkjStudyRecordAppDao.save(qkjStudyRecordApp);
        } else {
            if(Objects.nonNull(duration) && !Objects.equals(duration, 0)){
                studyRecordApp.setDuration(duration);
            }
            studyRecordApp.setPresentTime(currentTime);
            qkjStudyRecordAppDao.save(studyRecordApp);
        }
        return studyRecordApp;
    }

    @Override
    public QkjStudyRecordApp initStudyRecord(String memCard, Long objId, Integer objType) {
        QkjStudyRecordApp studyRecordApp = qkjStudyRecordAppDao.findByMemCardAndTypeAndId(memCard, objType, objId);
        if (Objects.isNull(studyRecordApp)) {
            QkjStudyRecordApp qkjStudyRecordApp = new QkjStudyRecordApp();
            qkjStudyRecordApp.setMemCard(memCard);
            qkjStudyRecordApp.setObjType(objType);
            qkjStudyRecordApp.setObjId(objId);
            qkjStudyRecordApp.setStudyAccomplish(0);
            studyRecordApp = qkjStudyRecordAppDao.save(qkjStudyRecordApp);
        }
        return studyRecordApp;
    }

    @Override
    public Result saveCommonApp(Long id, String memCard, String content) {
        QkjMemberApp byMemCard = qkjMemberAppDao.findByMemCard(memCard);
        QkjTqcourseCommentsApp qkjTqcourseComments = new QkjTqcourseCommentsApp();
        qkjTqcourseComments.setContent(content);
        qkjTqcourseComments.setTqcourseId(id.intValue());
        qkjTqcourseComments.setOprTime(LocalDateTime.now());
        if (byMemCard != null) {
            qkjTqcourseComments.setCommentMemHear(byMemCard.getMemHeadimg());
            String nickName = byMemCard.getMemNickname();
            if (StringUtils.isBlank(nickName)) {
                nickName = byMemCard.getMemMobile();
            }
            qkjTqcourseComments.setCommentMemName(nickName);
        }
        try {
            qkjTqcourseCommentsAppDao.save(qkjTqcourseComments);
        } catch (Exception e) {
            log.error("saveCommonApp e:{}", e);
            return Result.failed(BizCodeEnum.SAVE_COMMONAPP_ERR);
        }
        return Result.success(BizCodeEnum.SUCCESS);
    }

    @Override
    public Map<Integer, List<QkjQuestionDetailAppDTO>> getRandomQuestion(String memCard) {
        //获取四套试题
        List<Integer> exIds = qkjExaminationAppDao.getByType(1).stream().map(QkjExaminationApp::getId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(exIds)) {
            return Collections.emptyMap();
        }
        Random random = new Random();
        int n = random.nextInt(exIds.size());
        Integer exId = exIds.get(n);

        //查询这套题是否是刚做过 如果是换一套
        Integer objId = null;
        List<QkjQuestionAnswerApp> answerApps = questionAnswerAppService.findQuestionAnswer(memCard, 2);
        if (CollectionUtil.isNotEmpty(answerApps)) {
            objId = answerApps.get(0).getObjId();
        }
        if (Objects.equals(exId, objId)) {
            getRandomQuestion(memCard);
        }
        return questionnaireService.findQuestionszByExId(exId);
    }
}
