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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.ssj.api.controller.ApiMerchantController;
import com.ssj.api.domain.vo.merchant.ServiceVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssj.alipay.utils.AlipayOrderHelper;
import com.ssj.api.request.RequestOpenApiUtils;
import com.ssj.bean.curator.TbVacationLimit;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.give.GiveRecord;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.order.domain.Order;
import com.ssj.bean.weixin.sales.domain.LibBorrowedService;
import com.ssj.bean.weixin.sales.domain.LibOrderDetails;
import com.ssj.bean.weixin.sales.domain.LibSalesPrice;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.bean.weixin.sales.domain.WorkDay;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.bean.weixin.zyb.domain.ZuoybCourse;
import com.ssj.dao.weixin.sales.dao.LibCourseDao;
import com.ssj.dao.weixin.sales.dao.LibSalesPriceDao;
import com.ssj.dao.weixin.sales.dao.LibStaffingQueryDao;
import com.ssj.dao.weixin.sales.dao.LibVipServiceDao;
import com.ssj.dao.weixin.sales.dao.LibVipServiceQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.persistence.DynamicSpecifications;
import com.ssj.framework.core.persistence.SearchFilter;
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.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.StringUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.pay.OrderHelper;
import com.ssj.framework.weixin.pay.OrderUtil;
import com.ssj.framework.weixin.pay.util.MD5Util;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.conch.common.dto.ServiceRecordDto;
import com.ssj.service.conch.common.request.PayVipBatchReq;
import com.ssj.service.conch.curator.service.v1.IVacationLimitService;
import com.ssj.service.conch.parents.v2.dto.ServiceRecordV1Dto;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.sys.give.GiveRecordService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.order.service.OrderService;
import com.ssj.service.weixin.sales.service.LibBorrowedServiceService;
import com.ssj.service.weixin.sales.service.LibOrderDetailsService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.sales.service.WorkDayService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.service.weixin.zuoyb.service.ZuoybCourseService;

/** 
 * @author  ZhangCaibao 
 * @version 2017年6月22日 下午3:51:07 
 * 类说明 
 */
@Service
@Transactional
public class LibVipServiceServiceImpl extends BaseServiceImpl<LibVipService, String> implements LibVipServiceService{
	
	private   Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private LibVipServiceDao  libVipServiceDao;
	@Autowired
	private LibBorrowedServiceService  libBorrowedServiceService;
	@Autowired
	private LibStaffingQueryDao  libStaffingQueryDao;
	@Autowired
	private LibVipServiceQueryDao  libVipServiceQueryDao;
	@Autowired
	private WorkDayService  workDayService;
    @Autowired
 	private ILibJoinService joinService;    
	@Autowired
	private UserService  userService;
	@Autowired
	private ZuoybCourseService  zuoybCourseService;
	@Autowired
	private LibCourseDao libCourseDao;
	@Autowired
	private ILibVipService vipService;
	@Autowired
	private TokenManager tokenManager;
	@Autowired
	private OrderService orderService;
	@Autowired
	private LibSalesPriceDao libSalesPriceDao;
	@Autowired
	private LibOrderDetailsService libOrderDetailsService;
	@Autowired
	private IBookManagerService managerService;
	@Autowired
	private IVacationLimitService vacationLimitService;
	@Autowired
	private GiveRecordService giveRecordService;
	@Autowired
	private MerchantService merchantService;

	@Autowired
	private ApiMerchantController apiMerchantController;
	@Override
	public PagingAndSortingRepository<LibVipService, String> getDao() {
		return libVipServiceDao;
	}

    @Override
    public void saveLibVipServiceV1(String libId, String species, String type, String vipId, Date beginTime, Integer number, String orderDetailsId) {
        LibVipService libVipService = null;
        //作业吧服务
        if ("S003".equals(species)) {
            //作业吧服务(绑定虚拟图书馆)
            libVipService = libVipServiceDao.findByLibIdAndVipIdAndSpecies(libId, vipId, species);
            //最长有效期的有效的作业吧服务(为了在老数据后面增加时间)
            LibVipService validService = libVipServiceDao.findValidTopService(vipId,species);
            if (validService != null) {
                beginTime = validService.getEndTime();
            }
            //有效的作业吧服务
            if (libVipService != null) {
                try {
					if (DateHelper.compareTwoDate(beginTime, libVipService.getEndTime())) {
						beginTime = libVipService.getEndTime();
					}
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        //通讯服务
        } else if ("S007".equals(species)) {
            //通讯服务
            List<LibVipService> serviceList = this.findByVipIdAndSpecies(vipId, species);
            if (serviceList != null && serviceList.size() > 0) {
                libVipService = serviceList.get(0);
            }
            //有效的作业吧服务
            LibVipService zybService = this.findValidTopService(vipId, "S003");
            if (zybService != null) {
                beginTime = zybService.getEndTime();
            }
            if (libVipService != null && beginTime.compareTo(libVipService.getEndTime()) == -1) {
                beginTime = libVipService.getEndTime();
            }
        }
        //结束时间
        Date endTime = DateHelper.getMonthDate(beginTime, number);
        if (libVipService != null) {
            logger.info("插入之前的旧服务--》" + JSON.toJSONString(libVipService));
            libVipService.setEndTime(endTime);
            libVipService.setOrderDetailsId(orderDetailsId);
            libVipService.setIsJia(0);
            libVipService.setType(type);
            libVipService.setStat(1);
        } else {
            libVipService = new LibVipService();
            libVipService.setLibId(libId);
            libVipService.setSpecies(species);
            libVipService.setStartTime(beginTime);
            libVipService.setEndTime(endTime);
            libVipService.setStat(1);
            libVipService.setType(type);
            libVipService.setVipId(vipId);
            libVipService.setCreateTime(new Date());
            libVipService.setOrderDetailsId(orderDetailsId);
            libVipService.setIsJia(0);
        }
        this.save(libVipService);
    }

	@Override
	public void saveLibVipServiceV2(String species, String type, String vipId, Date beginTime, Integer number, String orderDetailsId) {
		LibVipService libVipService = null;
		//作业吧服务
		if ("S003".equals(species)) {
			//作业吧服务
			libVipService = libVipServiceDao.findTopByVipIdAndSpeciesOrderByEndTimeDesc(vipId, species);
			//有效的作业吧服务
			if (libVipService != null) {
				try {
					if (DateHelper.compareTwoDate(beginTime, libVipService.getEndTime())) {
						beginTime = libVipService.getEndTime();
					}
				} catch (Exception e) {
					logger.error(e.getMessage());
				}
			}
			//通讯服务
		} else if ("S007".equals(species)) {
			//通讯服务
			List<LibVipService> serviceList = this.findByVipIdAndSpecies(vipId, species);
			if (serviceList != null && serviceList.size() > 0) {
				libVipService = serviceList.get(0);
			}
			//有效的作业吧服务
			LibVipService zybService = this.findValidTopService(vipId, "S003");
			if (zybService != null) {
				beginTime = zybService.getEndTime();
			}
			if (libVipService != null && beginTime.compareTo(libVipService.getEndTime()) == -1) {
				beginTime = libVipService.getEndTime();
			}
		}
		//结束时间
		Date endTime;
		if ("C022".equals(type)) {
			endTime = DateUtil.getDateAfter(beginTime, number);
		} else {
			endTime = DateHelper.getMonthDate(beginTime, number);
		}
		//这里设置学生已经选过的馆
		LibVip libVip = vipService.getById(vipId);
		String libId = libVip != null ? libVip.getLibId() : null;
		if (libVipService != null) {
			logger.info("插入之前的旧服务--》" + JSON.toJSONString(libVipService));
			libVipService.setEndTime(endTime);
			libVipService.setOrderDetailsId(orderDetailsId);
			libVipService.setIsJia(0);
			libVipService.setType(type);
			libVipService.setStat(1);
			libVipService.setLibId(libId);
		} else {
			libVipService = new LibVipService();
			libVipService.setSpecies(species);
			libVipService.setStartTime(beginTime);
			libVipService.setEndTime(endTime);
			libVipService.setStat(1);
			libVipService.setType(type);
			libVipService.setVipId(vipId);
			libVipService.setCreateTime(new Date());
			libVipService.setOrderDetailsId(orderDetailsId);
			libVipService.setIsJia(0);
			libVipService.setLibId(libId);
		}
		this.save(libVipService);
	}

    @Override
    public void saveLibVipServiceV3(String species, String type, String vipId, Date beginTime, Integer number, String orderDetailsId) {
		//如果开始时间为空，则看有没有有效的服务，有则把有效服务结束时间作为本次续费服务开始时间，无则把今天当做本次续费服务开始时间
		if (beginTime == null) {
			//作业吧服务
			LibVipService validService = libVipServiceDao.findValidTopService(vipId, species);
			//有效的作业吧服务
			if (validService != null) {
				beginTime = DateHelper.getNextDay(validService.getEndTime(), 1);
			} else {
				beginTime = new Date();
			}
		}
		//结束时间
		Date endTime;
		if ("C022".equals(type)) {
			endTime = DateUtil.getDateAfter(beginTime, number);
		} else {
			endTime = DateHelper.getMonthDate(beginTime, number);
		}
		//因为可以有分段服务，所有每次续费都生成一条服务记录
		LibVipService libVipService = new LibVipService();
		libVipService.setSpecies(species);
		libVipService.setStartTime(beginTime);
		libVipService.setEndTime(endTime);
		libVipService.setStat(1);
		libVipService.setType(type);
		libVipService.setVipId(vipId);
		libVipService.setCreateTime(new Date());
		libVipService.setOrderDetailsId(orderDetailsId);
		libVipService.setIsJia(0);
		libVipService.setLibId(null);
		//批改方式类型，1家长购买平台服务，2机构自批改，3家长自批改，4机构购买平台服务
		if ("C023".equals(type)) {
			libVipService.setCorrectType(3);
			//生成一条家长自批改角色记录
			TbLibManager teacher = new TbLibManager();
			teacher.setType(16);
			teacher.setState(1);
			LibVip libVip = vipService.getById(vipId);
			if (libVip != null && StringUtil.isNotBlank(libVip.getUserId())) {
				User user = userService.getById(libVip.getUserId());
				if (user != null) {
					teacher.setName(user.getName());
					teacher.settPhoto(user.getPhoto());
					teacher.setTelephone(user.getMobile());
					teacher.setSex(user.getSex());
				}
				teacher.setUserId(libVip.getUserId());
			} else {
				logger.error("生成家长自批改角色失败");
			}
			managerService.save(teacher);
		} else {
			libVipService.setCorrectType(1);
		}
		this.save(libVipService);
    }

	@Override
	public LibVipService saveLibVipServiceV4(String species, String type, String vipId, Date beginTime, Date endTime, Integer number, String orderDetailsId, String libId) {
		//如果结束时间为空，则计算结束时间
		if (endTime == null) {
			if ("C022".equals(type)) {
				endTime = DateUtil.getDateAfter(beginTime, number);
			} else {
				endTime = DateHelper.getMonthDate(beginTime, number);
			}
		}
		//因为可以有分段服务，所有每次续费都生成一条服务记录
		LibVipService libVipService;
		//C023:平台服务（校区购买）;C024:校区服务）
		if ("C023".equals(type)) {
			libVipService = this.findValidTopService(vipId, species, 4);
		} else if ("C024".equals(type)) {
			libVipService = this.findValidTopService(vipId, species, 2);
		} else {
			libVipService = this.findValidTopService(vipId, species, 1);
		}
		if (libVipService != null) {
			libVipService.setEndTime(endTime);
			libVipService.setOrderDetailsId(orderDetailsId);
			libVipService.setIsJia(0);
			libVipService.setType(type);
			libVipService.setStat(1);
			libVipService.setLibId(libId);
		}else{
			libVipService = new LibVipService();
			libVipService.setSpecies(species);
			libVipService.setStartTime(beginTime);
			libVipService.setEndTime(endTime);
			libVipService.setStat(1);
			libVipService.setType(type);
			libVipService.setVipId(vipId);
			libVipService.setCreateTime(new Date());
			libVipService.setOrderDetailsId(orderDetailsId);
			libVipService.setIsJia(0);
			libVipService.setLibId(libId);
			//批改方式类型，1家长购买平台服务，2机构自批改，3家长自批改，4机构购买平台服务
			//"C023"平台服务（机构购买）；“C024”校区服务（机构自服务）
			// 按平台服务（家⻓购买）、平台服务（机构购买）、校区服务的顺序排列
			if ("C023".equals(type)) {
				libVipService.setCorrectType(4);
				libVipService.setServiceSort(2);
			} else if ("C024".equals(type)) {
				libVipService.setCorrectType(2);
				libVipService.setServiceSort(3);
			} else {
				libVipService.setCorrectType(1);
				libVipService.setServiceSort(1);
			}
		}

		this.save(libVipService);
		return libVipService;
	}

	@Override
	public void saveLibVipServiceV4(String species, String type, String vipId, Date beginTime, Date endTime, Integer number, String orderDetailsId) {
		this.saveLibVipServiceV4(species, type, vipId, beginTime, endTime, number, orderDetailsId, null);
	}

	@Override
	public void saveLibVipServiceForever(String vipId) {
		/*LibVipService libVipService = libVipServiceDao.findTopByVipIdAndSpeciesOrderByEndTimeDesc(vipId, "S003");
		String endTimeString = "9999-01-01";
		if (libVipService != null) {
			String endTimeCompare = DateUtil.format_yyyyMMdd(libVipService.getEndTime());
			if (endTimeString.equals(endTimeCompare)) {
				return;
			}
		}
		//结束时间
		Date endTime = DateUtil.parse_yyyyMMdd(endTimeString);
		if (libVipService == null) {
			libVipService = new LibVipService();
			libVipService.setSpecies("S003");
			libVipService.setType("C006");
			libVipService.setStartTime(new Date());
			libVipService.setVipId(vipId);
			libVipService.setCreateTime(new Date());
		}
		libVipService.setEndTime(endTime);
		libVipService.setStat(1);
		libVipService.setIsJia(0);
		libVipService.setOrderDetailsId("zyb");
		this.save(libVipService);*/
	}

	@Override
	public void saveLibVipService(String libId,String species,String type,String vipId,Date startTime,Date endTime,String orderDetailsId ) {
		LibBorrowedService  libBorrowedService  =libBorrowedServiceService.findByLibIdAndSpeciesAndType(libId, species, type);
		LibVipService libVipService =libVipServiceDao.findByLibIdAndVipIdAndSpecies(libId, vipId, species);
		TbLibJoin libJoin = joinService.getById(libId);
		if (libJoin == null) {
			libJoin = new TbLibJoin();
		}
		if (libBorrowedService == null) {
			libBorrowedService = new LibBorrowedService();
			libBorrowedService.setLibId(libId);
			libBorrowedService.setCreateTime(new Date());
			libBorrowedService.setSpecies(species);
			libBorrowedService.setType(type);
			libBorrowedService.setBorrowDay(0);
			libBorrowedService.setBorrowNum(0);
			libBorrowedService.setDeposit(0);
			libBorrowedService.setOutMoney(new BigDecimal(0));
			libBorrowedServiceService.save(libBorrowedService);
		}
		if(libVipService !=null){
			logger.info("插入之前的旧服务--》"+JSON.toJSONString(libVipService));
			libVipService.setBorrowDay(libBorrowedService.getBorrowDay());
			libVipService.setDeposit(libBorrowedService.getDeposit());
			libVipService.setOutMoney(libBorrowedService.getOutMoney());
			libVipService.setSpecies(species);
			libVipService.setOrderDetailsId(orderDetailsId);
			libVipService.setCreateTime(new Date());
			libVipService.setIsJia(0);
			
           Date oldEndTime =libVipService.getEndTime();
           int end =0;
           //会员过期后，直接设置开始时间，为订单的开始和结束时间
			//if(libVipService.getStat()==2){
			//此处判断通过结束日期来判断（定时器改变此字段是10点后，10点下单会出现日期不一致）
			if (DateHelper.compareTwoDate(libVipService.getEndTime(),new Date())) {
				libVipService.setBorrowNum(libBorrowedService.getBorrowNum());
				
				int day =DateHelper.daysOfTian(oldEndTime, startTime);
				//结束时间大于1个月，那就已购卡的开始时间为开始时间
				if(day>=30){
					libVipService.setStartTime(startTime);
					libVipService.setEndTime(endTime);
					//设置结束时间为开始时间，因为已过期
					oldEndTime = startTime;
					end=1;
				}
				
			}else{
				if(libVipService.getBorrowNum()==3){
					libVipService.setBorrowNum(libBorrowedService.getBorrowNum());
				}
			}
			
			// 以下逻辑只适用于  深圳地区——》作业吧月卡
			//可自动跳过法定假期避免计费，例：在5月购买了一个月服务，五一法定是x天，服务过期时间需自动对应往后延x天。
			//如果延x天后，刚好不是工作日，那就再延到下一个工作日的时间。
			//跳过假日，寒假时间
			//-----------------------------
			if(("C004".equals(type) || "C015".equals(type)) && libJoin.getLeagueCode().startsWith("SZ")){
				//int day =DateHelper.daysOfTian(startTime, endTime);
				int day =DateHelper.daysOfTian(oldEndTime, DateHelper.getMonthDate(oldEndTime, "C004".equals(type) ? 1 : 3));
				WorkDay workDay=workDayService.getEndWorkDay(oldEndTime, day-1,libId);
				if(workDay!=null){
					endTime=workDay.getDate();
					libVipService.setEndTime(endTime);
				}
			//-----------------------------
			}else{
				if(end==0){
					//有效时间=有效时间+(结束时间-开始时间) 
					//libVipService.setEndTime(DateHelper.dateAdd(startTime, endTime,libVipService.getEndTime()));
					//这里计算采用之前同样的方法
					int months = DateUtil.getMonthDiff(endTime, startTime);
					libVipService.setEndTime(DateHelper.getMonthDate(libVipService.getEndTime(), months));
				}
			}
			libVipService.setType(type);
			if("C008".equals(type) || "C018".equals(type)){
				if(libVipService.getEndTime().getTime()<endTime.getTime()){
					libVipService.setEndTime(endTime);//当有效时间小于寒假结束时间，那么有效时间设置为寒假结束时间
				}
				Integer isJia=libVipService.getIsJia();
				if(isJia==0){
					if("C008".equals(type)){
						libVipService.setIsJia(1);
					}else{
						libVipService.setIsJia(2);//暑假卡
					}
				}
			}
			
			
			libVipService.setStat(1);
		}else{
			libVipService = new LibVipService();
			libVipService.setBorrowDay(libBorrowedService.getBorrowDay());
			libVipService.setBorrowNum(libBorrowedService.getBorrowNum());
			libVipService.setDeposit(libBorrowedService.getDeposit());
			libVipService.setLibId(libId);
			libVipService.setOutMoney(libBorrowedService.getOutMoney());
			libVipService.setSpecies(species);
			libVipService.setStartTime(startTime);
			libVipService.setEndTime(endTime);
			libVipService.setStat(1);
			libVipService.setType(type);
			libVipService.setVipId(vipId);
			libVipService.setCreateTime(new Date());
			libVipService.setOrderDetailsId(orderDetailsId);
			libVipService.setIsJia(0);
			if("C008".equals(type)){
				libVipService.setIsJia(1);
			}
			if("C018".equals(type)){
				libVipService.setIsJia(2);
			}
			// 以下逻辑只适用于  深圳地区——》作业吧月卡
			//可自动跳过法定假期避免计费，例：在5月购买了一个月服务，五一法定是x天，服务过期时间需自动对应往后延x天。
			//如果延x天后，刚好不是工作日，那就再延到下一个工作日的时间。
			//跳过假日，寒假时间
			//-----------------------------
			if(("C004".equals(type) || "C015".equals(type)) && libJoin.getLeagueCode().startsWith("SZ")){
				int day =DateHelper.daysOfTian(startTime, endTime);
				WorkDay workDay=workDayService.getEndWorkDay(startTime, day-1,libId);
				if(workDay!=null){
					endTime=workDay.getDate();
					libVipService.setEndTime(endTime);
				}
			}
			//-----------------------------
		}
		if("S003".equals(species) && ( StringUtils.isEmpty(libVipService.getZybCourseId()) ||  StringUtils.isEmpty(libVipService.getCourseHour()))){
			 ZuoybCourse zuoybCourse =zuoybCourseService.findByLibIdAndCourseHour(libId, "A");
			 if(zuoybCourse!=null){
				 libVipService.setZybCourseId(zuoybCourse.getId());
				 libVipService.setCourseHour(zuoybCourse.getCourseHour());
			 }
		}
		this.save(libVipService);
		
	}
	@Override
	public void saveLibVipService(String libId,String species,String type,String vipId,Date startTime,Date endTime,String orderDetailsId,Integer courseCount  ) {
		LibVipService libVipService =libVipServiceDao.findByLibIdAndVipIdAndSpecies(libId, vipId, species);
		if(libVipService !=null){
			logger.info("一对一的旧服务--》"+JSON.toJSONString(libVipService));
			libVipService.setSpecies(species);
			libVipService.setOrderDetailsId(orderDetailsId);
			libVipService.setCreateTime(new Date());
			libVipService.setIsJia(0);
			libVipService.setStartTime(startTime);
			libVipService.setEndTime(endTime);
			libVipService.setType(type);
			libVipService.setStat(1);
			Integer newCount = libVipService.getCourseCount();
			libVipService.setCourseCount(newCount+courseCount);
			this.save(libVipService);
		}else{
			libVipService = new LibVipService();
			libVipService.setBorrowDay(0);
			libVipService.setBorrowNum(0);
			libVipService.setDeposit(0);
			libVipService.setLibId(libId);
			libVipService.setOutMoney(new BigDecimal(0));
			libVipService.setSpecies(species);
			libVipService.setStartTime(startTime);
			libVipService.setEndTime(endTime);
			libVipService.setStat(1);
			libVipService.setType(type);
			libVipService.setVipId(vipId);
			libVipService.setCreateTime(new Date());
			libVipService.setOrderDetailsId(orderDetailsId);
			libVipService.setIsJia(0);
			libVipService.setCourseCount(courseCount);
			this.save(libVipService);
		}
	}
	@Override
	public LibVipService getVipIdPTService(String vipId) {
		return libVipServiceDao.getVipIdService(vipId,"S001");
	}
	@Override
	public LibVipService getVipIdService(String vipId) {
		return libVipServiceDao.getVipIdService(vipId);
	}
	
	@Override
	public LibVipService getVipIdService(String vipId ,String species,String libId) {
		return libVipServiceDao.getVipIdService(vipId,species,libId);
	}
	
	@Override
	public LibVipService getVipIdCuService(String vipId) {
		return libVipServiceDao.getVipIdService(vipId,"S004");
	}
	@Override
	public LibVipService getVipIdPTService(String vipId,String libId) {
		return libVipServiceDao.getVipIdService(vipId,"S001",libId);
	}
	@Override
	public LibVipService getVipIdZXService(String vipId) {
		return libVipServiceDao.getVipIdService(vipId,"S003");
	}
	@Override
	public LibVipService getVipIdZXService(String vipId ,String libId) {
		return libVipServiceDao.getVipIdService(vipId,"S003",libId);
	}
	@Override
	public Integer getVipIdPTServiceCount(String vipId) {
		return libVipServiceDao.getVipIdServiceCount(vipId,"S001");
	}
	@Override
	public Integer getVipIdZXServiceCount(String vipId) {
		return libVipServiceDao.getVipIdServiceCount(vipId,"S003");
	}
	@Override
	public Integer getVipIdServiceCount(String vipId ,String species) {
		return libVipServiceDao.getVipIdServiceCount(vipId,species);
	}
	@Override
	public Integer getVipIdAndLibIdCount(String vipId, String libId) {
		return libVipServiceDao.getVipIdAndLibIdCount(vipId,libId);
	}
	@Override
	public Page<Map<String, Object>> findForPage(
			Map<String, Object> searchParams, Pageable pageable) {
		return libStaffingQueryDao.findForVipSerivcePage(searchParams, pageable);
	}
	@Override
	public Integer getVipIdPTServiceCount(String vipId, String libId) {
		return libVipServiceDao.getVipIdServiceCount(vipId,"S001",libId);
	}
	@Override
	public Integer getVipIdZXServiceCount(String vipId, String libId) {
		return libVipServiceDao.getVipIdServiceCount(vipId,"S003",libId);
	}
	@Override
	public Integer getVipIdExpired5days(String vipId ,String species,String libId) {
		return libVipServiceDao.getVipIdExpired5days(vipId, species, libId);
	}

	@Override
	public void insertIntoVipIdServiceAndLibId(String vipId,String libId) {
		libVipServiceDao.insertIntoVipIdServiceAndLibId(vipId,libId);
		
	}
	@Override
	public Integer updateStat(String id, Integer stat) {
		return libVipServiceDao.updateStat(id, stat);
	}
	@Override
	public void updateVipServiceStat(String orderDeatalId) {
		libVipServiceDao.updateVipServiceStat(orderDeatalId);
	}
	@Override
	public Page<LibVipService> findByPage(Map<String, Object> params,
			Pageable sp) {
		  Map<String, SearchFilter> filters = SearchFilter.parse(params);
			Specification<LibVipService> specification = DynamicSpecifications.bySearchFilter(filters.values(), LibVipService.class);    
			return  libVipServiceDao.findAll(specification, sp);
	}
	@Override
	public Integer getByLibIdCount(String libId,Date selectDate) {
		return libVipServiceDao.getByLibIdCount(libId,selectDate);
	}
	@Override
	public Integer getByLibIdAndSpeciesCount(String libId, String species) {
		return libVipServiceDao.getByLibIdAndSpeciesCount(libId, species);
	}
	@Override
	public Integer getByLibIdAndSpeciesCount(String species) {
		return libVipServiceDao.getByLibIdAndSpeciesCount(species);
	}
	@Override
	 public Integer getByLibIdAndSpeciesCount(List<String> libIds, List<String> species, String masterId){
		return libVipServiceDao.countStudentByLibIds(libIds, species, masterId);
	}
	@Override
	public List<LibVipService> getByUserIdAndSpeciesCount(String userId, String species) {
		return libVipServiceDao.getByUserIdAndSpeciesCount(userId, species);
	}
	@Override
	public List<Map<String, Object>> getLibAllService(String vipId,String species) {
		return libStaffingQueryDao.getLibAllService(vipId, species);
	}
	@Override
	public List<LibVipService> getLibServiceAll(String userId,String species) {
		return libVipServiceDao.getLibServiceAll(userId, species);
	}
	@Override
	public boolean isVipIdAndWeekService(String vipId,String type) {
		List<LibVipService> libVipServices = null;
		if(type == null){
			libVipServices = libVipServiceDao.getVipIdServiceAll(vipId);
		}else{
			libVipServices = libVipServiceDao.getVipIdServiceAll(vipId, type);
		}
		 
		boolean is=true;
		if(libVipServices==null || libVipServices.size()<=0){
			is=false;
		}else{
			for (LibVipService libVipService : libVipServices) {
				if(!"C007".equals(libVipService.getType())){
					is=false;
					break;
				}
			}
		}
		return is;
	}
	@Override
	public Integer findIsHaveJiaSer(String vipId, String libId) {
		
		return libVipServiceDao.findIsHaveJiaSer(vipId,libId);
	}
	@Override
	public Integer getMouthServiceCount(String vipid, String libId, String species, String type) {
		
		return libVipServiceDao.getMouthServiceCount(vipid,libId,species);
	}
	@Override
	public Integer getOcBuyServiceCount(String vipid, String libId, String species, String type) {
		
		return libVipServiceDao.getOcBuyServiceCount(vipid,libId,species,type);
	}
	@Override
	public boolean isVipHasJiaSer(String vipId, String libId,String type) {
		List<LibVipService> libVipServices =  libVipServiceDao.getVipIdLibServiceAll(vipId, libId);
		 //没写完
		boolean is=true;
		if(libVipServices==null || libVipServices.size()<=0){
			is=false;
		}else{
			
			for (LibVipService libVipService : libVipServices) {
				//签到签离  作业吧卡可签到签离
				// 阅读卡 17年10月1号后的卡
				if("2".equals(type)){
					if("C001".equals(libVipService.getType()) && libVipService.getStartTime().getTime()>DateHelper.parseDate("2017-10-01", "yyyy-MM-dd").getTime()){
						is=false;
						break;
					}
				}
				
				if("1".equals(type)){ //借阅
					
				}
				
			}
		}
		return is;
	}
	@Override
	public List<Map<String, Object>> findUserServiceList(String vipid, String libId) {
		
		return libStaffingQueryDao.findUserServiceList(vipid,libId);
	}
	@Override
	public LibVipService getLibVipService(String vipId, String libId) {
		
		return libVipServiceDao.getLibVipService(vipId,libId);
	}
	
	
	
	@Override
	public Map<String,Object> findLibVipService(String libId,String species,String type,String vipId,Integer num) {
		Map<String,Object> data=new HashMap<String, Object>();
		Date serviceStartTime=new Date();
		Date serviceEndTime=null;
		Date date = new Date();
		try {
			TbLibJoin libJoin=joinService.getById(libId);
			if(StringUtils.isNotEmpty(vipId)){
				LibVipService libVipService =libVipServiceDao.findByLibIdAndVipIdAndSpecies(libId, vipId, species);
				if(libVipService!=null){
					if(libVipService.getStat()==2){//过期了，用当前开始时间
						date = new Date();
					}else{//没过期的，用服务结束时间
						date = libVipService.getEndTime();
						serviceStartTime=libVipService.getStartTime();
					}
				}
			}
			
			if("C001".equals(type)){
				serviceEndTime=(DateHelper.getMonthDate(date, 12*num));
			}else if("C002".equals(type)){
				serviceEndTime=(DateHelper.getMonthDate(date, 6*num));
			}else if("C003".equals(type)){ 
				serviceEndTime=(DateHelper.getMonthDate(date, 1*num));
			}else if("C004".equals(type)){
				serviceEndTime=DateHelper.getMonthDate(date, 1*num);
			}else if("C005".equals(type)){
				serviceEndTime=(DateHelper.getMonthDate(date, 6*num));
			}else if("C006".equals(type)){
				serviceEndTime=(DateHelper.getMonthDate(date, 12*num));
			}else if("C007".equals(type)){
				serviceEndTime=(DateHelper.getMonthDate(date, 12*num));
			}else if("C008".equals(type)){
				serviceStartTime=(DateHelper.timeStitching(DateHelper.parseDate("2018-01-15", "yyyy-MM-dd"), "23:59:59"));
				serviceEndTime=(DateHelper.timeStitching(DateHelper.parseDate("2018-02-28", "yyyy-MM-dd"), "23:59:59"));
			}else if("C015".equals(type)){
				serviceEndTime=(DateHelper.getMonthDate(date, 3*num));
			}
			// 以下逻辑只适用于  深圳地区——》作业吧月卡
			//可自动跳过法定假期避免计费，例：在5月购买了一个月服务，五一法定是x天，服务过期时间需自动对应往后延x天。
			//如果延x天后，刚好不是工作日，那就再延到下一个工作日的时间。
			//跳过假日，寒假时间
			//-----------------------------
			if(("C004".equals(type) || "C015".equals(type)) && libJoin.getLeagueCode().startsWith("SZ")){
				int day =DateHelper.daysOfTian(date, serviceEndTime);
				WorkDay workDay=workDayService.getEndWorkDay(date, day-1,libId);
				if(workDay!=null){
					serviceEndTime=workDay.getDate();
				}
			}
			//-----------------------------
		} catch (Exception e) {
			return null;
		}
		if(serviceStartTime!=null && serviceEndTime!=null){
			data.put("startDate",DateHelper.format(serviceStartTime, "yyyy-MM-dd"));
			data.put("endDate",  DateHelper.format(serviceEndTime, "yyyy-MM-dd"));
		}else{
			data.put("startDate",  "");
			data.put("endDate",  "");
		}
		return data;
	
	}
	@Override
	public Integer findJiaServiceByLib(String id, String libId) {
		
		return libVipServiceDao.findJiaServiceByLib(id,libId);
	}
	@Override
	public Integer getVipServiceByAccount(String openid) {
		String userId=userService.findUserById(openid);
		if(userId==null){return 0;}
		return libVipServiceDao.getVipServiceByUserId(userId);
	}

	@Override
	public List<Map<String, Object>> getVipService(String[] vipIds, String[] species) {
		return libCourseDao.getVipService(vipIds, species, 1); //1表示生效
	}

	@Override
	public int countDistinctByLibId(String libId) {
		return libVipServiceDao.countDistinctByLibId(libId);
	}

	@Override
	public List<LibVipService> findByLibId(String libId) {
		return libVipServiceDao.findByLibId(libId);
	}

	@Override
	public List<LibVipService> findByVipIdInAndSpeciesAndLibIdIn(String[] vipIds, String[] libIds, String[] species) {
		return libVipServiceDao.findByVipIdInAndLibIdInAndSpeciesInAndStat(vipIds, libIds, species, 1);  //生效的
	}
	@Override
	public void updateVipServiceByVipId(String vipId) {
		libVipServiceDao.updateVipServiceByVipId(vipId);		
	}

	@Override
	public void updateVipServiceStatByVipId(String vipId) {
		libVipServiceDao.updateVipServiceStatByVipId(vipId);
	}
	@Override
	public Page<Map<String, Object>> findTeacherList(
			Map<String, Object> searchParams, Pageable pageable) {
		return libStaffingQueryDao.findTeacherList(searchParams, pageable);
	}
	@Override
	public void updateByLibIdAndVipIdAndCourseHour(String vipId, String libId,
			String courseHour) {
		libVipServiceDao.updateByLibIdAndVipIdAndCourseHour(vipId, libId, courseHour);
	}

	@Override
    public LibVipService getVipIdZXService5days(LibVip libVip, String libId) {

        String vipId = libVip.getId();
        if (libVip.getChildType() == 1) {
            //永久作业批改服务
            LibVipService libVipService = libVipServiceDao.findByLibIdAndVipIdAndSpecies(libId, vipId, "S999");
			return libVipService != null ? libVipService : new LibVipService();
        }
        return this.getVipIdService(vipId, "S003", libId);
    }
	@Override
	public LibVipService getVipIdService5days(String vipId, String species,
			String libId) {
		return libVipServiceDao.getVipIdService5days(vipId, species, libId);
	}
	@Override
	public LibVipService getVipIdZXService5days(String vipId) {
		return libVipServiceDao.getVipIdZXService5days(vipId);
	}

	@Override
	public LibVipService findLastZybService(String vipId){
		return libVipServiceDao.findLastZybService(vipId);
	}

	@Override
	public int checkIsZybServiceByVipId(String vipId) {
		/*int count = libVipServiceDao.checkIsZybServiceByVipId(vipId);
		if(count >1) {
			count = 1;
		}
		return count;*/
		return this.checkIsZybServiceByVipIdV2(vipId);
	}

	@Override
	public int checkIsZybServiceByVipIdV2(String vipId) {
		int count = 0;
		LibVipService service = libVipServiceDao.findValidTopService(vipId, "S003");
		if (service != null) {
			count = 1;
		} else {
			LibVip libVip = vipService.getById(vipId);
			//此小孩为永久用户，拥有永久服务
			if (libVip != null && libVip.getChildType() == 1) {
				count = 1;
			}
		}
		return count;
	}

	@Override
	public int getCurrentCorrectService(String vipId) {
		LibVipService service = libVipServiceDao.getCurrentCorrectService(vipId);
		if (service != null) {
			if ("S999".equals(service.getSpecies())) {
				return 1;
			} else if (service.getCorrectType() != null) {
				return service.getCorrectType() == 4 ? 1 : service.getCorrectType();
			}
		}
		return 0;
	}

	@Override
	public int getDetailedCurrentCorrectService(String vipId) {
		LibVipService service = libVipServiceDao.getCurrentCorrectService(vipId);
		if (service != null) {
			if ("S999".equals(service.getSpecies())) {
				return 999;
			} else if (service.getCorrectType() != null) {
				return service.getCorrectType();
			}
		}
		return 0;
	}

	@Override
	public int checkIsOnlyZybServiceByVipId(String vipId) {
		List<LibVipService> list = libVipServiceDao.findByVipIdAndSpeciesAndStat(vipId, "S003", 1);
		int count = 0;
		if (list != null && list.size() > 0) {
			count = 1;
		}
		return count;
		//return this.checkIsZybServiceByVipId(vipId);
	}

	@Override
	public List<LibVipService> getByVipIdAndSpecies(String vipId, String species) {
		return libVipServiceDao.getByVipIdAndSpecies(vipId, species);
	}

	@Override
	public List<LibVipService> getByVipIdAndSpeciesOrderByCreateTimeDesc(String vipId, String species) {
		return libVipServiceDao.getByVipIdAndSpeciesOrderByCreateTimeDesc(vipId, species);
	}

	@Override
	public List<LibVipService> findByVipIdAndSpeciesAndStat(String vipId, String species, int stat) {
		return libVipServiceDao.findByVipIdAndSpeciesAndStat(vipId, species, stat);
	}

	@Override
	public List<LibVipService> findByVipIdAndSpecies(String vipId, String species) {
		return libVipServiceDao.findByVipIdAndSpecies(vipId, species);
	}

	@Override
	public void pushVipServiceInfo() {
		Map<String, Date> zybMap = new HashMap<>(16);
		Map<String, Date> commuMap = new HashMap<>(16);
		//有效的作业吧服务
		List<LibVipService> zybList = libVipServiceDao.findBySpeciesAndStat("S003", 1);
		//有效的通讯服务
		List<LibVipService> commuList = libVipServiceDao.findBySpeciesAndStat("S007", 1);
		commuList.addAll(zybList);
		this.putServiceMap(zybList, zybMap,"作业吧服务");
		this.putServiceMap(commuList, commuMap,"⼩塾相机通讯服务");
	}

	private void putServiceMap(List<LibVipService> list, Map<String, Date> map,String type) {
		for (LibVipService service : list) {
			if (map.get(service.getVipId()) == null) {
				map.put(service.getVipId(), service.getEndTime());
			} else {
				Date maxEndDate = map.get(service.getVipId());
				Date endDate = service.getEndTime();
				if (DateHelper.compareTwoDate(maxEndDate, endDate)) {
					map.put(service.getVipId(), endDate);
				}
			}
		}
		for (String key : map.keySet()) {
			Date endDate = map.get(key);
			//距离过期前7天和过期当天进行推送
			try {
				//前七天
				if(DateHelper.daysBetween(new Date(),endDate) == 6) {
					LibVip libVip = vipService.getById(key);
					String contentMessage = "尊敬的" + libVip.getChildName() + "家长，您的孩子" + libVip.getChildName() + "的" + type + "将于" + DateUtil.format_yyyyMMdd(endDate) + "到期，为不影响使用，请及时续费。";
					//sconXingeService.asynPushThreadTask(libVip.getUserId(), null, 2, contentMessage, PushConstants.PUSH_OTHER);
				}
				//当天
				if(DateHelper.daysBetween(endDate,new Date()) == 1) {
					LibVip libVip = vipService.getById(key);
					String contentMessage = "尊敬的" + libVip.getChildName() + "家长，您的孩子" + libVip.getChildName() + "的" + type + "已经过期，为不影响使用，请及时续费。";
					//sconXingeService.asynPushThreadTask(libVip.getUserId(), null, 2, contentMessage, PushConstants.PUSH_OTHER);
				}
			} catch (Exception e) {
				logger.error("作业吧，通讯费续费提醒推送失败");
			}
		}
	}

	@Override
	public Map<String, Object> getServiceEndDate(List<LibVipService> list, String key, String format) {
		Map<String, Object> map = new HashMap<>(16);
		Date maxEndDate = null;
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				LibVipService libVipService = list.get(i);
				if (i == 0) {
					maxEndDate = libVipService.getEndTime();
				} else {
					if (maxEndDate.getTime() < libVipService.getEndTime().getTime()) {
						maxEndDate = libVipService.getEndTime();
					}
				}
			}
		}
		if ("timestamp".equals(format)) {
			//返回时间戳
			if (maxEndDate != null) {
				map.put(key, maxEndDate.getTime() / 1000);
			} else {
				map.put(key, 0L);
			}
		} else {
			if (maxEndDate != null) {
				map.put(key, DateHelper.format(maxEndDate, format));
			} else {
				map.put(key, "");
			}
		}
		return map;
	}

	@Override
	public String selectZybEndTimeByVipId(String vipId) {
		LibVipService libVipService = libVipServiceDao.findValidTopService(vipId,"S003");
		if(libVipService!=null){
			return DateHelper.format(libVipService.getEndTime(),"yyyy-MM-dd");
		}
		return "";
	}

	@Override
	public boolean checkZybExistOrExpiredByChildUserId(String childUserId) {
		String flag = libVipServiceDao.checkZybExistOrExpiredByChildUserId(childUserId);
		return StringUtil.isBlank(flag) ? false : true ;
	}

	@Override
	public LibVipService findValidTopService(String vipId, String species) {
		return libVipServiceDao.findValidTopService(vipId, species);
	}

	@Override
	public LibVipService findValidTopService(String vipId, String species, int correctType){
		return libVipServiceDao.findValidTopService(vipId, species,correctType);
	}

	@Override
	public LibVipService findByLibIdAndVipIdAndSpecies(String libId, String vipId, String species) {
		return libVipServiceDao.findByLibIdAndVipIdAndSpecies(libId, vipId, species);
	}

	@Override
	public LibVipService findTopByVipIdAndSpeciesOrderByEndTimeDesc(String vipId, String species) {
		return libVipServiceDao.findTopByVipIdAndSpeciesOrderByEndTimeDesc(vipId, species);
	}

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

    @Override
    public List<LibVipService> findExpiredListBySpecies(String species) {
        return libVipServiceDao.findExpiredListBySpecies(species);
    }

	@Override
	public ResponseEntity payVIPBatch(PayVipBatchReq req, String clientIP, String accessToken) {
		ResponseEntity responseEntity = new ResponseEntity();
				//订单明细列表
		List<LibOrderDetails> orderDetailList = new ArrayList<>();
		//商品的标题/交易标题/订单标题/订单关键字等
		String title = "";
		List<LibVip> vipList = vipService.findByIds(req.getVipIds());
		String libId = req.getLeagueId();
		if (StringUtil.isBlank(libId)) {
			TbLibJoin tbLibJoin = joinService.findByLeagueCode("fictitious");
			libId = tbLibJoin.getId();
		}
		LibSalesPrice libSalesPrice = libSalesPriceDao.findByLibIdAndSpeciesAndType(libId, "S003", req.getPriceType());
		for (LibVip libVip : vipList) {
			if (libVip.getChildType() == 1) {
				responseEntity.failure("小孩" + libVip.getChildName() + "为内部用户，永久使用服务，无需续费");
				return responseEntity;
			}
		}
		LibOrderDetails libOrderDetails = new LibOrderDetails();
		libOrderDetails.setNumber(req.getNumber());
		//此处修改，安全原因，价格取后台数据
		if (!libSalesPrice.getDiscount().equals(req.getPrice())) {
			responseEntity.failure("价格发生改变，请重新操作");
			return responseEntity;
		}
		libOrderDetails.setPrice(libSalesPrice.getDiscount());
		libOrderDetails.setVipId(StringUtils.join(req.getVipIds(), ";"));
		//作业吧服务
		libOrderDetails.setPriceSpecies("S003");
		//虚拟图书馆
		TbLibJoin tbLibJoin = joinService.findByLeagueCode("fictitious");
		libOrderDetails.setLibId(tbLibJoin.getId());
		libOrderDetails.setVipStatus(1);
		//卡类型（C004:作业吧月卡;C005:作业吧半年卡;C006:作业吧年卡;C015:作业吧季卡
		if ("C004".equals(req.getPriceType())) {
			title = "作业吧月卡";
		} else if ("C005".equals(req.getPriceType())) {
			title = "作业吧半年卡";
		} else if ("C006".equals(req.getPriceType())) {
			title = "作业吧年卡";
		} else if ("C015".equals(req.getPriceType())) {
			title = "作业吧季度卡";
		}
		libOrderDetails.setDetails(title);
		libOrderDetails.setPriceType(req.getPriceType());
		//自己购买
		libOrderDetails.setIsBuy(1);
		//设置该参数，进入新的作业吧支付成功回调方法
		libOrderDetails.setIsType("newZybMethod");
		orderDetailList.add(libOrderDetails);
		//总费用
		BigDecimal fee = libOrderDetails.getPrice().multiply(new BigDecimal(libOrderDetails.getNumber())).multiply(new BigDecimal(req.getVipIds().size()));
		String desc = "私塾家-会员卡支付酬金";
		//单价乘以数量
		logger.info("===私塾家-会员卡支付酬金fee：" + fee);
		//下订单，金额为0
		if (fee.compareTo(new BigDecimal(0)) <= 0) {
			responseEntity.failure("金额为0,不能发起支付");
			return responseEntity;
		}
		String url = SystemResourceLocator.getValue("sys_url") + "/weixin/payment/pay_vip_callback.html";
		try {
			Map<String, String> map;
			if (req.getPayType() == 1) {
				//支付宝支付方式
				map = this.payByAlipay(libOrderDetails, accessToken, fee, title, desc, req.getAppType());
			} else {
				//微信支付方式
				map = this.payByWeChatPay(libOrderDetails, url, accessToken, fee, desc, req.getAppType(), clientIP);
			}
			responseEntity.success(map, "发起支付接口数据准备成功");
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.failure(ResponseConstant.CODE_000, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}

	/**
	 * 微信支付方式
	 * @param libOrderDetails 订单详情对象
	 * @param url 支付成功回调地址
	 * @param accessToken
	 * @param fee 总价
	 * @param desc 支付详情
	 * @param appType 6:家长端小程序;7:老师端小程序（校长端和老师端);11:app老师端;12:app家长端
	 * @param clientIP 客户端IP
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> payByWeChatPay(LibOrderDetails libOrderDetails, String url, String accessToken, BigDecimal fee, String desc, Integer appType,String clientIP) throws Exception {
		//生成订单号
		String orderNo = OrderUtil.getOrderCode();
		String openId = tokenManager.getOpenId(accessToken);
		//购买人
		String userId = tokenManager.getUserId(accessToken);
		Map<String, String> map;
		//请求微信统一下单接口，获取最重要的prepay_id.
		if(appType == 13){
			map = OrderHelper.requestH5Order(openId, fee, orderNo, desc, url, clientIP);
		}else{
			map = OrderHelper.requestAPPOrder(openId, fee, orderNo, desc, appType, url,null);
		}
		String prepay_id = map.get("prepayid");
		logger.info("===微信统一下单接口返回的prepay_id：" + prepay_id);
		//微信统一下单接口返回后，生成订单保存到数据库
		Order o = new Order();
		o.setOrderMoney(fee);
		o.setOrderNo(orderNo);
		o.setOrderStatus(0);
		o.setPrepayId(prepay_id);
		o.setCreateTime(new Date());
		o.setUserId(userId);
		//1 H5 ，2小程序，3app
		if (appType == 13) {
			o.setPayBy(1);
		} else if (appType == 6 || appType == 7) {
			o.setPayBy(2);
		} else if (appType == 11 || appType == 12) {
			o.setPayBy(3);
		}
		o.setIsClosed(0);
		o.setOrderType(4);
		o = orderService.save(o);
		libOrderDetails.setCreateTime(new Date());
		libOrderDetails.setOrderId(o.getId());
		libOrderDetails.setOrderNo(orderNo);
		libOrderDetails.setUserId(userId);
		//存放redis
		tokenManager.set(orderNo, libOrderDetails, 7 * 24 * 3600);
		logger.info("==发起支付=orderNo-" + orderNo + "(libOrderDetails)" + JSON.toJSONString(libOrderDetails));
		logger.info("===发起支付接口数据准备成功:" + map);
		return map;
	}

	/**
	 * 支付宝支付
	 * @param libOrderDetails 订单详情对象
	 * @param accessToken
	 * @param fee 总价
	 * @param title 商品的标题/交易标题/订单标题/订单关键字等。
	 * @param body 支付提示语
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> payByAlipay(LibOrderDetails libOrderDetails, String accessToken, BigDecimal fee, String title, String body, int payType) throws Exception {
		//生成订单号
		String orderNo = OrderUtil.getOrderCode();
		//购买人
		String userId = tokenManager.getUserId(accessToken);
		Map<String, String> map;
		//请求支付宝统一下单接口
		if (payType == 13) {
			map = AlipayOrderHelper.reqestWapAliPayOrder(fee, orderNo, title, body);
		} else {
			map = AlipayOrderHelper.reqestAPPAliPayOrder(fee, orderNo, title, body);
		}
		//微信统一下单接口返回后，生成订单保存到数据库
		Order o = new Order();
		o.setOrderMoney(fee);
		o.setOrderNo(orderNo);
		o.setOrderStatus(0);
		o.setCreateTime(new Date());
		o.setUserId(userId);
		o.setPayBy(3);
		o.setIsClosed(0);
		o.setOrderType(4);
		o = orderService.save(o);
		libOrderDetails.setCreateTime(new Date());
		libOrderDetails.setOrderId(o.getId());
		libOrderDetails.setOrderNo(orderNo);
		libOrderDetails.setUserId(userId);
		//存放redis
		tokenManager.set(orderNo + "batch", libOrderDetails, 7 * 24 * 3600);
		logger.info("==发起支付=orderNo-" + orderNo + "(libOrderDetails)" + JSON.toJSONString(libOrderDetails));
		logger.info("===发起支付接口数据准备成功:" + map);
		return map;
	}

	@Override
	public ResponseEntity getServiceRecords(String vipId) {
		ResponseEntity responseEntity = new ResponseEntity();
		Map<String, Object> data = new HashMap<>(16);
		//作业批改服务购买记录
		List<LibOrderDetails> list = libOrderDetailsService.findByVipIdAndPriceSpecies(vipId, "S003");
		List<ServiceRecordDto> dtoList = new ArrayList<>();
		//计算总金额的
		Map<String, ServiceRecordDto> dtoMap = new LinkedHashMap<>(16);
		for (LibOrderDetails details : list) {
			String key = details.getOrderNo();
			BigDecimal num = details.getNumber() == null ? BigDecimal.ONE : new BigDecimal(details.getNumber());
			//价格
			BigDecimal price = details.getPrice();
			ServiceRecordDto dto;
			if (dtoMap.get(key) != null) {
				dto = dtoMap.get(key);
				dto.setNums(dto.getNums() + num.intValue());
				dto.setAmount(price.add(dto.getAmount()));
				dtoMap.put(key, dto);
			} else {
				dto = new ServiceRecordDto();
				dto.setNums(num.intValue());
				dto.setAmount(price);
				dto.setPriceType(details.getPriceType());
				dto.setCreateTime(DateHelper.format(details.getCreateTime(), "yyyy-MM-dd HH:mm"));
				dtoMap.put(key, dto);
			}
		}
		for (ServiceRecordDto dto : dtoMap.values()) {
			dtoList.add(dto);
		}
		data.put("list", dtoList);
		responseEntity.success(data, "成功");
		return responseEntity;
	}

	@Override
	public ResponseEntity getServiceRecords(String vipId, int appType) {
		ResponseEntity responseEntity = new ResponseEntity();
		Map<String, Object> data = new HashMap<>(16);
		//指定平台服务购买记录
		List<LibOrderDetails> list = libOrderDetailsService.findOrderDetailList(vipId, "S003", appType);
		List<ServiceRecordV1Dto> dtoList = new ArrayList<>();
		//计算总金额的
		Map<String, ServiceRecordV1Dto> dtoMap = new LinkedHashMap<>(16);
		for (LibOrderDetails details : list) {
			String key = details.getOrderNo();
			BigDecimal num = details.getNumber() == null ? BigDecimal.ONE : new BigDecimal(details.getNumber());
			//价格
			BigDecimal price = details.getPrice();
			ServiceRecordV1Dto dto;
			if (dtoMap.get(key) != null) {
				dto = dtoMap.get(key);
				dto.setNums(dto.getNums() + num.intValue());
				dto.setAmount(price.add(dto.getAmount()));
				dtoMap.put(key, dto);
			} else {
				dto = new ServiceRecordV1Dto();
				dto.setNums(num.intValue());
				dto.setAmount(price);
				dto.setName(details.getDetails());
				dto.setCreateTime(DateHelper.format(details.getCreateTime(), "yyyy-MM-dd HH:mm"));
				dtoMap.put(key, dto);
			}
		}
		for (ServiceRecordV1Dto dto : dtoMap.values()) {
			dtoList.add(dto);
		}
		data.put("list", dtoList);
		responseEntity.success(data, "成功");
		return responseEntity;
	}


	@Override
	public List<LibVipService> findVipIdServiceByLibId(String libId,String vipId, String species) {
		return libVipServiceDao.findVipIdServiceByLibId(libId, vipId, species);
	}
	
	

	@Override 
	public List<LibVipService> findVipIdServiceByIntersectTime(
			String vipId, String species, Date startTime,Date endTime) {
		return libVipServiceDao.findVipIdServiceByIntersectTime(vipId, species,startTime,endTime);
	}

	
	
	/**
	 * 添加机构学生服务
	 * takeType=1 ：设置为立即生效，查询出有交叉的服务
	 * takeType=2 ：设置为到期生效，直接插入一条有效数据。
	 * @param libVipService
	 * @param takeType
	 * @return
	 */
	@Override
	public boolean insertVipIdServiceByAndTakeType(LibVipService libVipService, Integer takeType) {
		Integer serviceSort=1;
		if(takeType!=null && takeType==1){
			//设置为立即生效，查询出有交叉的服务，都设置为无效。
			List<LibVipService> oldLibVipServices=this.findVipIdServiceByIntersectTime(libVipService.getVipId(), "S003",
					libVipService.getStartTime(),libVipService.getEndTime());
			for (LibVipService oldLibVipService : oldLibVipServices) {
				oldLibVipService.setStat(2);
			}
			//更新前面的所有服务:无效
			this.save(oldLibVipServices);
			
			//添加新的服务
			libVipService.setCreateTime(new Date());
			libVipService.setServiceSort(serviceSort);
			this.save(libVipService);
		}else{
			//设置为推后生效
			List<LibVipService> oldLibVipServices=this.findVipIdServiceByIntersectTime(libVipService.getVipId(), "S003",
					libVipService.getStartTime(),libVipService.getEndTime());
			if(oldLibVipServices!=null && oldLibVipServices.size()>0) {
				return false;
			}
			libVipService.setCreateTime(new Date());
			libVipService.setServiceSort(serviceSort);
			this.save(libVipService);
		}
		return true;
	}

	@Override
	public List<LibVipService> findValidService(String vipId, String species) {
		return libVipServiceDao.findValidService(vipId, species);
	}

	@Override
	public List<LibVipService> findValidService(String vipId, List<String> species) {
		return libVipServiceDao.findValidService(vipId, species);
	}

	@Override
	public List<LibVipService> findValidService(String vipId, String species, String libId) {
		return libVipServiceDao.findValidService(vipId, species, libId);
	}

	@Override
	public void setLibService(TbVacationLimit newVacation,TbVacationLimit oldVacation) throws Exception {
        //日期是否修改
        boolean dateChanged = false;
        boolean isFirst = false;
        if (oldVacation.getStartDate() == null && oldVacation.getEndDate() == null) {
            isFirst = true;
        }
        if(newVacation.getStartDate()==null || newVacation.getEndDate()==null){
            throw new Exception("开始、结束时间不能为空");
        }
        if (!isFirst &&
                !(newVacation.getStartDate().compareTo(oldVacation.getStartDate()) == 0
                        && newVacation.getEndDate().compareTo(oldVacation.getEndDate()) == 0)) {
            dateChanged = true;
        }
        /**
         * 判断服务时间是否有修改
         * 1.无修改：
         *      1.1 如果是设置开启的，延长相应的服务
         *      1.2 如果是设置关闭的，缩减相应的服务
         * 2.有修改：
         *      2.1 如果是设置开启的，需要将之前的服务先还原到原来的服务，然后按照新的服务进行延长
         *      2.2 如果是设置关闭的，缩减原来的服务
         */
        //馆下所有的服务
        List<LibVipService> list = libVipServiceDao.findValidServiceOfLib("S003", newVacation.getLibId());
        for (LibVipService libVipService : list) {
        	//5是校区永久批改服务，不需要因为节假日延长或缩短时间
			if (!Objects.equals(libVipService.getCorrectType(), 5)) {
				//1关闭 2-开启
				if (newVacation.getSetState() == 2) {
					if (dateChanged) {
						this.subServiceForHoliday(libVipService, oldVacation);
						this.addServiceForHoliday(libVipService, newVacation);
					} else {
						this.addServiceForHoliday(libVipService, newVacation);
					}
				} else if (newVacation.getSetState() == 1) {
					this.subServiceForHoliday(libVipService, newVacation);
				}
			}
        }
        this.save(list);
	}

    /**
     * 因为节假日延长相应服务
     * @param libVipService
     * @param vacationLimit
     * @throws Exception
     */
    private void addServiceForHoliday(LibVipService libVipService, TbVacationLimit vacationLimit) throws Exception {
        Date endTime = libVipService.getEndTime();
        //用作下一次时间段的开始时间，校验下一段时间是否包含有效的时间段
        Date newBeginTime = DateHelper.getNextDay(endTime, 1);
        //重叠天数
        Integer coincidenceDay = DateHelper.getDayCoincidence(libVipService.getStartTime(), libVipService.getEndTime(), vacationLimit.getStartDate(), vacationLimit.getEndDate());
        if (coincidenceDay > 0) {
            GiveRecord giveRecord = new GiveRecord();
            giveRecord.setGiveWay(4);
            giveRecord.setQuantity(coincidenceDay);
            giveRecord.setVacationLimitId(vacationLimit.getId());
            giveRecord.setCreateTime(new Date());
            giveRecord.setSpecies("S003");
            giveRecord.setVipId(libVipService.getVipId());
			giveRecord.setVipServiceId(libVipService.getId());
            giveRecordService.save(giveRecord);
            endTime = DateHelper.getNextDay(endTime, coincidenceDay);
        }
        while (newBeginTime != null) {
			newBeginTime = this.getEndTimeSkipHoliday(newBeginTime, endTime, vacationLimit.getLibId(), libVipService.getVipId(), true, libVipService.getId());
            if (newBeginTime != null) {
                endTime = newBeginTime;
            }
        }
        libVipService.setEndTime(endTime);
    }

    /**
     * 因为节假日缩减相应服务
     * @param libVipService
     * @param vacationLimit
     */
    private void subServiceForHoliday(LibVipService libVipService, TbVacationLimit vacationLimit) {
        Date endTime = libVipService.getEndTime();
        //查找所有有效的因节假日延长的时间天数，然后减去相应的天数
		List<GiveRecord> giveRecordList = giveRecordService.findValidGiveRecord(vacationLimit.getId(), libVipService.getVipId(), 4, libVipService.getId());
        int days = 0;
        for (GiveRecord giveRecord : giveRecordList) {
            days += giveRecord.getQuantity();
            //已经用过，失效掉
            giveRecord.setInvalid(1);
        }
        giveRecordService.save(giveRecordList);
        if (days > 0) {
            //记录因节假日关闭而减去的服务记录
            GiveRecord newGiveRecord = new GiveRecord();
            newGiveRecord.setGiveWay(5);
            newGiveRecord.setQuantity(days);
            newGiveRecord.setVacationLimitId(vacationLimit.getId());
            newGiveRecord.setCreateTime(new Date());
            newGiveRecord.setSpecies("S003");
            newGiveRecord.setVipId(libVipService.getVipId());
			newGiveRecord.setVipServiceId(libVipService.getId());
            giveRecordService.save(newGiveRecord);
            //减掉因为该节假日延长的服务天数
            endTime = DateHelper.getNextDay(endTime, -days);
            libVipService.setEndTime(endTime);
        }
    }

	/**
	 * 获取会员卡有效时间间隔
	 *
	 * @param libVipService 会员服务
	 * @param type          卡类型：平台服务（家长购买）：C004作业吧月卡C005作业吧半年卡C006作业吧年卡C015季度卡；C023平台服务(机构购买)C024校区服务
	 * @param num           数量
	 * @param libId    图书馆id
	 * @return
	 */
	@Override
	public Map<String, String> getInterVal(LibVipService libVipService, String type, int num, String libId, boolean addDelayHolidayService) {
		Map<String, String> map = new HashMap<>(16);
		//计算的开始时间
		Date beginTime;
		//实际的开始时间
		Date actualBeginTime;
		Date endTime = null;
		String vipId = null;
		//还处于有效日期内
        if (libVipService != null && DateHelper.compareTwoDate(new Date(), libVipService.getEndTime())) {
			if (libVipService.getStat() != null && libVipService.getStat() == 2) {
				//这里证明服务是失效的，直接用结束时间
				beginTime = libVipService.getEndTime();
			} else {
				//使用结束时间
				beginTime = DateHelper.getNextDay(libVipService.getEndTime(), 1);
			}
            actualBeginTime = libVipService.getStartTime();
            vipId = libVipService.getVipId();
        } else {
            beginTime = new Date();
            actualBeginTime = beginTime;
        }
		if ("C004".equals(type) || "C023".equals(type) || "C024".equals(type)) {
			endTime = DateHelper.getMonthDate(beginTime, 1 * num);
		} else if ("C005".equals(type)) {
			endTime = (DateHelper.getMonthDate(beginTime, 6 * num));
		} else if ("C006".equals(type)) {
			endTime = (DateHelper.getMonthDate(beginTime, 12 * num));
		} else if ("C015".equals(type)) {
			endTime = (DateHelper.getMonthDate(beginTime, 3 * num));
		}
		//如果馆里设置了节假日，应该往后面推
		if(StringUtil.isNotBlank(libId)){
			try {
				//循环遍历，直到延长的时间不和节假日有重叠的地方
				Date newBeginTime = beginTime;
				while (newBeginTime != null) {
					newBeginTime = this.getEndTimeSkipHoliday(newBeginTime, endTime, libId, vipId, addDelayHolidayService, libVipService != null ? libVipService.getId() : null);
					if (newBeginTime != null) {
						endTime = newBeginTime;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("计算服务延长时间失败...");
			}
		}
		map.put("beginDate", DateFormatUtils.format(actualBeginTime, "yyyy.MM.dd"));
		map.put("endDate", DateFormatUtils.format(endTime, "yyyy.MM.dd"));
		return map;
	}

	@Override
	public Date getEndTimeSkipHoliday(Date beginTime, Date endTime, String libId, String vipId, boolean addDelayHolidayService,String vipServiceId) throws Exception {
		//当前生效的节假日
		List<TbVacationLimit> vacationLimits = vacationLimitService.findValidVocationLimit(beginTime, endTime, libId);
		if (vacationLimits.size() > 0) {
			Integer days = 0;
			for (TbVacationLimit vacationLimit : vacationLimits) {
			    //重叠的天数
				Integer coincidenceDay = DateHelper.getDayCoincidence(beginTime, endTime, vacationLimit.getStartDate(), vacationLimit.getEndDate());
				//计算和假期重叠时间
				days += coincidenceDay;
				//这里是添加因假期设置，添加的延长服务记录
                if (addDelayHolidayService && coincidenceDay > 0) {
					GiveRecord giveRecord = new GiveRecord();
					giveRecord.setGiveWay(4);
					giveRecord.setQuantity(coincidenceDay);
					giveRecord.setVacationLimitId(vacationLimit.getId());
					giveRecord.setCreateTime(new Date());
					giveRecord.setSpecies("S003");
					giveRecord.setVipId(vipId);
					giveRecord.setVipServiceId(vipServiceId);
					giveRecordService.save(giveRecord);
				}
			}
			//相隔延长天数，往后延长相应天数
			if (days > 0) {
				endTime = DateHelper.getNextDay(endTime, days);
			}
			return endTime;
		}
		return null;
	}

	@Override
    @Cacheable(value = "key", keyGenerator = "keyGenerator_getChildServiceList" , cacheManager="cacheServiceManager")
	public List<LibVipService> getChildServiceList(String vipId) {
		List<LibVipService> serviceList = libVipServiceDao.findValidService(vipId, Arrays.asList("S003", "S999"));
		return serviceList;
	}

	
	@Override
	public LibVipService findCorrectTypeByVipId(String vipId){
         return libVipServiceDao.findCorrectTypeByVipId(vipId);


	}

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

	@Override
	public void clearServiceCache(String libId, List<String> vipIdList) {
		vipIdList.forEach(vipId -> {
			if (StringUtil.isNotBlank(libId)) {
				tokenManager.delString("CACH_SERVICE:ChildDerverService:com.ssj.service.conch.conch.service.impl.ConchDerverServiceImplgetChildDerverServiceByLibVip" + vipId + libId);
			}
            tokenManager.delString("CACH_SERVICE:ChildServiceList:com.ssj.service.weixin.sales.service.impl.LibVipServiceServiceImplgetChildServiceList" + vipId);
		});
	}
	
	
	
	@Override
    public void insertLibServiceByType(String vipId, String libId, Date endDate, int signType) {
        if (signType > 0) {
            //新套餐，需要给校区服务和批改服务两个，结束时间保持一致
            //查询这个馆下有没有有效的服务
            endDate = this.getEndDate(vipId, libId); 
            this.insertLibCorrectService(vipId, libId, endDate);
            this.insertLibService(vipId, libId, endDate);
        } else {
            //老套餐，只需要给指定的校区服务
            this.insertLibService(vipId, libId, DateUtil.parse_yyyyMMdd("9999-01-01"));
        }
    }

    @Override
    public void insertLibCorrectServiceByType(String vipId, String libId, Date endDate, int signType) {
        if (signType > 0) {
            //新套餐，给的这个服务需要和校区服务保持一致的结束时间
            //查询这个馆下有没有有效的服务
            endDate = this.getEndDate(vipId, libId);
            this.insertLibCorrectService(vipId, libId, endDate);
        } else {
            //老套餐，直接给永久服务
            this.insertLibCorrectService(vipId, libId, DateUtil.parse_yyyyMMdd("9999-01-01"));
        }
    }

	@Override
	public void insertLibServiceV1(String vipId, String libId) throws Exception{
		//查询这个馆下有没有有效的服务
		int type = this.findValidTopService(vipId, "S003", 2) != null ? 2 : 1;
		//查询这个服务是否有效
		ServiceVo vo = new ServiceVo();
		vo.setLibId(libId);
		vo.setType(type);
		ResponseEntity entity = apiMerchantController.service(vo);
		if(!"999".equals(entity.getCode())){
			throw new Exception();
		}
		Map<String, Object> data =(Map<String, Object>) entity.getData();
		Date endDate = null;
		String endSignTime = (String) data.get("endSummaryTime");
		if (StringUtil.isNotBlank(endSignTime)) {
			endDate = DateHelper.parseDate(endSignTime, "yyyy-MM-dd");
		}
		Date now = new Date();
		//是否期满
		boolean expired = false;
		if (!DateHelper.compareTwoDate(now, endDate)) {
			expired = true;
		}
		//之前的校区服务
		LibVipService libVipService = libVipServiceDao.findTopByVipIdAndLibIdAndSpeciesAndTypeOrderByCreateTimeDesc(vipId, libId, "S003", "C024");
		if (libVipService == null) {
			libVipService = new LibVipService();
			libVipService.setVipId(vipId);
			libVipService.setLibId(libId);
			libVipService.setStartTime(now);
			libVipService.setEndTime(endDate);
			libVipService.setSpecies("S003");
			libVipService.setType("C024");
			libVipService.setCreateTime(now);
			//为校区服务
			libVipService.setCorrectType(2);
			//排所有服务优先级第3
			libVipService.setServiceSort(3);
		}
		if (expired) {
			//期满，设置为失效
			libVipService.setStat(2);
		} else {
			libVipService.setStat(1);
		}
		this.save(libVipService);
	}

	@Override
	public void insertLibCorrectService(String vipId, String libId) {
		Date now = new Date();
		//之前的校区批改服务
		LibVipService libVipService = libVipServiceDao.findTopByVipIdAndLibIdAndSpeciesAndTypeOrderByCreateTimeDesc(vipId, libId, "S003", "C025");
		if (libVipService == null) {
			libVipService = new LibVipService();
			libVipService.setVipId(vipId);
			libVipService.setLibId(libId);
			libVipService.setStartTime(now);
			libVipService.setEndTime(DateUtil.parse_yyyyMMdd("9999-01-01"));
			libVipService.setStat(1);
			libVipService.setSpecies("S003");
			libVipService.setType("C025");
			libVipService.setCreateTime(now);
			//为校区批改服务
			libVipService.setCorrectType(5);
			//排所有服务优先级第4
			libVipService.setServiceSort(4);
		} else {
			libVipService.setStat(1);
		}
		this.save(libVipService);
	}

	/**
     * 获取馆服务的结束时间
     *
     * @param vipId
     * @param libId
     * @return
     */
    Date getEndDate(String vipId, String libId) {
        Merchant merchant=merchantService.getMerchantByLibId(libId);
        return merchant.getEndActiveTime();
    }


    /**
     * 新增校区批改服务
     *
     * @param vipId
     * @param libId
     * @param endDate
     */
    void insertLibCorrectService(String vipId, String libId, Date endDate) {
        Date now = new Date();
        //之前的校区批改服务
        LibVipService libVipService = libVipServiceDao.findTopByVipIdAndLibIdAndSpeciesAndTypeOrderByCreateTimeDesc(vipId, libId, "S003", "C025");
        if (libVipService == null) {
            libVipService = new LibVipService();
            libVipService.setVipId(vipId);
            libVipService.setLibId(libId);
            libVipService.setStartTime(now);
            libVipService.setEndTime(endDate);
            libVipService.setStat(1);
            libVipService.setSpecies("S003");
            libVipService.setType("C025");
            libVipService.setCreateTime(now);
            //为校区批改服务
            libVipService.setCorrectType(5);
            //排所有服务优先级第4
            libVipService.setServiceSort(4);
            this.save(libVipService);
        } else {
            libVipService.setStat(1);
            this.save(libVipService);
        }
    }

    /**
     * 新加校区服务
     *
     * @param vipId
     * @param libId
     * @param endDate
     */
    void insertLibService(String vipId, String libId, Date endDate) {
        Date now = new Date();
        //是否期满
        boolean expired = false;
        if (!DateHelper.compareTwoDate(now, endDate)) {
            expired = true;
        }
        //之前的校区服务
        LibVipService libVipService = libVipServiceDao.findTopByVipIdAndLibIdAndSpeciesAndTypeOrderByCreateTimeDesc(vipId, libId, "S003", "C024");
        if (libVipService == null) {
            libVipService = new LibVipService();
            libVipService.setVipId(vipId);
            libVipService.setLibId(libId);
            libVipService.setStartTime(now);
            libVipService.setEndTime(endDate);
            libVipService.setSpecies("S003");
            libVipService.setType("C024");
            libVipService.setCreateTime(now);
            //为校区服务
            libVipService.setCorrectType(2);
            //排所有服务优先级第3
            libVipService.setServiceSort(3);
            this.save(libVipService);
        }
        if (expired) {
            //期满，设置为失效
            libVipService.setStat(2);
            this.save(libVipService);
        } else {
            libVipService.setStat(1);
            this.save(libVipService);
        }

    }

	

	@Override
	public void openApiServiceCRM(Integer type,String libId,Integer signType,Integer mealType,Integer num,String startActiveTime,String computeTime,String endTime) {
		RequestOpenApiUtils.openApiServiceCRM(type, libId,signType,mealType, num, startActiveTime, computeTime, endTime);
	}
	
	
	
	


}
