package com.ssj.dao.kmt.kmt.dao.impl;

import com.ssj.bean.kmt.kmt.domain.KmtExerciseBookCourse;
import com.ssj.bean.kmt.kmt.domain.KmtExerciseQuestion;
import com.ssj.dao.kmt.kmt.dao.KmtExerciseQueryDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;
import com.ssj.framework.core.util.Constant;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.service.conch.parents.v1.dto.BookDTO;
import com.ssj.service.kmt.dto.ExerciseBookCourseDTO;
import com.ssj.service.kmt.dto.ExerciseQuestionDto;
import com.ssj.service.kmt.request.QuestionDistributeRequest;
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.stereotype.Repository;

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

@Repository
public class KmtExerciseQueryDaoImpl implements KmtExerciseQueryDao {
    @Autowired
    private PagingHibernateJdbcDao dao;

    @Override
    public List<KmtExerciseBookCourse> getAllBookCourse(String subject, String grade, int semester, int versionType) {
        StringBuilder sb  = new StringBuilder();
        sb.append("select eb.id book_id,  eb.book_name, ebc.unit_id, ebc.unit, ebc.id,  ebc.period, ebc.grade,")
                .append(" ebc.course_name, ebc.version, ebc.semester, eb.part_flag remark from kmt_exercise_book_course ebc")
                .append(" left join kmt_exercise_book eb on ebc.book_id=eb.book_id where eb.book_type in(0, 1, 3) ")
                .append(" and ebc.course_name = ? and ebc.grade = ? and ebc.semester = ?");
        List<Object> param = new ArrayList<>();
        param.add(subject);
        param.add(grade);
        param.add(semester);
        if (versionType > 0){
            sb.append(" and ebc.version = ?");
            param.add(versionType);
        }
        sb.append(" order by ebc.unit_sort, ebc.period_sort limit 0,").append(Constant.MAX_ROWS_COUNT);
        return dao.findList(sb.toString(), param.toArray(), KmtExerciseBookCourse.class);
    }

    @Override
    public List<KmtExerciseBookCourse> getAllPublishBookCourse(String subject, String grade, int semester) {
        StringBuilder sb  = new StringBuilder();
        sb.append("select book_id,  book_name, unit_id, unit, id,  period, grade, course_name, version from kmt_exercise_book_course where ")
                .append(" course_name = ? and grade = ? and semester = ?");
        List<Object> param = new ArrayList<>();
        param.add(subject);
        param.add(grade);
        param.add(semester);
        sb.append(" order by unit_sort, period_sort");
        return dao.findList(sb.toString(), param.toArray(), KmtExerciseBookCourse.class);
    }


    @Override
    public List<KmtExerciseQuestion> findByTypeAndIdAndPageNo(int type, String id, int page, int dealType, String userId) {
        StringBuilder sb = new StringBuilder();
        List<Object> param = new ArrayList<>();
        sb.append("select t1.* from kmt_exercise_questions t1 where");
        if (dealType == 1){
            //加工员
            sb.append(" t1.deal_status < 2 and t1.handle_user_id= ?"); //
            param.add(userId);
        } else {
            //审核员
            sb.append(" t1.deal_status = 3 and t1.auditing_user_id = ?"); //
            param.add(userId);
        }

        if (type == 1){
            //只查练习册id
            sb.append(" and t1.book_id = ?");
            param.add(id);
            if (page > 0){
                sb.append(" and t1.page_index = ?");
                param.add(page);
            }
        } else if (type == 2){
            //查单元id, 有单元id对应’
            sb.append(" and t1.unit_id = ?");
            param.add(id);
        } else if (type == 3){
            //查课时id, 有课时id必有唯一的单元id
            sb.append(" and t1.book_course_id = ?");
            param.add(id);
        }
        sb.append(" order by t1.num, create_time");
        return dao.findList(sb.toString(), param.toArray(), KmtExerciseQuestion.class);
    }

    @Override
    public List<Map<String, Object>> findHowDetailNameByQuestionIds(List<String> questionIds, int versionType) {
        if (questionIds.size() <= 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("select distinct t1.question_id, t1.how_details_id, t2.alias detail_name, t1.how_details_kd_id, t3.alias kd_name from kmt_exercise_question_know t1 ")
                .append(" left join zyb_know_how_details_sort t2 on t1.how_details_id = t2.how_details_id and t2.stat=2 and t2.type=?")
                .append(" left join zyb_know_how_details_sort t3 on t1.how_details_kd_id=t3.how_details_kd_id and t3.stat=3 and t3.type=?")
                .append(" where question_id in (");
        StringBuilder paramStr = new StringBuilder();
        questionIds.forEach(str -> {
            paramStr.append("'").append(str).append("',");
        });
        paramStr.deleteCharAt(paramStr.length() - 1);
        sb.append(paramStr).append(") order by t2.num, t3.num");
        List<Object> param = new ArrayList<>();
        param.add(versionType);
        param.add(versionType);
        return dao.findMap(sb.toString(), param.toArray());
    }

    @Override
    public List<ExerciseBookCourseDTO> getBookExerciseList(QuestionDistributeRequest request) {
        String sql =
                "select id, course_name, version, grade, semester, unit, period\n" +
                "from kmt_exercise_book_course\n" +
                "where grade = ?\n" +
                "  and course_name = ?\n" +
                "  and version = ?\n" +
                "  and semester = ? ";

        List<Object> paramList = new ArrayList<>();
        paramList.add(request.getGrade());
        paramList.add(request.getSubject());
        paramList.add(request.getVersionType());
        paramList.add(request.getSemester());

        if (StringUtils.isNotBlank(request.getBookId())) {
            sql += "  and book_id = ? ";
            paramList.add(request.getBookId());
        }

        if (StringUtils.isNotBlank(request.getUnitId())) {
            sql += "  and unit_id = ? ";
            paramList.add(request.getUnitId());
        }

        if (StringUtils.isNotBlank(request.getPeriodId())) {
            sql += "  and id = ? ";
            paramList.add(request.getPeriodId());
        }
        sql += " limit 0, ";
        sql += Constant.MAX_ROWS_COUNT;

        return dao.findList(sql, paramList.toArray(), ExerciseBookCourseDTO.class);
    }

    @Override
    public List<ExerciseQuestionDto> findAnswerByExerciseBookCourseId(String exerciseBookCourseId, int bookYear) {
        String sql = "select id question_id, big_question_index, small_question_name small_question_index, option_answer, answer_json answer_json, book_course_id\n" +
                "from kmt_exercise_questions\n" +
                "where (deal_status = 4 or deal_status = 5 or deal_status > 7) " +
                "and book_course_id = ? and (is_common_flag=0 or question_year=?) and  answer_json is not null and answer_json != '' and answer_json != '[]' " +
                "order by num, create_time";

        List<Object> paramList = new ArrayList<>();
        paramList.add(exerciseBookCourseId);
        paramList.add(bookYear);
        return dao.findList(sql, paramList.toArray(), ExerciseQuestionDto.class);
    }

    @Override
    public List<ExerciseQuestionDto> findQuestionByBookIdAndPage(String bookId, String unitId, String bookCourseId,
                                                                 List<Integer> pageIndex, int bookYear){
        List<Object> params = new ArrayList<>();
        String sql = "select id question_id, big_question_index, small_question_name small_question_index, option_answer, answer_json answer_json, book_course_id\n" +
                " from kmt_exercise_questions\n" +
                " where (deal_status = 4 or deal_status = 5 or deal_status > 7) " +
                " and book_id = ? and (is_common_flag = 0 or question_year=?)";
        params.add(bookId);
        params.add(bookYear);
        if (StringUtils.isNotBlank(unitId)){
            sql += " and unit_id=?";
            params.add(unitId);
        }
        if (StringUtils.isNotBlank(bookCourseId)){
            sql += " and book_course_id=?";
            params.add(bookCourseId);
        }
        sql +=" and  page_index in (" + StringUtil.join(pageIndex, ",") + ")"+
                " and  answer_json is not null and answer_json != '' and answer_json != '[]' " +
                " order by num, create_time";
        return dao.findList(sql, params.toArray(), ExerciseQuestionDto.class);
    }

    @Override
    public List<ExerciseQuestionDto> findQuestionByQuestionIds(List<String> questionIds){
        List<Object> params = new ArrayList<>();
        String sql = "select id question_id, big_question_index, small_question_name small_question_index, option_answer, answer_json answer_json, book_course_id\n" +
                " from kmt_exercise_questions\n" +
                " where (deal_status = 4 or deal_status = 5 or deal_status > 7) " +
                " and id in ('" + StringUtil.join(questionIds, "','") + "') and answer_json is not null && answer_json != '[]' && answer_json != '' order by num, create_time";
        return dao.findList(sql, params.toArray(), ExerciseQuestionDto.class);
    }
    
    
    @Override
    public List<ExerciseQuestionDto> findQuestionByBookIdAndPageByAll(String bookId, List<Integer> pageIndex){
        String sql = "select id question_id, big_question_index, small_question_name small_question_index, option_answer, answer_json, book_course_id,deal_status   \n" +
                " from kmt_exercise_questions\n" +
                " where  book_id = ?\n" +
                " and  page_index in (" + StringUtil.join(pageIndex, ",") + ")"+
                " and  option_answer is not null and option_answer != ''\n" +
                " order by num, create_time";
        List<Object> params = new ArrayList<>();
        params.add(bookId);
        return dao.findList(sql, params.toArray(), ExerciseQuestionDto.class);
    }

    @Override
    public List<ExerciseQuestionDto> findQuestionByBookIdAndPage(String bookId, String courseId,  int pageIndex){
        String sql = "select id question_id, big_question_index, small_question_name small_question_index, option_answer\n" +
                " from kmt_exercise_questions\n" +
                " where (deal_status = 4 or deal_status > 7 ) " +
                " and book_id = ?\n" +
                " and book_course_id = ?\n" +
                " and  page_index= ?\n" +
                " and  option_answer is not null\n" +
                " order by num, create_time";
        List<Object> params = new ArrayList<>();
        params.add(bookId);
        params.add(courseId);
        params.add(pageIndex);
        return dao.findList(sql, params.toArray(), ExerciseQuestionDto.class);
    }

    @Override
    public Integer findKnowledgeVersionById(String questionId) {
        String sql =
                "select cast(kmt_exercise_book_course.version as char) " +
                "from kmt_exercise_book_course, " +
                "     kmt_exercise_questions " +
                "where kmt_exercise_questions.id = ? " +
                "  and kmt_exercise_book_course.id = kmt_exercise_questions.book_course_id ";

        List<String> resultList = dao.findList(sql, new String[]{questionId}, String.class);
        if (CollectionUtils.isEmpty(resultList)) {
            return null;
        } else {
            return Integer.parseInt(resultList.get(0));
        }

    }

    @Override
    public Page<BookDTO> findBookPage(String grade, String subject, String bookName, Pageable pageable) {
        List<Object> paramList = new ArrayList<>();

        StringBuilder sql = new StringBuilder(
                "select book_id, book_name, course_name subject, version\n" +
                "from kmt_exercise_book\n" +
                "where grade = ?\n" +
                "  and course_name = ?\n");
        if (StringUtils.isNotBlank(bookName)) {
            sql.append(" and book_name like'%").append(bookName).append("%'\n");
        }
        sql.append("group by book_id,book_year\n");

        paramList.add(grade);
        paramList.add(subject);

        return dao.findPage(sql.toString(), paramList.toArray(), pageable, BookDTO.class);
    }

    @Override
    public List<String> findListAndParentByParentId(List<String> parentQuestionIdList) {
        if (CollectionUtils.isEmpty(parentQuestionIdList)) {
            return new ArrayList<>();
        }

        String parentQuestionIdStr = "'" + StringUtils.join(parentQuestionIdList, "','") + "'";
        String sql =
                "select question\n" +
                "from (select question, num\n" +
                "      from kmt_exercise_questions\n" +
                "      where parent_id in (" + parentQuestionIdStr + ")" +
                "      union all\n" +
                "      select question, num\n" +
                "      from kmt_exercise_questions\n" +
                "      where id in (" + parentQuestionIdStr + ")) temp\n" +
                "order by num";

        return dao.findList(sql, String.class);
    }

    @Override
    public List<KmtExerciseBookCourse> findBookDataByBookIds(List<String> bookIds) {
        StringBuilder sb = new StringBuilder();
        sb.append("select distinct book_id, book_name, grade, course_name, semester, version from kmt_exercise_book_course where book_id in ('")
                .append(StringUtil.join(bookIds.toArray(), "','"))
                .append("')");
        return dao.findList(sb.toString(), KmtExerciseBookCourse.class);
    }
    
    
    @Override
    public Page<KmtExerciseQuestion> findKmtExerciseQuestionsByPage(String date,Pageable pageable) {
        List<Object> paramList = new ArrayList<>();
        StringBuilder sql = new StringBuilder(" SELECT * from kmt_exercise_questions t where 1=1 ");
        if(StringUtils.isNotEmpty(date)) {
        	sql.append("  and TO_DAYS(t.create_time)>=TO_DAYS('"+date+"')  ");
        }
        sql.append(" ORDER BY create_time ASC  ");
        return dao.findPage(sql.toString(), paramList.toArray(), pageable, KmtExerciseQuestion.class);
    }
    
    
}