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

import com.ssj.bean.weixin.libmy.domain.LibBookLocking;
import com.ssj.bean.weixin.libmy.domain.LibBookSwitch;
import com.ssj.bean.weixin.libmy.domain.TbLibBookInfo;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.push.domain.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.dao.weixin.library.dao.IOneBookQueryDao;
import com.ssj.dao.weixin.library.dao.LibBookLockingDao;
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.SystemResourceLocator;
import com.ssj.framework.weixin.util.WxUtil;
import com.ssj.service.reading.out.BookListOutDto;
import com.ssj.service.weixin.library.dto.out.BookApplyShowOutDto;
import com.ssj.service.weixin.library.dto.out.BookDetaiOutDto;
import com.ssj.service.weixin.library.dto.out.BookHisOutDto;
import com.ssj.service.weixin.library.service.ILIbBookSwitchService;
import com.ssj.service.weixin.library.service.ILibBookService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.library.service.LibBookLockingService;
import com.ssj.service.weixin.push.service.PushTemplateService;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/** 
 * @author  ZhangCaibao 
 * @version 2018年11月16日 上午11:16:08 
 * 类说明 
 */
@Transactional
@Service
public class LibBookLockingServiceImpl  extends BaseServiceImpl<LibBookLocking, String> implements  LibBookLockingService{
    @Autowired
	private LibBookLockingDao dao;
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private PushTemplateService pushTemplateService;
    
    @Autowired
    private ILibJoinService joinService;
    
    @Autowired
    private UserService userService;

    @Autowired
    private IOneBookQueryDao queryDao;

	@Autowired
	private ILIbBookSwitchService switchService;

	@Autowired
	private ILibBookService bookService;

	@Override
	public PagingAndSortingRepository<LibBookLocking, String> getDao() {
		return dao;
	}
	@Override
	public int addLibBookLocking(String inLibId,String outLibId, String bookInfoId,
			 String isbn13,Integer type) {
		LibBookLocking locking=dao.findLibBookLockingBybookDetailId(isbn13,inLibId);
		if(locking==null){
			locking =new LibBookLocking();
			locking.setStat(1);
			locking.setBookInfoId(bookInfoId);
			//locking.setBookDetailId(bookDetailId);
			locking.setBookSize(1);
			locking.setType(type);
			locking.setInLibId(inLibId);
			locking.setOutLibId(outLibId);
			locking.setCreateTime(new Date());
			locking.setIsbn13(isbn13);
		}else{
			locking.setCreateTime(new Date());
			locking.setBookSize(locking.getBookSize()==null?1:locking.getBookSize()+1);
		}
		this.save(locking);
		//库存减一
//		TbLibBookInfo bookInfo = bookService.findByIsbnAndLibId(isbn13,outLibId);
//		bookInfo.setBookStockRemain(bookInfo.getBookStockRemain()==null?bookInfo.getBookStock()-1:bookInfo.getBookStockRemain()-1);
//		bookService.save(bookInfo);
		return 1;
	}
	@Override
	public int getReadNum(String libId) {
		String key = "read"+libId;
		Integer monthValue=tokenManager.get(key,Integer.class);
		if(monthValue!=null){
			if(monthValue>0){
				return 1;
			}
			return 0;
		}
//		int readNum=dao.getReadNum(libId); //不要这个判断了
//		if(readNum>0){
//			return 1;
//		}
		return 0;
	}
	@Override
	public int getBookOutExchangeNum(String libId) {
		
		return dao.getBookOutExchangeNum(libId);
	}
	@Override
	public int getBookInExchangeNum(String libId) {
		return dao.getBookInExchangeNum(libId);
	}
	@Override
	public void updateLibBookLockingAndLibId(String libId) {
		TbLibJoin libJoin= joinService.getById(libId);
		//测试馆不限制
		if(!libJoin.getLeagueName().contains("测试") && !libJoin.getLeagueName().contains("总部")){
			String key = "read"+libId;
			Integer monthValue=tokenManager.get(key,Integer.class);
			if(monthValue!=null){
				if(monthValue>0){
					return ;
				}
			}
			tokenManager.set(key, 1,60 * 24 * 3600);
		}
		dao.updateLibBookLockingInAndLibId(libId);

		List<LibBookLocking> lockingList = dao.findLibLockingList(libId);
		List<TbLibBookInfo> saveBookList = new ArrayList<>();
		for (LibBookLocking locking:lockingList){
			TbLibBookInfo info = bookService.getById(locking.getBookInfoId());
			int bookStockRemain = (info.getBookStockRemain()==null?info.getBookStock():info.getBookStockRemain())-locking.getBookSize();
			info.setBookStockRemain(bookStockRemain>0?bookStockRemain:0);
			saveBookList.add(info);
		}
		bookService.save(saveBookList);
		String template_id_short="OPENTM207273120";
		String openId = SystemResourceLocator.getValue("book_openid").toString();
		Map<String, String> data = new HashMap<String,String>();

		data.put("first", libJoin.getLeagueName());
		data.put("keyword1", "已发起书籍调度需求");
		data.put("keyword2", "请您尽快登陆微信小程序查看需求");
		data.put("keyword3",DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
		Miniprogram min = new Miniprogram();
		min.setPagepath("dispatcher/pages/dispatch_go/dispatch_go?libId="+libId);
		min.setAppid(WxUtil.map.get("readingAppId"));
		//data.put("remark","请登录后台查阅导出明细并可跟进办理。");
		SendTemplateShort templateShort = new SendTemplateShort(openId, template_id_short, null,data,min);
		pushTemplateService.saveAndSendPushWxTemplate(templateShort);

		//提交后将swtich表audit_stat 字段修改为0
		LibBookSwitch bookSwitch = switchService.findSwitchInfo(libId);
		if(bookSwitch == null){
			bookSwitch = new LibBookSwitch();
			bookSwitch.setCreateTime(new Date());
			bookSwitch.setUpdateTime(new Date());
			bookSwitch.setLibId(libId);
			bookSwitch.setStat(0);
			bookSwitch.setAuditStat(0);

		}else{
			bookSwitch.setAuditStat(0);
		}
		switchService.save(bookSwitch);
		
		String str =   tokenManager.getString("dispatcher2018");
		String[] userIds=str.split(",");
		for (String string : userIds) {
			if(string!=null&&string.length()>0){
				String wxopenId=userService.getAccount(string);
				templateShort = new SendTemplateShort(wxopenId, template_id_short, null,data,min);
				pushTemplateService.saveAndSendPushWxTemplate(templateShort);
			}
		}
	}
	@Override
	public void updateDataStat(String libId, int type,String batchId) {
		dao.updateDataStat(libId,type,batchId);
	}
	@Override
	public void updateDataStat2(String libId, int type,String batchId) {
		dao.updateDataStat2(libId,type,batchId);
	}
	@Override
	public int findLastNum(String inlibId, String outLibId) {
		
		return dao.findLastNum(inlibId,outLibId);
	}

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

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

	@Override
	public void updateDataStatByLibId(String libId, int stat) {
		dao.updateDataStatByLibId(libId,stat);
	}

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

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

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

	@Override
	public LibBookLocking findByInfoIdAndLibId(String str, String libId) {
		return dao.findByInfoIdAndLibId(str,libId);
	}

	@Override
	public List<LibBookLocking> findLibLockingList(String searchLibId) {
		return dao.findLibLockingList(searchLibId);
	}

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

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

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

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

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

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

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

}
