package com.ssj.service.kmt.kmt.service.impl;

import com.ssj.bean.kmt.kmt.domain.KmtExerciseBookCourse;
import com.ssj.dao.kmt.kmt.dao.KmtExerciseBookCourseDao;
import com.ssj.dao.kmt.kmt.dao.KmtExerciseQueryDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.Constant;
import com.ssj.service.conch.parents.v1.dto.BookDTO;
import com.ssj.service.kmt.constant.KnowledgeVersion;
import com.ssj.service.kmt.dto.ExerciseBookBaseDto;
import com.ssj.service.kmt.dto.ExerciseBookCourseDTO;
import com.ssj.service.kmt.dto.ExerciseBookDto;
import com.ssj.service.kmt.request.ExerciseConditionRequest;
import com.ssj.service.kmt.request.QuestionDistributeRequest;
import com.ssj.service.kmt.service.KmtExerciseBookCourseService;
import com.ssj.service.mapper.KmtExerciseMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class KmtExerciseBookCourseServiceImpl extends BaseServiceImpl<KmtExerciseBookCourse, String> implements KmtExerciseBookCourseService {

    @Autowired
    private KmtExerciseBookCourseDao dao;

    @Autowired
    private KmtExerciseQueryDao queryDao;

    @Autowired
    private KnowledgeVersion knowledgeVersion;
    @Autowired
    private KmtExerciseMapper kmtExerciseMapper;

    @Override
    public PagingAndSortingRepository<KmtExerciseBookCourse, String> getDao() {
        return dao;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<ExerciseBookDto> getExerciseCondition(ExerciseConditionRequest request, String userId) {
        List<KmtExerciseBookCourse> list = null;
        if (request.getDealType() == 1){
            if (StringUtils.isBlank(request.getGrade())){
                //待加工页面没有科目年级，只判断年级
                list = dao.findHandBooksByStatusAndUserId(userId, Constant.MAX_ROWS_COUNT);
            } else {
                list = dao.findUnHandlingBook(request.getSubject(), request.getGrade(), request.getVersionType(), request.getSemester(), Constant.MAX_ROWS_COUNT);
            }
        } else if (request.getDealType() == 2){
            if (StringUtils.isBlank(request.getGrade())){
                //待审核页面没有科目年级，只判断年级
                list = dao.findAudeBooksByStatusAndUserId(userId, Constant.MAX_ROWS_COUNT);
            } else {
                list = dao.findUnAuditingBook(request.getSubject(), request.getGrade(), request.getVersionType(), request.getSemester(), Constant.MAX_ROWS_COUNT);
            }
        } else if (request.getDealType() == 4) {
            list = kmtExerciseMapper.findUnAnalysisBookCourse(userId, Constant.MAX_ROWS_COUNT);
        } else {
            list = queryDao.getAllBookCourse(request.getSubject(), request.getGrade(),
                    request.getSemester(), request.getVersionType());
        }
        List<ExerciseBookDto> result = new ArrayList<>();
        if (list != null) {
            result = this.findBookList(list);
        }
        return result;
    }

    @Override
    public List<ExerciseBookCourseDTO> getBookExerciseList(QuestionDistributeRequest request) {
        return queryDao.getBookExerciseList(request);
    }


    /**
     *  循环插入练习册到结构列表中
     * @param list
     * @return
     */
    private List<ExerciseBookDto> findBookList (List<KmtExerciseBookCourse> list){
        List<ExerciseBookDto> result = new ArrayList<>();
        if (list != null) {
            ExerciseBookDto book = null;
            for (KmtExerciseBookCourse course : list) {
                book = this.isBookExist(result, course.getBookId());
                if (book == null){
                    String bookName = course.getBookName();
                    book = new ExerciseBookDto(course.getBookId(), bookName);
                    if (StringUtils.isNotBlank(course.getGrade())){
                        //如果有年级-科目等信息，组装一个描述信息 年级-上下册-版本-科目
                        book.setSemester(course.getSemester() == null ? 1 : course.getSemester());
                        book.setGrade(course.getGrade());
                        book.setSubject(course.getCourseName());
                        String versionStr = null;
                        if (StringUtils.isNotBlank(course.getCourseName())){
                            versionStr = knowledgeVersion.getVersionNameBySubjectAndVersionNum(course.getCourseName(), course.getVersion());
                            bookName += '(' + versionStr.substring(0, 1) + ')';
                            book.setName(bookName);
                        }
                        ExerciseBookBaseDto version = new ExerciseBookBaseDto(course.getVersion().toString(), versionStr);
                        book.setVersion(version);
                    }
                    result.add(0, book);
                }
                book.addUnit(course.getUnitId(), course.getUnit(), course.getId(), course.getPeriod());
            }
        }
        return result;
    }

    /**
     * 练习册是否已经存在
     * @param list
     * @param bookId
     * @return
     */
    private ExerciseBookDto isBookExist (List<ExerciseBookDto> list, String bookId){
        ExerciseBookDto result = null;
        for (ExerciseBookDto book : list){
            if (book.getId().equals(bookId)){
                result = book;
                break;
            }
        }
        return result;
    }

    @Override
    public String getExerciseBookByBookId(String bookId) {
        KmtExerciseBookCourse kmtExerciseBookCourse = dao.findOneByBookId(bookId);
        String result = "";
        if (kmtExerciseBookCourse != null){
            result = kmtExerciseBookCourse.getBookName();
        }
        return result;
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<KmtExerciseBookCourse> findByUnitId(String unitId) {
        return dao.findByUnitId(unitId);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<KmtExerciseBookCourse> findByBookId(String bookId) {
        return dao.findByBookId(bookId);
    }

    @Override
    public Page<BookDTO> findBookPage(String grade, String subject, String bookName, Pageable pageable) {
        Page<BookDTO> bookDTOPage = queryDao.findBookPage(grade, subject, bookName, pageable);

        List<BookDTO> bookDTOList = bookDTOPage.getContent();
        if (CollectionUtils.isNotEmpty(bookDTOList)) {
            KnowledgeVersion knowledgeVersion = new KnowledgeVersion();
            knowledgeVersion.init();

            //根据版本编号和科目设置版本名称
            bookDTOList.forEach(bookDTO -> bookDTO.setVersionName(knowledgeVersion.getVersionNameBySubjectAndVersionNum(bookDTO.getSubject(), bookDTO.getVersion())));
        }

        return bookDTOPage;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public int findVersionTypeByBookId(String bookId) {
        List<KmtExerciseBookCourse> bookCourses = this.findByBookId(bookId);
        int bookVersion = 2;
        if (bookCourses != null && bookCourses.size() > 0){
            bookVersion = bookCourses.get(0).getVersion();
        }
        return bookVersion;
    }

    @Override
    public List<KmtExerciseBookCourse> getAllBookCourse(String subject, String grade, int semester, int versionType) {
        return queryDao.getAllBookCourse(subject, grade, semester, versionType);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public KmtExerciseBookCourse findBookDataByBookId(String bookId) {
        List<KmtExerciseBookCourse> bookCourses = this.findByBookId(bookId);
        KmtExerciseBookCourse bookCourse = null;
        if (bookCourses != null && bookCourses.size() > 0){
            bookCourse = bookCourses.get(0);
        }
        return bookCourse;
    }

    @Override
    public List<KmtExerciseBookCourse> findBookDataByBookIds(List<String> bookIds) {
        return queryDao.findBookDataByBookIds(bookIds);
    }

    @Override
    public String findCourseNameByQuestionId(String questionId) {
        return dao.findCourseNameByQuestionId(questionId);
    }

    @Override
    public List<KmtExerciseBookCourse> findByBookId(List<String> bookIds) {
        return dao.findByBookIdIn(bookIds);
    }
}