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

import com.google.common.base.Strings;
import com.ssj.bean.sys.situation.domain.LearningSituation;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.dao.sys.situation.dao.LearningConditionDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;
import com.ssj.service.sys.situation.bo.DimesionCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Repository;

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

@Repository
public class LearningConditionDaoImpl implements LearningConditionDao {

	@Autowired
    private PagingHibernateJdbcDao dao;
	
	@Override
	public String queryLastDay() {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT 1 FROM scon_learning_situation_new t WHERE (TO_DAYS(now()) - TO_DAYS(t.create_time)) <= 1 limit 1");
		List<String> strList = dao.findList(sb.toString(), String.class);
		return strList.size() > 0 ? String.valueOf(strList.get(0)) : "";
	}

	@Override
	public List<LibVip> queryAllVip() {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT v.grade FROM tb_lib_vip v left join tb_lib_vip_service vs GROUP BY v.id WHERE vs.id is not null");
		return dao.findList(sb.toString(), LibVip.class);
	}

	@Override
	public String queryGradeByVipId(String id) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT IF(hw.grade IS NOT NULL,hw.grade,v.grade) FROM scon_homework hw LEFT JOIN tb_lib_vip v ON hw.vip_id = v.id where hw.vip_id = ? ORDER BY hw.create_time desc LIMIT 1");
		List<Object> params = new ArrayList<Object>();
		params.add(id);
		List<String> strList = dao.findList(sb.toString(), params.toArray(), String.class);
		return strList.size() > 0 ? strList.get(0) : "";
	}

	@Override
	public List<String> getServiceStudentIdsByGrade(String grade) {
		StringBuilder sb = new StringBuilder();
//		sb.append("select DISTINCT vip_id from tb_lib_vip_service vs left join tb_lib_vip v on vs.vip_id = v.id WHERE 1 = 1 ");
		sb.append("SELECT hw.vip_id FROM scon_homework hw LEFT JOIN kmt_homework_wrong_question hwq ON hwq.homework_id = hw.id "
				+ "LEFT JOIN scon_homework_how_details hhd ON hw.id = hhd.homework_id WHERE hwq.id IS NOT NULL OR hhd.id IS NOT NULL GROUP BY hw.vip_id");
//		List<Object> params = new ArrayList<Object>();
//		if( !Strings.isNullOrEmpty(grade)) {
//			sb.append(" v.grade = ?");
//			params.add(grade);
//		}
		return dao.findList(sb.toString(), String.class);
	}

	@Override
	public List<Map<String, Object>> queryManualHomeworkKnowMoudle(String vipId, String grade, String courseName) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT");
		if(courseName.equals("语文") || courseName.equals("数学")) {
			sb.append(" kd.two_module name,");
		} else {
			sb.append("	kd.module name,");
		}
		sb.append("	sum( hwd.detail_count ) wrongCount,");
		sb.append("	sum( hwd.total_count ) totalCount");
		sb.append(" FROM");
		sb.append("	scon_homework_how_details hwd");
		sb.append("	LEFT JOIN scon_homework hw ON hw.id = hwd.homework_id");
		sb.append("	LEFT JOIN zyb_know_how_details kd ON hwd.how_detail_id = kd.id ");
//		sb.append(" LEFT JOIN zyb_know_how_details_sort kds ON kd.id = kds.how_details_id AND kds.stat = 2 AND hwd.knowledge_version = kds.type");
//		sb.append(" WHERE kds.semester = (SELECT param_val from tb_sys_config where param_code = 'semester')");
		sb.append(" where kd.is_zt = 0");
		List<Object> param = new ArrayList<>();
		if( !Strings.isNullOrEmpty(courseName)) {
			sb.append(" AND	hw.`subject` = ? ");
			param.add(courseName);
		}
		if( !Strings.isNullOrEmpty(vipId)) {
			sb.append("	AND hw.vip_id = ? ");
			param.add(vipId);
		}
		if( !Strings.isNullOrEmpty(grade)) {
			sb.append("	AND hw.grade = ? ");
			param.add(grade);
		}
		sb.append(" GROUP BY kd.module");
		return dao.findMap(sb.toString(), param.toArray());
	}

	@Override
	public List<Map<String, Object>> queryAutoHomeworkKnowMoudle(String vipId, String grade, String courseName) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT");
		if(courseName.equals("语文") || courseName.equals("数学")) {
			sb.append(" kd.two_module name,");
		} else {
			sb.append("	kd.module name,");
		}
		sb.append("	count( hwq.type = 1 or NULL) wrongCount,\r\n" + 
				"	count(1) totalCount\r\n" + 
				"FROM\r\n" + 
				"	kmt_homework_wrong_question hwq\r\n" + 
				"	LEFT JOIN scon_homework hw ON hwq.homework_id = hw.id\r\n" + 
				"	LEFT JOIN kmt_exercise_question_know eqk ON hwq.question_id = eqk.question_id\r\n"); 
//		sb.append("	LEFT JOIN kmt_exercise_questions keq ON hwq.question_id = keq.id\r\n" ); 
//		sb.append("	LEFT JOIN kmt_exercise_book_course ebc ON keq.book_id = ebc.book_id\r\n" ); 
		sb.append("	LEFT JOIN zyb_know_how_details kd ON eqk.how_details_id = kd.id\r\n"); 
//		sb.append("	LEFT JOIN zyb_know_how_details_sort kds ON kd.id = kds.how_details_id AND kds.stat = 2 AND kds.type = ebc.version\r\n");
//		sb.append(" WHERE kds.semester = (SELECT param_val from tb_sys_config where param_code = 'semester')");
		sb.append(" where kd.is_zt = 0");
		List<Object> param = new ArrayList<>();
		if( !Strings.isNullOrEmpty(courseName)) {
			sb.append(" AND	hw.`subject` = ? ");
			param.add(courseName);
		}
		if( !Strings.isNullOrEmpty(vipId)) {
			sb.append("	AND hw.vip_id = ? ");
			param.add(vipId);
		}
		if( !Strings.isNullOrEmpty(grade)) {
			sb.append("	AND hw.grade = ? ");
			param.add(grade);
		}
		sb.append(" GROUP BY kd.module");
//		sb.append(",  ebc.book_id");
		return dao.findMap(sb.toString(), param.toArray());
	}

	@Override
	@Modifying
	public Integer insertOrUpdateLearnSituation(LearningSituation situation) {
		StringBuilder sb = new StringBuilder();
		sb.append("INSERT INTO scon_learning_situation_new (id, student_id, course_name, type, create_time, remark, wrong_count, total_count, grade, dimension, "
				+ "suggest_id, degree_percent, semester) "
				+ "VALUES ('");
		sb.append(situation.getId() + "', ");
		sb.append(situation.getStudentId() == null ? null : ("'" + situation.getStudentId() + "'"));
		sb.append(", '" + situation.getCourseName() + "', ");
		sb.append(situation.getType() + ", ");
		sb.append("now(), ");
		sb.append(situation.getRemark() == null ? null : ("'" + situation.getRemark() + "', "));
		sb.append(situation.getWrongCount() + ", ");
		sb.append(situation.getTotalCount() + ", ");
		sb.append(situation.getGrade() == null ? null : ("'" + situation.getGrade() + "', '"));
		sb.append(situation.getDimension() + "', '");
		sb.append(situation.getSuggestId()+ "', ");
		sb.append(situation.getDegreePercent()+ ", ");
		sb.append(situation.getSemester()+ " ");
		sb.append(") ON DUPLICATE KEY UPDATE wrong_count = wrong_count + ");
		sb.append(situation.getWrongCount() + ", ");
		sb.append("total_count = total_count + ");
		sb.append(situation.getTotalCount());
		sb.append(", degree_percent = (100 - ROUND((wrong_count)/(total_count ) * 100))");
		return dao.createSQLQuery(sb.toString()).executeUpdate();
	}

	@Override
	public List<DimesionCount> queryManualPointData(String vipId, String grade, String courseName) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT\r\n" );
		sb.append("	sum( kd.memorize * detail_count ) wrongMemorize,\r\n" );
		sb.append("	sum( kd.understanding * detail_count ) wrongunderstanding,\r\n" );
		sb.append("	sum( kd.apply * detail_count ) wrongapply,\r\n" );
		sb.append("	sum( kd.memorize * total_count ) memorize,\r\n" );
		sb.append("	sum( kd.understanding * total_count ) understanding,\r\n" );
		sb.append("	sum( kd.apply * total_count ) apply \r\n" );
		sb.append("FROM\r\n" );
		sb.append("	scon_homework_how_details hwd\r\n" );
		sb.append("	LEFT JOIN scon_homework hw ON hwd.homework_id = hw.id\r\n" );
		sb.append("	LEFT JOIN zyb_know_how_details kd ON hwd.how_detail_id = kd.id\r\n" );
//		sb.append("	LEFT JOIN zyb_know_how_details_sort kds ON kd.id = kds.how_details_id AND kds.stat = 2 AND hwd.knowledge_version = kds.type\r\n");
//		sb.append(" WHERE kds.semester = (SELECT param_val from tb_sys_config where param_code = 'semester')");
		sb.append(" where kd.is_zt = 0");
		List<Object> param = new ArrayList<>();
		if( !Strings.isNullOrEmpty(courseName)) {
			sb.append(" AND	hw.`subject` = ? ");
			param.add(courseName);
		}
		if( !Strings.isNullOrEmpty(vipId)) {
			sb.append("	AND hw.vip_id = ? ");
			param.add(vipId);
		}
		if( !Strings.isNullOrEmpty(grade)) {
			sb.append("	AND hw.grade = ? ");
			param.add(grade);
		}
		return dao.findList(sb.toString(),  param.toArray(), DimesionCount.class);
	}

	@Override
	public List<DimesionCount> queryAutoPointData(String vipId, String grade, String courseName) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT\r\n" );
		sb.append("	sum( kd.memorize ) memorize,\r\n" );
		sb.append("	sum( kd.understanding ) understanding,\r\n" );
		sb.append("	sum( kd.apply ) apply ,\r\n" );
		sb.append("	sum( IF(hwq.type = 1, kd.memorize, 0) ) memorizeWrong,\r\n" );
		sb.append("	sum( IF(hwq.type = 1, kd.understanding, 0) ) understandingWrong,\r\n" );
		sb.append("	sum( IF(hwq.type = 1, kd.apply, 0) ) applyWrong \r\n" );
		sb.append("FROM\r\n" );
		sb.append("	kmt_homework_wrong_question hwq\r\n" );
		sb.append("	LEFT JOIN kmt_exercise_question_know eqk ON eqk.question_id = hwq.question_id\r\n" );
//		sb.append("	LEFT JOIN kmt_exercise_questions keq ON hwq.question_id = keq.id\r\n" );
//		sb.append("	LEFT JOIN kmt_exercise_book_course ebc ON keq.book_id = ebc.book_id\r\n" );
		sb.append("	LEFT JOIN scon_homework hw ON hwq.homework_id = hw.id\r\n" );
		sb.append("	LEFT JOIN zyb_know_how_details kd ON eqk.how_details_id = kd.id \r\n" );
//		sb.append("  LEFT JOIN zyb_know_how_details_sort kds ON kd.id = kds.how_details_id AND kds.stat = 2 AND kds.type = ebc.version\r\n");
//		sb.append(" WHERE kds.semester = (SELECT param_val from tb_sys_config where param_code = 'semester')");
		sb.append(" where kd.is_zt = 0");
		List<Object> param = new ArrayList<>();
		if( !Strings.isNullOrEmpty(courseName)) {
			sb.append(" AND	hw.`subject` = ? ");
			param.add(courseName);
		}
		if( !Strings.isNullOrEmpty(vipId)) {
			sb.append("	AND hw.vip_id = ? ");
			param.add(vipId);
		}
		if( !Strings.isNullOrEmpty(grade)) {
			sb.append("	AND hw.grade = ? ");
			param.add(grade);
		}
		sb.append(" GROUP BY kd.module");
//		sb.append(" ,  ebc.book_id");
		// 总数和错误数一起返回
		return dao.findList(sb.toString(),  param.toArray(), DimesionCount.class);
	}

	@Override
	public List<Map<String, Object>> getAvgCountByDimension(String grade, Integer semester, String courseName) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT dimension dimension, ROUND(AVG( wrong_count )) wrongCount, ROUND(AVG( total_count )) totalCount, type, grade, semester, course_name courseName")
				.append(" FROM scon_learning_situation_new where course_name = ? AND grade = ? AND semester = ? GROUP BY dimension, type");
		List<Object> param = new ArrayList<>();
		param.add(courseName);
		param.add(grade);
		param.add(semester);
		return dao.findMap(sb.toString(), param.toArray());
	}

	@Override
	public String querySuggestByDimension(String dimension, String grade, Integer degree, String courseName, Integer type) {
		StringBuilder sb = new StringBuilder();
		sb.append("	SELECT id FROM scon_learning_situation_suggest WHERE course_name = ? AND module = ? AND LOCATE(?,grade) AND min <= ? AND max > ? AND type = ?");
		List<Object> param = new ArrayList<>();
		param.add(courseName);
		param.add(dimension);
		param.add(grade);
		param.add(degree);
		param.add(degree);
		param.add(type);
		List<String> strList = dao.findList(sb.toString(), param.toArray(), String.class);
 		return strList.size() > 0 ? strList.get(0) : "";
	}

	/**
	 * SELECT 
  IF(hw.`subject` ='语文' OR hw.`subject` = '数学',kd.two_module, kd.module)  dimension,
	IF(hwq.type = 1, 1, 0) wrongCount,
	1 totalCount,
	hw.`subject` courseName,
	hw.vip_id vipId,
	hw.grade grade,
	kds.semester semester
FROM
	kmt_homework_wrong_question hwq
	LEFT JOIN scon_homework hw ON hwq.homework_id = hw.id
	LEFT JOIN kmt_exercise_question_know eqk ON hwq.question_id = eqk.question_id
	LEFT JOIN kmt_exercise_questions keq ON hwq.question_id = keq.id
	LEFT JOIN kmt_exercise_book_course ebc ON keq.book_id = ebc.book_id
	LEFT JOIN zyb_know_how_details kd ON eqk.how_details_id = kd.id
	LEFT JOIN zyb_know_how_details_sort kds ON kd.id = kds.how_details_id 
	AND kds.stat = 2 
	AND kds.type = ebc.version 
WHERE
	kd.is_zt = 0 
	AND hwq.is_delete = 0
	AND hw.vip_id IS NOT NULL 
	AND hw.grade IS NOT NULL 
	AND hw.`subject` IS NOT NULL
	AND kds.semester IS NOT NULL
	 */
	@Override
	public List<Map<String, Object>> queryAutoHwMoudleByDate(Integer startNum, Integer size, String date) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT IF(hw.`subject` ='语文' OR hw.`subject` = '数学',kds.two_module, kds.module)  dimension, IF(hwq.type = 1, 1, 0) wrongCount, 1 totalCount,")
			.append(" hw.`subject` courseName, hw.vip_id vipId, hw.grade grade, kds.semester semester, kds.how_details_id howDetailId, kds.alias  alias, ")
			.append(" hwq.id, hwq.create_time")
			.append(" FROM kmt_homework_wrong_question hwq LEFT JOIN scon_homework hw ON hwq.homework_id = hw.id ")
			.append(" LEFT JOIN kmt_exercise_question_know eqk ON hwq.question_id = eqk.question_id ")
			.append(" LEFT JOIN kmt_exercise_questions keq ON hwq.question_id = keq.id ")
			.append(" LEFT JOIN kmt_exercise_book_course ebc ON keq.book_id = ebc.book_id ")
			.append(" LEFT JOIN zyb_know_how_details kd ON eqk.how_details_id = kd.id ")
			.append(" LEFT JOIN zyb_know_how_details_sort kds ON kd.id = kds.how_details_id AND kds.stat = 2 AND kds.type = ebc.version  ") //kd.is_zt = 0 AND
			.append(" WHERE  hwq.is_delete = 0 AND hw.vip_id IS NOT NULL AND hw.grade IS NOT NULL AND hw.`subject` IS NOT NULL AND kds.semester IS NOT NULL");
		List<Object> params = new ArrayList<Object>();
		if(!Strings.isNullOrEmpty(date)) {
			sb.append(" AND date(hwq.create_time ) = ?");
			params.add(date);
		}
		sb.append(" GROUP BY hwq.id ORDER BY hwq.create_time LIMIT ?, ?");
		params.add(startNum);
		params.add(size);
		return dao.findMap(sb.toString(), params.toArray());
	}

	/**
	 * SELECT
	IF(hw.`subject` ='语文' OR hw.`subject` = '数学',kd.two_module, kd.module)  dimension,
	IF(hhd.detail_count IS NULL, 0, hhd.detail_count) wrongCount,
	IF(hhd.total_count IS NULL, 0, hhd.total_count) totalCount,
	hw.`subject` courseName,
	hw.vip_id vipId,
	hw.grade grade, kds.semester semester
FROM
	scon_homework_how_details hhd
	LEFT JOIN scon_homework hw ON hhd.homework_id = hw.id
	LEFT JOIN zyb_know_how_details kd ON hhd.how_detail_id = kd.id
	LEFT JOIN zyb_know_how_details_sort kds ON kd.id = kds.how_details_id 
	AND kds.stat = 2 
	AND hhd.knowledge_version = kds.type 
WHERE
	kd.is_zt = 0 
	AND hw.vip_id IS NOT NULL
	AND hw.grade IS NOT NULL
	AND hw.`subject` IS NOT NULL
	ORDER BY hhd.create_time LIMIT 0, 1000
	 */
	@Override
	public List<Map<String, Object>> queryManualHwMoudleByDate(Integer startNum, Integer size, String date) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT	IF(hw.`subject` ='语文' OR hw.`subject` = '数学',kds.two_module, kds.module)  dimension,	")
			.append(" IF(hhd.detail_count IS NULL, 0, hhd.detail_count) wrongCount,	IF(hhd.total_count IS NULL, 0, hhd.total_count) totalCount,	")
			.append(" hw.`subject` courseName,	hw.vip_id vipId,	hw.grade grade, kds.semester semester, kds.how_details_id howDetailId, kds.alias alias, ")
			.append(" hhd.id, hhd.create_time ")
			.append(" FROM	scon_homework_how_details hhd	")
			.append(" LEFT JOIN scon_homework hw ON hhd.homework_id = hw.id	")
			.append(" LEFT JOIN zyb_know_how_details kd ON hhd.how_detail_id = kd.id	")
			.append(" LEFT JOIN zyb_know_how_details_sort kds ON kd.id = kds.how_details_id 	AND kds.stat = 2 	AND hhd.knowledge_version = kds.type ")
			.append(" WHERE	hhd.wrong_question_id is null and hw.vip_id IS NOT NULL	") //kd.is_zt = 0 AND
			.append(" AND hw.grade IS NOT NULL	AND hw.`subject` IS NOT NULL AND kds.semester IS NOT NULL");
		List<Object> params = new ArrayList<Object>();
		if(!Strings.isNullOrEmpty(date)) {
			sb.append(" AND date(hhd.create_time ) = ?");
			params.add(date);
		}
		sb.append(" GROUP BY hhd.id ORDER BY hhd.create_time LIMIT ?, ?");
		params.add(startNum);
		params.add(size);
		return dao.findMap(sb.toString(), params.toArray());
	}

	public List<String> queryAllDimensionByGradeCourseSemes(String grade, Integer semester, String courseName, Integer banben){
		StringBuilder sb = new StringBuilder();
		
		StringBuilder sqlStr = new StringBuilder();

		if("语文".equals(courseName) ) {
			sqlStr.append("t2.two_module");
		} else if("数学".equals(courseName)) {
			sqlStr.append("t2.two_module");
		} else {
			sqlStr.append("t2.module");
		}


		sb.append("SELECT DISTINCT ").append(sqlStr).append(" FROM zyb_know_how_details t1 LEFT JOIN zyb_know_how_details_sort t2 ON t1.id = t2.how_details_id " )
		.append("WHERE ").append(sqlStr).append(" IS NOT NULL AND ").append(sqlStr)
		.append(" != '' AND t2.stat = 2 AND t2.course_name =? AND t2.grade = ? AND t2.semester = ? AND t2.type = ?");
		if(courseName.equals("语文")) {
			sb.append(" AND t1.two_module <> '写作'");
		}
		sb.append(" AND ").append(sqlStr).append(" not like '%复习%'");
		List<Object> params = new ArrayList<Object>();
		params.add(courseName);
		params.add(grade);
		params.add(semester);
		params.add(banben);
		return dao.findList(sb.toString(), params.toArray(), String.class);
	}

	@Override
	@Modifying
	public void deleteAll() {
		StringBuilder sb = new StringBuilder();
		sb.append("delete from scon_learning_situation_new");
		dao.createSQLQuery(sb.toString()).executeUpdate();
	}

	@Override
	public List<LearningSituation> queryHistoryByVipIdAndSubject(String vipId, String subject) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT * FROM scon_learning_situation_new ")
		.append("WHERE (student_id = ? OR student_id IS NULL) AND course_name = ? ");
		List<Object> params = new ArrayList<Object>();
		params.add(vipId);
		params.add(subject);
		return dao.findList(sb.toString(), params.toArray(), LearningSituation.class);
	}

	@Override
	public void deleteAllAvg() {
		StringBuilder sb = new StringBuilder();
		sb.append("delete from scon_learning_situation_new where student_id is null");
		dao.createSQLQuery(sb.toString()).executeUpdate();
	}
}
