package com.ssj.dao.weixin.order.dao.impl;

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 com.ssj.dao.weixin.order.dao.OrderQueryDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;

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

/** 
 * @author  ZhangCaibao 
 * @version 2017年5月8日 上午9:41:38 
 * 类说明 
 */
@Repository
public class OrderQueryDaoImpl implements OrderQueryDao{

	@Autowired
	private PagingHibernateJdbcDao dao;

	@Override
	public Page<Map<String, Object>> findForPageList(
			Map<String, Object> searchParams, Pageable pageable) {
		 StringBuilder selSQL = new StringBuilder();
	        List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT   o.* ,u.wx_name ,r.create_time as refund_time from  tb_orders o join  tb_user  u  ");
	        selSQL.append("  on o.user_id  = u.id  ");
	        selSQL.append("  LEFT JOIN  tb_order_refund  r  on  o.order_no = r.order_no  ");
	        if(searchParams!=null && searchParams.size()>0){
	        	selSQL.append("  where 1=1 ");
	        }
	        if (searchParams.get("order_type") != null && !searchParams.get("order_type").equals("")) {
	        		selSQL.append(" and o.order_type = ?  ");
	        	queryParams.add(searchParams.get("order_type"));
	        }
	        if (searchParams.get("order_status") != null && !searchParams.get("order_status").equals("")) {
	        	selSQL.append(" and o.order_status = ?  ");
	        	queryParams.add(searchParams.get("order_status"));
	        }
	        
	        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
	        	selSQL.append(" and TO_DAYS(o.create_time) >=TO_DAYS(?) ");
	        	queryParams.add(searchParams.get("beginDate"));
	        }
	        if (searchParams.get("endDate") != null && !searchParams.get("endDate").equals("")) {
	        	selSQL.append(" and TO_DAYS(o.create_time) <=TO_DAYS(?) ");
	        	queryParams.add(searchParams.get("endDate"));
	        }
	        if (searchParams.get("order_no") != null && !searchParams.get("order_no").equals("")) {
        		selSQL.append(" and o.order_no = ?  ");
        	queryParams.add(searchParams.get("order_no"));
        }
	        
	        selSQL.append(" order by o.create_time  desc  ");
	    return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	public List<Map<String, Object>> countOrderDetailsNum(){
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT j.id as lib_id,IFNULL(Tmp.num,0) as count from tb_lib_join j LEFT JOIN( "+
			"SELECT b.lib_id,COUNT(1) as num from tb_order_details t "+
			"LEFT JOIN tb_lib_book_detail b ON t.book_detail_id=b.id "+
			"WHERE TO_DAYS(t.create_time)=TO_DAYS(date_add(NOW(), interval -1 day)) and t.is_close=2 "+
			"GROUP BY b.lib_id) as Tmp ON Tmp.lib_id=j.id;");
		return dao.findMap(selSQL.toString(),queryParams.toArray());
	}

	public  List<Map<String, Object>> countOrderDetailsPriceByDay(){
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT j.id as lib_id,IFNULL(Tmp.price,0) as count from tb_lib_join j LEFT JOIN( "+
			"SELECT t.lib_id,SUM(t.price) as price FROM `tb_lib_order_details` t "+
			"WHERE t.order_status='1' AND TO_DAYS(t.create_time)=TO_DAYS(date_add(NOW(), interval -1 day)) "+
			"GROUP BY t.lib_id) as Tmp ON Tmp.lib_id=j.id;");
		return dao.findMap(selSQL.toString(),queryParams.toArray());
	}
	

	public  List<Map<String, Object>> countOrderDetailsPriceByCount(){
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT j.id as lib_id,IFNULL(Tmp.price,0) as count from tb_lib_join j LEFT JOIN( "+
			"SELECT t.lib_id,SUM(t.price) as price FROM `tb_lib_order_details` t "+
			"WHERE t.order_status='1' "+
			"GROUP BY t.lib_id) as Tmp ON Tmp.lib_id=j.id;");
		return dao.findMap(selSQL.toString(),queryParams.toArray());
		
	}
	
	
	public  List<Map<String, Object>> countOrderDetailsByTop(String libId){
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT tmp.id,count(1) as top,tmp.title from ( "+
				"SELECT i.id,t.title from tb_order_details t "+
				"LEFT JOIN tb_lib_book_detail b ON b.id=t.book_detail_id "+
				"LEFT JOIN tb_lib_book_info i ON i.id=b.info_id");
		if(StringUtils.isNotEmpty(libId)){
			selSQL.append(" where ");
			String[] libIds=libId.split(";");
        	selSQL.append("  b.lib_id in ( ");
        	for (int i = 0; i < libIds.length; i++) {
        		selSQL.append(" ? ");
        		if(libIds.length-1>i){
        			selSQL.append(" , ");
        		}
            	queryParams.add(libIds[i]);
			}
        	selSQL.append(" ) ");
			
		}
		selSQL.append(") as tmp GROUP BY tmp.id ORDER BY top DESC LIMIT 0,10;");
		return dao.findMap(selSQL.toString(),queryParams.toArray());
	}
	

	public List<Map<String, Object>> countOrderDetailsByUser(String libId){
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT t.user_id,COUNT(1) as num,u.wx_name "+
				"from tb_order_details t "+
				"LEFT JOIN tb_lib_book_detail b on b.id=t.book_detail_id "+
				"LEFT JOIN tb_user u ON u.id=t.user_id ");
		if(StringUtils.isNotEmpty(libId)){
			selSQL.append(" WHERE ");
			String[] libIds=libId.split(";");
        	selSQL.append("  b.lib_id in ( ");
        	for (int i = 0; i < libIds.length; i++) {
        		selSQL.append(" ? ");
        		if(libIds.length-1>i){
        			selSQL.append(" , ");
        		}
            	queryParams.add(libIds[i]);
			}
        	selSQL.append(" ) ");
		}
		selSQL.append(" GROUP BY t.user_id ORDER BY num DESC LIMIT 0,10;");
		return dao.findMap(selSQL.toString(),queryParams.toArray());	
	}
	

	public List<Map<String, Object>> countOrderDetailsByDayUser(String libId){
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT t.user_id,COUNT(1) as num,u.wx_name "+
				"from tb_order_details t "+
				"LEFT JOIN tb_lib_book_detail b on b.id=t.book_detail_id "+
				"LEFT JOIN tb_user u ON u.id=t.user_id "+
			"where t.create_time between TO_DAYS(date_add(NOW(), interval -30 day)) and NOW() ");
		if(StringUtils.isNotEmpty(libId)){
			selSQL.append(" AND ");
			String[] libIds=libId.split(";");
        	selSQL.append("  b.lib_id in ( ");
        	for (int i = 0; i < libIds.length; i++) {
        		selSQL.append(" ? ");
        		if(libIds.length-1>i){
        			selSQL.append(" , ");
        		}
            	queryParams.add(libIds[i]);
			}
        	selSQL.append(" ) ");
		}
		selSQL.append(" GROUP BY t.user_id ORDER BY num DESC LIMIT 0,10;");
		return dao.findMap(selSQL.toString(),queryParams.toArray());	
	}

	@Override
	public Integer signSubscribCounter(String libId,Integer day,String compare) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT count(DISTINCT(vip_id)) as count from tb_lib_subscribe b where  ");
		selSQL.append("DATE_SUB(CURDATE(), INTERVAL ? DAY)   ");
		queryParams.add(day);
		selSQL.append(compare);
		selSQL.append(" date(b.ryke_time)");
		selSQL.append(" AND ");
		
		if(StringUtils.isNotEmpty(libId)){
			String[] libIds=libId.split(";");
        	selSQL.append("  b.lib_id in ( ");
        	for (int i = 0; i < libIds.length; i++) {
        		selSQL.append(" ? ");
        		if(libIds.length-1>i){
        			selSQL.append(" , ");
        		}
            	queryParams.add(libIds[i]);
			}
        	selSQL.append(" ) ");
		}
		List<Map<String,Object>> ret=dao.findMap(selSQL.toString(),queryParams.toArray());	
		return Integer.parseInt((ret.get(0).get("count").toString()));
	}

	@Override
	public Integer signSubscribCount(String libId) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT count(DISTINCT(vip_id)) as count FROM `tb_lib_vip_service` t ");
		if(StringUtils.isNotEmpty(libId)){
			selSQL.append(" WHERE  t.species='S001' and ");
			String[] libIds=libId.split(";");
        	selSQL.append("  t.lib_id in ( ");
        	for (int i = 0; i < libIds.length; i++) {
        		selSQL.append(" ? ");
        		if(libIds.length-1>i){
        			selSQL.append(" , ");
        		}
            	queryParams.add(libIds[i]);
			}
        	selSQL.append(" ) ");
		}
		List<Map<String,Object>> ret=dao.findMap(selSQL.toString(),queryParams.toArray());	
		return Integer.parseInt((ret.get(0).get("count").toString()));
	}
	
	
	@Override
	public Integer signSubscribByDayCounter(String libId,Date selectDate,Integer type) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT COUNT(DISTINCT(vip_id)) as count  from tb_lib_subscribe b  where ");
		if(type==0){//预约
			selSQL.append("TO_DAYS(b.order_date) = TO_DAYS(?) AND order_time IS NOT null ");
		}else if(type==1){//到馆
			selSQL.append(" TO_DAYS(b.ryke_time) = TO_DAYS(?) ");
		}else if(type==-1){//出馆
			selSQL.append(" TO_DAYS(b.leave_time) = TO_DAYS(?) ");
		}
		queryParams.add(selectDate);
		selSQL.append("  AND  EXISTS( ");
		selSQL.append("SELECT * FROM `tb_lib_vip_service` t  LEFT JOIN tb_lib_join i ON t.lib_id=i.id WHERE ");
		selSQL.append("  i.id=?   AND t.vip_id=b.vip_id and  t.species='S001' ); ");
		queryParams.add(libId);
		List<Map<String,Object>> ret=dao.findMap(selSQL.toString(),queryParams.toArray());	
		return Integer.parseInt((ret.get(0).get("count").toString()));
	}
	
	@Override
	public Integer signSubscribByMonthCounter(String libId,Date selectDate,Integer type) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT COUNT(DISTINCT(b.vip_id)) as count  from tb_lib_subscribe b  where ");
		if(type==0){//预约   
			selSQL.append("date_format(b.order_date,'%Y-%m')=date_format(?,'%Y-%m')  AND order_time IS NOT null ");
		}else if(type==1){//到馆    
			selSQL.append(" date_format(b.ryke_time,'%Y-%m')=date_format(?,'%Y-%m') ");
		}
		queryParams.add(selectDate);
		selSQL.append("  AND  EXISTS( ");
		selSQL.append("SELECT * FROM `tb_lib_vip_service` t  LEFT JOIN tb_lib_join i ON t.lib_id=i.id WHERE ");
		selSQL.append("  i.id=?  AND t.vip_id=b.vip_id  and t.species='S001'  ); ");
		queryParams.add(libId);
		List<Map<String,Object>> ret=dao.findMap(selSQL.toString(),queryParams.toArray());	
		return Integer.parseInt((ret.get(0).get("count").toString()));
	}
	
	@Override
	public Integer signSubscribByActiveCounter(String libId,Date selectDate) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT COUNT(DISTINCT(vip_id)) as count  from tb_lib_subscribe b  where ");
		selSQL.append(" ((date_format(b.leave_time,'%Y-%m')=date_format(?,'%Y-%m')) OR ");
		queryParams.add(selectDate);
		selSQL.append(" (date_format(b.ryke_time,'%Y-%m')=date_format(?,'%Y-%m'))) ");
		queryParams.add(selectDate);
		selSQL.append("  AND  EXISTS( ");
		selSQL.append("SELECT * FROM `tb_lib_vip_service` t  LEFT JOIN tb_lib_join i ON t.lib_id=i.id WHERE ");
		selSQL.append("  i.id=?  AND t.vip_id=b.vip_id and t.species='S001'  ); ");
		queryParams.add(libId);
		List<Map<String,Object>> ret=dao.findMap(selSQL.toString(),queryParams.toArray());	
		return Integer.parseInt((ret.get(0).get("count").toString()));
	}

	@Override
	public List<Map<String, Object>> countActivityByDayUser(String libId,String startDate, String endDate, String type) {
		List<Map<String,Object>> ret=new ArrayList<Map<String,Object>>();
		return ret;
	}

	@Override
	public List<Map<String, Object>> queryWeekGrOrderDetails(String userId) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT DATE_FORMAT( t.create_time, '%Y-%m-%d' ) as date ,t.title,SUM(i.book_gr) as gr,i.local_image FROM tb_order_details t LEFT JOIN tb_lib_book_detail d on t.book_detail_id=d.id LEFT JOIN tb_lib_book_info i ON d.info_id=i.id where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(t.create_time) AND t.user_id=? GROUP BY DATE_FORMAT( t.create_time, '%Y-%m-%d' ) ORDER BY DATE_FORMAT( t.create_time, '%Y-%m-%d' ) desc  ");
		queryParams.add(userId);
		return dao.findMap(selSQL.toString(),queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> queryOrderDetailsByIsbn(String isbn13) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append("SELECT u.weixin_photo,u.wx_name,u.photo from tb_order_details t LEFT JOIN tb_lib_book_detail d on t.book_detail_id=d.id LEFT JOIN tb_lib_book_info i on d.info_id=i.id LEFT JOIN tb_user u ON u.id=t.user_id LEFT JOIN sys_sort o ON o.`code`=i.book_tag where i.isbn13=? ORDER BY t.create_time desc LIMIT 3 ");
		queryParams.add(isbn13);
		return dao.findMap(selSQL.toString(),queryParams.toArray());
	}

	@Override
	public Integer countOrderDetailsByIsbn(String isbn13) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT COUNT(1) as count from tb_order_details t  LEFT JOIN tb_lib_book_detail d on t.book_detail_id=d.id LEFT JOIN tb_lib_book_info i on d.info_id=i.id where i.isbn13=?  ");
		queryParams.add(isbn13);
		List<Map<String,Object>> ret=dao.findMap(selSQL.toString(),queryParams.toArray());	
		return Integer.parseInt((ret.get(0).get("count").toString()));
	}
	
	
	@Override
	public Page<Map<String, Object>> findHotOrderDetailsPage(Map<String, Object> searchParams, Pageable pageable) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();        
        selSQL.append("  SELECT * from ( ");
        selSQL.append(" SELECT  COUNT(1) as count,i.*  from tb_order_details t ");
        selSQL.append(" LEFT JOIN tb_lib_book_detail d on t.book_detail_id=d.id ");
        selSQL.append(" LEFT JOIN tb_lib_book_info i on d.info_id=i.id  ");
        selSQL.append(" GROUP BY t.book_detail_id ORDER BY count desc ");
        selSQL.append(" ) as tmp where tmp.isbn13 is not NULL  and tmp.isbn13 <> '' AND tmp.summary is not NULL AND tmp.summary <> ''   ");
        if(countOrderDetailsNum(searchParams.get("userId").toString())!=null 
        		&& countOrderDetailsNum(searchParams.get("userId").toString()).size()>0){
	        selSQL.append(" and tmp.book_tag in ( ");
	        selSQL.append(" SELECT DISTINCT(i1.book_tag)  from tb_order_details t1 ");
	        selSQL.append(" LEFT JOIN tb_lib_book_detail d1 on t1.book_detail_id=d1.id ");
	        selSQL.append(" LEFT JOIN tb_lib_book_info i1 on d1.info_id=i1.id ");
	        selSQL.append(" where t1.user_id=? ");
	        selSQL.append(" )");
	        queryParams.add(searchParams.get("userId"));
        }
        selSQL.append(" GROUP BY tmp.isbn13 UNION (SELECT 1 as count,t.* from tb_lib_book_info t WHERE t.isbn13 is not NULL and t.isbn13 <> '' AND t.summary is not NULL AND t.summary <> '' ORDER BY t.create_time desc)");
        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public Page<Map<String, Object>> findNewOrderDetailsPage(
			Map<String, Object> searchParams, Pageable pageable) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT * from ( SELECT * from tb_lib_book_info t where 1=1 ");
        if( countOrderDetailsNum(searchParams.get("userId").toString())!=null 
        		&& countOrderDetailsNum(searchParams.get("userId").toString()).size()>0){
	        selSQL.append(" and t.book_tag in (  SELECT DISTINCT(i1.book_tag)  from tb_order_details t1  ");
	        selSQL.append(" LEFT JOIN tb_lib_book_detail d1 on t1.book_detail_id=d1.id  ");
	        selSQL.append(" LEFT JOIN tb_lib_book_info i1 on d1.info_id=i1.id  ");
	        selSQL.append(" where t1.user_id=? )  ");
	        queryParams.add(searchParams.get("userId"));
        }
        selSQL.append(" and t.isbn13 is not NULL and t.isbn13 <> '' AND t.summary is not NULL AND t.summary <> '' GROUP BY t.isbn13 ORDER BY t.create_time desc ) as tmp  UNION (SELECT t.* from tb_lib_book_info t WHERE t.isbn13 is not NULL and t.isbn13 <> '' AND t.summary is not NULL AND t.summary <> '' ORDER BY t.create_time desc)");
        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}
	
	@Override
	public Page<Map<String, Object>> findSearchBooksPage(Map<String, Object> searchParams, Pageable pageable) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT * from tb_lib_book_info t WHERE 1=1  ");
        if(searchParams.get("libId")!=null ){
	        selSQL.append(" AND t.lib_id=? ");
	        queryParams.add(searchParams.get("libId").toString());
        }
        if(searchParams.get("bookName")!=null){
	        selSQL.append(" AND t.title LIKE ? ");
	        queryParams.add("%"+searchParams.get("bookName").toString()+"%");
        }
        if(searchParams.get("gr").toString()!=null ){
	        selSQL.append(" ORDER BY ABS(?-t.book_gr) ASC ");
	        queryParams.add(searchParams.get("gr").toString());
        }
        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}
	
	
	
	public List<Map<String, Object>> countOrderDetailsNum(String userId){
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT DISTINCT(i1.book_tag)  from tb_order_details t1  ");
        selSQL.append(" LEFT JOIN tb_lib_book_detail d1 on t1.book_detail_id=d1.id  ");
        selSQL.append(" LEFT JOIN tb_lib_book_info i1 on d1.info_id=i1.id  ");
        selSQL.append(" where t1.user_id=?  ");
        queryParams.add(userId);
		return dao.findMap(selSQL.toString(),queryParams.toArray());
	
	}

	@Override
	public List<Map<String, Object>> findLibIdByUserId(String userId) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT t.* from tb_lib_vip_service t   ");
        selSQL.append(" 	LEFT JOIN tb_lib_vip v ON t.vip_id=v.id   ");
        selSQL.append(" WHERE t.stat=1 AND  TO_DAYS(end_time)  >=  TO_DAYS(now())  ");
        selSQL.append(" AND v.user_id=?  ");
        selSQL.append(" ORDER BY t.end_time DESC  LIMIT 1  ");
        queryParams.add(userId);
		return dao.findMap(selSQL.toString(),queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> getOrder(Map<String, Object> searchParams) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT o.*, u.wx_name,DATE_FORMAT(o.create_time,'%Y-%m-%d %H:%i:%s')as create_time2,  ");
        selSQL.append("  DATE_FORMAT(o.pay_time,'%Y-%m-%d %H:%i:%s')as pay_time2, CASE o.order_type  ");
        selSQL.append("  WHEN 4 THEN '会员卡支付酬金' WHEN 7 THEN '图书馆借书首次酬金'WHEN 8 THEN'图书馆借书普通酬金'ELSE'其他'   ");
        selSQL.append("  END  AS order_type2, CASE o.order_status  ");
        selSQL.append("  WHEN 0 THEN'未支付'WHEN 1 THEN'已支付'WHEN 4 THEN'已退款'ELSE'其他'END AS order_status2 ,  ");
        selSQL.append("  DATE_FORMAT(r.create_time,'%Y-%m-%d %H:%i:%s')as refund_time  ");
        selSQL.append("  FROM tb_orders o JOIN tb_user u ON o.user_id = u.id  ");
        selSQL.append("  LEFT JOIN tb_order_refund r ON o.order_no = r.order_no  ");
        if(searchParams!=null && searchParams.size()>0){
        	selSQL.append("  where 1=1 ");
        }
        if (searchParams.get("order_type") != null && !searchParams.get("order_type").equals("")) {
        		selSQL.append(" and o.order_type = ?  ");
        	queryParams.add(searchParams.get("order_type"));
        }
        if (searchParams.get("order_status") != null && !searchParams.get("order_status").equals("")) {
        	selSQL.append(" and o.order_status = ?  ");
        	queryParams.add(searchParams.get("order_status"));
        }
        
        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
        	selSQL.append(" and TO_DAYS(o.create_time) >=TO_DAYS(?) ");
        	queryParams.add(searchParams.get("beginDate"));
        }
        if (searchParams.get("") != null && !searchParams.get("endDate").equals("")) {
        	selSQL.append(" and TO_DAYS(o.create_time) <=TO_DAYS(?) ");
        	queryParams.add(searchParams.get("endDate"));
        }
        if (searchParams.get("order_no") != null && !searchParams.get("order_no").equals("")) {
    		selSQL.append(" and o.order_no = ?  ");
    	    queryParams.add(searchParams.get("order_no"));
        }
        
        selSQL.append(" order by o.create_time  desc  ");
    return dao.findMap(selSQL.toString(), queryParams.toArray());
}

	
	
//	#  以订单为单位统计财务数据 
//	SELECT j.league_name,t.order_no,t.create_time,o.order_status,o.order_money,t.is_listen_test,t.course_count,t.start_time,t.end_time,v.grade,
//	t.course_name,v.parent_name,v.phone,v.child_name,v.sex,v.family,
//	(SELECT m.`name` from tb_lib_manager m where m.type=6 AND m.user_id=t.master_id AND m.lib_id=t.lib_id LIMIT 1) as master_name,
//	(SELECT m.telephone from tb_lib_manager m where m.type=6 AND m.user_id=t.master_id AND m.lib_id=t.lib_id LIMIT 1) as master_telephone
//  FROM `tb_lesson_service` t  
//	LEFT JOIN tb_orders o ON t.order_no=o.order_no
//	LEFT JOIN tb_lib_vip v ON t.vip_id=v.id
//	LEFT JOIN tb_lib_join j ON t.lib_id=j.id
//	where TO_DAYS(t.create_time ) BETWEEN TO_DAYS('2018-06-01') AND TO_DAYS('2018-08-01') 
//	ORDER BY t.lib_id DESC , t.create_time DESC;
	@Override
	public Page<Map<String, Object>> findForPageLessonServiceList(Map<String, Object> searchParams, Pageable pageable) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT j.league_name,t.order_no,o.create_time,o.pay_time,o.order_status,o.order_money,t.is_listen_test,t.course_count,t.start_time,t.end_time,v.grade,  ");
        selSQL.append(" t.course_name,v.parent_name,v.phone,v.child_name,v.sex,v.family, ");
        selSQL.append(" (SELECT m.`name` from tb_lib_manager m where m.type=6 AND m.user_id=t.master_id AND m.lib_id=t.lib_id LIMIT 1) as master_name, ");
        selSQL.append(" (SELECT m.telephone from tb_lib_manager m where m.type=6 AND m.user_id=t.master_id AND m.lib_id=t.lib_id LIMIT 1) as master_telephone ");
        selSQL.append(" FROM `tb_lesson_service` t    ");
        selSQL.append(" LEFT JOIN tb_orders o ON t.order_no=o.order_no ");
        selSQL.append(" LEFT JOIN tb_lib_vip v ON t.vip_id=v.id  ");
        selSQL.append(" LEFT JOIN tb_lib_join j ON t.lib_id=j.id  ");
        selSQL.append(" where 1=1   ");
        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
    		selSQL.append(" and TO_DAYS(t.create_time ) >= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("beginDate"));
        }
        if (searchParams.get("endDate") != null && !searchParams.get("endDate").equals("")) {
    		selSQL.append(" and TO_DAYS(t.create_time ) <= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("endDate"));
        }
        if (searchParams.get("order_no") != null && !searchParams.get("order_no").equals("")) {
    		selSQL.append("  AND t.order_no=?  ");
    	    queryParams.add(searchParams.get("order_no"));
        }
        if (searchParams.get("order_status") != null && !searchParams.get("order_status").equals("")) {
    		selSQL.append("  AND o.order_status=?  ");
    	    queryParams.add(searchParams.get("order_status"));
        }
        selSQL.append(" ORDER BY  ");
        if (searchParams.get("is_exp") != null && !searchParams.get("is_exp").equals("")) {//导出的时候先按lib_id排序
    		selSQL.append("  t.lib_id DESC , ");
        }
        selSQL.append(" t.create_time DESC  ");
        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}
	
	

//	#   课耗明细表
//	SELECT s.order_no,v.parent_name,v.phone,v.child_name,j.league_name,k.course_name,
//	t.teacher_lever,t.teacher_type,t.course_time,t.start_time,t.end_time,s.price,
//	(SELECT m.`name` from tb_lib_manager m where m.type=6 AND m.user_id=s.master_id AND m.lib_id=s.lib_id LIMIT 1) as master_name,
//	(SELECT m.telephone from tb_lib_manager m where m.type=6 AND m.user_id=s.master_id AND m.lib_id=s.lib_id LIMIT 1) as master_telephone,
//  (SELECT m.`name` from tb_lib_manager m where m.type=7 AND m.user_id=t.teacher_id AND m.master_id=s.master_id LIMIT 1) as t_name,
//  (SELECT m.`telephone` from tb_lib_manager m where m.type=7 AND m.user_id=t.teacher_id AND m.master_id=s.master_id LIMIT 1) as t_telephone
//  from kmt_course t 
//	LEFT JOIN tb_lib_vip v ON t.vip_id=v.id
//	LEFT JOIN tb_lesson_service s ON s.id=t.lesson_service_id
//	LEFT JOIN tb_lib_join j ON s.lib_id=j.id
//	LEFT JOIN kmt_course_know k ON t.course_know_id=k.id
//	where s.id is NOT NULL
//	AND TO_DAYS(t.course_time ) BETWEEN TO_DAYS('2018-06-01') AND TO_DAYS('2018-08-01') 
//	ORDER BY  s.create_time DESC
	@Override
	public Page<Map<String, Object>> findForPageLessonServiceByCourseList(Map<String, Object> searchParams, Pageable pageable) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<>();
        selSQL.append(" SELECT s.order_no,v.parent_name,v.phone,v.child_name,j.league_name,k.course_name,t.plan_status,t.is_finish, ");
        selSQL.append(" t.teacher_lever,t.teacher_type,t.course_time,t.start_time,t.end_time,s.price,t11.finish_time,  ");
        selSQL.append(" (SELECT m.`name` from tb_lib_manager m where m.type=6 AND m.user_id=s.master_id AND m.lib_id=s.lib_id LIMIT 1) as master_name,  ");
        selSQL.append(" (SELECT m.telephone from tb_lib_manager m where m.type=6 AND m.user_id=s.master_id AND m.lib_id=s.lib_id LIMIT 1) as master_telephone, ");
        selSQL.append(" (SELECT m.`name` from tb_lib_manager m where m.type=7 AND m.user_id=t.teacher_id LIMIT 1) as t_name,  ");
        selSQL.append(" (SELECT m.`telephone` from tb_lib_manager m where m.type=7 AND m.user_id=t.teacher_id  LIMIT 1) as t_telephone ");
        selSQL.append(" ,t11.teacher_sales as t_price,t11.firm_sales as s_price,t11.lib_sales as l_price,t11.sd_sales as sd_price \n");
        selSQL.append(" from kmt_course t  ");
        selSQL.append(" INNER JOIN tb_lesson_service_sales t11 on t.id = t11.kmt_course_id  \n ");
        selSQL.append(" LEFT JOIN tb_lib_vip v ON t.vip_id=v.id  ");
        selSQL.append(" LEFT JOIN tb_lesson_service s ON s.id=t.lesson_service_id ");
        selSQL.append(" LEFT JOIN tb_lib_join j ON s.lib_id=j.id  ");
        selSQL.append(" LEFT JOIN kmt_course_know k ON t.course_know_id=k.id  ");
        selSQL.append(" where s.id is NOT NULL  ");
        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
    		selSQL.append(" and TO_DAYS(t.course_time ) >= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("beginDate"));
        }
        if (searchParams.get("endDate") != null && !searchParams.get("endDate").equals("")) {
    		selSQL.append(" and TO_DAYS(t.course_time ) <= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("endDate"));
        }
        if (searchParams.get("order_no") != null && !searchParams.get("order_no").equals("")) {
    		selSQL.append(" and s.order_no= ?  ");
    	    queryParams.add(searchParams.get("order_no"));
        }
        if (searchParams.get("libId") != null && !searchParams.get("libId").equals("")) {
    		selSQL.append(" AND s.lib_id=?  ");
    	    queryParams.add(searchParams.get("libId"));
        }
        
        selSQL.append("	ORDER BY  s.create_time DESC   ");
        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	
	
//	#   老师业绩表
	@Override
	public Page<Map<String, Object>> findForPageLessonServiceByTeacherList(Map<String, Object> searchParams, Pageable pageable) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append("	SELECT j.league_name,j.league_city,tmpt.* from (   ");
        selSQL.append("	 SELECT   ");
        selSQL.append("	s.lib_id,   ");
        selSQL.append("	 s.master_id,  ");
        selSQL.append("	 t.teacher_id,  ");
        selSQL.append("	 (  ");
        selSQL.append("		SELECT COUNT(DISTINCT(tmps.vip_id)) from kmt_course tmpt LEFT JOIN tb_lesson_service tmps ON tmpt.lesson_service_id=tmps.id    ");
        selSQL.append("	  	WHERE tmpt.teacher_id=t.teacher_id AND tmps.master_id=s.master_id AND tmps.lib_id=s.lib_id AND tmps.type=1 ");
        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
    		selSQL.append(" and TO_DAYS(tmps.create_time ) >= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("beginDate"));
        }
        if (searchParams.get("endDate") != null && !searchParams.get("endDate").equals("")) {
    		selSQL.append(" and TO_DAYS(tmps.create_time ) <= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("endDate"));
        }
        selSQL.append("	  ) as new_count,   ");
        selSQL.append("	 (  ");
        selSQL.append("	 SELECT COUNT(DISTINCT(tmps.vip_id)) from kmt_course tmpt LEFT JOIN tb_lesson_service tmps ON tmpt.lesson_service_id=tmps.id   ");
        selSQL.append("	 WHERE tmpt.teacher_id=t.teacher_id AND tmps.master_id=s.master_id AND tmps.lib_id=s.lib_id AND tmps.type=2  ");
        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
    		selSQL.append(" and TO_DAYS(tmps.create_time ) >= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("beginDate"));
        }
        if (searchParams.get("endDate") != null && !searchParams.get("endDate").equals("")) {
    		selSQL.append(" and TO_DAYS(tmps.create_time ) <= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("endDate"));
        }
        selSQL.append("	) as to_count,   ");
        selSQL.append("	(  ");
        selSQL.append("	 SELECT COUNT(DISTINCT(tmps.vip_id)) from kmt_course tmpt LEFT JOIN tb_lesson_service tmps ON tmpt.lesson_service_id=tmps.id  ");
        selSQL.append("	 WHERE tmpt.teacher_id=t.teacher_id AND tmps.master_id=s.master_id AND tmps.lib_id=s.lib_id AND tmpt.is_finish=1 AND tmpt.course_type=1 ");
        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
    		selSQL.append(" and TO_DAYS(tmps.create_time ) >= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("beginDate"));
        }
        if (searchParams.get("endDate") != null && !searchParams.get("endDate").equals("")) {
    		selSQL.append(" and TO_DAYS(tmps.create_time ) <= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("endDate"));
        }
        selSQL.append("	) as r_count,  ");
        selSQL.append("	(  ");
        selSQL.append("	SELECT COUNT(DISTINCT(tmps.vip_id)) from kmt_course tmpt LEFT JOIN tb_lesson_service tmps ON tmpt.lesson_service_id=tmps.id   ");
        selSQL.append("	WHERE tmpt.teacher_id=t.teacher_id AND tmps.master_id=s.master_id  AND tmps.lib_id=s.lib_id AND tmps.`status`=2  ");
        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
    		selSQL.append(" and TO_DAYS(tmps.create_time ) >= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("beginDate"));
        }
        if (searchParams.get("endDate") != null && !searchParams.get("endDate").equals("")) {
    		selSQL.append(" and TO_DAYS(tmps.create_time ) <= TO_DAYS(?)  ");
    	    queryParams.add(searchParams.get("endDate"));
        }
        selSQL.append("	 ) as tr_count, ");
        selSQL.append("	(  ");
        selSQL.append("	 SELECT COUNT(1) from kmt_course tmpt LEFT JOIN tb_lesson_service tmps ON tmpt.lesson_service_id=tmps.id  ");
        selSQL.append("	 WHERE tmpt.teacher_id=t.teacher_id AND tmps.master_id=s.master_id AND tmps.lib_id=s.lib_id AND tmpt.is_finish=1 AND tmpt.course_type=1  ");
        selSQL.append("	) as c_count,  ");
        selSQL.append("	(  ");
        selSQL.append("	SELECT SUM(tmps.price) from kmt_course tmpt LEFT JOIN tb_lesson_service tmps ON tmpt.lesson_service_id=tmps.id   ");
        selSQL.append("	WHERE tmpt.teacher_id=t.teacher_id AND tmps.master_id=s.master_id AND tmps.lib_id=s.lib_id AND tmpt.is_finish=1 AND tmpt.course_type=1  ");
        selSQL.append("	) as p_count,  ");
        selSQL.append("	 ( ");
        selSQL.append("	SELECT COUNT(1) from kmt_course tmpt LEFT JOIN tb_lesson_service tmps ON tmpt.lesson_service_id=tmps.id   ");
        selSQL.append("	  WHERE tmpt.teacher_id=t.teacher_id AND tmps.master_id=s.master_id AND tmps.lib_id=s.lib_id AND tmpt.is_finish!=1 AND tmpt.plan_status>=4  AND tmpt.course_type=1 ");
        selSQL.append("	) as nc_count,  ");
        selSQL.append("	 ( ");
        selSQL.append("	 SELECT COUNT(1) from kmt_course tmpt LEFT JOIN tb_lesson_service tmps ON tmpt.lesson_service_id=tmps.id  ");
        selSQL.append("	 WHERE tmpt.teacher_id=t.teacher_id AND tmps.master_id=s.master_id AND tmps.lib_id=s.lib_id AND  tmpt.plan_status<4  AND tmpt.course_type=1  ");
        selSQL.append("	) as noc_count  ");
        selSQL.append("	 from kmt_course t  ");
        selSQL.append("	 LEFT JOIN tb_lesson_service s ON t.lesson_service_id=s.id ");
        selSQL.append("	where t.teacher_id !='' AND t.teacher_id is not NULL  ");
        selSQL.append("	GROUP BY s.lib_id,s.master_id,t.teacher_id  ");
        selSQL.append("	) as tmpt LEFT JOIN tb_lib_join j ON tmpt.lib_id=j.id  ");
        if (searchParams.get("libId") != null && !searchParams.get("libId").equals("")) {
    		selSQL.append(" where j.id=?  ");
    	    queryParams.add(searchParams.get("libId"));
        }
        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public List<Map<String, Object>> countLessonServiceSalesByGroup(Date startDate, Date endDate) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT t.lib_id as joinid,GROUP_CONCAT(t.id) as ids,SUM(t.lib_sales) as countsales,GROUP_CONCAT(DISTINCT(t.teacher_lever)) as teacher_lever, 1 as type   FROM `tb_lesson_service_sales` t    ");
        selSQL.append(" where t.state=1 AND t.lib_pay_business_id is NULL  AND TO_DAYS(t.finish_time) BETWEEN TO_DAYS(?) AND TO_DAYS(?) ");
        selSQL.append(" GROUP BY t.lib_id  ");
        queryParams.add(startDate);
        queryParams.add(endDate);
        selSQL.append(" UNION  ");
        selSQL.append(" SELECT t.teacher_id as joinid,GROUP_CONCAT(t.id) as ids,SUM(t.teacher_sales) as countsales,GROUP_CONCAT(DISTINCT(t.teacher_lever)) as teacher_lever, 2 as type  FROM `tb_lesson_service_sales` t     ");
        selSQL.append(" where t.state=1 AND t.teacher_pay_business_id is NULL  AND TO_DAYS(t.finish_time) BETWEEN TO_DAYS(?) AND TO_DAYS(?) ");
        selSQL.append(" GROUP BY t.teacher_id  ");
        queryParams.add(startDate);
        queryParams.add(endDate);
        selSQL.append(" UNION  ");
        selSQL.append(" SELECT t.master_id as joinid,GROUP_CONCAT(t.id) as ids,SUM(t.sd_sales) as countsales,GROUP_CONCAT(DISTINCT(t.teacher_lever)) as teacher_lever, 3 as type  FROM `tb_lesson_service_sales` t    ");
        selSQL.append(" where t.state=1 AND t.sd_pay_business_id is NULL  AND TO_DAYS(t.finish_time) BETWEEN TO_DAYS(?) AND TO_DAYS(?)  ");
        selSQL.append(" GROUP BY t.master_id  ");
        queryParams.add(startDate);
        queryParams.add(endDate);
      
		return dao.findMap(selSQL.toString(),queryParams.toArray());
	}

    @Override
    public List<Map<String, Object>> countStudentSumStudyingInSharedLib(String startTime, String endTime) {
		List<Object> queryParams = new ArrayList<>();
		queryParams.add(startTime);
		queryParams.add(endTime);

		String selSQL = "select count(distinct kmt_course.vip_id) student_sum, tb_lib_join.id lib_id " +
				"from kmt_course, tb_lesson_service, tb_lib_join " +
				"where kmt_course.lesson_service_id = tb_lesson_service.id " +
				"and tb_lesson_service.lib_id = tb_lib_join.id " +
				"and date(kmt_course.course_time) between ? and ? " +
				"and kmt_course.plan_status = 5 " +
				"and tb_lib_join.libtype in (2, 3) " +
				"group by tb_lib_join.id ";
		return dao.findMap(selSQL,queryParams.toArray());
    }


}
