package com.ssj.dao.sys.homework.dao.impl;

import com.ssj.dao.sys.homework.dao.HomeworkQueryDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;
import com.ssj.service.conch.conch.vo.HomeworkVO;
import com.ssj.service.conch.student.dto.AppWrongTopicBookDto;
import com.ssj.service.conch.student.dto.WrongTopicBookDto;
import com.ssj.service.conch.teacher.dto.HomeworkDTO;
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.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author chchen
 * 作业持久层
 */
@Repository
public class HomeworkQueryDaoImpl implements HomeworkQueryDao {
    @Autowired
    private PagingHibernateJdbcDao dao;

    @Override
    public List<Map<String, Object>> findDatesLearningTime(String vipId, String beginTime, String endTime) {
        StringBuilder sb = new StringBuilder();
        //查询出有报告的每天学习时长
        sb.append("select DATE_FORMAT(date(create_time), '%m.%d') as date_time, sum(used_time) used_time ")
                .append("from scon_homework ")
                .append("where create_time between ? and ? ")
                .append("and vip_id = ? ")
                .append("group by date_time desc ");
        List<Object> param = new ArrayList<>();
        param.add(beginTime);
        param.add(endTime);
        param.add(vipId);

        return dao.findMap(sb.toString(), param.toArray());
    }

    @Override
    public Page<Map<String, Object>> getDatePageByVipId(String vipId, String maxCreateTime, Pageable pageable) {
        String sql = "select distinct date(create_time) date from scon_homework " +
                "where vip_id = '" + vipId + "' " +
                "and create_time < '" + maxCreateTime + "' " +
                "order by create_time desc ";

        return dao.findPage(sql, pageable);
    }

    @Override
    public Page<AppWrongTopicBookDto> findAppWrongTopicBook(String vipId, String subject, boolean isCorrected, Pageable pageable) {
        StringBuilder sql = new StringBuilder();
        sql.append("select scon_homework.id work_id, scon_homework_picture.subject, scon_homework_picture.file_key picture, date(scon_homework_picture.create_time) date,scon_homework_wrong_question.create_time ");
        sql.append("from scon_homework, scon_homework_picture, scon_homework_wrong_question ");
        if (isCorrected) {
            sql.append(", scon_work_image_revise ");
        }
        sql.append("where scon_homework.id = scon_homework_picture.homework_id ");
        sql.append("and scon_homework.id = scon_homework_wrong_question.homework_id ");
        if (isCorrected) {
            sql.append("and scon_homework.id = scon_work_image_revise.work_id ");
        }
        sql.append("and scon_homework.vip_id = '").append(vipId).append("' ");
        if (StringUtils.isNotBlank(subject)) {
            sql.append("and scon_homework.subject = '").append(subject).append("' ");
        }
        if (isCorrected) {
            sql.append("and exists(select 1 from scon_work_image_revise where work_id = scon_homework.id) ");
        } else  {
            sql.append("and not exists(select 1 from scon_work_image_revise where work_id = scon_homework.id) ");
        }
        sql.append("group by work_id ");
        sql.append("order by scon_homework_wrong_question.create_time desc");

        return dao.findPage(sql.toString(), pageable, AppWrongTopicBookDto.class);
    }

    @Override
    public List<HomeworkVO> findThreeDayList(String derver, String beginDateStr, String endDateStr) {
        String sql = "select scon_homework.id homework_id, subject course_name, scon_homework.create_time, !isnull(correct_time) is_feedback " +
                "from scon_homework, tb_lib_vip " +
                "where vip_id = tb_lib_vip.id " +
                "and tb_lib_vip.derver = '" + derver + "' " +
                "and scon_homework.create_time >= '" + beginDateStr + " 00:00:00' " +
                "and scon_homework.create_time <= '" + endDateStr + " 23:59:59' " +
                "and (scon_homework.work_type != 3 or scon_homework.work_type is null) " +
                "and exists(select 1 from scon_homework_picture where homework_id = scon_homework.id and type = 2 and derver_file_key is not null) " +
                "order by scon_homework.create_time desc ";

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

    @Override
    public Page<Map<String, Object>> findHomeworkPageByVipId(String vipId, String maxCreateTime, Pageable pageable) {
        String sql = "select t1.* ,\n" +
                "  (select file_key from scon_homework_picture where homework_id =t1.id limit 1) cover_url\n" +
                "from scon_homework t1\n" +
                "where t1.subject is not null\n";
        if(StringUtils.isNotBlank(maxCreateTime)){
            sql += ("and t1.create_time < '" + maxCreateTime + "' ");
        }
        sql += "and t1.vip_id = '" + vipId + "' ";
        sql += "order by date(t1.create_time) desc, t1.subject desc";
        return dao.findPage(sql, pageable);
    }

    @Override
    public Page<WrongTopicBookDto> findWrongTopicBook(String vipId, String subject, boolean isCorrected, Pageable pageable) {
        StringBuilder sql = new StringBuilder();
        List<Object> paramList = new ArrayList<>();

        sql.append("select temp.*, scon_homework_picture.file_key picture ");
        sql.append("from (select id work_id, date(create_time) date ");
        sql.append("      from scon_homework ");
        sql.append("      where 1=1 ");
        if (StringUtils.isNotBlank(subject)) {
            sql.append("    and scon_homework.subject = ?");
            paramList.add(subject);
        }
        sql.append("        and scon_homework.vip_id = ? ");
        sql.append("        and (exists(select 1 from kmt_homework_wrong_question where kmt_homework_wrong_question.homework_id = scon_homework.id) or ");
        sql.append("             exists(select 1 from scon_homework_how_details where scon_homework_how_details.homework_id = scon_homework.id)) ");
        if (isCorrected) {
            sql.append("    and exists(select 1 from scon_work_image_revise where scon_work_image_revise.work_id = scon_homework.id) ");
        } else {
            sql.append("    and not exists(select 1 from scon_work_image_revise where scon_work_image_revise.work_id = scon_homework.id) ");
        }
        sql.append("      order by scon_homework.create_time desc ");
        sql.append("      ) temp, scon_homework_picture ");
        sql.append("where temp.work_id = scon_homework_picture.homework_id ");
        sql.append("group by work_id ");
        sql.append("order by temp.date desc ");

        paramList.add(vipId);

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

    @Override
    public Page<HomeworkDTO> findByTeacherIdAndType(String teacherId, Integer type, String beginDateTimeStr, String endDateTimeStr, Pageable pageable, List<String> libIdList) {
        StringBuilder sql = new StringBuilder();
        List<Object> paramList = new ArrayList<>();

        sql.append("select tb_lib_vip.img_url, ");
        sql.append("       tb_lib_vip.id lib_vip_id, ");
        sql.append("       tb_lib_vip.child_name, ");
        sql.append("       tb_lib_vip.school, ");
        sql.append("       tb_lib_vip.grade, ");
        sql.append("       scon_homework_picture.homework_id, ");
        sql.append("       scon_homework.create_time, ");
        sql.append("       scon_homework.correct_time, scon_homework.end_time, ");
        sql.append("       scon_homework_picture.subject course_name ");
        sql.append("from scon_homework, scon_homework_picture, tb_lib_vip ");
        sql.append("where work_type < 3 ");
        if (CollectionUtils.isNotEmpty(libIdList)) {
            sql.append("and tb_lib_vip.lib_id in ('").append(StringUtils.join(libIdList, "','")).append("')\n");
        }
        if (type == 0) {
            sql.append("  and scon_homework_picture.is_feedback = 0 ");
        }
        sql.append("  and scon_homework.id = scon_homework_picture.homework_id ");
        sql.append("  and scon_homework_picture.teacher_id = ? ");
        sql.append("  and scon_homework_picture.is_delete = 0 ");
        sql.append("  and ? < scon_homework_picture.create_time ");
        sql.append("  and scon_homework_picture.create_time < ? ");
        sql.append("  and scon_homework.vip_id = tb_lib_vip.id ");
        if (type == 0) {
            sql.append("  and exists(select 1 ");
        } else {
            sql.append("  and not exists(select 1 ");
        }
        sql.append("             from scon_homework_picture ");
        sql.append("             where teacher_id = ? ");
        sql.append("               and scon_homework.id = homework_id ");
        sql.append("               and is_feedback = 0 ");
        sql.append("               and is_delete = 0 ");
        sql.append("               and is_mark in (0, 2)) ");
        sql.append("group by homework_id ");
        if (type == 0) {
            sql.append("order by scon_homework.end_time desc ");
        } else {
            sql.append("order by scon_homework.correct_time desc ");
        }
        paramList.add(teacherId);
        paramList.add(beginDateTimeStr);
        paramList.add(endDateTimeStr);
        paramList.add(teacherId);

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

    @Override
    public Map<String, Object> findHomeworkInfoById(String homeworkId) {
        String sql =
                "select tb_lib_vip.grade, scon_homework.subject, tb_lib_vip.banben " +
                "from scon_homework, tb_lib_vip " +
                "where scon_homework.vip_id = tb_lib_vip.id " +
                "  and scon_homework.id = ? ";

        List<Map<String, Object>> mapList = dao.findMap(sql, Collections.singleton(homeworkId).toArray());
        if (CollectionUtils.isEmpty(mapList)) {
            return null;
        } else {
            return mapList.get(0);
        }
    }

    @Override
    public List<Map<String, Object>> findDetailsByHomeworkId(String homeworkId) {
        String sql =
                "select ifnull(scon_homework_how_details.module, '') module, zyb_know_how_details_sort.alias " +
                "from scon_homework_how_details, zyb_know_how_details_sort " +
                "where scon_homework_how_details.homework_id = ? " +
                "  and scon_homework_how_details.work_detail_type = 1" +
                "  and scon_homework_how_details.detail_count > 0" +
                "  and scon_homework_how_details.how_detail_id = zyb_know_how_details_sort.how_details_id " +
                "  and zyb_know_how_details_sort.stat = 2 " +
                "  and scon_homework_how_details.knowledge_version = zyb_know_how_details_sort.type; ";

        return dao.findMap(sql, new String [] {homeworkId});
    }

    @Override
    public List<Map<String, Object>> countCorrectedHomeworkPictureSumAndUsedTime(String teacherId, String beginTimeStr, String endTimeStr) {
        List<Object> paramList = new ArrayList<>();

        String sql =
                "select count(*) picture_sum, sum(scon_homework_picture.correction_time) correction_time\n" +
                "from scon_homework,\n" +
                "     scon_homework_picture\n" +
                "where scon_homework.id = scon_homework_picture.homework_id\n" +
                "  and scon_homework_picture.teacher_id = ?\n";
        paramList.add(teacherId);

        if (beginTimeStr != null) {
            sql += "  and ? < scon_homework.correct_time\n";
            paramList.add(beginTimeStr);
        }

        sql += "  and scon_homework.correct_time < ?\n";
        paramList.add(endTimeStr);

        return dao.findMap(sql, paramList.toArray());
    }

    @Override
    public List<String> findIdPictureNotUpload(String vipId) {
        String sql =
                "					select scon_homework.id\n " +
                        "                      from scon_homework\n " +
                        "                               left join\n" +
                        "                           scon_homework_picture on scon_homework.id = scon_homework_picture.homework_id\n " +
                        "                      where scon_homework.vip_id =?\n " +
                        "                        and to_days(start_time) = to_days(now())\n " +
                        "                        and work_type in (1, 2)\n " +
                        "                      group by scon_homework.id\n " +
                        "                      HAVING count(scon_homework_picture.id) <1";
        return dao.findList(sql, new String [] {vipId}, String.class);
    }

    @Override
    public Page<Map<String, Object>> findHomeworkByPage(Map<String, Object> searchParam, Pageable pageable) {
        String childName = searchParam.get("LIKE_childName").toString();
        String beginTime = searchParam.get("beginTimeStr").toString();
        String endTime = searchParam.get("endTimeStr").toString();

        StringBuilder sb = new StringBuilder(
                "select scon_homework.subject,\n" +
                "       scon_homework.vip_id,\n" +
                "       scon_homework.grade,\n" +
                "       scon_homework.id,\n" +
                "       count(*)                                                               picture_sum,\n" +
                "       sum(case when scon_homework_picture.is_feedback = 0 and scon_homework_picture.is_mark in (0, 2) then 1 else 0 end) not_correct_picture_sum,\n" +
                "       scon_homework.derver,\n" +
                "       tb_lib_vip.child_name,\n" +
                "       tb_lib_vip.parent_name,\n" +
               // "       tb_lib_manager.name teacher_name,\n" +
                        "( SELECT GROUP_CONCAT( DISTINCT t.name) from  tb_lib_manager  t where\n" +
                        "find_in_set(t.user_id ,GROUP_CONCAT( DISTINCT scon_homework_picture.teacher_id )) and \n" +
                        " t.type in (8,11) and t.state =1  ) as teacher_name," +
                "       scon_homework.create_time\n" +
                "from scon_homework\n" +
                "         join tb_lib_vip on scon_homework.vip_id = tb_lib_vip.id\n" +
                "         join scon_homework_picture\n" +
                "              on scon_homework.id = scon_homework_picture.homework_id and scon_homework_picture.is_delete = 0\n"
                 );
        sb.append("where scon_homework.create_time between '").append(beginTime).append("' and '").append(endTime).append("' ");
        if (StringUtils.isNotBlank(childName)) {
            sb.append("  and tb_lib_vip.child_name like '%").append(childName).append("%'\n");
        }
        sb.append(" group by scon_homework.id\n");
        sb.append(" order by scon_homework.create_time desc, scon_homework.id");

        return dao.findByPage(sb.toString(), sb.toString(), pageable);
    }
}
