package com.ssj.dao.conch.schoolmaster.dao.impl;

import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.dao.conch.schoolmaster.dao.ISchoolQueryDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;
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 ISchoolQueryDaoImpl implements ISchoolQueryDao {
	
	
	@Autowired
	private PagingHibernateJdbcDao dao;

	@Override
	public Page<Map<String, Object>> findByPage(Map<String, Object> params, Pageable pageable) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT t.*,IF(t.type=7,1,0) as teacherType from tb_lib_manager t where ((t.lib_id = ? AND type=2) OR (t.master_id=? AND type=7))  " );
        queryParams.add(params.get("EQ_libId"));
		queryParams.add(params.get("master_id"));
		if (params.get("LIKE_name") != null && !params.get("LIKE_name").equals("")) {
	        selSQL.append(" AND t.`name` LIKE '' CONCAT(CONCAT('%',?,'%')) ");
	        queryParams.add(params.get("LIKE_name"));
	     }
		return dao.findPage(selSQL.toString(),queryParams.toArray(), pageable);
	}

	@Override
	public Page<Map<String, Object>> findStudentPage(Map<String, Object> params, Pageable pageable) {
		StringBuilder sb = new StringBuilder();
		sb.append("select t11.vip_id from tb_lib_vip_bind t11 left join tb_lib_vip t13 on t11.vip_id=t13.id")
				.append(" where t11.master_id='").append(params.get("masterId"))
				.append("' and t13.user_id is not null and t11.create_time < '").append(params.get("maxCreateTime")).append("'");

		//加上作业吧的学生
//		if (libIdStr != null && libIdStr.length() >0){
//			sb.append(" UNION select t14.vip_id from tb_lib_vip_service t14 left join tb_lib_vip t15 on t14.vip_id=t15.id where t14.lib_id in (")
//					.append(libIdStr)
//					.append(") and t14.species in (").append(params.get("services")).append(") and t14.stat=1 and t15.user_id is not null")
//					.append(" and t14.create_time <'").append(params.get("maxCreateTime")).append("'");
//		}
		return dao.findPage(sb.toString(), null, pageable);
	}

	@Override
	public List<String> findSearchStudents(Map<String, Object> params) {
		StringBuilder sb = new StringBuilder();
		sb.append("select t11.vip_id from tb_lib_vip_bind t11 left join tb_lib_vip t13 on t11.vip_id=t13.id")
				.append(" where t11.master_id='").append(params.get("masterId"))
				.append("' and t13.user_id is not null and t13.child_name REGEXP '").append(params.get("name")).append("'");

		//加上作业吧的学生
//		if (libIdStr != null && libIdStr.length() >0){
//			sb.append(" UNION select t14.vip_id from tb_lib_vip_service t14 left join tb_lib_vip t15 on t14.vip_id=t15.id where t14.lib_id in (")
//					.append(libIdStr)
//					.append(") and t14.species in (").append(params.get("services")).append(") and t14.stat=1 and t15.user_id is not null")
//					.append(" and t14.create_time <'").append(params.get("maxCreateTime")).append("'");
//		}
		return dao.findList(sb.toString(), String.class);
	}

    @Override
    public Page<Map<String, Object>> findStudentPageTest(Map<String, Object> params, Pageable pageable) {
        StringBuilder sb = new StringBuilder();
        String libIdStr = params.get("libIdStr") + "";
        //合作馆查所有作业吧的学生
		if (libIdStr != null && libIdStr.length() >0){
			sb.append("select t14.vip_id from tb_lib_vip_service t14 left join tb_lib_vip t15 on t14.vip_id=t15.id where t14.lib_id in (")
					.append(libIdStr)
					.append(") and t14.species in ('").append(params.get("services")).append("') and t14.stat=1 and t15.user_id is not null")
					.append(" and t14.create_time <'").append(params.get("maxCreateTime")).append("'");
		}
        return dao.findPage(sb.toString(), null, pageable);
    }

	@Override
	public List<String> findSearchStudentsTest(Map<String, Object> params) {
		StringBuilder sb = new StringBuilder();
		String libIdStr = params.get("libIdStr") + "";
		//合作馆查所有作业吧的学生
		if (libIdStr != null && libIdStr.length() >0){
			sb.append("select t14.vip_id from tb_lib_vip_service t14 left join tb_lib_vip t15 on t14.vip_id=t15.id where t14.lib_id in (")
					.append(libIdStr)
					.append(") and t14.species in ('").append(params.get("services")).append("') and t14.stat=1 and t15.user_id is not null")
					.append(" and t15.child_name regexp '").append(params.get("name")).append("'");
		}
		return dao.findList(sb.toString(), String.class);
	}

	@Override
	public Page<Map<String, Object>> findTeacherPage(Map<String, Object> params, Pageable pageable) {
		StringBuilder sb = new StringBuilder();
		sb.append("select distinct * from (")
				.append(" select lib_id, user_id, type, name, telephone, sex, GROUP_CONCAT(distinct course_name) course_name,")
				.append(" t_photo, school_age, teacher_lever, student_count, course_count, praise from tb_lib_manager  where")
				.append(" type = 7 and state = 1 and create_time < '").append(params.get("maxCreateTime")).append("'")
				.append(" group by lib_id, user_id, type, name, telephone, sex, t_photo, school_age, teacher_lever,")
				.append(" student_count, course_count, praise");
		String libIdsStr = params.get("libIds") + "";
		if (StringUtils.isNotBlank(libIdsStr)){
			sb.append(" UNION")
					.append(" select  lib_id, user_id, type, name, telephone, sex, course_name, t_photo, school_age, teacher_lever, student_count, course_count, praise from tb_lib_manager ")
					.append(" where lib_id in (").append(params.get("libIds"))
					.append(") and type = 2 and state = 1 and create_time < '").append(params.get("maxCreateTime")).append("'");
		}
		sb.append(") t1");
		return dao.findPage(sb.toString(), null, pageable);
	}

	@Override
	public List<Map<String, Object>> findStudentOrderList(String masterId, String vipId) {
		StringBuilder sb = new StringBuilder();
		sb.append("select o.id order_id, o.create_time, o.order_status, t.course_count, t.status, t.start_time, t.end_time,t.course_name, ")
				.append("t.grade, t.id lesson_service_id from tb_lesson_service t LEFT JOIN tb_orders o ON t.order_id = o.id ")
				.append(" where t.master_id = ? and t.vip_id = ? and o.order_status in (1, 4)");  //查出已支付和退款的
		Object[] objParam = {masterId, vipId};
		return dao.findMap(sb.toString(), objParam);
	}

	@Override
	public List<Map<String, Object>> getMaster121TeacherId(String masterId) {
		StringBuilder sb = new StringBuilder();
		sb.append("select distinct t2.teacher_id from tb_lesson_service t1 left join kmt_course t2 on t1.id=t2.lesson_service_id")
				.append(" where t2.teacher_id is not null and t2.teacher_id != ''")
				.append(" and t1.master_id='").append(masterId).append("'");
		return dao.findMap(sb.toString(), null);
	}

	@Override
	public List<TbLibManager> querySystemMatchTeacher(Map<String, Object> param) {
		StringBuilder sb = new StringBuilder();
		int sex = (Integer) param.get("sex");
		String courseName = (String)param.get("courseName");
		int orderType = (Integer) param.get("orderType");
		List<String> teacherVals = (List<String>)param.get("teacherVal");
		Integer tType = (Integer)param.get("tType");

		sb.append("select distinct lib_id,  user_id, name, t_photo, school_age, course_count,student_count, sex, course_name, teacher_lever,  telephone, praise from tb_lib_manager t1 where state = 1");

		//哪个类型的老师，7一对一老师，9小课老师, 老师类型
		if (tType != null) {
			sb.append(" and type = ").append(tType.intValue());
		} else {
			//默认一对一老师
			sb.append(" and type = 7");
		}

		//授课时段
		if (teacherVals != null && teacherVals.size() > 0){
			sb.append(" and EXISTS(select teacher_id from kmt_course_template t2 where t1.user_id=t2.teacher_id  and val in (");
			for (String str : teacherVals){
				sb.append("'").append(str).append("'").append(",");
			}
			sb.deleteCharAt(sb.length() - 1);
			sb.append(") and type =2 and state = 1)");
		}

		//科目
		if (StringUtils.isNotBlank(courseName)){
			sb.append(" and course_name regexp '").append(courseName).append("'");
		}

		//性别
		if (sex > 0){
			sb.append(" and sex=").append(sex);
		}

		//老师类别
		if (StringUtils.isNotBlank(param.get("teacherType") + "")){
			sb.append(" and teacher_lever REGEXP'").append(param.get("teacherType")).append("'");
		}

		//年级匹配
		if (StringUtils.isNotBlank(param.get("grade") + "")){
			sb.append(" and grade REGEXP '").append(param.get("grade")).append("'");
		}

		//老师姓名
		if(StringUtils.isNotBlank(param.get("teacherName") + "")){
			sb.append(" and name REGEXP '").append(param.get("teacherName")).append("'");
		}

		//教龄类型， 1五年以下，2五到十年， 3十年以上
		if ( 1 == (Integer)param.get("schoolAgeType")){
			sb.append(" and school_age < 5");
		} else if (2 == (Integer)param.get("schoolAgeType")){
			sb.append(" and school_age between 5 and 10");
		} else if (3 == (Integer)param.get("schoolAgeType")){
			sb.append(" and school_age > 10");
		}


		//排序
		if (orderType == 1){
			//离我最近
			double lon = Double.parseDouble((String)param.get("lon"));
			double lat= Double.parseDouble((String)param.get("lat"));
			sb.append(" order by ifnull((abs(lon - ").append(lon).append(") * abs(lon - ").append(lon)
					.append(") +  abs(lat - ").append(lat).append(") * abs(lat - ").append(lat)
					.append(")),").append(lon * lon + lat * lat).append(")");
		} else  if (orderType == 2){
			//口碑好到差排序
			sb.append(" order by praise desc");
		} else if (orderType == 3){
			//授课次数排序
			sb.append(" order by course_count desc");
		}
		return dao.findList(sb.toString(), TbLibManager.class);
	}

	@Override
	public List<Map<String, Object>> queryOrgTeacher(Map<String, Object> searchParams) {
		List<Object> queryParams = new ArrayList<>();
		String sql;
		//经纬度为空，这里设置没有距离
		if (StringUtils.isEmpty((String)searchParams.get("latitude")) || StringUtils.isEmpty((String)searchParams.get("longitude"))) {
			sql = "SELECT * , -1 AS distance," +
					" ifnull((select round(avg(judge_level),2)\n" +
					"          from tb_teacher_assessment t\n" +
					"          where t.teacher_id = user_id and t.subject = ?), 5) judge_level " +
					" FROM tb_lib_manager where type = 10 ";
			queryParams.add(searchParams.get("subject"));
		} else {
			sql = "SELECT\n" +
					"	* , " +
					" func_calcDistance(lon,lat,?,?) AS distance," +
					" ifnull((select round(avg(judge_level),2)\n" +
					"          from tb_teacher_assessment t\n" +
					"          where t.teacher_id = user_id and t.subject = ? ), 5) judge_level " +
					" FROM " +
					"	tb_lib_manager    where  type =10 ";
			queryParams.add(searchParams.get("longitude"));
			queryParams.add(searchParams.get("latitude"));
			queryParams.add(searchParams.get("subject"));
		}
		sql += " and course_name like CONCAT(CONCAT('%',?,'%'))  " +
				" ORDER BY distance ASC,name desc " +
				" limit 20 ";
		queryParams.add(searchParams.get("subject"));
		return dao.findMap(sql, queryParams.toArray());
	}
}