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


import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.libmy.domain.TbLibSubscribe;
import com.ssj.dao.weixin.library.dao.ILibJoinQueryDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;
import com.ssj.framework.core.util.StringUtil;
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.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class LibJoinQueryDaoImpl implements ILibJoinQueryDao{

	@Autowired
	private PagingHibernateJdbcDao dao;
	
	@Override
	public Page<Map<String, Object>> findForPage(
			Map<String, Object> searchParams, Pageable pageable) {
		 StringBuilder selSQL = new StringBuilder();
	        List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT  t.* ,ifnull(t.name,u.wx_name) as wx_name,ifnull(t_photo,u.photo) as photo  from   tb_lib_manager   t LEFT JOIN  tb_user  u ");
	        selSQL.append("  on t.user_id  = u.id  ");
	        selSQL.append(" where  t.lib_id = ? and t.state = 1 ");

	        if (searchParams.get("wx_name") != null && !searchParams.get("wx_name").equals("")) {
	            selSQL.append(" and  u.wx_name LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("wx_name"));
	        }
	        queryParams.add(searchParams.get("libId"));
			selSQL.append(" order by t.create_time desc ");
	        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public void insertTbLibManager(List<TbLibManager> list) {
		dao.batchInsert(list);
		
	}

	@Override
	public Page<Map<String, Object>> findBookDetailForPage(
			Map<String, Object> searchParams, Pageable pageable) {
		 StringBuilder selSQL = new StringBuilder();
	        List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT  t.* ,u.wx_name,u.photo  from   tb_lib_book_detail   t LEFT JOIN  tb_user  u ");
	        selSQL.append("  on t.user_id  = u.id  ");
	        selSQL.append(" where  t.info_id = ?");
	        queryParams.add(searchParams.get("libId"));
	        if (searchParams.get("wx_name") != null && !searchParams.get("wx_name").equals("")) {
	            selSQL.append(" and  u.wx_name LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("wx_name"));
	        }
	        selSQL.append(" order by  t.create_time desc ");
	        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public Page<Map<String, Object>> findForVIPPage(
			Map<String, Object> searchParams, Pageable pageable) {
		 StringBuilder selSQL = new StringBuilder();
	        List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT  t.*   from   tb_lib_read_vip  t  ");
	        selSQL.append(" where 1=1 ");
	        if (searchParams.get("name") != null && !searchParams.get("name").equals("")) {
	            selSQL.append(" and  t.child_name LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("name"));
	        }
	        if (searchParams.get("stat") != null && !searchParams.get("stat").equals("")) {
	            selSQL.append(" and t.stat = ?");
	            queryParams.add(searchParams.get("stat"));
	        }
	        if (searchParams.get("flow_id") != null && !searchParams.get("flow_id").equals("")) {
	            selSQL.append(" and t.flow_id = ?");
	            queryParams.add(searchParams.get("flow_id"));
	        }
	        if (searchParams.get("level") != null && !searchParams.get("level").equals("")) {
	            selSQL.append(" and t.level = ?");
	            queryParams.add(searchParams.get("level"));
	        }
			if (searchParams.get("activeTime") != null && !searchParams.get("activeTime").equals("")) {
				selSQL.append(" and to_days(t.active_time)=to_days(?) ");
				queryParams.add(searchParams.get("activeTime"));
			}

	        selSQL.append("   ORDER BY t.create_time desc ,t.flow_id desc   ");
	        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public List<Map<String, Object>> getAllSchoolMap(Map<String, Object> searchParams) {
		StringBuilder selSQL = new StringBuilder();
		 List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT  id,league_name,league_code,league_lat,league_lng,league_address,leadue_phone,create_time from tb_lib_join ");
	        selSQL.append("  where  1=1  ");
	        
	        if (searchParams.get("searchValue") != null && !searchParams.get("searchValue").equals("")) {
	            selSQL.append(" and  ( league_name like '%").append(searchParams.get("searchValue")).append("%'  ");
	            selSQL.append(" or   lower(league_code)  like '%").append(searchParams.get("searchValue").toString().toLowerCase()).append("%'  )");
	            //queryParams.add(searchParams.get("searchValue"));
	        }
	        if (searchParams.get("city") != null && !searchParams.get("city").equals("")) {
	            selSQL.append(" and   league_city  = ?");
	            queryParams.add(searchParams.get("city"));
	        }
	        selSQL.append("  ORDER BY  create_time desc    ");
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@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 t.id,t.title,t.keyword,t.start_age,t.end_age,t.price,t.local_image ,u.league_name  ,s.`name` as bq ,a.`name`as sj,ps.name as pname,cs.name as cname from   tb_lib_book_info  t LEFT JOIN  tb_lib_join  u ");
	        selSQL.append("  on t.lib_id  = u.id  ");
	        selSQL.append("  LEFT JOIN sys_sort s  on t.book_tag = s.`code` and s.pid='d1ec09d3-f924-40be-9e23-daa372d983da'  ");
	        selSQL.append("  LEFT JOIN sys_sort  a on  t.bookcase = a.`code`  AND a.pid='d1ec09d3-f924-40be-7e23-daa372d983da'  ");
	        selSQL.append("  LEFT JOIN sys_sort ps  on t.parent_theme = ps.`code` and ps.pid='44903f84-a4d8-47e7-ab82-11ffd8a3425f'  ");
	        selSQL.append("  LEFT JOIN sys_sort cs on  t.child_theme = cs.`code`  AND cs.pid='a316f70c-1184-44b9-a636-dbe10262f176'  ");
	        selSQL.append(" where   1=1 ");
	        
	        if (searchParams.get("orgCode") != null && !searchParams.get("orgCode").equals("")) {
	        	selSQL.append(" and  t.org_code in ( ");
	        	selSQL.append(searchParams.get("orgCode"));
	        	selSQL.append(" ) ");
	        }
	        
	        if (searchParams.get("title") != null && !searchParams.get("title").equals("")) {
	            selSQL.append(" and  t.title LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("title"));
	        }
	        if (searchParams.get("libId") != null && !searchParams.get("libId").equals("")) {
	        	selSQL.append(" and  u.id = ?  ");
	        	queryParams.add(searchParams.get("libId"));
	        }
	        if (searchParams.get("bookTae") != null && !searchParams.get("bookTae").equals("")) {
	        	selSQL.append(" and  t.book_tag = ?  ");
	        	queryParams.add(searchParams.get("bookTae"));
	        }
	        if (searchParams.get("bookCase") != null && !searchParams.get("bookCase").equals("")) {
	        	selSQL.append(" and  t.bookcase = ?  ");
	        	queryParams.add(searchParams.get("bookCase"));
	        }
	        if (searchParams.get("startAge") != null && !searchParams.get("startAge").equals("")) {
	        	selSQL.append(" and  t.start_age >=CAST(? AS SIGNED) ");
	        	queryParams.add(searchParams.get("startAge"));
	        }
	        if (searchParams.get("endAge") != null && !searchParams.get("endAge").equals("")) {
	        	selSQL.append(" and  t.end_age <=CAST(? AS SIGNED) ");
	        	queryParams.add(searchParams.get("endAge"));
	        }
	        if (searchParams.get("parentTheme") != null && !searchParams.get("parentTheme").equals("")) {
	            selSQL.append(" and  ps.name LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("parentTheme"));
	        }
	        if (searchParams.get("childTheme") != null && !searchParams.get("childTheme").equals("")) {
	            selSQL.append(" and  cs.name LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("childTheme"));
	        }
	        selSQL.append("   ORDER BY t.create_time desc  ");
	        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public List<Map<String, Object>> getLibVipList(
			Map<String, Object> searchParams) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT  CASE s.type  WHEN 'C001' THEN 	'年卡' WHEN 'C002' THEN	'半年卡'    ");
			 selSQL.append("   WHEN 'C003' THEN 	'月卡' WHEN 'C004' THEN	'单次卡（100元/2小时）' WHEN 'C005' THEN	'学霸卡40小时（1500元）' ELSE '学霸卡120小时（3600元）' END  as type     ,  ");
			 selSQL.append(" CASE v.`level` WHEN 1 THEN 	'普通卡' WHEN 5 THEN	'尊享卡'    ");
			 selSQL.append("   ELSE ' ' END  as `level`     ,  ");
	        selSQL.append(" s.id , date_format(s.start_time,'%Y-%m-%d %H:%i:%s') as start_time ,v.child_name,v.flow_id  , j.league_name ");
	        selSQL.append(" from  tb_lib_vip_service s LEFT JOIN  tb_lib_join  j ");
	        selSQL.append(" on s.lib_id =j.id  ");
	        selSQL.append(" LEFT JOIN  tb_lib_vip  v  on  s.vip_id  = v.id  ");
	        selSQL.append(" where   s.stat=1  ");
	        
	        if (searchParams.get("child_name") != null && !searchParams.get("child_name").equals("")) {
	        	selSQL.append(" and  v.child_name LIKE  CONCAT(CONCAT('%',?,'%')) ");
	        	queryParams.add(searchParams.get("child_name"));
	        }
	        if (searchParams.get("orgCode") != null && !searchParams.get("orgCode").equals("")) {
	        	selSQL.append(" and  j.org_code LIKE  CONCAT(CONCAT('%',?,'%')) ");
	        	queryParams.add(searchParams.get("orgCode"));
	        }
	        if (searchParams.get("level") != null && !searchParams.get("level").equals("")) {
	            selSQL.append(" and v.level = ?");
	            queryParams.add(searchParams.get("level"));
	        }
	        
	        if (searchParams.get("beginDate") != null && !searchParams.get("beginDate").equals("")) {
	        	selSQL.append(" and TO_DAYS(s.start_time) >=TO_DAYS(?) ");
	        	queryParams.add(searchParams.get("beginDate"));
	        }
	        if (searchParams.get("endDate") != null && !searchParams.get("endDate").equals("")) {
	        	selSQL.append(" and TO_DAYS(s.start_time) <=TO_DAYS(?) ");
	        	queryParams.add(searchParams.get("endDate"));
	        }
	        
	        if (searchParams.get("libId") != null && !searchParams.get("libId").equals("")) {
	        	selSQL.append(" and j.id = ? ");
	        	queryParams.add(searchParams.get("libId"));
	        }
	      selSQL.append(" ORDER BY  s.start_time desc  ");
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public Page<Map<String, Object>> findForBasePageList(Map<String, Object> searchParams, Pageable pageable) {
		 StringBuilder selSQL = new StringBuilder();
	        List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT  t.*  ,s.`name` as bq ,a.`name`as sj,ps.name as pname,cs.name as cname from   tb_lib_book_base  t ");
	        selSQL.append("  LEFT JOIN sys_sort s  on t.book_tag = s.`code` and s.pid='d1ec09d3-f924-40be-9e23-daa372d983da'  ");
	        selSQL.append("  LEFT JOIN sys_sort  a on  t.bookcase = a.`code`  AND a.pid='d1ec09d3-f924-40be-7e23-daa372d983da'  ");
	        selSQL.append("  LEFT JOIN sys_sort ps  on t.parent_theme = ps.`code` and ps.pid='44903f84-a4d8-47e7-ab82-11ffd8a3425f'  ");
	        selSQL.append("  LEFT JOIN sys_sort cs on  t.child_theme = cs.`code`  AND cs.pid='a316f70c-1184-44b9-a636-dbe10262f176'  ");
	        selSQL.append(" where 1=1 ");
	        if (searchParams.get("title") != null && !searchParams.get("title").equals("")) {
	            selSQL.append(" and  t.title LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("title"));
	        }
	        if (searchParams.get("isbn13") != null && !searchParams.get("isbn13").equals("")) {
	            selSQL.append(" and  t.isbn13 LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("isbn13"));
	        }
	        if (searchParams.get("parentTheme") != null && !searchParams.get("parentTheme").equals("")) {
	            selSQL.append(" and  ps.name LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("parentTheme"));
	        }
	        if (searchParams.get("childTheme") != null && !searchParams.get("childTheme").equals("")) {
	            selSQL.append(" and  cs.name LIKE  CONCAT(CONCAT('%',?,'%')) ");
	            queryParams.add(searchParams.get("childTheme"));
	        }
	        selSQL.append("   ORDER BY t.update_time desc  ");
	        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public List<Map<String, Object>> getLocationJoin(String league_lat, String league_lng,Integer type) {
		String sql ="SELECT\n" +
				 "	* , ROUND(\n" +
				 "		6378.138 * 2 * ASIN(\n" +
				 "			SQRT(\n" +
				 "				POW(\n" +
				 "					SIN(\n" +
				 "						(\n" +
				 "							? * PI() / 180 - league_lat * PI() / 180\n" +
				 "						) / 2\n" +
				 "					),\n" +
				 "					2\n" +
				 "				) + COS(? * PI() / 180) * COS(league_lat * PI() / 180) * POW(\n" +
				 "					SIN(\n" +
				 "						(\n" +
				 "							? * PI() / 180 - league_lng * PI() / 180\n" +
				 "						) / 2\n" +
				 "					),\n" +
				 "					2\n" +
				 "				)\n" +
				 "			)\n" +
				 "		)\n" +
				 "	,2) AS juli\n" +
				 "FROM\n" +
				 "	tb_lib_join  where  type >=? \n" +
				 "ORDER BY\n" +
				 "	juli ASC";
		List<Object> queryParams = new ArrayList<Object>();
		queryParams.add(league_lat);
		queryParams.add(league_lat);
		queryParams.add(league_lng);
		queryParams.add(type);
		return dao.findMap(sql, queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> getNoLocationJoin(Integer type) {
		String sql ="SELECT * from  tb_lib_join  where type >=? ";
		List<Object> queryParams = new ArrayList<Object>();
		queryParams.add(type);
		return dao.findMap(sql, queryParams.toArray());
	}

	@Override
	public	List<Map<String, Object>> countLibVipNum(){
		 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 t.lib_id,count(1) as num FROM `tb_lib_vip_service` t "+
			"where TO_DAYS(t.start_time)=TO_DAYS(date_add(NOW(), interval -1 day)) AND t.stat=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>> countLibSubscribeNum(){
		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 t.lib_id,count(DISTINCT(t.user_id)) as num  from tb_lib_subscribe t WHERE flow_stat>=3 "+
			"and TO_DAYS(t.ryke_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());
	}

	@Override
	public Map<String, Object> findSubCount(String libId, TbLibSubscribe subsccribe) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        selSQL.append("SELECT (IFNULL(a.ordercount,0)+IFNULL(b.dgcount,0)) as totalcount  from (\n" +
        		"SELECT count(1) as ordercount,t.lib_id from tb_lib_subscribe t \n" +
        		"where  t.ryke_time is null and t.lib_id= ?\n" +
        		" and t.order_date =? and t.order_time <= date_add(?, interval 2 hour) \n" +
        		") a left join (\n" +
        		"	SELECT count(1) as dgcount,t11.lib_id from tb_lib_subscribe t11\n" +
        		"where  t11.ryke_time is not null and t11.leave_time is null and t11.lib_id=?\n" +
        		"  and t11.order_date=? \n" +
        		")b on a.lib_id = b.lib_id ");
        queryParams.add(libId);
        queryParams.add(subsccribe.getOrderDate());
        queryParams.add(subsccribe.getOrderTime());
        queryParams.add(libId);
        queryParams.add(subsccribe.getOrderDate());
        List<Map<String, Object>> mapList= dao.findMap(selSQL.toString(), queryParams.toArray());
        if(mapList != null && mapList.size()>0){
        	map = mapList.get(0);
        }
        return map;
	}

	@Override
	public Map<String, Object> findInAndBorrow(String vipId) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        selSQL.append("SELECT IFNULL(a.jycount,0) as jycount,IFNULL(b.yycount,0) as yycount from (\n" +
        		"SELECT count(1) as jycount,t.vip_id from tb_lib_user_history t\n" +
        		"left join tb_order_details t11 on t.vip_id = t11.vip_id and t.detail_id= t11.id\n" +
        		"where t11.is_close='1' and t.order_type=1 and t.vip_id=?\n" +
        		") a left JOIN(\n" +
        		"	SELECT count(1) as yycount,t.vip_id from tb_lib_subscribe t \n" +
        		"	where t.ryke_time is not null and t.vip_id=?\n" +
        		")b on a.vip_id = b.vip_id");
        queryParams.add(vipId);
        queryParams.add(vipId);
        List<Map<String, Object>> mapList= dao.findMap(selSQL.toString(), queryParams.toArray());
        if(mapList != null && mapList.size()>0){
        	map = mapList.get(0);
        }
        return map;
	}

	@Override
	public Map<String, Object> findOneManager(String libId) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        selSQL.append("select ifnull(t.name,t11.wx_name) as wx_name,t11.photo,t12.league_name,t.telephone from tb_lib_manager t \n" +
        		"left join tb_lib_join t12 on t.lib_id = t12.id\n" +
        		"left join tb_user t11 on t.user_id = t11.id\n" +
        		"where t.lib_id=? and t.state = 1 ");
        queryParams.add(libId);
        List<Map<String, Object>> mapList= dao.findMap(selSQL.toString(), queryParams.toArray());
        if(mapList != null && mapList.size()>0){
        	map = mapList.get(0);
        }
        return map;
	}
	
	
	public List<Map<String, Object>> countCurOpenCard(boolean iscount){
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append("SELECT t.lib_id,COUNT(DISTINCT(t.vip_id)) as count,j.league_name ");
        selSQL.append("from tb_lib_vip_service t LEFT JOIN tb_lib_join j ON j.id=t.lib_id WHERE ");
        if(!iscount){
        	selSQL.append(" MONTH(t.start_time)=MONTH(NOW()) AND ");
        }
        selSQL.append(" t.stat=1 GROUP BY t.lib_id ORDER BY count DESC LIMIT 0,10");
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public Map<String, Object> getUserCountByLib(String libId) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        selSQL.append("SELECT a.vipcount,b.todaycount from ( \n");
        selSQL.append("SELECT count(1) as vipcount from tb_lib_vip t \n");
        selSQL.append("left join tb_lib_vip_service t11 on t.id = t11.vip_id\n");
        selSQL.append("where t11.stat =1 and t11.lib_id = ? and t.user_id is not null and t11.end_time > NOW() \n");
        selSQL.append(") a\n");
        selSQL.append("left join (\n");
        selSQL.append("SELECT count(1) as todaycount from tb_lib_vip t \n");
        selSQL.append("left join tb_lib_vip_service t11 on t.id = t11.vip_id\n");
        selSQL.append("where t11.stat =1 and t.user_id is not null and DATE_FORMAT(t.activate_time,'%Y-%m-%d')=CURDATE() and t11.lib_id = ?\n");
        selSQL.append(") b on 1=1\n");
        queryParams.add(libId);
        queryParams.add(libId);
        List<Map<String, Object>> mapList= dao.findMap(selSQL.toString(), queryParams.toArray());
        if(mapList != null && mapList.size()>0){
        	map = mapList.get(0);
        }
        return map;
	}

	@Override
	public List<Map<String, Object>> get2LibUser(String libId, String type) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append("SELECT t.child_name,t.id,t11.start_time,t11.end_time, t11.type,t.img_url,c.total from tb_lib_vip t  \n");
        selSQL.append("left JOIN tb_lib_vip_service t11 on t.id = t11.vip_id \n");
        selSQL.append("	left join ( \n");
        selSQL.append("	SELECT count(DISTINCT b.user_id) as total from tb_lib_vip_service a \n");
        selSQL.append("	INNER JOIN tb_lib_vip b on a.vip_id = b.id \n");
        selSQL.append("	where a.stat=1 and a.end_time > NOW() and a.lib_id = ? and a.species = ? \n");
        selSQL.append("	) c on 1 = 1 \n");
        selSQL.append("where   t11.stat=1 and t11.end_time > NOW() and t11.lib_id = ? and t11.species=?  limit 2\n");
        queryParams.add(libId);
        queryParams.add(type);
        queryParams.add(libId);
        queryParams.add(type);
        return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> findManageList(String libId) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append("SELECT t.id,t.user_id,t11.photo,IFNULL(t.`name`,t11.wx_name) as name,t.telephone,t.type from tb_lib_manager t   \n");
        selSQL.append("left join tb_user t11 on t.user_id = t11.id \n");
        selSQL.append("where t.lib_id = ? and t.state = 1 \n");
        queryParams.add(libId);
        return dao.findMap(selSQL.toString(), queryParams.toArray());
	}
	@Override
	public List<Map<String, Object>> findManageUserList(String userId){
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT t.id,t.user_id,t11.league_name,t.lib_id ,t.state,t.type ,t11.libtype from tb_lib_manager t     \n");
		selSQL.append(" join tb_lib_join t11 on t.lib_id = t11.id  \n");
		selSQL.append("where t.user_id = ? and t.state = 1 \n");
		queryParams.add(userId);
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> findSaleList(String libId) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append("SELECT t.id,t.user_id,t11.photo,IFNULL(c.salesCount,0) as salesCount,IFNULL(t.`name`,t11.wx_name) as name,t.telephone,t.type from tb_lib_staffing t   \n");
        selSQL.append("left join tb_user t11 on t.user_id = t11.id \n");
        selSQL.append("left join (\n");
        selSQL.append("	SELECT t.sales_user_id,count(1) as salesCount from tb_lib_order_details  t  \n");
        selSQL.append("where t.lib_id = ? \n");
        selSQL.append("group by sales_user_id \n");
        selSQL.append(") c on t.user_id = c.sales_user_id \n");
        selSQL.append("where t.lib_id = ? and t.stat = 1 \n");
        queryParams.add(libId);
        queryParams.add(libId);
        return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public Map<String, Object> getLibUserInfo(String userId,String libId) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        selSQL.append("SELECT t.id,t12.wx_name,t12.photo,t.`name`,ifnull(t.sex,t12.sex) as sex,t.type,t.type as managertype,t.lib_id,t.user_id,t.telephone from tb_lib_manager t \n");
        selSQL.append("left join tb_lib_staffing t11 on t.user_id = t11.user_id\n");
        selSQL.append("left join tb_user t12 on t.user_id = t12.id \n");
        selSQL.append("where t.lib_id = ? and t.user_id = ? and t.state=1 \n");
        queryParams.add(libId);
        queryParams.add(userId);
        List<Map<String, Object>> mapList= dao.findMap(selSQL.toString(), queryParams.toArray());
        if(mapList != null && mapList.size()>0){
        	map = mapList.get(0);
        }
        return map;
	}

	@Override
	public Page<Map<String, Object>> vipUserList(Map<String, Object> params, Pageable pageable) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT t.id,t.child_name,t11.start_time,t11.end_time,t11.type from tb_lib_vip t ");
        selSQL.append(" left join tb_lib_vip_service t11 on t.id = t11.vip_id ");
        String userType = params.get("userType").toString();
        String type = params.get("type").toString();
        if("1".equals(type)){   //阅读
        	 selSQL.append("   where t11.species= 'S001' and t11.stat =1  and t11.end_time > NOW()  ");
        	 if("1".equals(userType)){  //月卡
        		 selSQL.append("   and t11.type='C003'");
        	 }else if("2".equals(userType)){ //半年卡
        		 selSQL.append("   and t11.type='C002'");
        	 }else{  //年卡
        		 selSQL.append("   and t11.type='C001'");
        	 }
        }else{ //作业
        	selSQL.append("   where t11.species= 'S003' and t11.stat =1  and t11.end_time > NOW()  ");
        	if("1".equals(userType)){  //月卡
       		 selSQL.append("   and t11.type='C004'");
	       	 }else if("2".equals(userType)){ //半年卡
	       		 selSQL.append("   and t11.type='C005'");
	       	 }else{  //年卡
	       		 selSQL.append("   and t11.type='C006'");
	       	 }
        }
        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public Map<String, Object> getSaleUserInfo(String userId,String libId) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        
        selSQL.append("SELECT t.id,t12.wx_name,t12.photo,t.`name`,ifnull(t.sex,t12.sex) as sex,t.type,t11.type as managertype,t.lib_id,t.user_id,t.telephone from tb_lib_staffing t \n");
        selSQL.append("left join tb_lib_manager t11 on t.user_id = t11.user_id\n");
        selSQL.append("left join tb_user t12 on t.user_id = t12.id \n");
        selSQL.append("where t.lib_id = ? and t.user_id = ? and t11.state = 1\n");
        queryParams.add(libId);
        queryParams.add(userId);
        List<Map<String, Object>> mapList= dao.findMap(selSQL.toString(), queryParams.toArray());
        if(mapList != null && mapList.size()>0){
        	map = mapList.get(0);
        }
        return map;
	}

	@Override
	public Page<Map<String, Object>> vipList(Map<String, Object> searchParams, Pageable pageable) {
		 StringBuilder selSQL = new StringBuilder();
	        List<Object> queryParams = new ArrayList<Object>();
	       selSQL.append("SELECT t.id,t.img_url,DATE_FORMAT(t11.start_time,'%Y-%m-%d') as starttime ,DATE_FORMAT(t11.end_time,'%Y-%m-%d') as endtime,t.child_name  from tb_lib_vip t  \n");
	       selSQL.append("left join tb_lib_vip_service t11 on t.id = t11.vip_id  \n");
	       selSQL.append("where  t11.lib_id =? \n");
	       String libId = searchParams.get("libId").toString();
	       queryParams.add(libId);
	       String type = searchParams.get("type").toString();
	       String vipType = searchParams.get("vipType").toString();
	       
	       if("1".equals(type)){ //图书馆
	    	   selSQL.append(" and t11.species = 'S001' ");
	    	   if("1".equals(vipType)){ //月卡
	    		   selSQL.append(" and t11.type = 'C003'  ");
	    	   }else if ("2".equals(vipType)){ //半年卡
	    		   selSQL.append(" and t11.type = 'C002'  ");
	    	   }else{ //年卡
	    		   selSQL.append(" and t11.type = 'C001'  ");
	    	   }
	       }else{   //作业吧
	    	   selSQL.append(" and t11.species = 'S003' ");
	    	   if("1".equals(vipType)){ //月卡
	    		   selSQL.append(" and t11.type = 'C004'  ");
	    	   }else if ("2".equals(vipType)){ //半年卡
	    		   selSQL.append(" and t11.type = 'C005'  ");
	    	   }else{ //年卡
	    		   selSQL.append(" and t11.type = 'C006'  ");
	    	   }
	       }
	       selSQL.append(" and t11.stat=1 and t11.end_time > NOW() ");
	       return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public List<Map<String, Object>> findLibUserList(Map<String, Object> params) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        String libId = params.get("libId").toString();
        String searchName = params.get("searchName").toString();
        selSQL.append("SELECT t.id,t.user_id,t11.photo,IFNULL(c.salesCount,0) as salesCount,IFNULL(t.`name`,t11.wx_name) as name,t.telephone,t.type,'1' as usertype from tb_lib_staffing t   \n");
        selSQL.append("left join tb_user t11 on t.user_id = t11.id \n");
        selSQL.append("left join (\n");
        selSQL.append("	SELECT t.sales_user_id,count(1) as salesCount from tb_lib_order_details  t  \n");
        selSQL.append("where t.lib_id = ? \n");
        selSQL.append("group by sales_user_id \n");
        selSQL.append(") c on t.user_id = c.sales_user_id \n");
        selSQL.append("where t.lib_id = ?  and t.name like  concat('%',?,'%')\n");
        selSQL.append("union all \n");
        selSQL.append("select t.id,t.user_id,t11.photo,0 as  salesCount,IFNULL(t.`name`,t11.wx_name) as name,t.telephone,t.type,'2' as usertype from tb_lib_manager t \n ");
        selSQL.append("left join tb_user t11 on t.user_id = t11.id \n ");
        selSQL.append(" where t.lib_id = ? and t.name like  concat('%',?,'%') and t.state = 1 \n ");
        queryParams.add(libId);
        queryParams.add(libId);
        queryParams.add(searchName);
        queryParams.add(libId);
        queryParams.add(searchName);
        return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> findVipUserList(Map<String, Object> params) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        String libId = params.get("libId").toString();
        String searchName = params.get("searchName").toString();
        selSQL.append("select t.id,t.child_name,t.img_url,t.child_name as  name,t11.start_time,t11.end_time,t11.type from tb_lib_vip t \n ");
        selSQL.append("left join tb_lib_vip_service t11 on t.id = t11.vip_id \n ");
        selSQL.append(" where t11.lib_id = ? and t.child_name like  concat('%',?,'%') \n ");
        selSQL.append("  and t11.stat=1 and t11.end_time > NOW()  \n ");
        queryParams.add(libId);
        queryParams.add(searchName);
        return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> searchAddUser(Map<String, Object> params) {
		String addType = params.get("addType").toString();
		String libId = params.get("libId").toString();
		String searchContent = params.get("searchContent").toString();
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        //1-CD、2-CC、3-CDA、4-总部SD、5-图书馆管理员、6-作业吧管理员、7-学霸老师
		if("1".equals(addType) || "2".equals(addType) || "3".equals(addType)){ //
			selSQL.append("SELECT u.id,u.wx_name ,u.photo   \n");
			selSQL.append("    from tb_user  u  \n");
			selSQL.append("    where not exists (\n");
			selSQL.append("            select * from tb_lib_staffing t \n");
			selSQL.append("            where t.user_id = u.id  and t.stat =1  \n");
			selSQL.append("        )    ");
			selSQL.append("     and u.wx_name like concat('%',?,'%')");
			queryParams.add(searchContent);
		}else if ("4".equals(addType)){
			selSQL.append(" SELECT u.id,u.wx_name ,u.photo    \n");
			selSQL.append(" from tb_lib_staffing t \n");
			selSQL.append(" join tb_user u on  t.user_id = u.id  \n");
			selSQL.append(" WHERE not exists (\n");
			selSQL.append("            select * from\n");
			selSQL.append("            tb_lib_staffing g \n");
			selSQL.append("            where g.user_id = t.user_id  AND g.type = 's_sd' \n");
			selSQL.append("                and g.stat =1 \n");
			selSQL.append("        )     and   t.lib_id = ?   and   t.stat = 1 ");
			selSQL.append(" and (t.name like like concat('%',?,'%') or u.wx_name like concat('%',?,'%')) ");
			queryParams.add(libId);
			queryParams.add(searchContent);
		}else if ("6".equals(addType)){
			selSQL.append(" SELECT u.id,u.wx_name ,u.photo    \n");
			selSQL.append("  from  tb_user  u  where not exists (select 1 from tb_lib_manager t where t.user_id = u.id and t.state=1 and t.lib_id =?  and t.type =? ) and u.wx_name like concat('%',?,'%')  and u.wx_account is not null   ");
			queryParams.add(libId);
			queryParams.add(2);
			queryParams.add(searchContent);
		}else{
			//馆长、学霸老师、馆长助理
			selSQL.append("SELECT u.id,u.wx_name  , u.photo   \n");
			selSQL.append("  from  tb_user  u  where not exists (select * from tb_lib_manager t where t.user_id = u.id and t.state=1 and (t.type BETWEEN 0 and 1  or t.type=3))   ");
			selSQL.append(" and u.wx_name like concat('%',?,'%')  and u.wx_account is not null ");
			queryParams.add(searchContent);
		    selSQL.append("   order by   u.create_time desc   ");
			
		}
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	
			@Override
			public List<Map<String, Object>> searchAddUserList(Map<String, Object> params) {
				String addType = params.get("addType").toString();
				String libId = params.get("libId").toString();
				StringBuilder selSQL = new StringBuilder();
		        List<Object> queryParams = new ArrayList<Object>();
		        //1-CD、2-CC、3-CDA、4-总部SD、5-图书馆管理员、6-作业吧管理员、7-学霸老师
				if("1".equals(addType) || "2".equals(addType) || "3".equals(addType)){ //
					selSQL.append("SELECT u.id,u.wx_name ,u.photo   \n");
					selSQL.append("    from tb_user  u  \n");
					selSQL.append("    where not exists (\n");
					selSQL.append("            select * from tb_lib_staffing t \n");
					selSQL.append("            where t.user_id = u.id  and t.stat =1  \n");
					selSQL.append("        )   and length(u.wx_account)>0 ");
					selSQL.append("     order by u.create_time desc ");
					selSQL.append("     LIMIT 0,10 ");
				}else if ("4".equals(addType)){
					selSQL.append(" SELECT u.id,u.wx_name ,u.photo    \n");
					selSQL.append(" from tb_lib_staffing t \n");
					selSQL.append(" join tb_user u on  t.user_id = u.id  \n");
					selSQL.append(" WHERE not exists (\n");
					selSQL.append("            select * from\n");
					selSQL.append("            tb_lib_staffing g \n");
					selSQL.append("            where g.user_id = t.user_id  AND g.type = 's_sd' \n");
					selSQL.append("                and g.stat =1 \n");
					selSQL.append("        )     and   t.lib_id = ?   and   t.stat = 1  and length(u.wx_account)>0");
					selSQL.append(" order by u.create_time desc ");
					selSQL.append("  LIMIT 0,10 ");
					queryParams.add(libId);
				}else if ("6".equals(addType)){
					//在馆老师
					//馆长助理、学霸老师
					selSQL.append("SELECT u.id,u.wx_name  , u.photo   \n");
					selSQL.append("from  tb_user  u  where\n");
					selSQL.append("not exists ( \n");
					selSQL.append(" select 1 from tb_lib_manager t where t.user_id = u.id and t.state=1 and t.lib_id=? and t.type=?  )  and length(u.wx_account)>0  ");
					selSQL.append(" order by u.create_time desc ");
					selSQL.append("  LIMIT 0,10 ");
					queryParams.add(libId);
					queryParams.add("5".equals(addType)?1:"6".equals(addType)?2:3);
				}else{
					//馆长助理、学霸老师
					selSQL.append("SELECT u.id,u.wx_name  , u.photo   \n");
					selSQL.append("from  tb_user  u  where\n");
					selSQL.append("not exists ( \n");
					selSQL.append(" select 1 from tb_lib_manager t where t.user_id = u.id and t.state=1 and t.lib_id is not null and t.type<>6 )  and length(u.wx_account)>0  ");
					selSQL.append(" order by u.create_time desc ");
					selSQL.append("  LIMIT 0,10 ");
				}
				return dao.findMap(selSQL.toString(), queryParams.toArray());
			}

			@Override
			public List<Map<String, Object>> pushNotice(String libId) {
				StringBuilder selSql = new StringBuilder();
				List<Object> queryParams = new ArrayList<Object>();
				selSql.append("  SELECT 	t.id,t.details,t.price,s.end_time,t.lib_id ");
				selSql.append(" , u.wx_account , v.parent_name ,v.child_name ,v.flow_id, us.wx_account as xs_openid ,  j.league_name");
				selSql.append("  FROM tb_lib_vip_service  s left join  tb_lib_order_details t on s.order_details_id = t.id     ");
				selSql.append("  LEFT  JOIN tb_user us ON t.sales_user_id = us.id     ");
				selSql.append("  LEFT  join  tb_lib_read_vip  v  on s.vip_id = v.id      ");
				selSql.append("   LEFT  JOIN tb_user u ON v.user_id = u.id  ");
				selSql.append(" LEFT   join  tb_lib_join  j on j.id = s.lib_id      ");
				selSql.append(" left join tb_lib_vip_service vs on v.id = vs.vip_id and vs.stat='1'      ");
				selSql.append("   where    (TO_DAYS(now())-TO_DAYS(s.end_time)) between  0  and  20  and s.lib_id = ? and vs.id is null");
				queryParams.add(libId);
				return dao.findMap(selSql.toString(), queryParams.toArray());
			}

	@Override
	public Page<Map<String, Object>> getLocationJoin(Map<String, Object> searchParams, Pageable pageable) {
		List<Object> queryParams = new ArrayList<>();
        String sql;
        //经纬度为空，这里设置没有距离
        if (StringUtil.isEmpty(searchParams.get("league_lat")) || StringUtil.isEmpty(searchParams.get("league_lng"))) {
            sql = "SELECT t.* , -1 AS juli FROM tb_lib_join t ";
        } else {
            sql ="SELECT\n" +
                    "	t.* , func_calcDistance(t.league_lng,t.league_lat,?,?) AS juli\n" +
                    "FROM\n" +
                    "	tb_lib_join t    \n" ;
			queryParams.add(searchParams.get("league_lng"));
			queryParams.add(searchParams.get("league_lat"));
        }
        if(searchParams.get("schoolName") !=null &&  searchParams.get("schoolName").toString().trim().length()>0){
			sql += "  join fx_merchant t11 on t.id = t11.lib_id \n";
			sql += "  join fx_merchant_area t12  on t12.merchant_id = t11.id  \n";
		}
        sql +=" where  t.type >=? ";
		queryParams.add(searchParams.get("type"));

		if(searchParams.get("schoolName") !=null &&  searchParams.get("schoolName").toString().trim().length()>0){
			sql += " and t12.school_name =? \n";
			queryParams.add(searchParams.get("schoolName"));
		}
		//最大时间,格式(yyyy-MM-dd HH:mm:ss)
		String maxCreateTime = (String) searchParams.get("maxCreateTime");
		if (StringUtil.isNotBlank(maxCreateTime)) {
			sql += (" and t.create_time <= '" + maxCreateTime +"'");
		}
		//馆名或馆地址模糊查询
		if( searchParams.get("value") !=null &&  searchParams.get("value").toString().trim().length()>0){
			sql += "  and (t.league_name LIKE CONCAT(CONCAT('%',?,'%')) or t.league_address LIKE CONCAT(CONCAT('%',?,'%')))  " ;
			queryParams.add(searchParams.get("value").toString().trim());
			queryParams.add(searchParams.get("value").toString().trim());
		}
		if( searchParams.get("leagueName") !=null &&  searchParams.get("leagueName").toString().trim().length()>0){
			sql += "  and t.league_name LIKE CONCAT(CONCAT('%',?,'%'))   " ;
			queryParams.add(searchParams.get("leagueName").toString().trim());
		}
		sql	+=	 " ORDER BY\n" +
				 "	juli ASC,t.league_name desc";
		return dao.findPage(sql, queryParams.toArray(), pageable);
	}
	@Override
	public Page<Map<String, Object>> getLocationJoinService(Map<String, Object> searchParams, Pageable pageable) {
		List<Object> queryParams = new ArrayList<Object>();
		String sql ="SELECT\n" +
				"	j.id , j.league_name ,j.league_code ,j.league_address , CASE WHEN s.id is null   THEN 0  ELSE 1 END  as stype , ROUND(\n" +
				"		6378.138 * 2 * ASIN(\n" +
				"			SQRT(\n" +
				"				POW(\n" +
				"					SIN(\n" +
				"						(\n" +
				"							? * PI() / 180 - j.league_lat * PI() / 180\n" +
				"						) / 2\n" +
				"					),\n" +
				"					2\n" +
				"				) + COS(? * PI() / 180) * COS(j.league_lat * PI() / 180) * POW(\n" +
				"					SIN(\n" +
				"						(\n" +
				"							? * PI() / 180 - j.league_lng * PI() / 180\n" +
				"						) / 2\n" +
				"					),\n" +
				"					2\n" +
				"				)\n" +
				"			)\n" +
				"		)\n" +
				"	,2) AS juli\n" +
				"FROM\n" +
				"	tb_lib_join j  LEFT join   tb_lib_vip_service s on j.id = s.lib_id   and s.vip_id =?   where  j.type >=?  \n" ;
		if( searchParams.get("leagueName") !=null &&  searchParams.get("leagueName").toString().trim().length()>0){
			sql += "  and   j.league_name LIKE CONCAT(CONCAT('%',?,'%'))   " ;
		}
		if( searchParams.get("libtype") !=null &&  searchParams.get("libtype").toString().trim().length()>0){
			sql += "  and   j.libtype >? " ;
		}
		sql	+=	 " ORDER BY\n" +
				"	s.id DESC,juli ASC,j.id desc";
		queryParams.add(searchParams.get("league_lat"));
		queryParams.add(searchParams.get("league_lat"));
		queryParams.add(searchParams.get("league_lng"));
		queryParams.add(searchParams.get("vipId"));
		queryParams.add(searchParams.get("type"));
		if(searchParams.get("leagueName") !=null &&  searchParams.get("leagueName").toString().trim().length()>0){
			queryParams.add(searchParams.get("leagueName").toString().trim());
		}
		if( searchParams.get("libtype") !=null &&  searchParams.get("libtype").toString().trim().length()>0){
			queryParams.add(searchParams.get("libtype"));
		}
		return dao.findPage(sql, queryParams.toArray(), pageable);
	}
	@Override
	public Page<Map<String, Object>> getLocationArea(Map<String, Object> searchParams, Pageable pageable) {
		List<Object> queryParams = new ArrayList<Object>();
		String sql ="SELECT\n" +
				"	* , ROUND(\n" +
				"		6378.138 * 2 * ASIN(\n" +
				"			SQRT(\n" +
				"				POW(\n" +
				"					SIN(\n" +
				"						(\n" +
				"							? * PI() / 180 - school_lat * PI() / 180\n" +
				"						) / 2\n" +
				"					),\n" +
				"					2\n" +
				"				) + COS(? * PI() / 180) * COS(school_lat * PI() / 180) * POW(\n" +
				"					SIN(\n" +
				"						(\n" +
				"							? * PI() / 180 - school_lng * PI() / 180\n" +
				"						) / 2\n" +
				"					),\n" +
				"					2\n" +
				"				)\n" +
				"			)\n" +
				"		)\n" +
				"	,2) AS juli\n" +
				"FROM\n" +
				"	sys_cn_area  where  type =? \n" ;
		if( searchParams.get("schoolName") !=null &&  searchParams.get("schoolName").toString().trim().length()>0){
			sql += "  and  ( school_address LIKE CONCAT(CONCAT('%',?,'%'))   " ;
			sql += "  or    `name` LIKE CONCAT(CONCAT('%',?,'%')) ) " ;
		}
		sql	+=	 " ORDER BY\n" +
				"	juli ASC";
		queryParams.add(searchParams.get("league_lat"));
		queryParams.add(searchParams.get("league_lat"));
		queryParams.add(searchParams.get("league_lng"));
		queryParams.add(searchParams.get("type"));
		if(searchParams.get("schoolName") !=null &&  searchParams.get("schoolName").toString().trim().length()>0){
			queryParams.add(searchParams.get("schoolName").toString().trim());
			queryParams.add(searchParams.get("schoolName").toString().trim());
		}
		return dao.findPage(sql, queryParams.toArray(), pageable);
	}

	@Override
	public List<Map<String, Object>> getPositionArea(String league_lat,
			String league_lng, Integer type,String schoolName) {
		 String sql ="SELECT\n" +
				 "	* , ROUND(\n" +
				 "		6378.138 * 2 * ASIN(\n" +
				 "			SQRT(\n" +
				 "				POW(\n" +
				 "					SIN(\n" +
				 "						(\n" +
				 "							? * PI() / 180 - school_lat * PI() / 180\n" +
				 "						) / 2\n" +
				 "					),\n" +
				 "					2\n" +
				 "				) + COS(? * PI() / 180) * COS(school_lat * PI() / 180) * POW(\n" +
				 "					SIN(\n" +
				 "						(\n" +
				 "							? * PI() / 180 - school_lng * PI() / 180\n" +
				 "						) / 2\n" +
				 "					),\n" +
				 "					2\n" +
				 "				)\n" +
				 "			)\n" +
				 "		)\n" +
				 "	,2) AS juli\n" +
				 "FROM\n" +
				 "	sys_cn_area  where  type =? \n" ;
		 if(schoolName !=null && schoolName.trim().length()>0){
			 sql += "  and  ( school_address LIKE CONCAT(CONCAT('%',?,'%'))   " ;
			 sql += "  or    `name` LIKE CONCAT(CONCAT('%',?,'%')) ) " ;
		 }
			sql +=" ORDER BY\n" +
				  "	juli ASC";
		List<Object> queryParams = new ArrayList<Object>();
		queryParams.add(league_lat);
		queryParams.add(league_lat);
		queryParams.add(league_lng);
		queryParams.add(type);
		if(schoolName !=null && schoolName.trim().length()>0){
			 queryParams.add(schoolName.trim());
			 queryParams.add(schoolName.trim());
		}
		return dao.findMap(sql, queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> findRecommendBook(int grTotal,int pageSize) {
		StringBuilder selSql = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSql.append("  select a.local_image,a.title,a.author,a.publisher,b.`name`  from tb_lib_book_base  a  \n");
		selSql.append(" left join sys_sort b on a.book_tag = b.`code` and b.pid='d1ec09d3-f924-40be-9e23-daa372d983da' \n");
		selSql.append("  where a.book_gr is not null and cast( a.book_gr   as   SIGNED   INTEGER) BETWEEN ? and ?    ");
		selSql.append("  where a.book_gr is not null and cast( a.book_gr   as   SIGNED   INTEGER) BETWEEN ? and ?      ");
		selSql.append("  limit ?    ");
		queryParams.add(grTotal-100);
		queryParams.add(grTotal+100);
		queryParams.add(pageSize);
		return dao.findMap(selSql.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> getJoinAll(int i) {
		String sql ="SELECT * from  tb_lib_join  where type >=? limit 10";
		List<Object> queryParams = new ArrayList<Object>();
		queryParams.add(i);
		return dao.findMap(sql, queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> getNearJoin(String league_lat, String league_lng, int i) {
		String sql ="SELECT\n" +
				 "	* , ROUND(\n" +
				 "		6378.138 * 2 * ASIN(\n" +
				 "			SQRT(\n" +
				 "				POW(\n" +
				 "					SIN(\n" +
				 "						(\n" +
				 "							? * PI() / 180 - league_lat * PI() / 180\n" +
				 "						) / 2\n" +
				 "					),\n" +
				 "					2\n" +
				 "				) + COS(? * PI() / 180) * COS(league_lat * PI() / 180) * POW(\n" +
				 "					SIN(\n" +
				 "						(\n" +
				 "							? * PI() / 180 - league_lng * PI() / 180\n" +
				 "						) / 2\n" +
				 "					),\n" +
				 "					2\n" +
				 "				)\n" +
				 "			)\n" +
				 "		)\n" +
				 "	,2) AS juli\n" +
				 "FROM\n" +
				 "	tb_lib_join  where  type >=? \n" +
				 "ORDER BY\n" +
				 "	juli ASC limit 10";
		List<Object> queryParams = new ArrayList<Object>();
		queryParams.add(league_lat);
		queryParams.add(league_lat);
		queryParams.add(league_lng);
		queryParams.add(i);
		return dao.findMap(sql, queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> findManageOpenidList(String libId, int type) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        
        selSQL.append("SELECT t12.wx_account as openid from tb_lib_manager t \n");
        selSQL.append("left join tb_user t12 on t.user_id = t12.id \n");
        selSQL.append("where t.lib_id = ? and t.type = ? and t.state = 1\n");
        queryParams.add(libId);
        queryParams.add(type);
        return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> findAnything(String libId, int type) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        
        selSQL.append("SELECT t12.wx_account as openid,t.user_id,IFNULL(t.`name`,t12.wx_name) as username from tb_lib_manager t \n");
        selSQL.append("left join tb_user t12 on t.user_id = t12.id \n");
        selSQL.append("where t.lib_id = ? and t.type = ? and t.state = 1 \n");
        queryParams.add(libId);
        queryParams.add(type);
        return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> getTopAndLibId( int topSize) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        
        
                selSQL.append(" SELECT i.title,i.local_image ,i.isbn13, count(1) AS cishu   FROM                    ");
        		selSQL.append(" tb_order_details h  JOIN tb_lib_book_detail d ON h.book_detail_id = d.id ");
        		selSQL.append("   join  tb_lib_book_info i  on d.info_id = i.id                                          ");
        		selSQL.append(" where i.isbn13 is not null                                            ");
        		selSQL.append("  GROUP BY   	i.isbn13                                                     ");
        		selSQL.append(" ORDER BY count(1) desc                                              ");
        		selSQL.append(" LIMIT ?                                                        ");
        queryParams.add(topSize);
        return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> getdefaultBookAndLibId(String libId,
			String[] isbn,String searchContent,String vipId,int type) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT  i.title,i.summary ,i.local_image ,i.author,i.isbn13,case when t.id is null then 2 else 1 end  as can_oper     ");
		if(isbn!=null && isbn.length>0){
			selSQL.append(" ,(SELECT count(id) from  tb_lib_book_borrow  b where b.isbn13 = i.isbn13 and b.type=1 and b.stat=1 ) as cishu ");
		}
		selSQL.append("  from     tb_lib_book_info i                 ");
		selSQL.append("  left join tb_lib_book_borrow t on i.isbn13 = t.isbn13  and i.lib_id =t.lib_id   and t.stat=1  and t.vip_id = ? ");
		queryParams.add(vipId);
		//if("fa14e041-3823-4dac-b061-1e250e5a7d49".equals(libId)){
		if(type == 2){
			selSQL.append("  and t.type=1  ");
			selSQL.append(" where i.lib_id='fa14e041-3823-4dac-b061-1e250e5a7d49'  and i.isbn13   is not null ");
		}else{
			selSQL.append("  and t.type=3  ");
			selSQL.append(" where i.lib_id=?  and i.isbn13   is not null ");
			queryParams.add(libId);
		}
		
		if(searchContent!=null && !"".equals(searchContent)){
			selSQL.append(" and  i.title LIKE  CONCAT(CONCAT('%',?,'%')) ");
			queryParams.add(searchContent);
		}
		if(isbn!=null && isbn.length>0){
        	selSQL.append(" AND i.isbn13 not in ( ");
        	selSQL.append("'"+StringUtils.join(isbn, "','")+"'");
        	selSQL.append(")");
        }
		if(type == 2){
			selSQL.append(" and  not EXISTS(select 1 from tb_lib_book_info x where i.isbn13 = x.isbn13 and x.lib_id=?)");
			queryParams.add(libId);
		}
		selSQL.append(" LIMIT 3  ");
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}
	@Override
	public List<Map<String, Object>> getdefaultBookAndLibId(String libId,
			String bookName) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT  i.title,i.summary ,i.local_image ,i.author,i.isbn13       ");
		selSQL.append("  from     tb_lib_book_info i                 ");
		queryParams.add(libId);
		selSQL.append(" where i.lib_id=?  and i.isbn13   is not null  ");
		selSQL.append(" and  (select count(1) as num from tb_lib_book_borrow b where b.isbn13  = i.isbn13 and b.stat=1  and b.type =3) = 0  ");
		if(bookName!=null && bookName.length()>0){
			selSQL.append(" and  i.title LIKE  CONCAT(CONCAT('%',?,'%')) ");
			queryParams.add(bookName);
		}
		selSQL.append(" LIMIT 5  ");
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> getdefaultBookAndLibId(String[] isbn,String searchContent,String vipId) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT  i.title,i.summary ,i.local_image ,i.author,i.isbn13,case when t.id is null then 2 else 1 end  as can_oper      ");
		selSQL.append(" ,(SELECT count(id) from  tb_lib_book_borrow  b where b.isbn13 = i.isbn13 and b.type=2 and b.stat=1 ) as cishu ");
		selSQL.append("  from   tb_lib_book_base i              ");
		selSQL.append("  left join tb_lib_book_borrow t on i.isbn13 = t.isbn13     and t.stat=1  and t.vip_id = ?  and t.type=2 ");
		queryParams.add(vipId);
		selSQL.append("  where  i.isbn13   is not null                ");
		
		if(searchContent!=null && !"".equals(searchContent)){
			selSQL.append(" and  i.title LIKE  CONCAT(CONCAT('%',?,'%')) ");
			queryParams.add(searchContent);
		}
		
		if(isbn!=null && isbn.length>0){
        	selSQL.append(" and i.isbn13 not in ( ");
        	selSQL.append("'"+StringUtils.join(isbn, "','")+"'");
        	selSQL.append(")");
        }
		selSQL.append(" and not EXISTS(select 1 from tb_lib_book_info x where i.isbn13 = x.isbn13 and x.lib_id='fa14e041-3823-4dac-b061-1e250e5a7d49') ");
		selSQL.append("  LIMIT 3  ");
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public List<Map<String, Object>> alreadyBookAndLibId(String libId,
			String vipId) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" select  i.title,i.summary ,i.local_image ,i.author,i.isbn13  ,       ");
		selSQL.append(" ( to_days(date_add(b.create_time,interval 3 day)) - to_days(now()) ) as days       ");
		selSQL.append("   from tb_lib_book_borrow b join   tb_lib_book_info  i  on  b.isbn13  = i.isbn13           ");
		selSQL.append(" where b.type =3 and b.stat =1   and b.lib_id=? and  b.vip_id=?  and   i.isbn13   is not null        ");
		selSQL.append("  GROUP BY i.isbn13  ");
		queryParams.add(libId);
		queryParams.add(vipId);
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public Page<Map<String, Object>> growthRecordList(
			Map<String, Object> searchParams, Pageable pageable) {
		 StringBuilder selSQL = new StringBuilder();
	        List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT  h.author,h.title ,o.local_image ,o.summary,o.isbn13 ");
	        selSQL.append(" ,DATE_FORMAT(h.create_time ,'%Y-%m-%d') as create_time   ");
	        selSQL.append(" ,( to_days(NOW()) - to_days(h.create_time) ) as days  ");
	        selSQL.append(" from  tb_order_details  h join  tb_lib_book_detail l ");
	        selSQL.append(" on h.book_detail_id =l.id  ");
	        selSQL.append(" JOIN   tb_lib_book_info o on o.id  = l.info_id  ");
	            selSQL.append(" where h.vip_id =? and l.lib_id=? and  o.isbn13   is not null    ");
	            selSQL.append(" order by  h.create_time  desc ");
	            queryParams.add(searchParams.get("vipId"));
	            queryParams.add(searchParams.get("libId"));
	        return dao.findPage(selSQL.toString(), queryParams.toArray(), pageable);
	}

	@Override
	public List<Map<String, Object>> getServiceVip(String userId, String libId,
			String species) {
		StringBuilder selSQL = new StringBuilder();
		 List<Object> queryParams = new ArrayList<Object>();
	        selSQL.append(" SELECT  v.id as vip_id,v.child_name,v.img_url,e.species, e.type , DATE_FORMAT(e.end_time ,'%Y-%m-%d') as end_time  ");
	        selSQL.append(" , (SELECT n.league_name from  tb_lib_join  n where n.id =e.lib_id) as lname  ");
	        selSQL.append("  FROM  tb_lib_vip v   JOIN tb_lib_vip_service  e  ");
	        selSQL.append("  on e.vip_id =v.id  ");
	        selSQL.append("  where   v.user_id=? and e.species=? and e.lib_id =? and e.stat=1   ");
	        
	        queryParams.add(userId);
	        queryParams.add(species);
	        queryParams.add(libId);
	        selSQL.append("  ORDER BY  e.end_time desc    ");
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}
	@Override
	public List<Map<String, Object>> getServiceVip(String userId, 
			String species) {
		StringBuilder selSQL = new StringBuilder();
		List<Object> queryParams = new ArrayList<Object>();
		selSQL.append(" SELECT  e.lib_id,v.id as vip_id,v.child_name,v.img_url,e.species, e.type , DATE_FORMAT(e.end_time ,'%Y-%m-%d') as end_time  ");
		selSQL.append(" , (SELECT n.league_name from  tb_lib_join  n where n.id =e.lib_id) as lname  ");
		selSQL.append("  FROM  tb_lib_vip v   JOIN tb_lib_vip_service  e  ");
		selSQL.append("  on e.vip_id =v.id  ");
		selSQL.append("  where   v.user_id=? and e.species=?  and e.stat=1   ");
		
		queryParams.add(userId);
		queryParams.add(species);
		selSQL.append("  ORDER BY  e.end_time desc    ");
		return dao.findMap(selSQL.toString(), queryParams.toArray());
	}

	@Override
	public Map<String, Object> getIsbnBorrowInfo(String isbn13) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        selSQL.append("SELECT substring_index(GROUP_CONCAT( DISTINCT t13.img_url),',',3) as head_img,count(1) as borrow_num from tb_order_details t  \n");
        selSQL.append("INNER JOIN tb_lib_book_detail t11 on t.book_detail_id = t11.id \n");
        selSQL.append("INNER JOIN tb_lib_book_info t12 on t11.info_id = t12.id \n");
        selSQL.append("INNER JOIN tb_lib_vip t13 on t.vip_id = t13.id \n");
        selSQL.append("where t12.isbn13 = ?\n");
        queryParams.add(isbn13);
        List<Map<String, Object>> mapList= dao.findMap(selSQL.toString(), queryParams.toArray());
        if(mapList != null && mapList.size()>0){
        	map = mapList.get(0);
        }
        return map;
	}

	@Override
	public List<TbLibJoin> findByLikeNameAndCity(String name, String province, String city, String area,Integer pageNo,Integer pageSize) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT * FROM `tb_lib_join` t where 1=1 ");
		if(StringUtils.isNotEmpty(name)) {
			 selSQL.append("  AND t.league_name like  CONCAT(CONCAT('%',?,'%')) ");
			 queryParams.add(name);
		}else {
			if(StringUtils.isNotEmpty(city)) {
				 selSQL.append("  AND t.league_city like  CONCAT(CONCAT('%',?,'%'))  ");
				 queryParams.add(city.replaceAll("市", ""));
			}
			if(StringUtils.isNotEmpty(area)) {
				 selSQL.append("  AND t.league_address like CONCAT(CONCAT('%',?,'%'))  ");
				 queryParams.add(area.replaceAll("区", ""));
			}
		}
	    selSQL.append(" ORDER BY t.create_time asc limit ?,?");
	    queryParams.add((pageNo-1)*pageSize);
	    queryParams.add(pageSize);
	    
        return dao.findList(selSQL.toString(), queryParams.toArray(),TbLibJoin.class);
	}
	
	@Override
	public Long countByLikeNameAndCity(String name, String province, String city, String area) {
		StringBuilder selSQL = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();
        selSQL.append(" SELECT * FROM `tb_lib_join` t where 1=1 ");
		if(StringUtils.isNotEmpty(name)) {
			 selSQL.append("  AND t.league_name like  CONCAT(CONCAT('%',?,'%')) ");
			 queryParams.add(name);
		}else {
			if(StringUtils.isNotEmpty(city)) {
				 selSQL.append("  AND t.league_city like  CONCAT(CONCAT('%',?,'%'))  ");
				 queryParams.add(city.replaceAll("市", ""));
			}
			if(StringUtils.isNotEmpty(area)) {
				 selSQL.append("  AND t.league_address like CONCAT(CONCAT('%',?,'%'))  ");
				 queryParams.add(area.replaceAll("区", ""));
			}
		}
        return dao.count(selSQL.toString(), queryParams.toArray());
	}
	
	
}
