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.push.domain.SendTemplateShort;
import com.ssj.dao.weixin.library.dao.BookBorrowQueryDao;
import com.ssj.dao.weixin.library.dao.IBookBorrowDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.weixin.util.Collections3;
import com.ssj.service.reading.request.BookRecommendReq;
import com.ssj.service.reading.request.ConfirmLibReq;
import com.ssj.service.reading.request.DispatcherAuditReq;
import com.ssj.service.weixin.library.dto.out.BookScanViewOutDto;
import com.ssj.service.weixin.library.service.*;
import com.ssj.service.weixin.push.service.PushTemplateService;
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.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.text.NumberFormat;
import java.util.*;


/** 
 * @author  ZhangCaibao 
 * @version 2018年8月15日 下午4:31:43 
 * 类说明 
 */
@Service(version="1.0")
@Transactional
public class BookBorrowServiceImpl extends BaseServiceImpl<TbLibBookBorrow, String> implements IBookBorrowService{
   @Autowired
	private IBookBorrowDao bookBorrowDao;
   @Autowired
   private BookBorrowQueryDao queryDao;
   
   @Autowired
   private ILibJoinService joinService;
	@Autowired
	private ILibBookService bookService;
	@Autowired
	private IBookDetailService bookDetailService;
	
	@Autowired
	private ILIbBookSwitchService switchService;
	
	@Autowired
	private IBookSwitchInfoService switchInfoService;
	
	@Autowired
	private LibBookLockingService lockingService;
	
	@Autowired
	 private ILibCancelService cancelService;

	@Autowired
	private TokenManager tokenManager;

	@Autowired
	private IBookManagerService managerService;

	@Autowired
	private PushTemplateService pushTemplateService;
	
   private String[] strarr =new String[]{"助你一臂之力！", 
"这本书很棒，我也想看！ ", 
"小心愿，大世界，助力心愿达成！ ", 
"赶快拿下你的心愿单吧~ ", 
"在知识的海洋遨游，心愿早日达成。"};
	@Override
	public PagingAndSortingRepository<TbLibBookBorrow, String> getDao() {
		return bookBorrowDao;
	}
	@Override
	public void addBookBorrow(String libId, String userId, String vipId,
			String isbn13, Integer type) {
		TbLibBookBorrow  bookBorrow=	bookBorrowDao.findByLibIdAndUserIdAndIsbnAndType(libId, userId, vipId, isbn13,type);
		if(bookBorrow!=null){
			bookBorrow.setStat(1);
		}else{
			bookBorrow = new TbLibBookBorrow(isbn13, userId, vipId, type, 1, libId,1);
		}
		this.save(bookBorrow);
	}
	@Override
	public TbLibBookBorrow findByLibIdAndVipIdAndIsbn13(String libId,
			String vipId, String isbn13, Integer type) {
		return bookBorrowDao.findByLibIdAndVipIdAndIsbn13(libId, vipId, isbn13, type);
	}
	@Override
	public Page<Map<String, Object>> myWish(Map<String, Object> params,
			Pageable pageable) {
		return queryDao.myWish(params, pageable);
	}
	@Override
	public Page<Map<String, Object>> othersWish(Map<String, Object> params,
			Pageable pageable) {
		return queryDao.othersWish(params, pageable);
	}
	@Override
	public Map<String, Object> wishDetails(String isbn13,String vipId ,String libId) {
		return queryDao.wishDetails(isbn13,vipId, libId);
	}
	@Override
	public List<Map<String, Object>> wishUserList(String isbn13, String vipId,String userId,String libId) {
		List<Map<String, Object>>  list =queryDao.wishUserList(isbn13, vipId,userId,libId);
		if(list!=null &&list.size()>0){
			for (Map<String, Object> map : list) {
				int number = new Random().nextInt(5) + 1;
				if(number>4){
					number=4;
				}
				map.put("content", strarr[number]);
			}
		}
		return list;
	}
	@Override
	public Page<Map<String, Object>> getLibJoinDispatcher(Map<String, Object> params, Pageable pageable) {
		
		return queryDao.getLibJoinDispatcher(params,pageable);
	}
	@Override
	public Page<Map<String, Object>> libDispatchingList(Map<String, Object> params, Pageable pageable) {
		
		return queryDao.libDispatchingList(params,pageable);
	}
	@Override
	public ResponseEntity confirmToLib(ConfirmLibReq req,int type,String userId) {
		String libId = "";
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			//查询上一次是否已经带书离馆
			LibBookSwitch bookSwitch = switchService.findSwitchInfo(req.getLibId());
			if(type == 1){ //带书离馆
				libId = req.getLibId();
				req.setLibId("fa14e041-3823-4dac-b061-1e250e5a7d49");
			}else{ //送书到馆
				libId = "fa14e041-3823-4dac-b061-1e250e5a7d49";
			}
			if(bookSwitch ==null){
				bookSwitch = new LibBookSwitch();
				bookSwitch.setCreateTime(new Date());
				bookSwitch.setUpdateTime(new Date());
				if(type==1){
					bookSwitch.setLibId(libId);
				}else{
					bookSwitch.setLibId(req.getLibId());
				}

				bookSwitch.setStat(type);
			}else{
				bookSwitch.setUpdateTime(new Date());
				bookSwitch.setStat(type);
			}
			String searchLibId = "";
			if(type==1){
				searchLibId=libId;
			}else{
				searchLibId=req.getLibId();
			}
			List<LibBookSwitchInfo> searchList = switchInfoService.findSwitchList(searchLibId,type);

			List<LibBookLocking> lockingList = lockingService.findLibLockingList(searchLibId);
			String bachId = Collections3.isNotEmpty(lockingList)?lockingList.get(0).getBatchId():"";
			bachId = StringUtils.isNotEmpty(bachId)?bachId:(int)((Math.random()*9+1)*10000000)+"";
			switchService.save(bookSwitch);
			TbLibJoin join = joinService.getById(req.getLibId());
			List<LibBookSwitchInfo> switchList = new ArrayList<LibBookSwitchInfo>();
			for (LibBookSwitchInfo info : searchList) {

				BookDetail  bookDetail=bookDetailService.getById(info.getBookDetailId());
				//检查书籍是否是调出馆书籍，否则抛异常
				if(!bookDetail.getLibId().equals(libId)){
					throw new Exception("图书已经处理");
				}
				TbLibBookInfo bookinfo=bookService.getById(bookDetail.getInfoId());
				TbLibBookInfo bookinfo2 = bookService.findByIsbnAndLibId(bookinfo.getIsbn13(), req.getLibId());
				if(bookinfo2 == null){
					bookinfo2 = new TbLibBookInfo();
					bookinfo2.setTitle(bookinfo.getTitle());
					bookinfo2.setAuthor(bookinfo.getAuthor());
					bookinfo2.setAuthorIntro(bookinfo.getAuthorIntro());
					bookinfo2.setCatalog(bookinfo.getCatalog());
					bookinfo2.setCreateTime(new Date());
					bookinfo2.setIsbn13(bookinfo.getIsbn13());
					bookinfo2.setIsbn10(bookinfo.getIsbn10());
					bookinfo2.setDoubanImage(bookinfo.getLocalImage());
					bookinfo2.setLocalImage(bookinfo.getLocalImage());
					bookinfo2.setPages(bookinfo.getPages());
					bookinfo2.setPrice(bookinfo.getPrice());
					bookinfo2.setPubdate(bookinfo.getPubdate());
					bookinfo2.setPublisher(bookinfo.getPublisher());
					bookinfo2.setCsisbn(bookinfo.getCsisbn());
					bookinfo2.setIsSerial(bookinfo.getIsSerial()); //1指代主
					bookinfo2.setBookStock(1);
					bookinfo2.setBookStockRemain(bookDetail.getBookcase()==null?0:1);
					bookinfo2.setLibId(req.getLibId());
					bookinfo2.setOrgCode(join.getOrgCode());
					bookinfo2.setSection(bookinfo.getSection());
					bookinfo2.setParentTheme(bookinfo.getParentTheme());
					bookinfo2.setChildTheme(bookinfo.getChildTheme());
					bookService.save(bookinfo2);
				}else{
					bookinfo2.setBookStock(bookinfo2.getBookStock()==null?0:bookinfo2.getBookStock()+1);
					bookinfo2.setBookStockRemain(bookinfo2.getBookStockRemain()==null?bookDetail.getBookcase()==null?0:1:bookDetail.getBookcase()==null?bookinfo2.getBookStockRemain():bookinfo2.getBookStockRemain()+1);
					bookService.save(bookinfo2);
				}
				bookDetail.setLibId(req.getLibId());
				bookDetail.setInfoId(bookinfo2.getId());
				bookDetailService.save(bookDetail);
				//拿书的馆的库存减去1
				bookinfo.setBookStock(bookinfo.getBookStock()-1);
				bookinfo.setBookStockRemain(bookinfo.getBookStockRemain()==null?0:bookDetail.getBookcase()==null?bookinfo.getBookStockRemain():bookinfo.getBookStockRemain()-1);
				bookService.save(bookinfo);

				//保存记录
				info.setState(2);
				info.setBatchId(bachId);
				switchList.add(info);
			}
			//处理locking表数据

			List<TbLibBookInfo> saveBookList = new ArrayList<>();
			if(!lockingList.isEmpty()){
				for (LibBookLocking locking:lockingList){
					TbLibBookInfo info = bookService.getById(locking.getBookInfoId());
					int bookStockRemain = ((info.getBookStockRemain()==null?0:info.getBookStockRemain())+(locking.getBookSize()==null?1:locking.getBookSize()));
					info.setBookStockRemain(bookStockRemain>info.getBookStock()?info.getBookStock():bookStockRemain);
					saveBookList.add(info);
				}
			}
			bookService.save(saveBookList);
			//更新locking 表
			if(type==1){//带书离馆
				lockingService.updateDataStat(libId,type,bachId);
			}else{ //送书到馆
				lockingService.updateDataStat2(req.getLibId(),type,bachId);
			}
			switchInfoService.save(switchList);
			responseEntity.success();
		}catch (Exception e){
			if(e.getMessage().equals("图书已经处理")){
				responseEntity.failure("000",e.getMessage());
			}else{
				responseEntity.failure("000","图书调度出现异常");
			}
		}
		return responseEntity;
	}
	@Override
	public TbLibBookBorrow findIsHelp(String userId, String isbn13, String vipId,String libId) {
		
		return bookBorrowDao.findIsHelp(userId,isbn13,vipId,libId);
	}
	@Override
	public void orderOverTime() {
		List<Map<String, Object>> overList = queryDao.orderOverTime();
		if(overList !=null && overList.size()>0){
			for (Map<String, Object> map : overList) {
				//更新为无效
				TbLibBookBorrow borrow = this.getById(map.get("id").toString());
				borrow.setStat(2);
				this.save(borrow);
				//将剩余库存加1
				TbLibBookInfo bookinfo2 = bookService.findByIsbnAndLibId(map.get("isbn13").toString(), map.get("lib_id").toString());
				bookinfo2.setBookStockRemain(bookinfo2.getBookStockRemain()+1);
				bookService.save(bookinfo2);
			}
		}
	}
	@Override
	public Map<String, Object> findHelpTimes(String libId, String vipId, String isbn13) {
		
		return queryDao.findHelpTimes(libId,vipId,isbn13);
	}
	@Override
	public Page<Map<String, Object>> findForPage(Map<String, Object> params, Pageable initPage) {
		
		return queryDao.findForPage(params,initPage);
	}
	@Override
	public List<Map<String, Object>> getExportData(Map<String, Object> searchParams) {
		
		return queryDao.getExportData(searchParams);
	}
	@Override
	public Map<String, Object> bookRecommend(BookRecommendReq req, String libId) {
		Map<String, Object> data = new HashMap<String, Object>();
		//饼图 取总部调度馆的书籍
		List<Map<String, Object>> mapList = queryDao.findLibThemeData(libId,req.getVipId());
		double sumBook = 0;
		NumberFormat nt = NumberFormat.getPercentInstance(); 
		  //设置百分数保留两位小数 
		  nt.setMinimumFractionDigits(0); 
		for (Map<String, Object> map : mapList) {
			sumBook += Integer.parseInt(map.get("bnum").toString());
		}
		for (Map<String, Object> map : mapList) {
			map.put("proportion", nt.format(Double.parseDouble(map.get("bnum").toString())/sumBook));
		}
		//获取正在借阅记录
		List<Map<String, Object>> borrowList = queryDao.findBorrowList(req.getVipId(),req.getLibId());
		List<Map<String, Object>> borrowInfoList = new ArrayList<Map<String, Object>>();
		if(borrowList !=null && borrowList.size()>0){
			Map<String, Object> themeMap = new HashMap<String, Object>();
			for (Map<String, Object> map2 : borrowList) {
				themeMap.put(map2.get("child_theme").toString(), map2.get("name"));
			}
			for(String key:themeMap.keySet()){
				Map<String, Object> infoMap = new HashMap<String, Object>();
				List<Map<String, Object>> bookList = new ArrayList<Map<String, Object>>();
				for (Map<String, Object> map2 : borrowList) {
					if(key.equals(map2.get("child_theme").toString())){
						if(!infoMap.containsKey("child_theme")){
							infoMap.put("child_theme", key);
							infoMap.put("theme_name", map2.get("child_name"));
							infoMap.put("book_num", map2.get("book_num"));
							infoMap.put("aliases", map2.get("aliases"));
						}
						Map<String, Object> bookMap = new HashMap<String, Object>();
						bookMap.put("title", map2.get("title"));
						bookMap.put("summary", map2.get("summary"));
						bookMap.put("local_image", map2.get("local_image"));
						bookMap.put("isbn13", map2.get("isbn13"));
						bookList.add(bookMap);
					}
				}
				infoMap.put("bookList", bookList);
				borrowInfoList.add(infoMap);
			}
		}
		
		data.put("headInfoList", mapList);
		data.put("borrowInfoList", borrowInfoList);
		return data;
	}
	@Override
	public Page<Map<String, Object>> findThemeBookList(Map<String, Object> params, Pageable pageable) {
		
		return queryDao.findThemeBookList(params,pageable);
	}
	@Override
	public Page<Map<String, Object>> cancelLibList(Map<String, Object> params, Pageable pageable) {
		return queryDao.cancelLibList(params,pageable);
	}
	@Override
	public Map<String, Object> findLibCancelInfo(String libId) {
		
		return queryDao.findLibCancelInfo(libId);
	}
	@Override
	public Page<Map<String, Object>> recoveryList(Map<String, Object> params, Pageable pageable) {
		
		return queryDao.recoveryList(params,pageable);
	}
	@Override
	public Map<String, Object> cancelLibHeadInfo(String libId,int type) {
		
		return queryDao.cancelLibHeadInfo(libId,type);
	}
	@Override
	public ResponseEntity confirmRecovery(String libId, Integer type,String userId) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			//确认回收(入库)
			TbLibJoin join = joinService.getById(libId);
			if(type==1){ //确认回收  join 表字段需要改变 cancel_stat=2
				join.setCancelStat(2);
				joinService.save(join);
				//将已经扫码的书籍更新字段
				bookDetailService.updateStep2(libId,2);
				
				TbLibcancelInfo info = cancelService.findByLibId(libId);
				info.setRecoveryUser(userId);
				info.setRecoveryTime(new Date());
				cancelService.save(info);
			}else if (type==2){ //确认入库 join 表 type=0 标记的数据全部转移到总部调度馆
				join.setType(0);
				joinService.save(join);
				
				TbLibcancelInfo info = cancelService.findByLibId(libId);
				info.setInuser(userId);
				info.setInTime(new Date());
				cancelService.save(info);
				
				//将入库扫过的数据归并到总部馆 没扫的数据视为丢失不处理
				List<BookDetail> detailList = bookDetailService.findInList(libId);
				TbLibJoin join2 = joinService.getById("fa14e041-3823-4dac-b061-1e250e5a7d49");
				for (BookDetail bookDetail : detailList) {
					TbLibBookInfo bookinfo=bookService.getById(bookDetail.getInfoId());
					//查询总部调度馆是否有这本书
					TbLibBookInfo bookinfo2 = bookService.findByIsbnAndLibId(bookinfo.getIsbn13(),"fa14e041-3823-4dac-b061-1e250e5a7d49");
					if(bookinfo2 == null){
						bookinfo2 = new TbLibBookInfo();
						bookinfo2.setTitle(bookinfo.getTitle());
						bookinfo2.setAuthor(bookinfo.getAuthor());
						bookinfo2.setAuthorIntro(bookinfo.getAuthorIntro());
						bookinfo2.setCatalog(bookinfo.getCatalog());
						bookinfo2.setCreateTime(new Date());
						bookinfo2.setIsbn13(bookinfo.getIsbn13());
						bookinfo2.setIsbn10(bookinfo.getIsbn10());
						bookinfo2.setDoubanImage(bookinfo.getLocalImage());
						bookinfo2.setLocalImage(bookinfo.getLocalImage());
						bookinfo2.setPages(bookinfo.getPages());
						bookinfo2.setPrice(bookinfo.getPrice());
						bookinfo2.setPubdate(bookinfo.getPubdate());
						bookinfo2.setPublisher(bookinfo.getPublisher());
						bookinfo2.setCsisbn(bookinfo.getCsisbn());
						bookinfo2.setIsSerial(bookinfo.getIsSerial()); //1指代主
						bookinfo2.setBookStock(1);
						bookinfo2.setBookStockRemain(1);
						bookinfo2.setLibId("fa14e041-3823-4dac-b061-1e250e5a7d49");
						bookinfo2.setOrgCode(join2.getOrgCode());
						bookService.save(bookinfo2);
					}else{
						bookinfo2.setBookStock(bookinfo2.getBookStock()+1);
						bookinfo2.setBookStockRemain(bookinfo2.getBookStockRemain()+1);
						bookService.save(bookinfo2);
					}
					bookDetail.setLibId("fa14e041-3823-4dac-b061-1e250e5a7d49");
					bookDetail.setInfoId(bookinfo2.getId());
					bookDetail.setRecoveryStat(null);
					bookDetail.setRecoveryType(null);
					bookDetail.setIsscan(null);
					bookDetailService.save(bookDetail);
					
				}
				//删除撤销馆没有明细数据存在的info表数据
				bookService.delNodetailInfoData(libId);
			}
			responseEntity.success("确认成功");
		} catch (Exception e) {
			responseEntity.failure("确认出现异常,请联系管理员");
		}
		
		return responseEntity;
	}
	@Override
	public ResponseEntity cancelComfirm(String libId,String userId) {
		ResponseEntity responseEntity = new ResponseEntity();
		TbLibcancelInfo info = cancelService.findByLibId(libId);
		if(info == null){
			info =new TbLibcancelInfo();
			info.setLibId(libId);
			info.setCancelUser(userId);
			info.setCancelTime(new Date());
			cancelService.save(info);
			
			//
			TbLibJoin join = joinService.getById(libId);
			join.setCancelStat(1);
			joinService.save(join);
			
			//更新书籍字段信息
			bookDetailService.updateStep(libId,1);
			responseEntity.success("撤销成功");
		}else{
			responseEntity.failure("此图书馆已经在撤销当中！");
			
		}
		return responseEntity;
	}

	@Override
	public ResponseEntity dispatcherAudit(DispatcherAuditReq req) {
		LibBookSwitch bookSwitch = switchService.findSwitchInfo(req.getLibId());
		if(bookSwitch == null){
			bookSwitch = new LibBookSwitch();
			bookSwitch.setCreateTime(new Date());
			bookSwitch.setUpdateTime(new Date());
			bookSwitch.setLibId(req.getLibId());
			bookSwitch.setStat(0);
			bookSwitch.setAuditStat(req.getType());

		}else{
			bookSwitch.setAuditStat(req.getType());
		}
		switchService.save(bookSwitch);
		//拒绝要将该馆书籍状态改变
		if(req.getType()==2){
			lockingService.updateDataStatByLibId(req.getLibId(),1);
			//将rides值改变
			String key = "read"+req.getLibId();
			tokenManager.set(key, 0,90 * 24 * 3600);
		}
		//发送消息模板通知馆长和馆长助理 1跟4
		List<String> typelist = managerService.findManageOpenidList(req.getLibId(),1);
		typelist.addAll(managerService.findManageOpenidList(req.getLibId(),4));
		Map<String, String> data = new HashMap<String,String>();
		TbLibJoin libjoin= joinService.getById(req.getLibId());
		data.put("first", libjoin.getLeagueName());
		data.put("keyword1", "书籍调度");
		data.put("keyword2", req.getType()==2?"调度员驳回您的调书申请，你可以重新挑选书籍再次提交！":"调度员已确认你馆调书申请，请等待调度员与你联系。");
		data.put("keyword3", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
		//data.put("remark","请登录后台查阅导出明细并可跟进办理。");

		String template_id_short="OPENTM207273120";
		for(String str:typelist){
			SendTemplateShort templateShort = new SendTemplateShort(str, template_id_short, null,data);
			pushTemplateService.saveAndSendPushWxTemplate(templateShort);
		}

		ResponseEntity responseEntity = new ResponseEntity();
		responseEntity.success();
		return responseEntity;
	}

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

	@Override
	public BookScanViewOutDto findScanForBookDetail(String detailId) {
		return queryDao.findScanForBookDetail(detailId);
	}

}
