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

import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.weixin.libmy.domain.*;
import com.ssj.bean.weixin.order.domain.OrderDetails;
import com.ssj.bean.weixin.push.domain.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.bean.weixin.user.domain.UserIntegral;
import com.ssj.dao.weixin.library.dao.IBookDetailDao;
import com.ssj.dao.weixin.library.dao.IBookDetailQueryDao;
import com.ssj.dao.weixin.library.dao.LibUserHistoryQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.basic.utils.StringUtils;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.BarcodeFactory;
import com.ssj.framework.weixin.util.Collections3;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.framework.weixin.util.WxUtil;
import com.ssj.service.weixin.library.service.*;
import com.ssj.service.weixin.order.service.OrderDetailsService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.UserIntegralService;
import com.ssj.service.weixin.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;


@Service(version="1.0")
@Transactional
public class BookDetailServiceImpl extends BaseServiceImpl<BookDetail, String> implements IBookDetailService {

	@Autowired
	private IBookDetailDao dao;
	
	@Autowired
	private IBookDetailQueryDao queryDao;
	
	@Autowired
	private ILibBookService  infoService;
	
	@Autowired
	private ILibJoinService libJoinService;
	
	 @Autowired
	 private ILibNoVip  noVipService;
	 
	
	
	 @Autowired
	private PushTemplateService pushTemplateService;

	
	@Autowired
    private LibVipServiceService libVipServiceService;
	
	@Autowired
	private IReadVipService vipService;

	@Autowired
	private UserService userService;

	@Autowired
	private IUserChargeService userChargeService;

	@Autowired
	private UserIntegralService integralService;

	@Autowired
	private OrderDetailsService orderDetailsService;

	@Autowired
	private LibUserHistoryService historyService;
	@Autowired
	private IBookSwitchInfoService switchInfoService;

	@Autowired
	private LibUserHistoryQueryDao libUserHistoryQueryDao;
	
	@Override
	public PagingAndSortingRepository<BookDetail, String> getDao() {
		
		return dao;
	}

	@Override
	public Map<String, Object> searchBookInfo(String id) {
		
		return queryDao.searchBookInfo(id);
	}

	@Override
	public BookDetail findById(String id) {
		
		return dao.findById(id);
	}

	@Override
	public List<Map<String, Object>> findBookList(String userId,String vipId) {
		
		return queryDao.findBookList(userId, vipId);
	}

	@Override
	public void saveOrderDetail(String id, String money, String userId,String userId2, LibVipService vip) {
		BookDetail detail = this.getById(id);
		TbLibBookInfo info = infoService.getById(detail.getInfoId());

		Date now = new Date();
		//订单数据
		OrderDetails orderDetails = new OrderDetails();
		orderDetails.setIsClose("2");
		orderDetails.setCreateTime(now);
		orderDetails.setAuthor(info.getAuthor());
		orderDetails.setTitle(info.getTitle());
		orderDetails.setBookDetailId(id);
		orderDetails.setMoney("1");
		orderDetails.setManagerUserid(userId2);
		orderDetails.setUserId(userId);
		orderDetails.setVipId(vip.getVipId());
		orderDetails.setLibId(detail.getLibId());
		orderDetails.setBookTheme(info.getChildTheme());
		orderDetails.setBookImg(info.getLocalImage());
		orderDetails.setSummary(info.getSummary());
		orderDetailsService.save(orderDetails);

		//书籍数据
		detail.setVipId(vip.getVipId());
		detail.setUserId(userId);
		detail.setType(2);
		detail.setBackBookTime(DateUtil.addDays(now,vip.getBorrowDay()));
		detail.setBorrowedTime(now);
		this.save(detail);
		
		//插入历史记录
		LibUserHistory history = new LibUserHistory();
		history.setUserId(userId);
		history.setAuthor(info.getAuthor());
		history.setTitle(info.getTitle());
		history.setBookDetailId(id);
		history.setMoney(1);
		history.setDetailId(orderDetails.getId());
		history.setOrderType(1);
		history.setStart_time(now);
		history.setEnd_time(detail.getBackBookTime());
		history.setVipId(vip.getVipId());
		history.setLibId(detail.getLibId());
		history.setBookTheme(info.getChildTheme());
		history.setBookImg(info.getLocalImage());
		history.setSummary(info.getSummary());
		historyService.save(history);
		//dao.saveCommonOrder(id,1,userId);
	}

	@Override
	public void backBook(String id, String userId) {
		//先查询这本书是否逾期
		//修改书本状态
		BookDetail bookDetail = this.getById(id);
		//update tb_lib_book_detail set type=1,user_id=null,vip_id=null,borrowed_time=null,back_book_time=null where id in (?1)
		bookDetail.setType(1);
		bookDetail.setUserId(null);
		bookDetail.setVipId(null);
		bookDetail.setBorrowedTime(null);
		bookDetail.setBackBookTime(null);
		this.save(bookDetail);
		//dao.backBook(id);
		OrderDetails orderDetails = orderDetailsService.findbyBookDetailId(id);
		//修改订单状态 set is_close='1',update_time=NOW()
		//dao.updateOrderStat(id);
		if(orderDetails!=null){
			orderDetails.setIsClose("1");
			orderDetails.setUpdateTime(new Date());
			orderDetailsService.save(orderDetails);
		}

	}

	@Override
	public List<BookDetail> bookDetailByInfoId(String infoId) {
		return dao.bookDetailByInfoId(infoId);
	}

	@Override
	public void bookenCode(String infoId, String library, String bookName) throws Exception {
		if(library ==null) { library="私塾家图书馆";}
		if(bookName ==null) { bookName="图书";}
		List<BookDetail> booklist=	this.bookDetailByInfoId(infoId);
		if(booklist !=null && booklist.size()>0){
			String file_path = (String) SystemResourceLocator.getValue("file_save_path");
			String fPath = "/BOOK/"+library;
			fPath += DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
			if (!fPath.endsWith("/")) {
				fPath += "/";
			}
			fPath +=bookName +"/";
			File  f = new File(file_path+fPath);
			if (!f.exists()) {
				f.mkdirs();
			}
			String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/bkManager/initBorrowCar_BOOKDetails.html";
			for (BookDetail bookDetail : booklist) {
				String fPathId = fPath + bookDetail.getId() + ".bmp";
				url=url.replace("BOOKDetails", bookDetail.getId());
				BarcodeFactory.bookencode(url,bookDetail.getFlowId(),file_path+fPathId,270, 270);
				bookDetail.setQrUrl(fPathId);
				bookDetail.setStat(2);
				this.save(bookDetail);
			}
		}
	}

	@Override
	public List<String> weChatBookEnCode(List<BookDetail> list, String libId,
			String bookName) throws Exception {
		TbLibJoin  libJoin  =libJoinService.getById(libId);
		String file_path = (String) SystemResourceLocator.getValue("file_save_path");
		String fPath = "/BOOK/"+libJoin.getLeagueName();
		fPath += DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
		if (!fPath.endsWith("/")) {
			fPath += "/";
		}
		fPath +=bookName +"/";
		File  f = new File(file_path+fPath);
		if (!f.exists()) {
			f.mkdirs();
		}
		String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/bkManager/initBorrowCar_BOOKDetails.html";
		List<String> listStr = new ArrayList<String>();
		for (BookDetail bookDetail : list) {
			String fPathId = fPath + bookDetail.getId() + ".bmp";
			url=url.replace("BOOKDetails", bookDetail.getId());
			BarcodeFactory.bookencode(url,bookDetail.getFlowId(),file_path+fPathId,270, 270);
			bookDetail.setQrUrl(fPathId);
			bookDetail.setStat(2);
			this.save(bookDetail);
			listStr.add(fPathId);
		}
		return listStr;
	}

	
	@Override
	public List<Map<String, Object>> backBookList(String id,String userId) {
		
		return queryDao.backBookList(id,userId);
	}

	@Override
	public void updateMoney(String userId, BigDecimal i, BigDecimal j) {
		//dao.updateMoney(userId,i,j);
	}

	@Override
	public List<Map<String, Object>> getOrderList(String id, String userId) {
		
		return queryDao.getOrderList(id,userId);
	}

	@Override
	public void saveContinueOrder(String id, String money, String userId) {
		
		//扣钱
	//	dao.updateUserMoney(userId,Integer.parseInt(money));
		//保存数据(插入续借订单)
		dao.saveContinueOrder(id,1,userId);
		//更新状态
		dao.updateDetailStat2(id,userId);
	}

	@Override
	public void saveOverdueOrder(String ids, BigDecimal yqDay, String userId) {
		
		dao.saveOverdueOrder(ids,yqDay,userId);
	}

	@Override
	public List<Map<String, Object>> jsBookList(String id, String userId,LibReadVip vip) {
		
		return queryDao.jsBookList(id,userId,vip);
	}

	@Override
	public Map<String, Object> getOrderDetail(String id, String userId) {
		String detailIds = id.replace(",", "','");
		return queryDao.getOrderDetail(detailIds,userId);
	}

	@Override
	public List<Map<String, Object>> getManagerList(String bookId) {
		
		return queryDao.getManagerList(bookId);
	}

	@Override
	public List<Map<String, Object>> libManageList(String id) {
		return queryDao.libManageList(id);
	}

	@Override
	public Map<String, Object> getLibBookCounts(String libId,String stat) {
		
		return queryDao.getLibBookCounts(libId,stat);
	}

	@Override
	public List<Map<String, Object>> getBookInfoList(String libId) {
		
		return queryDao.getBookInfoList(libId);
	}

	@Override
	public List<Map<String, Object>> getBookDriftList(String id, String userId) {
		
		return queryDao.getBookDriftList(id,userId);
	}

	@Override
	public Map<String, Object> getDirftDetail(String oldUserId, String detailId,String userId) {
		
		return queryDao.getDirftDetail(oldUserId,detailId,userId);
	}

	@Override
	public Map<String, Object> getBookInfo(String id) {
		
		return queryDao.getBookInfo(id);
	}

	@Override
	public void sendBookOverMsg() {
		List<Map<String, Object>> list = queryDao.sendBookOverMsg();
		Map<String, String> data = new HashMap<String, String>();
		/**
		 * XX家长您好，您在我馆借阅的图书即将到期，请及时准备归还
			图书名称：《xx》、《xx》
			到期时间：2017-6-3
			剩余天数：xx天
			
			再次扫码查看此图书的漂流轨迹，可分享孩子的阅读心得哦。

		 */
		String template_id_short="OPENTM206044974";
		String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/bkManager/borrowSuccess_VIPID.html";
		if(list != null && list.size()>0){
			for(Map<String, Object> map:list){
				int sendDay = Integer.parseInt(map.get("day1").toString());
				if(sendDay>=0 || sendDay==-3 || sendDay==-6 || sendDay==-9){
					String[] bookArr = map.get("title").toString().split(",");
					String bookName = "";
					for(int i= 0;i<bookArr.length;i++){
						bookName +="《"+bookArr[i]+"》";
						if(i>0 && i<bookArr.length-1){
							bookName +="、";
						}
					}
					data.put("first",map.get("child_name").toString()+"妈妈/爸爸，您好，您在我馆借阅的图书"+(sendDay>=0?"即将到期，请及时准备归还":"已过期，请及时归还"));
					data.put("keyword1",bookName);
					data.put("keyword2", map.get("days2").toString());
					data.put("remark", (sendDay>=0?"剩余天数："+sendDay:"过期天数："+Math.abs(sendDay))+"\n再次扫码查看此图书的漂流轨迹，可分享孩子的阅读心得哦。");
					SendTemplateShort templateShort = new SendTemplateShort(map.get("wx_account").toString(), template_id_short, url.replace("VIPID", map.get("id").toString()), data);
					pushTemplateService.savePushWxTemplate(templateShort);
				}

			}
		}
		
		
	}



	@Override
	public List<Map<String, Object>> getDetailQrList(String libId) {
		
		return queryDao.getDetailQrList(libId);
	}

	@Override
	public void BatchBookQrCode(List<Map<String, Object>> detailList,String libName,String dataStr) throws Exception {
		
		if(detailList !=null && detailList.size()>0){
			String file_path = (String) SystemResourceLocator.getValue("file_save_path");
			String fPath = "";
			int pageSize = Integer.parseInt((String) SystemResourceLocator.getValue("export_page_size"));
//			File  f = new File(file_path+fPath);
//			if (!f.exists()) {
//				f.mkdirs();
//			}
		
			List<BookDetail> list = new ArrayList<BookDetail>();
			int i=0;
			for (Map<String, Object> map : detailList) {
				BookDetail bookDetail = this.findById(map.get("id").toString());
				if(i%pageSize ==0 || i==0){
					fPath = "/BOOK/"+dataStr+"/";
					fPath +=libName ;
					fPath+="/"+i;
					if (!fPath.endsWith("/")) {
						fPath += "/";
					}
					File  f2 = new File(file_path+fPath);
					if (!f2.exists()) {
						f2.mkdirs();
					}
				}
				String fPathId = fPath + bookDetail.getFlowId() + ".bmp";
				String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/bkManager/initBorrowCar_BOOKDetails.html";
				url=url.replace("BOOKDetails", bookDetail.getId());
				
				BarcodeFactory.bookencode(url,bookDetail.getFlowId(),file_path+fPathId,378, 378);
				bookDetail.setQrUrl(fPathId);
				bookDetail.setStat(2);
				list.add(bookDetail);
				if(list.size()%1000==0){
					this.save(list);
					list.clear();
				}
				i++;
			}
			this.save(list);
			
		}
		
	}

	@Override
	public List<Map<String, Object>> findServiceList(String userId,String libId) {
		
		return queryDao.findServiceList(userId,libId);
	}

	@Override
	public Map<String, Object> findVipServiceByVip(String vipid) {
		
		return queryDao.findVipServiceByVip(vipid);
	}

	@Override
	public Integer getLibBkDetailCount(String libId) {
		
		return dao.getLibBkDetailCount(libId);
	}

	@Override
	public Integer getLibBkInCount(String libId) {
		
		return dao.getLibBkInCount(libId);
	}

	@Override
	public List<Map<String, Object>> getLIbBkTagDetail(String libId) {
		
		return queryDao.getLIbBkTagDetail(libId);
	}

	@Override
	public Page<Map<String, Object>> libBookList(Map<String, Object> params, Pageable pageable) {
		
		return queryDao.libBookList(params,pageable);
	}

	@Override
	public Map<String, Object> findMyMap(String libId, String type) {
		
		return queryDao.findMyMap(libId,type);
	}

	@Override
	public Page<Map<String, Object>> BookWeekList(Map<String, Object> params, Pageable pageable) {
		
		return queryDao.BookWeekList(params,pageable);
	}

	@Override
	public List<Map<String, Object>> getUserBookDetail(String vipId, String rq,String libId,String type) {
		
		return queryDao.getUserBookDetail(vipId,rq,libId,type);
	}

	@Override
	public List<Map<String, Object>> getDateBorrowList(String libId, String sdate,String type) {
		
		return queryDao.getDateBorrowList(libId,sdate,type);
	}

	@Override
	public List<Map<String, Object>> adminCallBack(Map<String, Object> params) {
		
		return queryDao.adminCallBack(params);
	}

	@Override
	public Map<String, Object> borrowInfoWeek(String vipId, String userId,String stat) {
		
		return queryDao.borrowInfoWeek(vipId,userId,stat);
	}

	@Override
	public Map<String, Object> getRankCheck(LibReadVip vip, String userId, String libId) {
		
		return queryDao.getRankCheck(vip,userId,libId);
	}

	@Override
	public Map<String, Object> getLibRank(String libId) {
		
		return queryDao.getLibRank(libId);
	}

	@Override
	public List<Map<String, Object>> getOrderUserList(String id) {
		String detailIds = id.replace(",", "','");
		return queryDao.getOrderUserList(detailIds);
	}

	@Override
	public List<Map<String, Object>> findBorrowList(String infoId) {
		
		return queryDao.findBorrowList(infoId);
	}

	@Override
	public List<Map<String, Object>> getByLibIdList(String libId) {
		return queryDao.getByLibIdList(libId);
	}

	@Override
	public Integer borrowedByVipId(String vipId, String libId) {
		return dao.borrowedByVipId(vipId, libId);
	}

	@Override
	public List<Map<String, Object>> haveToBorrow(String vipId, String libId) {
		return queryDao.haveToBorrow(vipId, libId);
	}

	@Override
	public void saveBorrowBooks(List<String> bookDetailsId, String borrowUserId, String vipId) {
		LibReadVip vip = vipService.getById(vipId);
		for (String detailId : bookDetailsId) {
			BookDetail detail = this.getById(detailId);
			LibVipService vservice = libVipServiceService.getVipIdPTService(vipId, detail.getLibId());
			this.saveOrderDetail(detailId,"1",vip.getUserId(),borrowUserId,vservice);
			TbLibBookInfo bookInfo = infoService.getById(detail.getInfoId());
			//更新剩余库存
			bookInfo.setBookStockRemain(bookInfo.getBookStock()-1);
			infoService.save(bookInfo);
			//更新预约数据()
			dao.updateBorrowData(bookInfo.getIsbn13(),vipId,bookInfo.getLibId());
		}		
	}

	@Override
	public List<Map<String, Object>> findBorrowedList(List<String> bookDetailsId) {
		
		return queryDao.findBorrowedList(bookDetailsId);
	}

	@Override
	public Integer getbooksByLibId(String libId) {
		return dao.getbooksByLibId(libId);
	}

	@Override
	public Integer getbooksBorrowingByLibId(String libId) {
		return dao.getbooksBorrowingByLibId(libId);
	}

	@Override
	public Page<Map<String, Object>> getbooksList(Map<String, Object> params,
			Pageable pageable) {
		return queryDao.getbooksList(params, pageable);
	}

	@Override
	public Page<Map<String, Object>> getGoodBooksToRead(
			Map<String, Object> params, Pageable pageable) {
		return queryDao.getGoodBooksToRead(params, pageable);
	}


	@Override
	public Page<Map<String, Object>> getCallOutOrInList(String libId, int type,Pageable pageable) {
		return queryDao.getCallOutOrInList(libId, type,pageable);
	}

	@Override
	public List<BookDetail> findInList(String libId) {
		
		return dao.findInList(libId);
	}

	@Override
	public void updateStep2(String libId,int type) {
		dao.updateStep2(libId,type);
	}

	@Override
	public void updateStep(String libId,int type) {
		dao.updateStep(libId,type);
	}

	@Override
	public ResponseEntity saveBorrow(Map<String, String> param, LibReadVip vip,User user) {
		ResponseEntity response = new ResponseEntity();
		//通过userId 查询管理员所在的图书馆
		//id = id.replace(",", "','");
		//往订单详情表内插入记录
		//借书就扣钱
		String id = param.get("id");
		String vipid = param.get("vipid");
		//String money = param.get("money");
//		String borrowUserId = param.get("borrowUserId");
		String userId = param.get("userId");
		String libId = "";
		String[] idArr = id.split(",");
		for (String ids : idArr) {
			BookDetail detail = this.getById(ids);
			LibVipService vservice = libVipServiceService.getVipIdPTService(vipid, detail.getLibId());
			libId = detail.getLibId();
			this.saveOrderDetail(ids, "1", user.getId(), userId, vservice);
		}


		//推送模板消息给用户
		/**
		 *  {{first.DATA}}
		 订单名称：{{keyword1.DATA}}
		 订单状态：{{keyword2.DATA}}
		 确认时间：{{keyword3.DATA}}
		 {{remark.DATA}}

		 您好， 共计xx本绘本借阅成功。
		 订单名称：私塾家*家庭图书馆借阅
		 订单状态：已支付
		 订单确认时间：xx年x月xx日 xx : xx
		 归还绘本时间：xx年x月xx日 xx : xx
		 本次订单充值金额：xx元（没有充值就隐藏）

		 记得按时归还，宝宝未看完绘本可再次扫码续借哦
		 */
		Map<String, String> data = new HashMap<String, String>();
		String template_id_short = "OPENTM408917121";
		String ChildName = "";
		if (vip == null) {
			ChildName = user.getName();
		} else {
			if (vip.getChildName() == null) {
				ChildName = user.getName();
			} else {
				ChildName = vip.getChildName();
			}
		}
		Map<String, Object> borrowInfo = this.borrowInfoWeek(vip==null?"":vip.getId(), userId, "2");

		String conStr = "";
		if (vip != null) {
			Map<String, Object> rankCheck = this.getRankCheck(vip, userId, libId);
			conStr = "，您孩子外借书籍的频次已成功超越" + rankCheck.get("outrank")==null?"99%":rankCheck.get("outrank") + "的小会员";
		}

		data.put("first", ChildName + "妈妈/爸爸，您好。近一周已成功借阅" + borrowInfo.get("borrow_count") + "本图书" + conStr + "。\n");
		List<Map<String, Object>> orderList = this.getOrderList(id, user.getId());
		String firstDate = "";
		String keywords1 = "";
		int i = 0;
		for (Map<String, Object> map : orderList) {
			if (i == 0) {
				firstDate = map.get("back_book_time").toString();
			} else {
				if (firstDate.compareTo(map.get("back_book_time").toString()) > 0) {
					firstDate = map.get("back_book_time").toString();
				}
			}
			keywords1 += "《" + map.get("title") + "》";
			if (i < orderList.size() - 1) {
				keywords1 += "、";
			}
			i++;
		}
		data.put("keyword1", ChildName);
		data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
		data.put("keyword3", keywords1);
		//查询

		String url = (String) SystemResourceLocator.getValue("sys_url") + "/weixin/mylib/myBorrowInfo_" + vipid + ".html";
		TbLibJoin join = libJoinService.getById(libId);
		StringBuilder remark = new StringBuilder();
		remark.append("借阅状态：已借阅  \n");
		remark.append("应归还时间：").append(firstDate).append("\n\n");
		remark.append("借阅所在图书馆：").append(join.getLeagueName()).append("\n\n");
		remark.append("再次扫码查看此图书的漂流轨迹，可分享孩子的阅读心得哦。");
		data.put("remark", remark.toString());
		//NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(),  new  SendTemplate(user.getAccount(),template_id,url,data));
		SendTemplateShort templateShort = new SendTemplateShort(user.getAccount(), template_id_short, url, data);
		pushTemplateService.saveAndSendPushWxTemplate(templateShort);
		data.clear();


		String adminUrl = (String) SystemResourceLocator.getValue("sys_url") + "/weixin/adminbook/borrowRecode_2.html";
		List<Map<String, Object>> managerList = this.getManagerList(idArr[0]);
		//String libId = managerList.get(0).get("lib_id").toString();
		Map<String, Object> countBooks = this.getLibBookCounts(libId, "2");
		//Map<String, Object>  libRank = detailService.getLibRank(libId);
        String userCount = countBooks.get("user_count")==null?"1":countBooks.get("user_count").toString().equals("0")?"1":countBooks.get("user_count").toString();
        String borrowCount = countBooks.get("borrow_count")==null?"1":countBooks.get("borrow_count").toString();
		data.put("first", "馆长，您好。近一周已有" + userCount + "位会员成功借阅" + borrowCount + "本图书。\n");
		data.put("keyword3", keywords1);
		data.put("keyword1", ChildName);
		data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
		StringBuilder remarks = new StringBuilder();
		remarks.append("借阅状态：已借阅\n");
		remarks.append("应归还时间：").append(firstDate).append("\n\n");
		remarks.append("更多借阅详情可点击查看。");
		data.put("remark", remarks.toString());
		for (Map<String, Object> map : managerList) {
			SendTemplateShort templateShort2 = new SendTemplateShort(map.get("wx_account").toString(), template_id_short, adminUrl, data);
			pushTemplateService.saveAndSendPushWxTemplate(templateShort2);
			//NewsUtil.sendTemplate(tokenManager.getSSJAccessToken(),  new  SendTemplate(map.get("wx_account").toString(),template_id,adminUrl,data));
		}

		response.success("保存成功");
		return response;
	}


	@Override
	public ResponseEntity backBorrwBook(String id, String vipId) {
		ResponseEntity response = new ResponseEntity();
		String[] idArr = id.split(",");
		BookDetail detail2 = this.getById(idArr[0]);
		User user2 = userService.getById(detail2.getUserId());
		BigDecimal outlay = new BigDecimal(0);
		List<Map<String,Object>> orderList = this.getOrderList(id,user2.getId());
		LibReadVip vip = vipService.getById(vipId);
		//查询还书的是不是同一个用户
		List<Map<String,Object>> userList = this.getOrderUserList(id);
		if(userList.size()>1){
			response.failure("所还书籍并不是一个用户所借阅，批量还书请选择同一用户还书！");
			return response;
		}

		for(String ids :idArr){
			BookDetail detail = this.findById(ids);
			this.backBook(ids,detail.getUserId());  //没过期
		}

		String ChildName = "";
		if(vip == null){
			ChildName = user2.getName();
		}else{
			if(vip.getChildName() == null){
				ChildName = user2.getName();
			}else{
				ChildName = vip.getChildName();
			}
		}
		String keywords1 = "";
		int i=0;
		for(Map<String,Object> map:orderList){
			keywords1+="《"+map.get("title")+"》";
			if(i<orderList.size()-1){
				keywords1 +="、";
			}
			i++;
		}

		UserIntegral userIntegral = integralService.findByUserId(user2.getId());
		String remark = "";
		StringBuilder remarks = new StringBuilder();
		remarks.append("借阅状态：已归还\n ");
		if(vip == null){
			remark = "借阅状态：已归还\n订单结算金额："+(outlay.add(new BigDecimal(idArr.length)))+"元  \n\n本次借阅费用共计"+(outlay.add(new BigDecimal(idArr.length)))+"元,您的账户余额为"+userIntegral.getUser_ye()+"元\n\n感谢您的使用，可点击查看借阅详情";
			remarks.append("订单收益金额："+(outlay.add(new BigDecimal(idArr.length)))+"元  \n\n更多借阅详情可点击查看。");
		}else{
			remark = "借阅状态：已归还\n\n感谢您的使用，可点击查看借阅详情。";
			remarks.append(" \n更多借阅详情可点击查看。");
		}
		Map<String, Object>  borrowInfo = this.borrowInfoWeek(vip==null?"":vip.getId(),user2.getId(),"1");
		String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/mylib/toMyBorrowHis_"+vip.getId()+".html";
		Map<String,String> data =new HashMap<String, String>();
		String template_id_short="OPENTM408917121";
		data.put("first", ChildName+"妈妈/爸爸，您好。近一周已成功归还"+borrowInfo.get("borrow_count")+"本图书。\n");
		data.put("keyword1",ChildName);
		data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
		data.put("keyword3",keywords1);
		data.put("remark", remark);
		SendTemplateShort templateShort = new SendTemplateShort(user2.getAccount(), template_id_short, url, data);
		pushTemplateService.saveAndSendPushWxTemplate(templateShort);
		data.clear();

		String adminUrl=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/adminbook/borrowRecode_1.html";
		List<Map<String,Object>> managerList = this.getManagerList(idArr[0]);
		String libId = managerList.get(0).get("lib_id").toString();
		Map<String, Object>  countBooks = this.getLibBookCounts(libId,"1");
		String userCount = countBooks.get("user_count")==null?"1":countBooks.get("user_count").toString().equals("0")?"1":countBooks.get("user_count").toString();
		String borrowCount = countBooks.get("borrow_count")==null?"1":countBooks.get("borrow_count").toString();
		data.put("first","馆长，您好。近一周已有"+userCount+"位会员成功归还"+borrowCount+"本图书。\n");
		data.put("keyword1",ChildName);
		data.put("keyword3",keywords1);
		data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
		data.put("remark", remarks.toString());
		for(Map<String,Object> map:managerList){
			SendTemplateShort templateShort2 = new SendTemplateShort(map.get("wx_account").toString(), template_id_short, adminUrl, data);
			pushTemplateService.saveAndSendPushWxTemplate(templateShort2);
		}
		response.success("保存成功");
		return response;
	}

	@Override
	public ResponseEntity saveBorrowBooksNew(List<String> bookDetails, String borrowUserId, String vipId) throws Exception {
		ResponseEntity responseEntity = new ResponseEntity();
		BookDetail detail = this.getById(bookDetails.get(0));
		LibVipService libVipService=libVipServiceService.getVipIdPTService(vipId, detail.getLibId());
		int borrowNum = libVipService!=null?libVipService.getBorrowNum():0;
		int canBorrowNum=borrowNum==0?0:borrowNum - this.borrowedByVipId(vipId, detail.getLibId());
		if(canBorrowNum<0){
			responseEntity.failure(ResponseConstant.CODE_000, "您已不能借更多书了，请还书后再借阅！");
			return responseEntity;
		}
		if(canBorrowNum<bookDetails.size()){
			responseEntity.failure(ResponseConstant.CODE_000, "您已经超过借阅上限，读完再借吧！");
			return responseEntity;
		}
		LibReadVip vip = vipService.getById(vipId);
		for (String detailId:bookDetails){

			BookDetail book = this.getById(detailId);
			if(StringUtils.isNotEmpty(book.getUserId())){
				TbLibBookInfo bookInfo = infoService.getById(book.getInfoId());
				throw  new Exception(bookInfo.getTitle()+"已被别人抢先借走,请换一本借阅!");
			}
			this.saveOrderDetail(detailId,"1",vip.getUserId(),borrowUserId,libVipService);
		}

		//推送通知
		//pushSaveBorrow(bookDetails,vip,borrowUserId,libVipService.getLibId());

		responseEntity.success("加入成功");
		return  responseEntity;
	}
    @Override
	public void pushSaveBorrow(List<String> bookDetails, LibReadVip vip,String userId,String libId){
		String template_id_short = "OPENTM408917121";
		String ChildName = vip.getChildName();
		Map<String,String> data = new HashMap<>(16);
		String keywords1 = "";
		List<Map<String,Object>> userList = libUserHistoryQueryDao.getBackDetailList(bookDetails);
		if(Collections3.isNotEmpty(userList)){
			Map<String, Object> borrowInfo = this.borrowInfoWeek(vip.getId(), userId, "2");
			Map<String, Object> rankCheck = this.getRankCheck(vip, userId, libId);
			Map<String,Object> map = userList.get(0);
			String conStr = "，您孩子外借书籍的频次已成功超越" + rankCheck.get("outrank")==null?"99%":rankCheck.get("outrank") + "的小会员";
			data.put("first", ChildName + "妈妈/爸爸，您好。近一周已成功借阅" + borrowInfo.get("borrow_count")==null?"1":borrowInfo.get("borrow_count") + "本图书" + conStr + "。\n");
			keywords1 = map.get("title").toString();
			data.put("keyword1", ChildName);
			data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
			data.put("keyword3", keywords1);
			TbLibJoin join = libJoinService.getById(libId);
			StringBuilder remark = new StringBuilder();
			remark.append("借阅状态：已借阅  \n");
			remark.append("应归还时间：").append(map.get("back_book_time")).append("\n\n");
			remark.append("借阅所在图书馆：").append(join.getLeagueName()).append("\n\n");
			data.put("remark", remark.toString());
			Miniprogram miniprogram = new Miniprogram();
			miniprogram.setAppid(WxUtil.map.get("readingAppId"));
			miniprogram.setPagepath("parents/pages/borrow_record/borrow_record?navIndex=0&vipId="+vip.getId()+"&libId="+libId);
			SendTemplateShort templateShort = new SendTemplateShort(map.get("wx_account").toString(), template_id_short,null, data,miniprogram);
			pushTemplateService.saveAndSendPushWxTemplate(templateShort);
			data.clear();
			List<Map<String, Object>> managerList = this.getManagerList(bookDetails.get(0));
			Map<String, Object> countBooks = this.getLibBookCounts(libId, "2");
			String userCount =countBooks==null?"1":countBooks.get("user_count")==null?"1":countBooks.get("user_count").toString().equals("0")?"1":countBooks.get("user_count").toString();
			String borrowCount =countBooks==null?"1":countBooks.get("borrow_count")==null?"1":countBooks.get("borrow_count").toString();
			data.put("first", "馆长，您好。近一周已有" + userCount + "位会员成功借阅" + borrowCount + "本图书。\n");
			data.put("keyword3", keywords1);
			data.put("keyword1", ChildName);
			data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
			StringBuilder remarks = new StringBuilder();
			remarks.append("借阅状态：已借阅\n");
			remarks.append("应归还时间：").append(map.get("back_book_time")).append("\n\n");
			remarks.append("更多借阅详情可点击查看。");
			data.put("remark", remarks.toString());
			Miniprogram miniprogram2 = new Miniprogram();
			miniprogram2.setAppid(WxUtil.map.get("readingAppId"));
			miniprogram2.setPagepath("president/pages/borrow_record/borrow_record?navIndex=0&type=1&libId="+libId);
			for (Map<String, Object> map2 : managerList) {
				SendTemplateShort templateShort2 = new SendTemplateShort(map2.get("wx_account").toString(), template_id_short, null, data,miniprogram2);
				pushTemplateService.saveAndSendPushWxTemplate(templateShort2);
			}
		}
	}

	@Override
	public Page<Map<String, Object>> getBooksAndLibIdAndchildTheme(Pageable pageable, Map<String, Object> params) {
		return queryDao.getBooksAndLibIdAndchildTheme(params, pageable);
	}

	/**
	 * 日期比较
	 *
	 * @param fDate
	 * @param oDate
	 * @return
	 */
	public static BigDecimal daysOfTwo(Date fDate, Date oDate) {

		Calendar aCalendar = Calendar.getInstance();

		aCalendar.setTime(fDate);

		int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

		aCalendar.setTime(oDate);

		int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

		return new BigDecimal(day2 - day1);

	}
}
