package com.ssj.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.weixin.grword.domain.TbReadSubject;
import com.ssj.bean.weixin.libmy.domain.*;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.HttpRemote;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.BarcodeFactory;
import com.ssj.service.sys.organization.service.OrganizationService;
import com.ssj.service.sys.sort.service.SortService;
import com.ssj.service.weixin.library.service.*;
import com.ssj.service.weixin.problem.service.CnAreaService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.UserCountService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.service.weixin.zuoyb.service.ZuoybCourseService;
import com.ssj.service.weixin.zuoyb.service.ZuoybScoringContentService;
import com.ssj.sys.util.thirdparty.excel.CustomizeToExcel;
import com.ssj.sys.util.thirdparty.excel.ExcelColumn;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RequestMapping("sys/lib")
@Controller
public class SysLibController extends BaseController {
	@Autowired
	 private LibUserHistoryService libUserHistoryService;
	
    @Autowired
	private UserService userService;

	@Autowired
	private UserCountService userCountService;

    
    @Autowired
    private ILibJoinService libJoinService;
    @Autowired
    private ILibBookService libBookService;
    @Autowired
    private IBookDetailService bookDetailService;
    
    @Autowired
    private IReadVipService libVipService;
    @Autowired
    private SortService sortService;

	 @Autowired
	 private LibVipServiceService libVipServiceService;//判断是否有服务
	 
	 @Autowired
	 private ZuoybScoringContentService zuoybScoringContentService;
	 
	 @Autowired
	 private IBookBaseService bookBaseService;

	@Autowired
	 private TokenManager tokenManager;
	 @Autowired
	 private IBookManagerService  managerService;
	 
	 @Autowired
	 private PushTemplateService pushTemplateService;
	 
	@Autowired
	private CnAreaService cnAreaService;
		
//	@Autowired
//	private ReadQueryService readQueryService;

    @Autowired
	private OrganizationService organizationService;
    
    @Autowired
	private IBookBorrowService bookBorrowService;

    @Autowired
	 private ZuoybCourseService zuoybCourseService;
    

    
	/**
	 * 图书馆列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/libJoinList")
	public String libJoinList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("LIKE_leagueName", request.getParameter("LIKE_leagueName")==null?"":request.getParameter("LIKE_leagueName"));
		params.put("LIKE_leagueCode", request.getParameter("LIKE_leagueCode")==null?"":request.getParameter("LIKE_leagueCode"));
		params.put("IN_orgCode", orgcodeList());
		params.put("GTE_type", "1");
		SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI().toString());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	    Page<TbLibJoin> page= libJoinService.findByPage(params, initPage(pageNo,pageSize,Direction.DESC, new String[] { "type" }));
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);

		return "sys/lib/libJoinList";
	}
	/**
	 * 图书馆管理员列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/libManagerList")
	public String libManagerList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo,String libId,String orgCode,
			@RequestParam(required = false, defaultValue = "1") String libtype)
					throws Exception {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("wx_name",request.getParameter("wx_name") == null ? "" : request.getParameter("wx_name"));
		params.put("libId", libId);
		params.put("libtype", libtype.equals("1")?"1":"2");
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String, Object>> page = libJoinService.findForPage(params, initPage(pageNo, pageSize));
		params.put("orgCode", orgCode);
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);
		
		return "sys/lib/libManagerList";
	}
	/**
	 * 图书馆新增、修改
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	 @RequestMapping("/libJoinAdd")
	 public String libJoinAdd(Model model,@RequestParam( defaultValue = "0")String id) throws Exception {
		 TbLibJoin lib= libJoinService.getById(id);
		 if(lib==null) {
			 lib = new TbLibJoin();
			// lib.setOrgCode(orgCode());
		 }
		 Admin admin = (Admin)request.getSession().getAttribute("admin");
		 model.addAttribute("ws", lib); 
		 model.addAttribute("orgList", organizationService.getOrganizationByAdminOrg(admin.getId(),3)); 
		 return "sys/lib/libJoinAdd";
	 }
	 /**
	  * 保存
	  * @param lib
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value = "/libJoinSave", method = RequestMethod.POST)
	 @ResponseBody
	 public Response libJoinSave(TbLibJoin lib) throws Exception{
	    	Response response = new  Response();
	    	try{
	    		if(StringUtils.isNotEmpty(lib.getId())) {
	    			TbLibJoin oldTbLibJoin=libJoinService.getById(lib.getId());
	    			lib.setLibService(oldTbLibJoin.getLibService());
	    			lib.setSignType(oldTbLibJoin.getSignType());
	    			lib.setSignTime(oldTbLibJoin.getSignTime());
	    			lib.setEndSignTime(oldTbLibJoin.getEndSignTime());
	    		}
				libJoinService.libJoinSave(lib);
				response.success();
			}catch (Exception e){
				logger.error(e.getMessage());
				response.failure("保存失败");
			}
	    	return response;
	 }
	 
	    @RequestMapping(value = "/downloadQrCode", method = RequestMethod.POST)
		@ResponseBody
		public void downloadQrCode(HttpServletResponse response,HttpServletRequest request,String url,String leagueName) {
			try {
						
						String file_path = (String) SystemResourceLocator.getValue("file_save_path");
						File file = new File(file_path+url);	
						FileInputStream fis = new FileInputStream(file);
						BufferedInputStream buff = new BufferedInputStream(fis);
						String fileName=new String((leagueName+"二维码").getBytes("gb2312"), "iso8859-1");
						response.setContentType("application/octet-stream;charset=UTF-8");
						response.setHeader("Content-Disposition", "attachment;filename=" + fileName+".jpg");
						response.setCharacterEncoding("utf-8");
						
						
						byte[] b = new byte[8096];// 相当于我们的缓存
						long k = 0;// 该值用于计算当前实际下载了多少字节
						OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载
						// 开始循环下载
						while (k < file.length()) {
							int j = buff.read(b, 0, 1024);
							k += j;
							myout.write(b, 0, j);
						}
						buff.close();
						fis.close();
			} catch (Exception e) {
				logger.error("异常", e);
			}
		}
	 
	 /**
	  * 删除
	  * @param id
	  * @return
	  */
	 @RequestMapping(value = "/libJoinDelete", method = RequestMethod.POST)
	 @ResponseBody
	 public Response libJoinDelete( String id){
		 Response response = new  Response();
		// libJoinService.delete(id);
		 response.success();
		 return response;
	 }
	 
	
	 
	 @RequestMapping(value = "/libManagerDelete", method = RequestMethod.POST)
	 @ResponseBody
	 public Response libManagerDelete( String id){
		 Response response = new  Response();
		 TbLibManager manager= managerService.getById(id);
		 String userId = manager.getUserId();
		 int type = manager.getType();
		 if(type==1){
			 userId="JIEYUE"+userId;//图书借阅
         }else if(type==2){
        	 userId ="ZUOYB"+userId;//作业吧
         }else if(type==3){
        	 userId ="XUEBA"+userId; //学霸老师
         }else{
        	 userId ="CD"+userId; //学霸老师
         }
		 tokenManager.createManageType(userId,"0");
		 tokenManager.delToken(manager.getUserId());
		 libJoinService.libManagerDelete(manager.getId(),type);
		 response.success();
		 return response;
	 }
	 
	 
	    @RequestMapping("/selectUserList")
	    public String selectUserList(Model model,
	    		@RequestParam(required = false, defaultValue = "10") int pageSize,
	    		@RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
	    	Map<String, Object> params = new HashMap<String, Object>();
	    	params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
	    	params.put("mobile", request.getParameter("mobile")==null?"":request.getParameter("mobile"));
	    	params.put("libId", request.getParameter("libId"));
	    	params.put("type", request.getParameter("type"));
	    	params.put("subscribe", request.getParameter("subscribe")==null?"":request.getParameter("subscribe"));
	    	SplitPage sp = new SplitPage();
	    	sp.setAction(request.getRequestURI());
	    	sp.setPageNo(pageNo);
	    	sp.setPageSize(pageSize);
	    	sp.setParams(params);
	    	Page<Map<String, Object>> page= userService.getTSGUser(params, initPage(pageNo,pageSize));
	    	sp.setRowCnt((int)page.getTotalElements());
	    	model.addAttribute("list",  page.getContent());
	    	model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
	    	model.addAttribute("page", sp);
	    	model.addAttribute("search", params);
	    	
	    	return "sys/lib/selectUserList";
	    }
	    
		@RequestMapping(value = "/addAdmin", method = RequestMethod.POST)
	 	@ResponseBody
	 	public Response addAdmin(@RequestParam(value = "id")String id,
	 			@RequestParam(value = "type")Integer type,
	 			@RequestParam(value = "ids[]")String[] ids,@RequestParam(value = "mobiles[]")String[] mobiles,@RequestParam(value = "names[]")String[] names) {
	 	        Response response = new Response();
	 	        try {
	 	        	libJoinService.addAdmin(ids, id,type,mobiles,names);
	 	            response.success("添加成功");
	 	        } catch (Exception e) {
					logger.error("异常", e);
	 	            response.failure("添加失败：" + e.getMessage());
	 	        }
	 	        return response;
	 	 }  
		
		/**
		 * 图书列表
		 * @param model
		 * @param pageSize
		 * @param pageNo
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/libBookInfoList")
		public String libBookInfoList(Model model,
				@RequestParam(required = false, defaultValue = "10") int pageSize,
				@RequestParam(required = false, defaultValue = "1") int pageNo)
				throws Exception {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("title",request.getParameter("title") == null ? "" : request.getParameter("title"));
			if(!"admin".equals(loginName())){
				params.put("orgCode",orgCodeStr());
			}
			params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
			params.put("bookTae", request.getParameter("bookTae")==null?"":request.getParameter("bookTae"));
			params.put("bookCase", request.getParameter("bookCase")==null?"":request.getParameter("bookCase"));
			params.put("startAge", request.getParameter("startAge")==null?"":request.getParameter("startAge"));
			params.put("endAge", request.getParameter("endAge")==null?"":request.getParameter("endAge"));
			params.put("parentTheme",request.getParameter("parentTheme") == null ? "" : request.getParameter("parentTheme"));
			params.put("childTheme",request.getParameter("childTheme") == null ? "" : request.getParameter("childTheme"));
			SplitPage sp = new SplitPage();
			sp.setAction(request.getRequestURI().toString());
			sp.setPageNo(pageNo);
			sp.setPageSize(pageSize);
			sp.setParams(params);
			Page<Map<String, Object>> page = libBookService.findForPageList(params, initPage(pageNo, pageSize));
			sp.setRowCnt((int) page.getTotalElements());
			model.addAttribute("list", page.getContent());
			model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
			model.addAttribute("page", sp);
			model.addAttribute("search", params);
			model.addAttribute("book_tags", sortService.getParamValByCode("book_tags"));
			model.addAttribute("book_case", sortService.getParamValByCode("book_case"));
			model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
			return "sys/lib/libBookInfoList";
		}	
		
	
		 @RequestMapping("/libBookInfoAdd")
		 public String libBookInfoAdd(Model model,@RequestParam( defaultValue = "0")String id) throws Exception {
			 TbLibBookInfo info= libBookService.getById(id);
			 if(info==null) {
				 info = new TbLibBookInfo();
				// info.setOrgCode(orgCode());
				// info.setLibId(libId());
			 }
			 model.addAttribute("book_tags", sortService.getParamValByCode("book_tags"));
			 model.addAttribute("book_ages", sortService.getParamValByCode("book_ages"));
			 model.addAttribute("book_case", sortService.getParamValByCode("book_case"));
			 model.addAttribute("info", info); 
			 model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
			// model.addAttribute("list", libJoinService.findAll()); 
			 return "sys/lib/libBookInfoAdd";
		 }	
		 
		 @RequestMapping(value = "/libBookInfoSave", method = RequestMethod.POST)
		 @ResponseBody
		 public Response libBookInfoSave(  TbLibBookInfo info){
		    	Response response = new  Response();
		    	info.setCreateTime(new Date());
		    	info.setUpdateTime(new Date());
		    	String libId =info.getLibId();
		    	libBookService.save(info);
		    	if(info!=null && info.getId().length()>0){
		    		if(info.getNum()!=null && info.getNum()>0){
		    			for (int i = 0; i <info.getNum(); i++) {
			    			BookDetail book = new  BookDetail();
			    			book.setCreateTime(new Date());
			    			book.setStat(1);
			    			book.setType(1);
			    			book.setLibId(libId);
			    			book.setInfoId(info.getId());
			    			bookDetailService.save(book);
		    			}
		    		}
		    	}
		    	response.success();
		    	return response;
		 }	 
		 
		 /**
			 * 书本明细列表，借书人，借书时间
			 * @param model
			 * @param pageSize
			 * @param pageNo
			 * @param libId
			 * @return
			 * @throws Exception
			 */
			@RequestMapping("/bookDetailList")
			public String bookDetailList(Model model,
					@RequestParam(required = false, defaultValue = "10") int pageSize,
					@RequestParam(required = false, defaultValue = "1") int pageNo,String libId)
							throws Exception {
				
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("wx_name",request.getParameter("wx_name") == null ? "" : request.getParameter("wx_name"));
				params.put("libId", libId);
				SplitPage sp = new SplitPage();
				sp.setAction(request.getRequestURI().toString());
				sp.setPageNo(pageNo);
				sp.setPageSize(pageSize);
				sp.setParams(params);
				Page<Map<String, Object>> page = libJoinService.findBookDetailForPage(params, initPage(pageNo, pageSize));
				sp.setRowCnt((int) page.getTotalElements());
				model.addAttribute("list", page.getContent());
				model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
				model.addAttribute("page", sp);
				model.addAttribute("search", params);
				model.addAttribute("libId", libId);
				
				return "sys/lib/bookDetailList";
			}	
		 @RequestMapping(value = "/bookDetailDelete", method = RequestMethod.POST)
		 @ResponseBody
		 public Response bookDetailDelete(  String  id){
			 Response response = new  Response();
			 bookDetailService.delete(id);
			 response.success();
			 return response;
		 }
		 
		 @RequestMapping("/bookDetailAdd")
		 public String bookDetailAdd(Model model,@RequestParam( defaultValue = "0")String infoId) throws Exception {
			 model.addAttribute("infoId", infoId);
			 return "sys/lib/bookDetailAdd";
		 }	
		 
		 
		 @RequestMapping(value = "/bookDetailSave", method = RequestMethod.POST)
		 @ResponseBody
		 public Response bookDetailSave( String infoId,Integer num){
		    	Response response = new  Response();
		    	if(infoId!=null && infoId.length()>0){
		    		if(num!=null && num>0){
		    			for (int i = 0; i <num; i++) {
		    				BookDetail  book = new  BookDetail();
		    				book.setCreateTime(new Date());
		    				book.setStat(1);
		    				book.setType(1);
		    				book.setInfoId(infoId);
		    				bookDetailService.save(book);
						}
		    		}
		    	}
		    	response.success();
		    	return response;
		 }	

		/**
		 * 图书馆VIP会员卡管理列表
		 * @param model
		 * @param pageSize
		 * @param pageNo
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/libVipList")
		public String libVipList(Model model,
				@RequestParam(required = false, defaultValue = "10") int pageSize,
				@RequestParam(required = false, defaultValue = "1") int pageNo)
						throws Exception {
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name",request.getParameter("name") == null ? "" : request.getParameter("name"));
			params.put("stat",request.getParameter("stat") == null ? "" : request.getParameter("stat"));
			params.put("flow_id",request.getParameter("flow_id") == null ? "" : request.getParameter("flow_id"));
			params.put("level",request.getParameter("level") == null ? "" : request.getParameter("level"));
			params.put("activeTime",request.getParameter("activeTime") == null ? "" : request.getParameter("activeTime"));
			//params.put("orgCode",orgCode());
			 
			// model.addAttribute("libId", libId());
			SplitPage sp = new SplitPage();
			sp.setAction(request.getRequestURI().toString());
			sp.setPageNo(pageNo);
			sp.setPageSize(pageSize);
			sp.setParams(params);
			Page<Map<String, Object>> page = libJoinService.findForVIPPage(params, initPage(pageNo, pageSize));
			sp.setRowCnt((int) page.getTotalElements());
			model.addAttribute("list", page.getContent());
			model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
			model.addAttribute("page", sp);
			model.addAttribute("search", params);
			
			return "sys/lib/libVipList";
		}
	/**	
	 * 新增会员卡数量
	 * @param model
	 * @return
	 * @throws Exception
	 */
	 @RequestMapping("/libVipAdd")
	 public String libVIPAdd(Model model) throws Exception {
			 return "sys/lib/libVipAdd";
	}
	 @RequestMapping(value = "/libVipSave", method = RequestMethod.POST)
	 @ResponseBody
	 public Response libVIPSave(Integer num,Integer level){
	    	Response response = new  Response();
	    		if(num!=null && num>0){
	    			Date date = new   Date();
	    			for (int i = 0; i <num; i++) {
	    				LibReadVip libVip= new LibReadVip();
	    				libVip.setCreateTime(date);
	    				libVip.setStat("1");//生成的会员卡设置为有效状态 1--有效 2--无效',
	    				libVip.setLevel(level);
	    				libVipService.save(libVip);
					}
	    		}
	    	response.success();
	    	return response;
	 }	
	 /**
	  * 修改有效或无效
	  * @return
	  */
	 @RequestMapping(value = "/libVipUpdateSave", method = RequestMethod.POST)
	 @ResponseBody
	 public Response libVipUpdateSave(LibReadVip  libVip){
		 Response response = new  Response();
		 libVipService.save(libVip);
		 response.success();
		 return response;
	 }	
	 @RequestMapping(value = "/libVipStatSave", method = RequestMethod.POST)
	 @ResponseBody
	 public Response libVipStatSave( String id,String stat){
		 Response response = new  Response();
		 LibReadVip  libVip=libVipService.getById(id);
		 libVip.setStat(stat);
		 libVipService.save(libVip);
		 response.success();
		 return response;
	 }	
	 
	 @RequestMapping("/libVipUpdate")
	 public String libVipUpdate(Model model,@RequestParam( defaultValue = "0")String  id,
			 @RequestParam(required = false, defaultValue = "1")Integer isType) throws Exception {
		 LibReadVip  libVip=libVipService.getById(id);
		 if(libVip ==null ){
			 libVip = new LibReadVip();
		 }
		 model.addAttribute("area", cnAreaService.findByTypeList("4"));//学校
		 model.addAttribute("grade", sortService.getParamValByCode("grade"));//年级
			 model.addAttribute("vip", libVip);
			 model.addAttribute("isType", isType);
			 return "sys/lib/libVipUpdate";
	}
	 
	 @RequestMapping(value = "/printBookImg", method = RequestMethod.POST)
	 @ResponseBody
	 public Response printBookImg( String id){
		 Response response = new  Response();
		 BookDetail  bookDetail = bookDetailService.getById(id);
		 //先进行打印操作
		 if(bookDetail.getQrUrl() == null){
			 response.failure("生成二维码之后再打印");
			 return response;
		 }
		 String url = "http://open.memobird.cn/home/setuserbind";
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("ak", "0197c9d840294ef19bb9333c69d49b80");
			map.put("timestamp",DateHelper.getDateTime(new Date()));
			map.put("memobirdID", "014148564b450d2a");
			//map.put("memobirdID", "680fe7726b8cf140");
			//?ak=0197c9d840294ef19bb9333c69d49b80&timestamp=2017-03-13%2017:47:39&memobirdID=680fe7726b8cf140&userid
			//entifying=12121212
			//{"showapi_res_code":1,"showapi_res_error":"ok","showapi_userid":233362}
			//String json = JSONObject.toJSONString(map);
			JSONObject jsonObject;
			try {
				jsonObject = JSONObject.parseObject(HttpRemote.POSTMethod(url, map));
				String showapi_res_code = jsonObject.getString("showapi_res_code");
				if("1".equals(showapi_res_code)){  //获取成功
					String showapi_userid = jsonObject.getString("showapi_userid");
					url = "http://open.memobird.cn/home/printpaper";
					map.put("userID", showapi_userid);
					map.put("printcontent","P:"+getImageStr(bookDetail.getQrUrl()));
					JSONObject jsonObject2 =  JSONObject.parseObject(HttpRemote.POSTMethod(url, map));
					if("1".equals(jsonObject2.getString("showapi_res_code"))){  //获取成功
					    response.success();
					}else{
						response.failure(jsonObject2.getString("showapi_res_error"));
					}
				}else{
					response.failure(jsonObject.getString("showapi_res_error"));
				}
			} catch (Exception e) {
				response.success("请求发生错误！","请求发生错误！");
				logger.error("异常", e);
			}
		 

		 return response;
	 }
		/**
		 * @Description: 根据图片地址转换为base64编码字符串
		 * @Author: 
		 * @CreateTime: 
		 * @return
		 */
		public   String getImageStr(String imgFile) {
			imgFile = PropertiesUtil.getValue("file_save_path")+imgFile; //关注第一条
		
		    InputStream inputStream = null;
		    byte[] data = null;
		    try {
		        inputStream = new FileInputStream(imgFile);
		        data = new byte[inputStream.available()];
		        inputStream.read(data);
		        inputStream.close();
		    } catch (IOException e) {
				logger.error("异常", e);
		    }
		    // 加密
		   // Base64Encoder encoder = new Base64Encoder();
		    return new String(Base64.encodeBase64(data));
		}
	 
		
		/**
		 * 获取所有私塾家图书馆的坐标信息
		 * @param request
		 * @param model
		 * @return
		 */
		@RequestMapping(value = "/getAllSchoolMap", method = RequestMethod.POST)
		@ResponseBody
		public ResponseEntity getAllSchoolMap(HttpServletRequest request, Model model,String searchValue,String city ){
			Map<String, Object> data = new HashMap<String, Object>();
			 Map<String, Object> params = new HashMap<String, Object>();
		     params.put("searchValue", searchValue);
		     params.put("city", city);
		    List<Map<String, Object>> list= libJoinService.getAllSchoolMap(params);
			data.put("list", list);
			ResponseEntity responseEntity = new ResponseEntity();
			responseEntity.success(data, "获取成功！");
	        return responseEntity;
		}
		
		/**	
		 * 新增图书明细二维码数量
		 * @param model
		 * @return
		 * @throws Exception
		 */
		 @RequestMapping("/libDetailAdd")
		 public String libDetailAdd(Model model,@RequestParam( defaultValue = "0")String libId) throws Exception {
				 model.addAttribute("libId", libId);
				 return "sys/lib/libDetailAdd";
		}
	
	 
	 /**
	  * 保存明细
	  * @Title: libDetailSave
	  * @Description: 批量生产二维码图书明细
	  * @param @param libId
	  * @param @param num
	  * @param @return    设定文件
	  * @return Response    返回类型
	  * @author shenhao
	  * @date 2017年4月17日 上午10:14:38
	  * @throws
	  */
	 @RequestMapping(value = "/libDetailSave", method = RequestMethod.POST)
	 @ResponseBody
	 public Response libDetailSave( String libId,Integer num){
	    	Response response = new  Response();
	    	if(libId!=null && libId.length()>0){
	    		if(num!=null && num>0){
	    			Date date = new   Date();
	    			List<BookDetail> detailList = new ArrayList<BookDetail>();
	    			for (int i = 0; i <num; i++) {
	    				BookDetail  detail= new BookDetail();
	    				detail.setCreateTime(date);
	    				//detail.setLibId(libId);//20180309修改不预设图书二维码所属馆
	    				detail.setType(1);
	    				detail.setStat(1);
	    				detailList.add(detail);
					}
	    			bookDetailService.save(detailList);
	    		}
	    	}
	    	response.success();
	    	return response;
	 }	
	 
		/**
		 * 批量生成二维码，打包生成zip,下载zip 图书明细未关联图书
		 * @param response
		 * @param request
		 */
		@RequestMapping(value = "/ajaxDetailQrCode", method = RequestMethod.POST)
	    @ResponseBody
		public void ajaxDetailQrCode(HttpServletResponse response,HttpServletRequest request) {
				try {
					//查出所有图书馆未生成二维码且info_id 为空的数据
					//List<TbLibJoin> libList = libJoinService.findAll();
					String file_path = (String) SystemResourceLocator.getValue("file_save_path");
					String  result =  DateHelper.format(new Date(), "yyyy_MM_dd");
					
					String dataStr = DateHelper.formatDateByFormat(new Date(), "yyyyMMddHHmmss");
					String fPath = "/BOOK"+dataStr;
					String zip = "/BOOK/"+"BOOK_"+result+"_.zip";
					List<Map<String, Object>> detailList =  bookDetailService.getDetailQrList("");
					if(detailList !=null && detailList.size()>0){
	    				//bookDetailService.bookenCode(tbLibBookInfo.getId(), tbLibJoin.getLeagueName(), tbLibBookInfo.getTitle());
	    				bookDetailService.BatchBookQrCode(detailList,"私塾家图书馆",dataStr);
					}
    				 
    				   
						if (!fPath.endsWith("/")) {fPath += "/";}
						File  f = new File(file_path+fPath);
						if (!f.exists()) {f.mkdirs();}
					 
    				
    				 BarcodeFactory.linuxZip(file_path,"."+zip, "."+fPath);
					
    				File file = new File(file_path+zip);	
    				FileInputStream fis = new FileInputStream(file);
    				BufferedInputStream buff = new BufferedInputStream(fis);
    				response.setContentType("application/octet-stream;charset=UTF-8");
    				String fileName=new String((result).getBytes("gb2312"), "iso8859-1");
 		            response.setHeader("Content-Disposition", "attachment;filename=" + fileName+"_.zip");
 		            response.setCharacterEncoding("utf-8");
 		            byte[] b = new byte[8096];// 相当于我们的缓存
 					long k = 0;// 该值用于计算当前实际下载了多少字节
 					OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载
 					// 开始循环下载
 					while (k < file.length()) {
 						int j = buff.read(b, 0, 1024);
 						k += j;
 						myout.write(b, 0, j);
 					}
 					buff.close();
 					fis.close();
				} catch (Exception e) {
					logger.error("异常", e);
				}
	 }
		
		@RequestMapping("/libVipSumList")
		public String libVipSumList(Model model,
				@RequestParam(required = false, defaultValue = "10") int pageSize,
				@RequestParam(required = false, defaultValue = "1") int pageNo)
						throws Exception {
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("child_name",request.getParameter("child_name") == null ? "" : request.getParameter("child_name"));
			params.put("level",request.getParameter("level") == null ? "" : request.getParameter("level"));
			params.put("beginDate", request.getParameter("beginDate")==null?DateHelper.format(DateHelper.getTheMonthFirstDay(), "yyyy-MM-dd"):request.getParameter("beginDate"));
			params.put("endDate", request.getParameter("endDate")==null?DateHelper.format(new Date(), "yyyy-MM-dd"):request.getParameter("endDate"));
			params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
			if(!"admin".equals(loginName())){
				params.put("orgCode",orgCodeStr());
			}
			SplitPage sp = new SplitPage();
			sp.setAction(request.getRequestURI().toString());
			sp.setPageNo(pageNo);
			sp.setPageSize(pageSize);
			sp.setParams(params);
			Page<Map<String, Object>> page = libVipServiceService.findForPage(params, initPage(pageNo, pageSize));
			sp.setRowCnt((int) page.getTotalElements());
			model.addAttribute("list", page.getContent());
			model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
			model.addAttribute("page", sp);
			model.addAttribute("search", params);
			model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
			model.addAttribute("cardType", sortService.getParamValByCode("cardType"));
			model.addAttribute("species", sortService.getParamValByCode("species"));
			return "sys/lib/libVipSumList";
		}	
		
		/**
		 * admin下载全部会员卡
		 * @param response
		 * @param request
		 */
		@RequestMapping(value = "/ajaxVipQrCodeAdmin", method = RequestMethod.POST)
		@ResponseBody
		public void ajaxVipQrCodeAdmin(HttpServletResponse response,HttpServletRequest request) {
			try {
				   String file_path = (String) SystemResourceLocator.getValue("file_save_path");
				   String zipPath =DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
				   String fPath = "/VIP"+zipPath;
				   String  result =  DateHelper.format(new Date(), "yyyy_MM_dd");
				   String zip = fPath+"/VIP_"+result+".zip";
					libVipService.vipEnCodeAll();
					if (!fPath.endsWith("/")) {fPath += "/";}
					File  f = new File(file_path+fPath);
					if (!f.exists()) {f.mkdirs();}
					BarcodeFactory.linuxZip(file_path,"."+zip, "."+fPath);
				File file = new File(file_path+zip);
				FileInputStream fis = new FileInputStream(file);
				BufferedInputStream buff = new BufferedInputStream(fis);
				response.setContentType("application/octet-stream;charset=UTF-8");
				response.setHeader("Content-Disposition", "attachment;filename=" + "VIP_"+result+"_.zip");
				response.setCharacterEncoding("utf-8");
				byte[] b = new byte[8096];// 相当于我们的缓存
				long k = 0;// 该值用于计算当前实际下载了多少字节
				OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载
				// 开始循环下载
				while (k < file.length()) {
					int j = buff.read(b, 0, 1024);
					k += j;
					myout.write(b, 0, j);
				}
				buff.close();
				fis.close();
			} catch (Exception e) {
				logger.error("异常", e);
			}
		}
		
		/**
		 * 
		* 创建人:zhanglin
		* @param @param model
		* @param @param pageSize
		* @param @param pageNo
		* @param @return
		* @param @throws Exception       
		* 方法说明：借阅记录查询方法
		 * @date 2017年6月20日 下午5:48:54
		 */
		@RequestMapping("/libUserHistorylist")
		 public String libUserHistorylist(Model model,
		    		@RequestParam(required = false, defaultValue = "10") int pageSize,
		    		@RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("state", request.getParameter("state")== null ? "":request.getParameter("state"));
			 params.put("title", request.getParameter("title")== null ? "":request.getParameter("title"));
			 params.put("child_name", request.getParameter("child_name")== null ? "":request.getParameter("child_name"));
			 params.put("beginDate", request.getParameter("beginDate")==null?"":request.getParameter("beginDate"));
				params.put("endDate", request.getParameter("endDate")==null?"":request.getParameter("endDate"));
				params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
				if(!"admin".equals(loginName())){
					params.put("orgCode", orgCodeStr());
    			}
			    SplitPage sp = new SplitPage();
		        sp.setAction(request.getRequestURI().toString());
		        sp.setPageNo(pageNo);
		        sp.setPageSize(pageSize);
		        sp.setParams(params);
		        Page<Map<String, Object>> page = libUserHistoryService.findForPage(params, initPage(pageNo, pageSize));
			 sp.setRowCnt((int)page.getTotalElements());
			 model.addAttribute("list", page.getContent());
			 model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
	       model.addAttribute("page", sp);
	       model.addAttribute("search", params);
	       model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
		     return "sys/lib/libUserHistorylist";
		 }
		/**
		 * 
		 * @Title: libQGlist
		 * @Description:签到签离
		 * @param @param model
		 * @param @param pageSize
		 * @param @param pageNo
		 * @param @return
		 * @param @throws Exception    设定文件
		 * @return String    返回类型
		 * @author shenhao
		 * @date 2017年7月14日 上午10:54:35
		 * @throws
		 */
		@RequestMapping("/libQGlist")
		 public String libQGlist(Model model,
		    		@RequestParam(required = false, defaultValue = "10") int pageSize,
		    		@RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("child_name", request.getParameter("child_name")== null ? "":request.getParameter("child_name"));
			 params.put("ryke_time", request.getParameter("ryke_time")== null ? "":request.getParameter("ryke_time"));
				params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
				if(!"admin".equals(loginName())){
					params.put("orgCode", orgCodeStr());
    			}
			    SplitPage sp = new SplitPage();
		        sp.setAction(request.getRequestURI().toString());
		        sp.setPageNo(pageNo);
		        sp.setPageSize(pageSize);
		        sp.setParams(params);
		        Page<Map<String, Object>> page = libUserHistoryService.findForQGPage(params, initPage(pageNo, pageSize));
			 sp.setRowCnt((int)page.getTotalElements());
			 model.addAttribute("list", page.getContent());
			 model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
	      model.addAttribute("page", sp);
	      model.addAttribute("search", params);
	      model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
		     return "sys/lib/libQGlist";
		 }
		/**
		 * 
		* 创建人:zhanglin
		* @param @param model
		* @param @param pageSize
		* @param @param pageNo
		* @param @return
		* @param @throws Exception       
		* 方法说明：月度签到签离
		 * @date 2017年6月28日 下午5:39:58
		 */
		@RequestMapping("/libYDlist")
		 public String libYDlist(Model model,
		    		@RequestParam(required = false, defaultValue = "10") int pageSize,
		    		@RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("child_name", request.getParameter("child_name")== null ? "":request.getParameter("child_name"));
			 String date =  DateHelper.format(new Date(), "yyyy-MM");
			 String  monthDate = request.getParameter("monthDate")== null ? date:request.getParameter("monthDate");
			 params.put("monthDate", monthDate);
			 params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
			 if(!"admin".equals(loginName())){
					params.put("orgCode", orgCodeStr());
 			}
			    SplitPage sp = new SplitPage();
		        sp.setAction(request.getRequestURI().toString());
		        sp.setPageNo(pageNo);
		        sp.setPageSize(pageSize);
		        sp.setParams(params);
		        Page<Map<String, Object>> page = libUserHistoryService.findForYDPage(params, initPage(pageNo, pageSize));
		        List<Map<String,Object>> list= page.getContent();
			 sp.setRowCnt((int)page.getTotalElements());
			 model.addAttribute("list", list);
			 model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
	     model.addAttribute("page", sp);
	     model.addAttribute("search", params);
	     model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
		     return "sys/lib/libYDlist";
		 }
		
		/**
		 * 图书列表
		 * @param model
		 * @param pageSize
		 * @param pageNo
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/libBookBaseList")
		public String libBookBaseList(Model model,
				@RequestParam(required = false, defaultValue = "10") int pageSize,
				@RequestParam(required = false, defaultValue = "1") int pageNo)
				throws Exception {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("title",request.getParameter("title") == null ? "" : request.getParameter("title"));
			params.put("isbn13",request.getParameter("isbn13") == null ? "" : request.getParameter("isbn13"));
			params.put("parentTheme",request.getParameter("parentTheme") == null ? "" : request.getParameter("parentTheme"));
			params.put("childTheme",request.getParameter("childTheme") == null ? "" : request.getParameter("childTheme"));
			SplitPage sp = new SplitPage();
			sp.setAction(request.getRequestURI().toString());
			sp.setPageNo(pageNo);
			sp.setPageSize(pageSize);
			sp.setParams(params);
			Page<Map<String, Object>> page = bookBaseService.findForPageList(params, initPage(pageNo, pageSize));
			sp.setRowCnt((int) page.getTotalElements());
			model.addAttribute("list", page.getContent());
			model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
			model.addAttribute("page", sp);
			model.addAttribute("search", params);
			return "sys/lib/libBookBaseList";
		}	
		
	
		 @RequestMapping("/libBookBaseAdd")
		 public String libBookBaseAdd(Model model,@RequestParam( defaultValue = "0")String id) throws Exception {
			 TbLibBookBase info= bookBaseService.getById(id);
			 if(info==null) {
				 info = new TbLibBookBase();
				 info.setIsSerial("1");
			 }else{
				 String iscs = info.getIsSerial();
				 if("2".equals(iscs)){ //是丛书
					 info.setCsisbnshow(info.getIsbn13().replace(info.getCsisbn(),""));
					 info.setIsbnshow(info.getCsisbn());
				 }else{  //非丛书
					 info.setIsbnshow(info.getIsbn13());
				 }
			 }
			 model.addAttribute("book_tags", sortService.getParamValByCode("book_tags"));
			 model.addAttribute("book_ages", sortService.getParamValByCode("book_ages"));
			 model.addAttribute("book_case", sortService.getParamValByCode("book_case"));
			 model.addAttribute("info", info); 
			// model.addAttribute("list", libJoinService.findAll()); 
			 return "sys/lib/libBookBaseAdd";
		 }	
		 
		 @RequestMapping(value = "/libBookBaseSave", method = RequestMethod.POST)
		 @ResponseBody
		 public Response libBookBaseSave(  TbLibBookBase info){
		    	Response response = new  Response();
		    	TbLibBookBase base2 = bookBaseService.findByIsbn13(info.getIsbn13());
		    	if(base2 != null ){
		    		if(base2.getId().equals(info.getId())){
		    			     //同一条数据，更新
		    			info.setUpdateTime(new Date());
				    	bookBaseService.save(info);
				    	response.success();
		    		}else{
		    			//不同数据新增操作，不允许新增编码一样的
		    			response.failure("已存在该isbn号的基础图书，如需更新请查找到原来的图书进行修改！");
		    		}
		    	}else{
		    		if(info.getId()==null || "".equals(info.getId())){
		    			info.setCreateTime(new Date());
		    			info.setUpdateTime(new Date());
		    		}else{
		    			info.setUpdateTime(new Date());
		    		}
		    		
			    	bookBaseService.save(info);
			    	response.success();
		    	}
		    	return response;
		 }	
		 
		 @RequestMapping(value = "/pushNotice", method = RequestMethod.POST)
		    @ResponseBody
		    public Response pushNotice(Model model,String libId){
		    	Response response = new  Response();
		    	List<Map<String, Object>>  list  =libJoinService.pushNotice(libId);
		      if(list!=null && list.size()>0){
					for (Map<String, Object> map : list) {
						   //发送给销售／馆长收到模板消息推
						//pCtMtGwmO9Z6c5kN3F8RVtJxmw0n7dredAl-cCYFWZE
						String child_name = map.get("child_name").toString();
							//会员卡到期通知，家长端收到模板消息推送，动态跳转到购买页面
							// wU5wpGnTXT2jBu0RAlsL1lu6LDfPyT37KZqjiieadH0
							Map<String,String> dataMap =new HashMap<String, String>();
							String league_name = map.get("league_name").toString();
							dataMap.put("first", child_name+"妈妈/爸爸，您好，您为孩子在"+league_name+"购买的会员卡，已经过期\n");
							dataMap.put("keyword1",map.get("details").toString());
							dataMap.put("keyword2",DateHelper.format(DateHelper.parseDate(map.get("end_time").toString(), "yyyy-MM-dd HH:mm:ss.SSS"),"yyyy年MM月dd日 HH:mm ") );
							dataMap.put("remark", "\n请续费");
							 String template_id_short="TM203917139";
							 String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/payment/xuVipBuy_"+libId+".html";
//							 SendTemplate sendTemplate  =new  SendTemplate(map.get("wx_account").toString(),templateId,url,dataMap);
//							NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
							SendTemplateShort templateShort = new SendTemplateShort(map.get("wx_account").toString(), template_id_short, url, dataMap);
							pushTemplateService.savePushWxTemplate(templateShort);
					}
				}
		    	response.success();
		    	return response;
		    }
		 
		 @RequestMapping("/libBookInfoSubject")
		 public String libBookInfoSubject(Model model,@RequestParam( defaultValue = "0")String id) throws Exception {
			 TbLibBookInfo info= libBookService.getById(id);
			 if(StringUtils.isEmpty(info.getIsbn13())){
				 model.addAttribute("error", "本书不存在isbn号,无法添加题目。"); 
			 }else{
//				 List<Map<String, Object>> subjects=readQueryService.findSubjectByIsbn13Page(info.getIsbn13());
//				 model.addAttribute("subjects", subjects); 
			 }
			 model.addAttribute("info", info); 
			 return "sys/lib/libBookInfoSubject";
		 }	
		 
		 @RequestMapping(value = "/saveLibBookInfoSubject", method = RequestMethod.POST)
		 public String saveLibBookInfoSubject(String bookid,String[] ids,String[] titles,String[] answers,String[] correctAnswers,String isbn13_t,Integer level_t,String libId_t){
		    	TbReadSubject tbReadSubject=null;
		    	for (int i = 0; i < titles.length; i++) {
		    		if(StringUtils.isEmpty(titles[i])){
		    			break;
		    		}
		    		tbReadSubject=new TbReadSubject();   
		    		tbReadSubject.setLibId(libId_t);
		    		tbReadSubject.setAnswer(answers[i]);
		    		tbReadSubject.setTitle(titles[i]);
		    		tbReadSubject.setSort(i+1);
		    		tbReadSubject.setCorrectAnswer(correctAnswers[i]);
		    		tbReadSubject.setIsbn13(isbn13_t);
		    		if(ids.length>=i+1){
		    			tbReadSubject.setId(ids[i]);
		    		}
		    		tbReadSubject.setLevel(level_t);
		    		tbReadSubject.setCreateTime(new Date());
		    		//readQueryService.save(tbReadSubject);
				}
		    	return "redirect:/sys/lib/libBookInfoSubject.html?id="+bookid;
		 }	 
		 
		 
	/**
	 * 管理员修改资料
	 * 
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/libManagerEdit")
	public String libManagerEdit(Model model, @RequestParam(defaultValue = "0") String id) throws Exception {
		TbLibManager lib = managerService.getById(id);
		if (lib == null) {
			lib = new TbLibManager();
			// lib.setOrgCode(orgCode());
		}
		
		model.addAttribute("ws", lib);
		return "sys/lib/libManagerEdit";
	}
	@RequestMapping("/libManagerAdd4")
	public String libManagerAdd4(Model model, @RequestParam(defaultValue = "0") String libId) throws Exception {

		model.addAttribute("libId", libId);
		return "sys/lib/libManagerAdd4";
	}
	
	@RequestMapping(value = "/managerSave", method = RequestMethod.POST)
	@ResponseBody
	public Response managerSave(  TbLibManager tbLibManager){
		Response response = new  Response();
		TbLibManager tm = managerService.getById(tbLibManager.getId());
		List<TbLibManager> manageList = managerService.getByUserId(tm.getUserId());
		for(TbLibManager ma:manageList){
			ma.setName(tbLibManager.getName());
			//ma.setTelephone(tbLibManager.getTelephone());
			managerService.save(ma);
		}
		
		response.success();
    	return response;
	}

	@RequestMapping(value = "/managerAddSave", method = RequestMethod.POST)
	@ResponseBody
	public Response managerAddSave(String libId,String name,String mobile){
		Response response = new  Response();
		//查找
		try{
			response = managerService.managerAddSave(libId,name,mobile);
		}catch (Exception e){
			response.failure("保存出现异常，请联系管理员");
			logger.error("添加校长异常",e);
		}
    	return response;
	}
	
	/**
	 * 心愿书单达成列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/libWishList")
	public String libWishList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo,String libId,String orgCode,
			@RequestParam(required = false, defaultValue = "1") String libtype)
					throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("lib_name",request.getParameter("lib_name") == null ? "" : request.getParameter("lib_name"));
//		params.put("libId", libId);
//		params.put("libtype", libtype.equals("1")?"1":"2");
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String, Object>> page = bookBorrowService.findForPage(params, initPage(pageNo, pageSize));
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);
		
		return "sys/lib/libWishList";
	}

	@RequestMapping("/usercount")
	public String usercount(Model model,
							  @RequestParam(required = false, defaultValue = "10") int pageSize,
							  @RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception {

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
		params.put("child_name", request.getParameter("child_name")==null?"":request.getParameter("child_name"));
		params.put("beginDate", request.getParameter("beginDate")==null?DateHelper.format(new Date(), "yyyy-MM-dd"):request.getParameter("beginDate"));
		params.put("endDate", request.getParameter("endDate")==null?DateHelper.format(new Date(), "yyyy-MM-dd"):request.getParameter("endDate"));
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String, Object>> page = userCountService.getUserAll(params, initPage(pageNo, pageSize));
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);

		return "sys/lib/usercount";
	}



	@RequestMapping(value = "/exportDetail", method = RequestMethod.POST)
	@ResponseBody
	public void exportDetail(HttpServletRequest request, HttpServletResponse response) {
		ServletOutputStream os = null;
		try {
			String libId =request.getParameter("libId");
			TbLibJoin lib= libJoinService.getById(libId);
			String libName=lib.getLeagueName()+"统计表";
			os = response.getOutputStream(); //获得输出流
			response.reset();   //清空输出流
			String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
			response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setCharacterEncoding("utf-8");
			Map<String, Object> params = new HashMap<String, Object>();

			params.put("libId", libId);
			params.put("child_name",  request.getParameter("child_name")==null?"":request.getParameter("child_name"));
			params.put("beginDate", request.getParameter("beginDate")==null?DateHelper.format(new Date(), "yyyy-MM-dd"):request.getParameter("beginDate"));
			params.put("endDate", request.getParameter("endDate")==null?DateHelper.format(new Date(), "yyyy-MM-dd"):request.getParameter("endDate"));


			Page<Map<String, Object>> list= userCountService.getUserAll(params, initPage(1,100000));


			List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
			myColumns3.add(new ExcelColumn("学生名字", "child_name", 20));
			myColumns3.add(new ExcelColumn("小塾号", "derver", 20));
			myColumns3.add(new ExcelColumn("学校", "school", 20));
			myColumns3.add(new ExcelColumn("年级", "grade", 20));
			myColumns3.add(new ExcelColumn("类型名称", "type_name", 20));

			myColumns3.add(new ExcelColumn("操作时间", "create_time", 20));


			CustomizeToExcel.downFile(myColumns3, list.getContent(), os);


		}catch (IOException e) {
			logger.error("异常", e);
		}catch (Exception e1){
			logger.error("异常", e1);
		}finally{
			if(os != null){
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					logger.error("异常", e);
				}
			}
		}
	}

}
