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.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.weixin.library.dao.LibUserHistoryDao;
import com.ssj.dao.weixin.library.dao.LibUserHistoryQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.weixin.util.WxUtil;
import com.ssj.service.reading.in.BookBackInDto;
import com.ssj.service.reading.in.VipSignSaveInDto;
import com.ssj.service.reading.out.*;
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.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.util.*;


@Service(version="1.0")
@Transactional
public class LibUserHistoryServiceImpl extends BaseServiceImpl<LibUserHistory, String> implements LibUserHistoryService{

	@Autowired
	private LibUserHistoryDao  libUserHistoryDao;
	@Autowired
	private LibUserHistoryQueryDao  libUserHistoryQueryDao;

	@Autowired
	private ILibSubscribeService libSubscribeService;
	@Autowired
	private PushTemplateService pushTemplateService;

	@Autowired
	private IBookManagerService managerService;
	@Autowired
	private UserService userService;
	@Autowired
	private ILibJoinService joinService;
	@Autowired
	private IReadVipService vipService;
	@Autowired
	private LibVipServiceService libVipServiceService;
	@Autowired
	private OrderDetailsService orderDetailsService;
	@Autowired
	private IBookDetailService bookDetailService;
	
	@Override
	public Page<Map<String, Object>> findForPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libUserHistoryQueryDao.findForPage(searchParams, pageable);
	}

	@Override
	public PagingAndSortingRepository<LibUserHistory, String> getDao() {
		return libUserHistoryDao;
	}

	@Override
	public Page<Map<String, Object>> findForQGPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libUserHistoryQueryDao.findForQGPage(searchParams, pageable);
	}

	@Override
	public Page<Map<String, Object>> findForYDPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libUserHistoryQueryDao.findForYDPage(searchParams, pageable);
	}

	@Override
	public List<Map<String, Object>> getLibQGList(
			Map<String, Object> searchParams) {
		return libUserHistoryQueryDao.getLibQGList(searchParams);
	}

	@Override
	public List<Map<String, Object>> findRechargeInfo(String userId) {
		
		return libUserHistoryQueryDao.findRechargeInfo(userId);
	}

	@Override
	public List<Map<String, Object>> getLibYDList(
			Map<String, Object> searchParams) {
		return libUserHistoryQueryDao.getLibYDList(searchParams);
	}

	@Override
	public Page<Map<String, Object>> findCheckPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libUserHistoryQueryDao.findCheckPage(searchParams, pageable);
	}

	@Override
	public Page<Map<String, Object>> findCheckOutPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libUserHistoryQueryDao.findCheckOutPage(searchParams, pageable);
	}


	@Override
	public int findUserHistoryIsbn(String isbn13, Integer serviceCount) {
		Integer count =libUserHistoryDao.findUserHistoryIsbn(isbn13);
		double dob=(float) count / (float) serviceCount * 100;
		   if(dob>=5){
			   return 3;
		   }else if(dob<5&&dob>=2){
			   return 2;
		   }else if(dob<2&&dob>0){
			   return 1;
		   }else{
			   return 0;
		   }
	}

	@Override
	public String findUserHistoryChildTheme(String childTheme, Integer serviceCount) {
		Integer count =libUserHistoryDao.findUserHistoryChildTheme(childTheme);
		double dob=(float) count / (float) serviceCount * 100;
		   if(dob>=5){
			   return "3";
		   }else if(dob<5&&dob>=2){
			   return "2";
		   }else if(dob<2&&dob>0){
			   return "1";
		   }else{
			   return "0";
		   }
	}

	@Override
	public int findUserIsbnHeat(String isbn13) {
		return libUserHistoryDao.findUserIsbnHeat(isbn13);
	}

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

	@Override
	public ResponseEntity signSubmit(VipSignSaveInDto req,String userId) {
		ResponseEntity responseEntity = new ResponseEntity();
		User user = userService.getById(userId);
		//1-签到-2-签离
		int type = req.getType();
		//1-全选-2-非全选
		int selectAll = req.getSelectAll();
		TbLibSubscribe libSubscribe=null;
		List<TbLibSubscribe> saveList = new ArrayList<>();
		TbLibJoin join = joinService.getById(req.getLibId());
		if(selectAll ==1){
			Map<String,Object> params = new HashMap<>(2);
			params.put("type",type);
			params.put("libId",req.getLibId());
			params.put("childName",req.getChildName()==null?"":req.getChildName());
			List<VipSignOutDto> list =  libUserHistoryQueryDao.signList2(params);
			for (VipSignOutDto dto:list){
				if(type==1){
					libSubscribe = new TbLibSubscribe();
					libSubscribe.setUserId(dto.getUserId());
					libSubscribe.setFlowStat("3");
					libSubscribe.setStat("1");
					libSubscribe.setOrderDate(new Date());
					libSubscribe.setRykeConfirmUser(userId);
					libSubscribe.setRykeTime(new Date());
					libSubscribe.setVipId(dto.getId());
					libSubscribe.setLibId(req.getLibId());
					libSubscribe.setCreateTime(new Date());
					signPush(dto.getChildName(),req.getLibId(),join.getLeagueName(),dto.getParentName(),dto.getUserId(),user.getName());
				}else{
					libSubscribe =libSubscribeService.getById(dto.getId());
					libSubscribe.setFlowStat("4");
					libSubscribe.setStat("2");
					libSubscribe.setLeaveTime(new Date());
					libSubscribe.setLeaveConfirmUser(userId);
					leavePush(dto.getChildName(),join.getLeagueName(),user.getName(),dto.getUserId());
				}
				saveList.add(libSubscribe);
			}
		}else{
			List<String> ids = req.getIds();
			for (String id:ids){
				if(type==1){
					libSubscribe = new TbLibSubscribe();
					libSubscribe.setFlowStat("3");
					libSubscribe.setStat("1");
					libSubscribe.setOrderDate(new Date());
					libSubscribe.setRykeConfirmUser(userId);
					libSubscribe.setRykeTime(new Date());
					libSubscribe.setVipId(id);
					libSubscribe.setLibId(req.getLibId());
					libSubscribe.setCreateTime(new Date());
					LibReadVip vip = vipService.getById(id);
					libSubscribe.setUserId(vip.getUserId());
					signPush(vip.getChildName(),req.getLibId(),join.getLeagueName(),vip.getParentName(),vip.getUserId(),user.getName());
				}else{
					libSubscribe =libSubscribeService.getById(id);
					libSubscribe.setFlowStat("4");
					libSubscribe.setStat("2");
					libSubscribe.setLeaveTime(new Date());
					libSubscribe.setLeaveConfirmUser(userId);
					LibReadVip vip = vipService.getById(libSubscribe.getVipId());
					leavePush(vip.getChildName(),join.getLeagueName(),user.getName(),vip.getUserId());
				}
				saveList.add(libSubscribe);
			}

		}
		libSubscribeService.save(saveList);
		return responseEntity.success("提交成功！");
	}

	public  void signPush(String childName,String libId,String leagueName,String parentName,String vipUserId,String managerName){
		User user = userService.getById(vipUserId);

		Map<String,String> data =new HashMap<String, String>();
		String template_id_short="OPENTM207941156";
		data.put("first", childName+"妈妈/爸爸，您好！我是馆长"+managerName+"，您的孩子已安全到达"+leagueName+"\n");
		data.put("keyword1", childName);
		data.put("keyword2", leagueName);
		data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分"));
		data.put("remark", "\n状态：已到馆");


		SendTemplateShort sendTemplateShort=new SendTemplateShort(user.getAccount(), template_id_short, null, data);
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
	}

	public  void leavePush(String childName,String leagueName,String managerName,String vipUserId){
		User user = userService.getById(vipUserId);
		Map<String,String> data =new HashMap<String, String>();
		String template_id_short="OPENTM406027659";
		data.put("first", childName+"妈妈/爸爸，您好。我是馆长"+managerName+"您的孩子已离开"+leagueName+",请留意孩子是否安全到家。\n");
		data.put("keyword1", childName);
		data.put("keyword2", DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分"));
		data.put("keyword3",leagueName);
		data.put("remark", "\n状态：已离馆");
		SendTemplateShort sendTemplateShort=new SendTemplateShort(user.getAccount(), template_id_short, null, data);
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
	}

	@Override
	public VipSignDayOutDto dayCount(Map<String, String> params) {
		Date datetime = DateHelper.parseDate(params.get("date")+" 23:59:59","yyyy-MM-dd HH:mm:ss");
		String libId = params.get("libId").toString();
		Integer countNum=libVipServiceService.getByLibIdCount(libId,datetime);
		Integer rykeNum=orderDetailsService.signSubscribByDayCounter(libId, datetime,1);
		Integer leaveNum=orderDetailsService.signSubscribByDayCounter(libId, datetime,-1);

		VipSignDayOutDto dto = new VipSignDayOutDto();
		dto.setAllCount(countNum);
		dto.setSignCount(rykeNum);
		dto.setLeaveCount(leaveNum);
		return dto;
	}

	@Override
	public VipSignMonthOutDto monthCount(Map<String, String> params) {
		Date datetime = DateHelper.parseDate(params.get("month")+"-01","yyyy-MM-dd");
		String libId = params.get("libId");
		Integer rykeNum=orderDetailsService.signSubscribByMonthCounter(libId, datetime, 1);
		Integer countNum=orderDetailsService.signSubscribCount(libId);
		Integer activeNum= orderDetailsService.signSubscribByActiveCounter(libId, datetime);
		VipSignMonthOutDto dto = new VipSignMonthOutDto();
		dto.setActiveCount(activeNum);
		dto.setAllCount(countNum);
		dto.setSignCount(rykeNum);
		return dto;
	}

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

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

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

	@Override
	public List<LibBookLableOutDto> findThemeInfo(Map<String, Object> params) {
		return libUserHistoryQueryDao.findThemeInfo(params);
	}

	@Override
	public List<LibBookGradeOutDto> findGradeInfo(Map<String, Object> params) {
		return libUserHistoryQueryDao.findGradeInfo(params);
	}

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

	@Override
	public List<VipBorrowOutDto> findBorrowDetailList(String infoId, String dateStr, String isClose, String libId) {
		return libUserHistoryQueryDao.findBorrowDetailList(infoId, dateStr,isClose,libId);
	}

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

	@Override
	public int findTotayAdd(String libId) {
		return libUserHistoryDao.findTotayAdd(libId);
	}

	@Override
	public List<VipServiceOutDto> findVipLibServiceList(Map<String, Object> params) {
		return libUserHistoryQueryDao.findVipLibServiceList(params);
	}

	@Override
	public VipManagerOutDto vipDetailInfo(Map<String, Object> params) {
		return null;
	}

	@Override
	public List<VipSignDayDetailOutDto> vipSignInfoList(Map<String, Object> params) {
		return libUserHistoryQueryDao.vipSignInfoList(params);
	}

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

	@Override
	public List<ManagerOutDto> findUserList(Map<String, Object> params) {
		return libUserHistoryQueryDao.findUserList(params);
	}

	@Override
	public Map<String, Object> findBorrowInfo(Map<String, Object> params) {
		return libUserHistoryQueryDao.findBorrowInfo(params);
	}

	@Override
	public ResponseEntity callBookBack(String libId) {
		List<Map<String,Object>> callList = libUserHistoryQueryDao.callBookBack(libId);
		ResponseEntity responseEntity = new ResponseEntity();
		String template_id_short="OPENTM206044974";
		Map<String, String> data = new HashMap<String, String>();
		if(callList != null && callList.size()>0){
			for(Map<String, Object> map:callList){
				data.put("first",map.get("parent_name").toString()+"家长您好，您在我馆借阅的图书已经过期，请及时准备归还");
				data.put("keyword1",map.get("title").toString());
				data.put("keyword2", map.get("days2").toString());
				data.put("remark", "剩余天数：已逾期"+map.get("days1")+"天\n");
				SendTemplateShort templateShort = new SendTemplateShort(map.get("wx_account")+"", template_id_short, null, data);
				pushTemplateService.saveAndSendPushWxTemplate(templateShort);
			}
		}
		responseEntity.success("催送成功！");
		return responseEntity;
	}

	@Override
	public void confirmBackBorrow(BookBackInDto req) {
		List<String> idArr = req.getBookDetailsId();
		List<Map<String,Object>> userList = libUserHistoryQueryDao.getBackDetailList(idArr);

		for(String ids :idArr){
			BookDetail detail = bookDetailService.findById(ids);
			bookDetailService.backBook(ids,detail.getUserId());
		}

		String libId = req.getLibId();
		StringBuilder remarks = new StringBuilder();
		StringBuilder name = new StringBuilder();
		StringBuilder title = new StringBuilder();
		remarks.append("借阅状态：已归还\n ");
		remarks.append(" \n更多借阅详情可点击查看。");
		String template_id_short="OPENTM408917121";
		Map<String,String> data =new HashMap<>();

		//parents/pages/borrow_record/borrow_record?navIndex
		//=1&
		//vipId=${vipId}&libId
		//=${libId}
		Miniprogram miniprogram = new Miniprogram();
		miniprogram.setAppid(WxUtil.map.get("readingAppId"));
		for(Map<String,Object> map:userList){
			Map<String, Object>  borrowInfo = bookDetailService.borrowInfoWeek(map.get("vip_id").toString(),map.get("user_id").toString(),"1");
			name.append(map.get("name")).append("、");
			title.append(map.get("title")).append("、");;

			data.put("first", map.get("name")+"妈妈/爸爸，您好。近一周已成功归还"+borrowInfo.get("borrow_count")+"本图书。\n");
			data.put("keyword1",map.get("name")+"");
			data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
			data.put("keyword3",map.get("title")+"");
			data.put("remark", "借阅状态：已归还\n\n感谢您的使用，可点击查看借阅详情。");
			miniprogram.setPagepath("parents/pages/borrow_record/borrow_record?navIndex=1&libId="+libId+"&vipId="+map.get("vip_id"));
			SendTemplateShort templateShort = new SendTemplateShort(map.get("wx_account")+"", template_id_short, null, data,miniprogram);
			pushTemplateService.saveAndSendPushWxTemplate(templateShort);
			data.clear();
		}

		String pushName = name.toString();
		if(pushName.endsWith("、")){
			pushName= pushName.substring(0,pushName.length()-1);
		}

		String pushTitle = title.toString();
		if(pushTitle.endsWith("、")){
			pushTitle= pushTitle.substring(0,pushTitle.length()-1);
		}

		List<Map<String,Object>> managerList = bookDetailService.libManageList(req.getLibId());

		Map<String, Object>  countBooks = bookDetailService.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",pushName);
		data.put("keyword3",pushTitle);
		data.put("keyword2", DateHelper.format(new Date(), "yyyy年MM月dd日  HH时mm分 "));
		data.put("remark", remarks.toString());
		miniprogram.setPagepath("president/pages/borrow_record/borrow_record?navIndex=1&type=3&libId="+libId);
		for(Map<String,Object> map:managerList){
			SendTemplateShort templateShort2 = new SendTemplateShort(map.get("wx_account")+"", template_id_short,null,  data,miniprogram);
			pushTemplateService.saveAndSendPushWxTemplate(templateShort2);
		}
	}

	@Override
	public List<BookBackOutDto> findBackdList(List<String> bookDetailsId) {
		return libUserHistoryQueryDao.findBackdList(bookDetailsId);
	}


}
