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

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.ssj.bean.sys.codeexchange.CodeExchange;
import com.ssj.bean.weixin.card.domain.LibCardDetail;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.sales.domain.LibOrderDetails;
import com.ssj.bean.weixin.sales.domain.LibStaffing;
import com.ssj.bean.weixin.sales.domain.LibVipCode;
import com.ssj.bean.weixin.sales.domain.LibVipService;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.weixin.sales.dao.LibOrderDetailsDao;
import com.ssj.dao.weixin.sales.dao.LibOrderDetailsQueryDao;
import com.ssj.dao.weixin.sales.dao.LibStaffingQueryDao;
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.StringUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.conch.parents.v2.service.ParentV2Service;
import com.ssj.service.sys.codeexchange.CodeExchangeService;
import com.ssj.service.weixin.card.service.ILibCardService;
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.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.*;
import com.ssj.service.weixin.user.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
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.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/** 
 * @author  ZhangCaibao 
 * @version 2017年4月28日 下午3:07:45 
 * 类说明 
 */
@Service(version="1.0")
@Transactional
public class LibOrderDetailsServiceImpl extends BaseServiceImpl<LibOrderDetails, String> implements  LibOrderDetailsService{
	
	private   Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private LibOrderDetailsDao  libOrderDetailsDao;
	@Autowired
	private LibOrderDetailsQueryDao  libOrderDetailsQueryDao;
	
	@Autowired
	private UserService  userService;
	
	@Autowired
	private LibStaffingQueryDao  libStaffingQueryDao;
	@Autowired
	private TokenManager  tokenManager;
	
	 @Autowired
	private PushTemplateService  pushTemplateService;
	
	@Autowired
	private LibVipServiceService  libVipServiceService;
	@Autowired
	private LibStaffingService  libStaffingService;
	
	@Autowired
	private LibVipCodeService  libVipCodeService;
	 
    @Autowired
	private ILibVipService vipService; 
    @Autowired
    private ParentV2Service parentV2Service;
    @Autowired
 	private ILibJoinService joinService;    
    
    @Autowired
    private LibCourseService libCourseService;
    
    @Autowired
    private ILibCardService libCardService;
	
	private String template_id_short="OPENTM407169642";
	
	@Autowired
	private IBookManagerService  managerService;
	@Autowired
	private CodeExchangeService codeExchangeService;
	
	@Override
	public PagingAndSortingRepository<LibOrderDetails, String> getDao() {
		return libOrderDetailsDao;
	}
	@Override
	public List<LibOrderDetails> getByUserId(String account) {
		return libOrderDetailsDao.getByUserId(account);
	}
	@Override
	public List<Map<String, Object>> getOrderDetailByAccount(String account) {
		String userId=userService.findUserById(account);
		return libStaffingQueryDao.getOrderDetail(userId);
	}
	@Override
	public void sendReviewTemplate(String id,String openId,String childName,String details,BigDecimal price) {
		    Map<String,String> data =new HashMap<String, String>();
			data.put("first", childName+"发起"+details+"（实付金额"+price+"元）的退款申请，需要您及时处理\n ");
			data.put("keyword1","未审核");
			data.put("keyword2", DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
			data.put("remark", "\n若未做审核，我们将再次提醒。");
			String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/applyTwo_"+id+".html";
			SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, url, data);
			pushTemplateService.savePushWxTemplate(sendTemplateShort);
	}
	@Override
	public void sendRefuseTemplate(String id,String openId,String reason) {
		Map<String,String> data =new HashMap<String, String>();
		data.put("first", "您的退款被拒绝，理由:"+reason+"，需要重新申请退款\n");
		data.put("keyword1","已拒绝");
		data.put("keyword2", DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
		data.put("remark", "\n");
		String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/applyJuJue_"+id+".html";
		
		SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, url, data);
		pushTemplateService.savePushWxTemplate(sendTemplateShort);
		
	}
	@Override
	public void sendSuperiorTemplate(String url,String libId, String type,String id,String childName,BigDecimal price) {
		List<String> openIdlist=libOrderDetailsDao.getByStaffingOpenId(libId, type);
		url=(String) SystemResourceLocator.getValue("sys_url")+url;
		for (String openId : openIdlist) {
			    Map<String,String> data =new HashMap<String, String>();
				data.put("first", childName+"发起"+price+"元的退款申请，需要您及时处理\n");
				data.put("keyword1","未审核");
				data.put("keyword2", DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
				data.put("remark", "\n若未做审核，我们将再次提醒。");
				SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, url, data);
				pushTemplateService.savePushWxTemplate(sendTemplateShort);
		}
	}
	@Override
	public void sendSubordinateTemplate(String initiateOpenId, String libId,
			String orderDetailsId,String id,String reason ) {
		List<String> openIdlist=libOrderDetailsDao.getOrderRefundsOpenId(libId, orderDetailsId,id);
		if(!openIdlist.contains(initiateOpenId)){
			openIdlist.add(initiateOpenId);
		}
		Map<String,String> data =new HashMap<String, String>();
		for (String openId : openIdlist) {
			if(initiateOpenId .equals(openId)){
				data.put("first", "您的退款被拒绝，理由:"+reason+"，需要重新申请退款\n");
			}else{
				data.put("first", "您有一则审批处理通知，请知晓\n");
			}
			data.put("keyword1","已拒绝");
			data.put("keyword2", DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
			data.put("remark", "\n");
			String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/applyJuJue_"+id+".html";
			//SendTemplate  sendTemplate  =new  SendTemplate(openId,template_id,url,data);
			//NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
			
			SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, url, data);
			pushTemplateService.savePushWxTemplate(sendTemplateShort);
			
			data.clear();
	}
	}
	@Override
	public void sendAgreeTemplate(String id, String openId) {
		Map<String,String> data =new HashMap<String, String>();
		data.put("first", "您的退款申请已通过，退款将在1-2个工作日内返回微信账户\n");
		data.put("keyword1","已通过");
		data.put("keyword2", DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
		data.put("remark", "\n");
		String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/applyOk_"+id+".html";
		
		SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, url, data);
		pushTemplateService.savePushWxTemplate(sendTemplateShort);

	}
	@Override
	public Integer getSalesPrice(String account) {
		return libOrderDetailsDao.getSalesPrice(account);
	}
	@Override
	public Page<Map<String, Object>> findForPageList(
			Map<String, Object> searchParams, Pageable pageable) {
		return libOrderDetailsQueryDao.findForPageList(searchParams, pageable);
	}
	@Override
	public Integer getUserHistory(String salesPriceId ,String vipId,String  libId,String species ) {
		// 1 新签  2 续签
		if("S003".equals(species)){
			/*Integer ci =  libOrderDetailsDao.isVipDc(salesPriceId,libId);
			if(ci == 1){
				return 0;
			} */
				
				Integer count =	libOrderDetailsDao.getUserHistoryVIP(libId,vipId);
				if(count>0){
					return 2;
				}
				return  1;
		}
		Integer count = libOrderDetailsDao.getUserHistory(libId,vipId);
		if(count>0){
		  Integer days=	this.getLibVipService(vipId, libId);
		  if(days !=null && days <=15){
			  count =1;
		  }else{
			  count =2; 
		  }
		  return  count;
		}
		
		return  1;
	}
	@Override
	public List<Map<String, Object>> getOrderDetailByOrgCode(Map<String, Object> searchParams) {
		return libOrderDetailsQueryDao.getOrderDetailByOrgCode(searchParams);
	}
	@Override
	public List<Map<String, Object>> getOrderDetailMonthByOrgCode(Map<String, Object> searchParams) {
		List<Map<String, Object>>  list =   libOrderDetailsQueryDao.getOrderDetailMonthByOrgCode(searchParams);
		if(list !=null && list.size()>0){
			for (Map<String, Object> map : list) {
				 BigDecimal sd_hy_nk_xin_price  =   new BigDecimal(map.get("sd_hy_nk_xin_count").toString()).multiply(new BigDecimal("100"));
				 BigDecimal sd_hy_nk_xu_price   =   new BigDecimal(map.get("sd_hy_nk_xu_count").toString()).multiply(new BigDecimal("50"));
				 BigDecimal sd_hy_yk_xin_price  =   new BigDecimal(map.get("sd_hy_yk_xin_count").toString()).multiply(new BigDecimal("20"));
				 BigDecimal sd_hy_yk_xu_price   =   new BigDecimal(map.get("sd_hy_yk_xu_count").toString()).multiply(new BigDecimal("10"));
				 BigDecimal sd_vip_yk_xin_price =   new BigDecimal(map.get("sd_vip_yk_xin_count").toString()).multiply(new BigDecimal("80"));
				 BigDecimal sd_vip_yk_xu_price  =   new BigDecimal(map.get("sd_vip_yk_xu_count").toString()).multiply(new BigDecimal("40"));
				 BigDecimal sd_vip_nk_xin_price =   new BigDecimal(map.get("sd_vip_nk_xin_count").toString()).multiply(new BigDecimal("600"));
				 BigDecimal sd_vip_nk_xu_price  =   new BigDecimal(map.get("sd_vip_nk_xu_count").toString()).multiply(new BigDecimal("300"));
				 map.put("sd_hy_nk_xin_price", sd_hy_nk_xin_price); //年卡新签
				 map.put("sd_hy_nk_xu_price", sd_hy_nk_xu_price); //年卡续签
				 map.put("sd_hy_yk_xin_price", sd_hy_yk_xin_price); //月卡新签
				 map.put("sd_hy_yk_xu_price", sd_hy_yk_xu_price); //月卡续签
				 map.put("sd_vip_yk_xin_price", sd_vip_yk_xin_price); //vip月卡新签
				 map.put("sd_vip_yk_xu_price", sd_vip_yk_xu_price); //vip月卡续签
				 map.put("sd_vip_nk_xin_price", sd_vip_nk_xin_price); //vip年卡新签
				 map.put("sd_vip_nk_xu_price", sd_vip_nk_xu_price); //vip年卡续签
				 
				 
				 BigDecimal sd_zm_xin_price =   new BigDecimal(map.get("sd_zm_xin_count").toString()).multiply(new BigDecimal("20"));//周末
				 BigDecimal sd_hj_xin_price  =   new BigDecimal(map.get("sd_hj_xin_count").toString()).multiply(new BigDecimal("100"));//寒假
				 
				 map.put("sd_zm_xin_price", sd_zm_xin_price); //周末
				 map.put("sd_hj_xin_price", sd_hj_xin_price); //寒假
				 BigDecimal sd_c009_price =   new BigDecimal(map.get("sd_c009_count").toString()).multiply(new BigDecimal("48"));//特色
				 map.put("sd_c009_price", sd_c009_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //特色应付金额
				 BigDecimal sd_c010_price =   new BigDecimal(map.get("sd_c010_count").toString()).multiply(new BigDecimal("90"));//拼音识字
				 map.put("sd_c010_price", sd_c010_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //拼音识字应付金额
				 BigDecimal sd_c011_price =   new BigDecimal(map.get("sd_c011_count").toString()).multiply(new BigDecimal("90"));//数学思维
				 map.put("sd_c011_price", sd_c011_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //数学思维应付金额
				 BigDecimal sd_c012_price =   new BigDecimal(map.get("sd_c012_count").toString()).multiply(new BigDecimal("180"));//全天班
				 map.put("sd_c012_price", sd_c012_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //全天班应付金额
				 
				 BigDecimal c009_price =   new BigDecimal(map.get("c009_price").toString()).multiply(new BigDecimal("0.5"));//特色
				 map.put("c009_price", c009_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //特色应付咨询服务费
				 BigDecimal c010_price =   new BigDecimal(map.get("c010_price").toString()).multiply(new BigDecimal("0.15"));//拼音识字
				 map.put("c010_price", c010_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //拼音识字咨询服务费
				 BigDecimal c011_price =   new BigDecimal(map.get("c011_price").toString()).multiply(new BigDecimal("0.15"));//数学思维
				 map.put("c011_price", c011_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //数学思维咨询服务费
				 BigDecimal c012_price =   new BigDecimal(map.get("c012_price").toString()).multiply(new BigDecimal("0.15"));//全天班
				 map.put("c012_price", c012_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //全天班应咨询服务费
				 BigDecimal  zixun_price = c009_price.add(c010_price).add(c011_price).add(c012_price);
				 map.put("zixun_price", zixun_price.setScale(2,BigDecimal.ROUND_HALF_UP)); //咨询服务费累加
				 
				 //总部管理分成=（借阅会员卡新签实收总额+借阅会员卡续费实收总额+联名卡周末卡新签实收总额+寒假卡新签实收总额）*5%
				 BigDecimal company_total_price =  new BigDecimal(map.get("xin_huiyuan_price").toString());
				 company_total_price =company_total_price.add(new BigDecimal(map.get("xu_huiyuan_price").toString()));
				 company_total_price =company_total_price.add(new BigDecimal(map.get("hj_xin_price").toString()));
				 company_total_price=company_total_price.multiply(new BigDecimal("0.05").setScale(2,BigDecimal.ROUND_HALF_UP));
				 logger.info("company_total_price="+company_total_price);
				 map.put("company_total_price", company_total_price); //总部管理分成
				 
				 
				 BigDecimal total_price = new BigDecimal(map.get("total_price").toString());
				 //计算手续费
				 BigDecimal jysxf_price = total_price.multiply(new BigDecimal("0.012").setScale(3,BigDecimal.ROUND_HALF_UP));
				 jysxf_price = jysxf_price.setScale(2,BigDecimal.ROUND_HALF_UP);
				 map.put("jysxf_price", jysxf_price); 
				 BigDecimal  zhichuTotal  =jysxf_price.add(company_total_price);
				 BigDecimal zhichu = new BigDecimal("0");
				 
				 zhichu=zhichu.add(sd_hy_nk_xin_price );
				 zhichu=zhichu.add(sd_hy_nk_xu_price  );
				 zhichu=zhichu.add(sd_hy_yk_xin_price );
				 zhichu=zhichu.add(sd_hy_yk_xu_price  );
				 zhichu=zhichu.add(sd_vip_yk_xin_price);
				 zhichu=zhichu.add(sd_vip_yk_xu_price );
				 zhichu=zhichu.add(sd_vip_nk_xin_price);
				 zhichu=zhichu.add(sd_vip_nk_xu_price );
				 
				 zhichu=zhichu.add(sd_zm_xin_price );
				 zhichu=zhichu.add(sd_hj_xin_price );
				 zhichu=zhichu.add(sd_c009_price );
				 zhichu=zhichu.add(sd_c010_price );
				 zhichu=zhichu.add(sd_c011_price );
				 zhichu=zhichu.add(sd_c012_price );
				 map.put("zhichu", zhichu.setScale(2,BigDecimal.ROUND_HALF_UP)); 
				 zhichuTotal = zhichuTotal.add(zhichu);
				 zhichuTotal = zhichuTotal.add(zixun_price);
				 map.put("zhichuTotal", zhichuTotal.setScale(2,BigDecimal.ROUND_HALF_UP)); 
				 
				 //得出结余金额
				 BigDecimal balance_amount = total_price.subtract(zhichuTotal);
				 
				 map.put("balance_amount", balance_amount.setScale(2,BigDecimal.ROUND_HALF_UP)); 
			}
		}
		return list;
	}
	
	@Override
	public List<Map<String, Object>> getOrderDetailMonthA(Map<String, Object> searchParams) {
		List<Map<String, Object>>  list =   libOrderDetailsQueryDao.getOrderDetailMonthA(searchParams);
		if(list !=null && list.size()>0){
			for (Map<String, Object> map : list) {
				 BigDecimal total_price = new BigDecimal(map.get("total_price").toString());
				 map.put("total_price", total_price.setScale(2,BigDecimal.ROUND_HALF_UP));
				 
				 //计算手续费
				 BigDecimal jysxf_price = total_price.multiply(new BigDecimal("0.012"));
				 map.put("jysxf_price", jysxf_price.setScale(2,BigDecimal.ROUND_HALF_UP));
				 
				 //管理提成
				 BigDecimal gltc_price = total_price.multiply(new BigDecimal("0.05"));
				 map.put("gltc_price", gltc_price.setScale(2,BigDecimal.ROUND_HALF_UP));
				 
				 // 售卡奖励
				 Integer total_count = Integer.parseInt(map.get("total_count").toString());//总卡数

				 String months = map.get("months").toString();//统计月份
				 String qy_months = map.get("qy_months").toString();//签约月份

//				 Integer zm_count = Integer.parseInt(map.get("zm_count").toString());//周末卡总数
//				 BigDecimal zm_price = new BigDecimal(map.get("zm_price").toString());//周末卡金额
//				 
//				 Integer huiyuan_count = Integer.parseInt(map.get("huiyuan_count").toString());//年卡总数
//				 BigDecimal huiyuan_price = new BigDecimal(map.get("huiyuan_price").toString());//年卡金额
				 
				 String libtype = map.get("libtype").toString();//图书馆的模式 2,3
				 String arrive_time = map.get("arrive_time")!=null ?map.get("arrive_time").toString(): "";//图书馆达标月份  如;2017年10月
				 
				 Integer monthNum=differMonth(qy_months,months);//计算是不是第一周期间
				 BigDecimal per=new BigDecimal("0");
				 BigDecimal award_price = new BigDecimal("0");
				 if("2".equals(libtype)){//A模式
					 
					 if(monthNum<2){//签约当月与次月为一个月度计算周期,第一周期不可能会算40%
						 Integer cycle_count = Integer.parseInt(map.get("cycle_count").toString());//第一周期卡总数
						 if(cycle_count<=15){
							 per=new BigDecimal("0.2");
						 }else  if(cycle_count<=30){
							 per=new BigDecimal("0.3");
						 }else{
							 per=new BigDecimal("0.5");
						 }
					 }else{//第二周期开始判断，图书馆是否已达标。
						 
						//图书馆未达标了
						 if(total_count<=10){
							 per=new BigDecimal("0.2");
						 }else  if(total_count<=20){
							 per=new BigDecimal("0.3");
						 }else{
							 per=new BigDecimal("0.5");
						 }
						 
						 if(StringUtils.isNotEmpty(arrive_time)){//图书馆达标了
							monthNum=differMonth(arrive_time,months);//当前统计的月份大于图书馆达标月份，就算40%
							if(monthNum>=1){
								 per=new BigDecimal("0.4");
							}
						 }
					 }
					 award_price = total_price.multiply(per.setScale(3,BigDecimal.ROUND_HALF_UP));
					 map.put("award_price", award_price.setScale(2,BigDecimal.ROUND_HALF_UP));
				 }else{//B模式
					 
					 if(monthNum<2){//签约当月与次月为一个月度计算周期,第一周期不可能会算40%
						 Integer cycle_count = Integer.parseInt(map.get("cycle_count").toString());//第一周期卡总数
						 if(cycle_count<=10){
							 per=new BigDecimal("0.2");
						 }else  if(cycle_count<=20){
							 per=new BigDecimal("0.3");
						 }else{
							 per=new BigDecimal("0.5");
						 }
					 }else{//第二周期开始判断，图书馆是否已达标。
						 
						//图书馆未达标了
						 if(total_count<=10){
							 per=new BigDecimal("0.2");
						 }else  if(total_count<=20){
							 per=new BigDecimal("0.3");
						 }else{
							 per=new BigDecimal("0.5");
						 }
						 if(StringUtils.isNotEmpty(arrive_time)){//图书馆达标了
							monthNum=differMonth(arrive_time,months);//当前统计的月份大于图书馆达标月份，就算40%
							if(monthNum>=1){
								 per=new BigDecimal("0.4");
							}
						 }
						 
					 }
					 award_price = total_price.multiply(per);
					 map.put("award_price", award_price.setScale(2,BigDecimal.ROUND_HALF_UP));
				 }
				 BigDecimal pay_price=award_price.add(jysxf_price).add(gltc_price);
				 map.put("pay_price", pay_price.setScale(2,BigDecimal.ROUND_HALF_UP));
				 map.put("finally_price", total_price.subtract(pay_price).setScale(2,BigDecimal.ROUND_HALF_UP));
			}
		}
		return list;
	}

	public static Integer differMonth(String startMonth,String endMonth){
		Integer monthNum=0;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
	        Calendar bef = Calendar.getInstance();
	        Calendar aft = Calendar.getInstance();
	        bef.setTime(sdf.parse(startMonth));
	        aft.setTime(sdf.parse(endMonth));
	        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
	        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
	        monthNum=month + result;  
		} catch (Exception e) {
			
		}
		return monthNum;
	}

	@Override
	public List<String> getLibVipId(String account) {
		return libOrderDetailsDao.getLibVipId(account);
	}
	@Override
	public List<Map<String, Object>> getOrderDetailZongBuRenZheng(
			Map<String, Object> searchParams) {
		return libOrderDetailsQueryDao.getOrderDetailZongBuRenZheng(searchParams);
	}
	@Override
	public List<Map<String, Object>> getOrderDetailQuDao(
			Map<String, Object> searchParams) {
		List<Map<String, Object>>  list  = libOrderDetailsQueryDao.getOrderDetailQuDao(searchParams);
		return list;
     }
	@Override
	public void sendSales(String details, String salesUserId, String parentName ,String childName,BigDecimal price,
			Integer count,String libId) {
			childName=childName!=null ? childName :"";
			parentName=parentName!=null ? parentName :"";
			String xin = count ==0 ?"新签":"续签";
		    Map<String,String> data =new HashMap<String, String>();
		    StringBuffer sb = new StringBuffer();
		    sb.append("您好");
			sb.append(parentName).append("通过你的推荐已成功购买了").append(details).append("\n");
			data.put("first", sb.toString());
			data.put("keyword1",childName);
			data.put("keyword2",price.toString()+"元");
			data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
			List<Object[]> result=libOrderDetailsDao.monthlySalesUser(salesUserId,libId);
			Object price_total =0;
			Object user_total =0;
			if(result != null && !result.isEmpty()){
				Object[] tempObj = result.get(0);
				price_total = (Object)tempObj[0];
				user_total = (Object)tempObj[1];
			}
			data.put("remark", "订单状态："+xin+"\n\n本月通过您成功推荐购卡累计："+user_total+"人，实际营收金额："+price_total+"元。");
			String template_id_short=(String) SystemResourceLocator.getValue("sendTemplate101");
			//SendTemplate  sendTemplate  =new  SendTemplate(userService.getAccount(salesUserId),templateId,null,data);
			//JSONObject jsonObject = NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
			//logger.info("销售售出订单后，发送给销售="+jsonObject.toJSONString());
			SendTemplateShort sendTemplateShort=new SendTemplateShort(userService.getAccount(salesUserId), template_id_short, null, data);
			pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
			
	}
	@Override
	public void sendGroupSales(String details,String salesUserId,Integer startVip,Integer endVip,BigDecimal price,
			Integer vipCount,String libId) {
		Map<String,String> data =new HashMap<String, String>();
		StringBuffer sb = new StringBuffer();
		sb.append("馆长，您好。本次成功购买").append(vipCount).append("张联名卡（仅限周末使用，不包含寒暑假，不承诺配阅读顾问），只需给至家长扫卡激活即可享受阅读特权\n");
		data.put("first", sb.toString());
		data.put("keyword1","联名卡（仅限与社区机构/学校进行图书馆共建合作）");
		data.put("keyword2",price.multiply(new BigDecimal(vipCount)).toString()+"元");
		data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
		Integer count=libOrderDetailsDao.monthlySales(salesUserId,libId);
		String  remark ="联名卡编号区间:"+startVip+"-"+endVip;
		data.put("remark", remark+"\n\n本月推荐购卡累计："+count+"人。");
		String template_id_short=(String) SystemResourceLocator.getValue("sendTemplate101");
		//SendTemplate  sendTemplate  =new  SendTemplate(userService.getAccount(salesUserId),templateId,null,data);
		//JSONObject jsonObject = NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
		//logger.info("批量售出订单后，发送给馆长="+jsonObject.toJSONString());
		SendTemplateShort sendTemplateShort=new SendTemplateShort(userService.getAccount(salesUserId), template_id_short, null, data);
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
	}
	@Override
	public void sendCD(String details, String libId, String parentName,
			String childName, BigDecimal price,String salesUserId,Integer count) {
		List<String> userList= libStaffingService.findByCDAndOpenId(libId, "s_cd");
		if(userList !=null && userList.size()>0){
			List<Object[]> result =  libOrderDetailsDao.getlibPriceTotal(libId);
			Object price_total =0;
			Object user_total =0;
			if(result != null && !result.isEmpty()){
				Object[] tempObj = result.get(0);
				price_total = (Object)tempObj[0];
				user_total = (Object)tempObj[1];
			}
			childName=childName!=null ? childName :"";
			parentName=parentName!=null ? parentName :"";
			LibStaffing  libStaffing =libStaffingService.findByLibIdAndUserId(libId, salesUserId);
			String xin = count ==0 ?"新签":"续签";
			for (String openId : userList) {
			   Map<String,String> data =new HashMap<String, String>();
				StringBuffer sb = new StringBuffer();
				sb.append("馆长，您好。");
				sb.append(parentName).append("通过").append(libStaffing.getName()).append("的推荐已成功购买了").append(details).append("\n");
				data.put("first", sb.toString());
				data.put("keyword1",DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
				data.put("keyword2",price.toString()+"元");
				data.put("keyword3", details);
				data.put("remark", "订单状态："+xin+"\n\n本月馆内成功推荐购卡累计："+user_total+"人，馆内实际营收："+price_total+"元。");
				String template_id_short="OPENTM204602735";
				//SendTemplate  sendTemplate  =new  SendTemplate(openId,templateId,null,data);
				//JSONObject jsonObject = NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
				//logger.info("销售售出订单后，发送给馆长="+jsonObject.toJSONString());
				SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				
			}
			
		}
		
	}
	/**
	 * 推送给共享馆的馆长
	* @param details
	* @param libId
	* @param parentName
	* @param price
	* @param count
	* 创建人：ZhangCaibao 
	* 2018年4月23日 下午4:29:58 
	* @void
	 */
	private void sendGXCD(String details, String libId, String parentName,BigDecimal price,Integer count) {
		List<String> userList= managerService.findManageOpenidList(libId, 4);
		if(userList !=null && userList.size()>0){
			List<Object[]> result =  libOrderDetailsDao.getlibPriceTotal(libId);
			Object price_total =0;
			Object user_total =0;
			if(result != null && !result.isEmpty()){
				Object[] tempObj = result.get(0);
				price_total = (Object)tempObj[0];
				user_total = (Object)tempObj[1];
			}
			parentName=parentName!=null ? parentName :"";
			String xin = count ==0 ?"新签":"续签";
			for (String openId : userList) {
				Map<String,String> data =new HashMap<String, String>();
				StringBuffer sb = new StringBuffer();
				sb.append("馆长，您好。");
				sb.append(parentName).append("通过").append("您的推荐已成功购买了").append(details).append("\n");
				data.put("first", sb.toString());
				data.put("keyword1",DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
				data.put("keyword2",price.toString()+"元");
				data.put("keyword3", details);
				data.put("remark", "订单状态："+xin+"\n\n本月馆内成功推荐购卡累计："+user_total+"人，馆内实际营收："+price_total+"元。");
				String template_id_short="OPENTM204602735";
				SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				
			}
			
		}
	}
	/**
	 * 推送给馆长助理。
	* @param details
	* @param libId
	* @param parentName
	* @param price
	* @param count
	* 创建人：ZhangCaibao 
	* 2018年4月23日 下午4:30:15 
	* @void
	 */
	private void sendGXCDA(String details, String libId, String parentName,BigDecimal price,Integer count) {
		List<String> userList= managerService.findManageOpenidList(libId, 4);
		if(userList !=null && userList.size()>0){
			parentName=parentName!=null ? parentName :"";
			String xin = count ==0 ?"新签":"续签";
			for (String openId : userList) {
				Map<String,String> data =new HashMap<String, String>();
				StringBuffer sb = new StringBuffer();
				sb.append("馆长助理，您好。");
				sb.append(parentName).append("通过").append("您的推荐已成功购买了").append(details).append("\n");
				data.put("first", sb.toString());
				data.put("keyword1",DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
				data.put("keyword2",price.toString()+"元");
				data.put("keyword3", details);
				data.put("remark", "订单状态："+xin);
				String template_id_short="OPENTM204602735";
				SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				
			}
			
		}
	}
	
	@Override
	public void sendGroupCD(String details, String libId, String parentName,
			String childName, BigDecimal price, String salesUserId) {
		List<String> userList= libStaffingService.findByCDAndOpenId(libId, "s_cd");
		if(userList !=null && userList.size()>0){
			List<Object[]> result =  libOrderDetailsDao.getlibPriceTotal(libId);
			Object price_total =0;
			Object user_total =0;
			if(result != null && !result.isEmpty()){
				Object[] tempObj = result.get(0);
				price_total = (Object)tempObj[0];
				user_total = (Object)tempObj[1];
			}
			childName=childName!=null ? childName :"";
			parentName=parentName!=null ? parentName :"";
			LibStaffing  libStaffing =libStaffingService.findByLibIdAndUserId(libId, salesUserId);
			for (String openId : userList) {
			   Map<String,String> data =new HashMap<String, String>();
				StringBuffer sb = new StringBuffer();
				sb.append(parentName).append("通过").append(libStaffing.getName()).append("的推荐成功购买了").append(details).append("\n");
				data.put("first", sb.toString());
				data.put("keyword1",childName);
				data.put("keyword2",price.toString()+"元");
				data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
				data.put("remark", "\n本月馆内购卡累计："+user_total+"人，实际营收："+price_total+"元。");
				String template_id_short=(String) SystemResourceLocator.getValue("sendTemplate101");
				//SendTemplate  sendTemplate  =new  SendTemplate(openId,templateId,null,data);
				//JSONObject jsonObject = NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
				//logger.info("销售售出订单后，发送给馆长="+jsonObject.toJSONString());
				
				SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				
			}
			
		}
		
	}
	
	@Override
	public void updateOrderStatus(String orderId) {
		libOrderDetailsDao.updateOrderStatus(orderId);		
	}
	@Override
	public int getExpiredTemplate() {
		List<Map<String, Object>>  list  =libOrderDetailsQueryDao.getExpiredTemplate();
		if(list!=null && list.size()>0){
			for (Map<String, Object> map : list) {
				   //发送给销售／馆长收到模板消息推
				//pCtMtGwmO9Z6c5kN3F8RVtJxmw0n7dredAl-cCYFWZE
				   logger.debug("tb_lib_order_details ---id--->"+map.get("child_name"));
				   Map<String,String> data =new HashMap<String, String>();
				   String child_name = map.get("child_name").toString();
				   String template_id_short=(String) SystemResourceLocator.getValue("sendTemplate102");
				   SendTemplateShort sendTemplateShort = null;
				   if(map.get("xs_openid")!=null && !"".equals(map.get("xs_openid"))){
						data.put("first", "销售您好，"+child_name+"的会员卡，即将到期，请及时跟进沟通\n");
						data.put("keyword1",map.get("details").toString());
						data.put("keyword2",map.get("flow_id").toString());
						data.put("keyword3", map.get("price").toString());
						data.put("keyword4",DateHelper.format(DateHelper.parseDate(map.get("end_time").toString(), "yyyy-MM-dd HH:mm:ss.SSS"),"yyyy年MM月dd日 HH:mm ") );
						data.put("remark", "\n请注意时间，防止过期失效");
						//SendTemplate  sendTemplate  =new  SendTemplate(map.get("xs_openid").toString(),templateId,null,data);
						//NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
						
						sendTemplateShort=new SendTemplateShort(map.get("xs_openid").toString(), template_id_short, null, data);
						pushTemplateService.savePushWxTemplate(sendTemplateShort);
				   }
				   
					
					//推送给CD
					String libId = (String)map.get("lib_id");
					List<String> userList= libStaffingService.findByCDAndOpenId(libId, "s_cd");
					if(userList !=null && userList.size()>0){
						for (String openId : userList) {
							    data =new HashMap<String, String>();
								data.put("first", "馆长您好，"+child_name+"的会员卡，即将到期，请及时跟进沟通\n");
								data.put("keyword1",map.get("details").toString());
								data.put("keyword2",map.get("flow_id").toString());
								data.put("keyword3", map.get("price").toString());
								data.put("keyword4",DateHelper.format(DateHelper.parseDate(map.get("end_time").toString(), "yyyy-MM-dd HH:mm:ss.SSS"),"yyyy年MM月dd日 HH:mm ") );
								data.put("remark", "\n请注意时间，防止过期失效");
								template_id_short=(String) SystemResourceLocator.getValue("sendTemplate102");
								 //sendTemplate  =new  SendTemplate(openId,templateId,null,data);
								//NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
								sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
								pushTemplateService.savePushWxTemplate(sendTemplateShort);
							}
					}
					//会员卡到期通知，家长端收到模板消息推送，动态跳转到购买页面
					// wU5wpGnTXT2jBu0RAlsL1lu6LDfPyT37KZqjiieadH0
					Map<String,String> dataMap =new HashMap<String, String>();
					String league_name = map.get("league_name")!="" ?map.get("league_name").toString():"";
					dataMap.put("first", child_name+"妈妈/爸爸，您好，您为孩子在"+league_name+"购买的会员卡，即将到期\n");
					dataMap.put("keyword1",map.get("details").toString());
					dataMap.put("keyword2",DateHelper.format(DateHelper.parseDate(map.get("end_time").toString(), "yyyy-MM-dd HH:mm:ss.SSS"),"yyyy年MM月dd日 HH:mm ") );
					dataMap.put("remark", "\n请注意时间，防止过期失效");
					template_id_short=(String) SystemResourceLocator.getValue("sendTemplate103");
					 String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/payment/xuVipBuy_"+libId+".html";
					 //sendTemplate  =new  SendTemplate(map.get("wx_account").toString(),templateId,url,dataMap);
					//NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(), sendTemplate);
					sendTemplateShort=new SendTemplateShort(map.get("wx_account").toString(), template_id_short, url, dataMap);
					pushTemplateService.savePushWxTemplate(sendTemplateShort);
					
			}
		}
		// 自动处理过期的服务，添加离馆记录，改状态为2
		try {
			List<LibVipService> libVipServiceList = libVipServiceService.findExpiredListBySpecies("S003");
			if (CollectionUtils.isNotEmpty(libVipServiceList)) {
				for (int i = 0, len = libVipServiceList.size(); i < len; i++) {
					LibVipService libVipService = libVipServiceList.get(i);
					parentV2Service.updateExitLibRecord(libVipService.getVipId(), libVipService.getLibId(), null);
				}
			}
		} catch (Exception e) {
			logger.info("添加离馆记录异常", e);
		}
		libOrderDetailsDao.updateVipServiceStat();
		return 0;
	}
	@Override
	public  List<String> findByUserIdAndVipIsNull(String userId) {
		return libOrderDetailsDao.findByUserIdAndVipIsNull(userId);
	}
	@Override
	public void updateVipId(List<String> list,String vipId) {
		for (String string : list) {
			LibOrderDetails libOrderDetails=this.getById(string);
			libOrderDetails.setVipId(vipId);
			this.save(libOrderDetails);
			//添加服务
			libVipServiceService.saveLibVipService(libOrderDetails.getLibId(), 
					libOrderDetails.getPriceSpecies(), libOrderDetails.getPriceType(), vipId, libOrderDetails.getCreateTime(), libOrderDetails.getEndTime(), string);
		}
		
	}
	@Override
	public Page<Map<String, Object>> findForsellPageList(
			Map<String, Object> searchParams, Pageable pageable) {
		return libOrderDetailsQueryDao.findForsellPageList(searchParams, pageable);
	}
	@Override
	public Integer getLibVipService(String vipId, String libId) {
		return  libOrderDetailsDao.getLibVipService(libId,vipId);
	}
	@Override
	public Integer getLibVipServiceNumber(String vipId, String libId) {
		return  libOrderDetailsDao.getLibVipServiceNumber(libId,vipId);
	}
	@Override
	public void saveOrderDetails(LibOrderDetails libOrderDetails) {
		Date date = libOrderDetails.getCreateTime();
		String isType = libOrderDetails.getIsType();
		if("2".equals(isType)){
			logger.info("自己购买支付成功后，添加图书销售订单--"+DateHelper.getDateTime(date));
		}else if("3".equals(isType)){
			logger.info("自己购买周末卡，添加图书销售订单--"+DateHelper.getDateTime(date));
		}else{
			logger.info("从图书馆销售进来支付成功后，添加图书销售订单--"+DateHelper.getDateTime(date));
		}
		
		libOrderDetails.setCreateTime(date);
		libOrderDetails.setOrderStatus(1);//支付成功
		Integer hicount=0;
		LibOrderDetails newLibOrderDetails=null;
		Integer number = libOrderDetails.getNumber();
		String vipCode = libOrderDetails.getVipCode();
		
		LibVip  libVip = null;
		if("3".equals(isType)){
			    String code=vipService.getVipCode()+"";
				libVip =  vipService.findByCode(code);
				libOrderDetails.setVipId(libVip.getId());
		}else{
			    libVip = vipService.getById(libOrderDetails.getVipId());
		}
		
		try {
			for (int i = 1; i <= number; i++) {
				if(i>1){
					libOrderDetails.setType(2);
					hicount=1;
				}else{
					Integer count= this.getUserHistory(libOrderDetails.getSalesPriceId(),libOrderDetails.getVipId() ,libOrderDetails.getLibId(),libOrderDetails.getPriceSpecies());
					libOrderDetails.setType(count);
					hicount = count>1?1:0;
					if("S001".equals(libOrderDetails.getPriceSpecies())){
						if(vipCode !=null && vipCode.trim().length()>0){
							LibVipCode  libVipCode  =libVipCodeService.findByVipCodeAndType(vipCode, libOrderDetails.getLibId());
							if(libVipCode!=null){
								BigDecimal  discount  =new  BigDecimal(libVipCode.getDiscount());
								BigDecimal  price=libOrderDetails.getPrice().multiply(discount).divide(new BigDecimal("100")); 
								libOrderDetails.setPrice(price);
								libVipCode.setType(2);
								libVipCode.setUpdateTime(new Date());
								libVipCode.setUserId(libOrderDetails.getUserId());
								libVipCodeService.save(libVipCode);
							}
						}
					}
				}
				if("C001".equals(libOrderDetails.getPriceType())){
					libOrderDetails.setEndTime(DateHelper.getMonthDate(date, 12));
				}else if("C002".equals(libOrderDetails.getPriceType())){
					libOrderDetails.setEndTime(DateHelper.getMonthDate(date, 6));
				}else if("C003".equals(libOrderDetails.getPriceType())){ 
					libOrderDetails.setEndTime(DateHelper.getMonthDate(date, 1));
				}else if("C004".equals(libOrderDetails.getPriceType())){
					Date endTime=DateHelper.getMonthDate(date, 1);
					if(i==1){//
						if(libOrderDetails.getEndTime()!=null){//下单的时候如果设置了结束时间，就用下单设置的结束时间。
							endTime=libOrderDetails.getEndTime();
						}
					}
					libOrderDetails.setEndTime(endTime);
				}else if("C005".equals(libOrderDetails.getPriceType())){
					libOrderDetails.setEndTime(DateHelper.getMonthDate(date, 6));
				}else if("C006".equals(libOrderDetails.getPriceType())){
					libOrderDetails.setEndTime(DateHelper.getMonthDate(date, 12));
				}else if("C007".equals(libOrderDetails.getPriceType())){
					libOrderDetails.setEndTime(DateHelper.getMonthDate(date, 12));
				}else if("C008".equals(libOrderDetails.getPriceType())){
					//libOrderDetails.setCreateTime(DateHelper.timeStitching(DateHelper.parseDate("2018-01-15", "yyyy-MM-dd"), "00:00:00"));
					libOrderDetails.setEndTime(DateHelper.timeStitching(DateHelper.parseDate("2018-02-28", "yyyy-MM-dd"), "23:59:59"));
				}else if("C015".equals(libOrderDetails.getPriceType())){
					//libOrderDetails.setCreateTime(DateHelper.timeStitching(DateHelper.parseDate("2018-01-15", "yyyy-MM-dd"), "00:00:00"));
					libOrderDetails.setEndTime(DateHelper.getMonthDate(date, 3));
				}else if("C018".equals(libOrderDetails.getPriceType())){ //暑假卡
					//libOrderDetails.setCreateTime(DateHelper.timeStitching(DateHelper.parseDate("2018-01-15", "yyyy-MM-dd"), "00:00:00"));
					libOrderDetails.setEndTime(DateHelper.timeStitching(DateHelper.parseDate("2018-08-31", "yyyy-MM-dd"), "23:59:59"));
				}
				newLibOrderDetails=new LibOrderDetails();
				BeanUtils.copyProperties(libOrderDetails, newLibOrderDetails);
				if(i==1 && libOrderDetails.getExtraPrice()!=null){
					newLibOrderDetails.setPrice(newLibOrderDetails.getPrice().add(libOrderDetails.getExtraPrice()));
				}
				this.save(newLibOrderDetails);
				logger.info("支付成功后，添加图书销售订单"+newLibOrderDetails.getId());

				//插入服务(如果没有卡，那么先不插入服务，等注册的时候插入服务)
				if(libOrderDetails.getVipId() !=null){
					libVipServiceService.saveLibVipService(libOrderDetails.getLibId(), libOrderDetails.getPriceSpecies(), libOrderDetails.getPriceType(), libOrderDetails.getVipId(), date, libOrderDetails.getEndTime(),newLibOrderDetails.getId());
				}
				date=libOrderDetails.getEndTime();//结束时间按实际的月份叠加.没有卡,等注册的时候插入服务需要用到第一条数据的结束时间

			}
			User  user =userService.getById(libOrderDetails.getUserId());
			
			if(libVip!=null && libVip.getUserId()==null&&("2".equals(isType)||"3".equals(isType))){
				
				TbLibJoin join = joinService.getById(libOrderDetails.getLibId());
				if(join!=null && join.getLeagueCode().startsWith("SZ")){
					libVip.setBanben(2);
				}else{
					libVip.setBanben(1);
				}
				
					if(libOrderDetails.getParentName()!=null){libVip.setParentName(libOrderDetails.getParentName());}
					if(libOrderDetails.getChildName()!=null){libVip.setChildName(libOrderDetails.getChildName());}
					if(libOrderDetails.getPhone()!=null){libVip.setPhone(libOrderDetails.getPhone());}
					if(libOrderDetails.getGrade()!=null){libVip.setGrade(libOrderDetails.getGrade());}
					if(libOrderDetails.getSchool()!=null){libVip.setSchool(libOrderDetails.getSchool());}
					libVip.setUserId(user.getId());
					libVip.setImgUrl(user.getPhoto());
					libVip.setActivateTime(new Date());
					vipService.save(libVip);
			}
			//推送客服消息
			String name =user.getName();
			String childName=libVip !=null ?(libVip.getChildName()!=null?libVip.getChildName():name):name;
			String parentName=libVip !=null ?(libVip.getParentName()!=null?libVip.getParentName():name):name;
			
			Integer  libtype = libOrderDetails.getLibtype();//区分共享馆还是家庭馆
			if(libtype==1){
				this.sendSales(libOrderDetails.getDetails(), libOrderDetails.getSalesUserId(),parentName, childName,
						libOrderDetails.getPrice(),hicount,libOrderDetails.getLibId());
				this.sendCD(libOrderDetails.getDetails(), libOrderDetails.getLibId(),parentName, childName,libOrderDetails.getPrice(),libOrderDetails.getSalesUserId(),hicount);
			}else{
				this.sendGXCD(libOrderDetails.getDetails(), libOrderDetails.getLibId(),parentName,libOrderDetails.getPrice(),hicount);
				this.sendGXCDA(libOrderDetails.getDetails(), libOrderDetails.getLibId(),parentName,libOrderDetails.getPrice(),hicount);
			}
			
			
			tokenManager.createServiceCount("ZUOYB_SERVICE_"+libVip.getId()+"_"+libOrderDetails.getLibId(), "1");	

		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}catch(Exception e){
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}
		
	}
	@Override
	public void saveOrderDetailsOneTwoOne(LibOrderDetails libOrderDetails) {
		Date date = libOrderDetails.getCreateTime();
		String isType = libOrderDetails.getIsType();
		logger.info("一对一课程购买进来--"+DateHelper.getDateTime(date));
		
		libOrderDetails.setCreateTime(date);
		libOrderDetails.setOrderStatus(1);//支付成功
		Integer hicount=0;
		LibOrderDetails newLibOrderDetails=null;
		Integer number = libOrderDetails.getNumber();
		
		LibVip  libVip = vipService.getById(libOrderDetails.getVipId());
		
		try {
			for (int i = 1; i <= number; i++) {
				
				/*if(i>1){
					libOrderDetails.setType(2);
					hicount=1;
				}else{
					Integer count= this.getUserHistory(libOrderDetails.getSalesPriceId(),libOrderDetails.getVipId() ,libOrderDetails.getLibId(),libOrderDetails.getPriceSpecies());
					libOrderDetails.setType(count);
					hicount = count>1?1:0;
				}*/
				libOrderDetails.setEndTime(DateHelper.getMonthDate(date, 12));
				newLibOrderDetails=new LibOrderDetails();
				BeanUtils.copyProperties(libOrderDetails, newLibOrderDetails);
				if(i==1 && libOrderDetails.getExtraPrice()!=null){
					newLibOrderDetails.setPrice(newLibOrderDetails.getPrice().add(libOrderDetails.getExtraPrice()));
				}
				this.save(newLibOrderDetails);
				logger.info("支付成功后，添加图书销售订单"+newLibOrderDetails.getId());
				
				//插入服务(如果没有卡，那么先不插入服务，等注册的时候插入服务)
				if(libOrderDetails.getVipId() !=null){
					//libVipServiceService.saveLibVipService(libOrderDetails.getLibId(), libOrderDetails.getPriceSpecies(), libOrderDetails.getPriceType(), libOrderDetails.getVipId(), date, libOrderDetails.getEndTime(),newLibOrderDetails.getId());
				}
				date=libOrderDetails.getEndTime();//结束时间按实际的月份叠加.没有卡,等注册的时候插入服务需要用到第一条数据的结束时间
				
			}
			User  user =userService.getById(libOrderDetails.getUserId());
			
			if(libVip!=null && libVip.getUserId()==null&&("2".equals(isType)||"3".equals(isType))){
				
				TbLibJoin join = joinService.getById(libOrderDetails.getLibId());
				if(join!=null && join.getLeagueCode().startsWith("SZ")){
					libVip.setBanben(2);
				}else{
					libVip.setBanben(1);
				}
				
				if(libOrderDetails.getParentName()!=null){libVip.setParentName(libOrderDetails.getParentName());}
				if(libOrderDetails.getChildName()!=null){libVip.setChildName(libOrderDetails.getChildName());}
				if(libOrderDetails.getPhone()!=null){libVip.setPhone(libOrderDetails.getPhone());}
				if(libOrderDetails.getGrade()!=null){libVip.setGrade(libOrderDetails.getGrade());}
				if(libOrderDetails.getSchool()!=null){libVip.setSchool(libOrderDetails.getSchool());}
				libVip.setUserId(user.getId());
				libVip.setImgUrl(user.getPhoto());
				libVip.setActivateTime(new Date());
				vipService.save(libVip);
			}
			//推送客服消息
			String name =user.getName();
			String childName=libVip !=null ?(libVip.getChildName()!=null?libVip.getChildName():name):name;
			String parentName=libVip !=null ?(libVip.getParentName()!=null?libVip.getParentName():name):name;
			
			Integer  libtype = libOrderDetails.getLibtype();//区分共享馆还是家庭馆
			if(libtype==1){
				this.sendSales(libOrderDetails.getDetails(), libOrderDetails.getSalesUserId(),parentName, childName,
						libOrderDetails.getPrice(),hicount,libOrderDetails.getLibId());
				this.sendCD(libOrderDetails.getDetails(), libOrderDetails.getLibId(),parentName, childName,libOrderDetails.getPrice(),libOrderDetails.getSalesUserId(),hicount);
			}else{
				this.sendGXCD(libOrderDetails.getDetails(), libOrderDetails.getLibId(),parentName,libOrderDetails.getPrice(),hicount);
				this.sendGXCDA(libOrderDetails.getDetails(), libOrderDetails.getLibId(),parentName,libOrderDetails.getPrice(),hicount);
			}
		} catch(Exception e){
			e.printStackTrace();
			logger.error("一对一课程购买进来-购卡信息异常");
		}
		
	}
	@Override
	public LibOrderDetails getByOrderNo(String orderNo) {
		return libOrderDetailsDao.getByOrderNo(orderNo);
	}
	
	
	@Override
	public void saveProxyCourseOrderDetails(LibOrderDetails libOrderDetails) {
			Date date = libOrderDetails.getCreateTime();
			logger.info("代购购买支付成功后，特色课程--->代购购买订单--"+DateHelper.getDateTime(date));
			logger.info("代购购买支付成功后，特色课程--->代购购买订单卡--"+libOrderDetails.getPriceType());
			libOrderDetails.setCreateTime(date);
			libOrderDetails.setOrderStatus(1);//支付成功
			libOrderDetails.setVipStatus(5);
			libOrderDetails.setIsBuy(2);
	
			try{
				List<Map<String, Object>> libCourses=libCourseService.getByLibIdLibCourse(libOrderDetails.getLibId(), libOrderDetails.getPriceType());
				String endTime=DateHelper.format(new Date(), "yyyy-MM-dd");
				if(libCourses!=null && libCourses.size()>0){
					String calendar=libCourses.get(0).get("c_calendar").toString();
					Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}$");
					Matcher matcher = pattern.matcher(calendar);
					if(matcher.find()){
						endTime=(matcher.group(0)).toString();
					}
				}
				libOrderDetails.setType(1);
				libOrderDetails.setCreateTime(date);
				libOrderDetails.setEndTime(DateHelper.timeStitching(DateHelper.parseDate(endTime, "yyyy-MM-dd"), "23:59:59"));	
				this.save(libOrderDetails);
	
			} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}catch(Exception e){
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}
	}
	
	@Override
	public void saveProxyCourseVipService(LibOrderDetails libOrderDetails) {
		Date date = new Date();
		logger.info("代购购买支付成功后，特色课程--->代购保存服务--"+DateHelper.getDateTime(date));
		logger.info("代购购买支付成功后，特色课程--->代购保存服务--"+libOrderDetails.getPriceType());

		User  user =userService.getById(libOrderDetails.getUserId());
		LibVip libVip=vipService.getById(libOrderDetails.getVipId());

		try{
			List<Map<String, Object>> libCourses=libCourseService.getByLibIdLibCourse(libOrderDetails.getLibId(), libOrderDetails.getPriceType());
			String endTime=DateHelper.format(new Date(), "yyyy-MM-dd");
			String sTime=DateHelper.format(new Date(), "yyyy-MM-dd");
			if(libCourses!=null && libCourses.size()>0){
				String calendar=libCourses.get(0).get("c_calendar").toString();
				Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}$");
				Matcher matcher = pattern.matcher(calendar);
				if(matcher.find()){
					endTime=(matcher.group(0)).toString();
				}
				
				pattern = Pattern.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}");
				matcher = pattern.matcher(calendar);
				if(matcher.find()){
					sTime=(matcher.group(0)).toString();
				}
			}
			
			this.save(libOrderDetails);
			logger.info("代购购买支付成功后，添加特色课程--->保存服务-->"+libOrderDetails.getId());
			
			//插入购买的服务
				libVipServiceService.saveLibVipService(libOrderDetails.getLibId(), libOrderDetails.getPriceSpecies(),
						libOrderDetails.getPriceType(), libOrderDetails.getVipId(), DateHelper.timeStitching(DateHelper.parseDate(sTime, "yyyy-MM-dd"), "00:00:00"),
						DateHelper.timeStitching(DateHelper.parseDate(endTime, "yyyy-MM-dd"), "23:59:59"),libOrderDetails.getId());
				
				TbLibJoin tbLibJoin=joinService.getById(libOrderDetails.getLibId());
				this.sendBinding(libOrderDetails.getDetails(),String.valueOf(libOrderDetails.getPrice()),tbLibJoin.getLeagueName(),
						tbLibJoin.getLeadueManager(),tbLibJoin.getLeaduePhone(),libVip.getUserId(),
							libOrderDetails.getCreateTime());
				
				
				//推送客服消息
				String name =user.getName();
				String childName=libVip !=null ?(libVip.getChildName()!=null?libVip.getChildName():name):name;
				String parentName=libVip !=null ?(libVip.getParentName()!=null?libVip.getParentName():name):name;
				this.sendSales(libOrderDetails.getDetails(), libOrderDetails.getSalesUserId(),parentName, childName,
						libOrderDetails.getPrice(),0,libOrderDetails.getLibId());
				this.sendCD(libOrderDetails.getDetails(), libOrderDetails.getLibId(),parentName, childName,libOrderDetails.getPrice(),libOrderDetails.getSalesUserId(),0);

				// tokenManager.createServiceCount("ZUOYB_SERVICE_"+CodecUtil.replaceAllUUID(libVip.getId())+"_"+CodecUtil.replaceAllUUID(libOrderDetails.getLibId()), "1");	
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}catch(Exception e){
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}
		
	}
	@Override
	public void saveCourseOrderDetails(LibOrderDetails libOrderDetails,String activateUserId) {
		Date date = libOrderDetails.getCreateTime();
		logger.info("自己购买支付成功后，特色课程--->自己购买订单--"+DateHelper.getDateTime(date));
		logger.info("自己购买支付成功后，特色课程--->自己购买订单卡--"+libOrderDetails.getPriceType());
		libOrderDetails.setOrderStatus(1);//支付成功
		libOrderDetails.setVipStatus(5);
	
		//生成 会员卡
		User  user =null;
		if(StringUtils.isNotEmpty(activateUserId)){
			 user =userService.getById(activateUserId);
			 libOrderDetails.setIsBuy(2);
		}else{
			user =userService.getById(libOrderDetails.getUserId());	
			 libOrderDetails.setIsBuy(1);
		}
		LibVip  libVip= new LibVip();
		libVip.setCreateTime(date);
		libVip.setStat("1");//生成的会员卡设置为有效状态 1--有效 2--无效',
		libVip.setLevel(1);
		libVip.setUserId(user.getId());
		libVip.setImgUrl(user.getPhoto());
		libVip.setActivateTime(new Date());
		if(libOrderDetails.getParentName()!=null){libVip.setParentName(libOrderDetails.getParentName());}
		if(libOrderDetails.getChildName()!=null){libVip.setChildName(libOrderDetails.getChildName());}
		if(libOrderDetails.getPhone()!=null){libVip.setPhone(libOrderDetails.getPhone());}
		if(libOrderDetails.getGrade()!=null){libVip.setGrade(libOrderDetails.getGrade());}
		if(libOrderDetails.getSchool()!=null){libVip.setSchool(libOrderDetails.getSchool());}
		vipService.save(libVip);
		logger.info("自己购买支付成功后，特色课程--->自己购买订单卡生成VIPID--"+libVip.getId());
		logger.info("自己购买支付成功后，特色课程--->自己购买订单卡生成VIPID--"+libVip.getFlowId());
		libOrderDetails.setVipId(libVip.getId());
		
		try{
			List<Map<String, Object>> libCourses=libCourseService.getByLibIdLibCourse(libOrderDetails.getLibId(), libOrderDetails.getPriceType());
			String endTime=DateHelper.format(new Date(), "yyyy-MM-dd");
			String sTime=DateHelper.format(new Date(), "yyyy-MM-dd");
			if(libCourses!=null && libCourses.size()>0){
				String calendar=libCourses.get(0).get("c_calendar").toString();
				Pattern pattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}$");
				Matcher matcher = pattern.matcher(calendar);
				if(matcher.find()){
					endTime=(matcher.group(0)).toString();
				}
				
				pattern = Pattern.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}");
				matcher = pattern.matcher(calendar);
				if(matcher.find()){
					sTime=(matcher.group(0)).toString();
				}
				
			}
			libOrderDetails.setType(1);
			libOrderDetails.setCreateTime(libOrderDetails.getCreateTime()!=null?libOrderDetails.getCreateTime():date);
			libOrderDetails.setEndTime(DateHelper.timeStitching(DateHelper.parseDate(endTime, "yyyy-MM-dd"), "23:59:59"));
			
			this.save(libOrderDetails);
			logger.info("自己购买支付成功后，添加特色课程--->自己购买订单-->"+libOrderDetails.getId());
			
			//插入购买的服务
			if(libOrderDetails.getVipId() !=null){
				libVipServiceService.saveLibVipService(libOrderDetails.getLibId(), libOrderDetails.getPriceSpecies(),
						libOrderDetails.getPriceType(), libOrderDetails.getVipId(), DateHelper.timeStitching(DateHelper.parseDate(sTime, "yyyy-MM-dd"), "00:00:00"),
						libOrderDetails.getEndTime(),libOrderDetails.getId());
			}
			
			//推送一张电子会员卡
		    //自己购买的，只能推送一条
			String cardId=(String) SystemResourceLocator.getValue("course_cardId");
			List<LibCardDetail> libCardDetail=libCardService.findByOpenIdAndCardId(cardId, user.getAccount(), "normal");
			if(libCardDetail==null || libCardDetail.size()<=0 ){
				vipService.pushVipCard(user.getAccount(),cardId);
			}
			

			TbLibJoin tbLibJoin=joinService.getById(libOrderDetails.getLibId());
			this.sendBinding(libOrderDetails.getDetails(),String.valueOf(libOrderDetails.getPrice()),tbLibJoin.getLeagueName(),
					tbLibJoin.getLeadueManager(),tbLibJoin.getLeaduePhone(),user.getId(),
						libOrderDetails.getCreateTime());
			
			
			//推送客服消息
			String name =user.getName();
			String childName=libVip.getChildName()!=null?libVip.getChildName():name;
			String parentName=libVip.getParentName()!=null?libVip.getParentName():name;
			this.sendSales(libOrderDetails.getDetails(), libOrderDetails.getSalesUserId(),parentName, childName,
					libOrderDetails.getPrice(),0,libOrderDetails.getLibId());
			this.sendCD(libOrderDetails.getDetails(), libOrderDetails.getLibId(),parentName, childName,libOrderDetails.getPrice(),libOrderDetails.getSalesUserId(),0);

			 tokenManager.createServiceCount("ZUOYB_SERVICE_"+libVip.getId()+"_"+libOrderDetails.getLibId(), "1");	
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}catch(Exception e){
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}
	}
	@Override
	public void sendBindingUser(String details, String orderNo,String vipId,String userId) {
		String template_id_short=(String) SystemResourceLocator.getValue("sendTemplate106");
		Map<String,String> data =new HashMap<String, String>();
		data.put("first", "你好，你有一张"+details+"的会员家长未激活电子会员卡。");
		data.put("keynote1","电子卡");
		data.put("keynote2",details+"/5次课");
		data.put("remark", "\n点击详情，转发该链接并督导学员家长及时绑定微信会员卡，即可享受会员安全到馆通知服务。");
		String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/notCuActive_"+orderNo+".html";
		SendTemplateShort sendTemplateShort=new SendTemplateShort(userService.getAccount(userId), template_id_short, url, data);
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
	}
	
	@Override
	public void sendBinding(String details, String price,String joinname,String name,String telephone,String userId,Date createTime) {
		String template_id_short=(String) SystemResourceLocator.getValue("sendTemplate107");
		Map<String,String> data =new HashMap<String, String>();
		data.put("first", "家长，您好。我是馆长"+name+"，已为您已成功购买"+details);
		data.put("keyword1",details);
		data.put("keyword2",price);
		data.put("keyword3",DateHelper.format(createTime, "yyyy-MM-dd hh:mm:ss"));
		data.put("remark", "\n记得及时上课哦！如需变更，请致电联系"+joinname+" ："+telephone+"("+name+")");
		SendTemplateShort sendTemplateShort=new SendTemplateShort(userService.getAccount(userId), template_id_short, "", data);
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
	}
	@Override
	public void saveTiYanVipService(String libId, String openId, String stat,String userId) {
		User user = userService.findByAccount(openId);
		List<LibVip> list = vipService.getByUserId(user.getId());
		Date date =new  Date();
		String id="vipId";
		Integer level=0;
		if(list ==null || list.size()==0){
			LibVip  libVip= new LibVip();
			libVip.setCreateTime(date);
			libVip.setStat("1");//生成的会员卡设置为有效状态 1--有效 2--无效',
			libVip.setLevel(1);
			libVip.setUserId(user.getId());
			libVip.setImgUrl(user.getPhoto());
			libVip.setActivateTime(date);
			libVip=vipService.save(libVip);
			list=new ArrayList<LibVip>(1);
			list.add(libVip);
			id=libVip.getId();
			level=libVip.getLevel();
		}
		String species ="1".equals(stat)?"S001":"S003";
		String type  ="1".equals(stat)?"C014":"C013";
		Date endDate =DateHelper.getNextDay(date, 1);
		for (LibVip libVip : list) {
			libVipServiceService.saveLibVipService(libId, 
					species,type, 
					libVip.getId(), date,endDate,"tiyanjuan");
		}
		//是否需要发送消息？？
		if(!"vipId".equals(id)){
			String template_id_short="TM405959868";
			Map<String,String> data =new HashMap<String, String>();
			data.put("keynote1",level.toString());
			data.put("keynote2","体验 1天");
			if("1".equals(stat)){
				data.put("first", "家长您好，您有一张尚未激活的阅读卡体验版电子会员卡。");
				data.put("remark", "\n请及时完善会员信息，即可享受会员预约到馆外借图书及安全到馆通知体验服务。");
			}else{
				data.put("first", "家长您好，您有一张尚未激活的作业卡体验版电子会员卡。");
				data.put("remark", "\n请及时完善会员信息，即可享受会员安全到馆通知及作业反馈报告体验服务。");
			}
			String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/mylib/userInfo_"+id+".html?type=3";
			SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, url, data);
			pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		}
		
	}


	@Override
	public float findPriceByVipIdAndCurrentMonth(String vipId, String beginTime, String endTime) {
		Float result = libOrderDetailsDao.findPriceByVipId(vipId, beginTime, endTime);
		if (result == null){
			return 0f;
		}
		return  result.floatValue();
	}

	@Override
	public LibOrderDetails findLastOrderDetail(String vipId) {
		return libOrderDetailsDao.findFirstByVipId(vipId);
	}

	@Override
	public List<LibOrderDetails> findOrderDetailByVipId(String vipId){
		return libOrderDetailsDao.findOrderDetailByVipId(vipId);
	}

	@Override
	public void saveCommuOrderDetails(LibOrderDetails libOrderDetails) {
        logger.info("saveCommuOrderDetails-libOrderDetails："+JSON.toJSONString(libOrderDetails));
        //开始时间
		Date beginTime = libOrderDetails.getCreateTime();
		libOrderDetails.setCreateTime(beginTime);
		//支付成功
		libOrderDetails.setOrderStatus(1);
		Integer number = libOrderDetails.getNumber();
		LibVip libVip = vipService.getById(libOrderDetails.getVipId());
		try {
			//设置服务结束时间
			Date endTime = DateHelper.getMonthDate(beginTime, number);
			//下单的时候如果设置了结束时间，就用下单设置的结束时间。
			if (libOrderDetails.getEndTime() != null) {
				endTime = libOrderDetails.getEndTime();
			}
			libOrderDetails.setEndTime(endTime);
			this.save(libOrderDetails);
			logger.info("支付成功后，添加通讯服务订单" + JSON.toJSONString(libOrderDetails));
            //新增通讯服务数据
            if (StringUtil.isNotBlank(libOrderDetails.getVipId())) {
                libVipServiceService.saveLibVipServiceV1(libOrderDetails.getLibId(), libOrderDetails.getPriceSpecies(), libOrderDetails.getPriceType(), libOrderDetails.getVipId(), beginTime, number, libOrderDetails.getId());
            }
			tokenManager.createServiceCount("COMMUNICATION_SERVICE_" + libVip.getId(), "1");
		} catch (BeansException e) {
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}
	}

	@Override
	public void saveBatchZybOrderDetails(LibOrderDetails libOrderDetails) {
		String[] vipIds=libOrderDetails.getVipId().split(";");
		for (String vipId : vipIds) {
			LibOrderDetails newLibOrderDetails=new LibOrderDetails();
			try {
				BeanUtils.copyProperties(libOrderDetails,newLibOrderDetails);
				newLibOrderDetails.setVipId(vipId);
				//单价X数量，等于单个订单的总金额
				newLibOrderDetails.setPrice(newLibOrderDetails.getPrice().multiply(new BigDecimal(newLibOrderDetails.getNumber())));
				//设置为100单都是新业务更改后的订单，用来算提成的(add by Mount Liu)
				newLibOrderDetails.setLibtype(100);
				this.saveZybOrderDetails(newLibOrderDetails);
			} catch (Exception e) {
				logger.error("支付回调保存作业把服务异常", e);
				e.printStackTrace();
			}

			try {
				parentV2Service.updateExitLibRecord(vipId, null, newLibOrderDetails.getLibId());
			} catch (Exception e) {
				logger.error("更新redis学生离馆记录异常", e);
			}
		}
	}
	
	@Override
	public void saveZybOrderDetails(LibOrderDetails libOrderDetails) {
		//开始时间
		Date beginTime = libOrderDetails.getCreateTime();
		logger.info("添加作业吧销售订单--" + DateHelper.getDateTime(beginTime));
		libOrderDetails.setCreateTime(beginTime);
		//支付成功
		libOrderDetails.setOrderStatus(1);
		Integer number = libOrderDetails.getNumber();
		if (number == null) {
			number = 1;
		}
		LibVip libVip = vipService.getById(libOrderDetails.getVipId());
		try {
			Integer count = this.getUserHistory(libOrderDetails.getSalesPriceId(), libOrderDetails.getVipId(), libOrderDetails.getLibId(), libOrderDetails.getPriceSpecies());
			libOrderDetails.setType(count);
			//新版：如果前端已经选择了开始续费时间，这里也会有结束时间，就不用再计算一次了
			if (libOrderDetails.getEndTime() == null) {
				if ("C001".equals(libOrderDetails.getPriceType())) {
					libOrderDetails.setEndTime(DateHelper.getMonthDate(beginTime, 12));
					number = 12;
				} else if ("C002".equals(libOrderDetails.getPriceType())) {
					libOrderDetails.setEndTime(DateHelper.getMonthDate(beginTime, 6));
					number = 6;
				} else if ("C003".equals(libOrderDetails.getPriceType())) {
					libOrderDetails.setEndTime(DateHelper.getMonthDate(beginTime, number));
				} else if ("C004".equals(libOrderDetails.getPriceType())) {
					Date endTime = DateHelper.getMonthDate(beginTime, number);
					//下单的时候如果设置了结束时间，就用下单设置的结束时间。
					if (libOrderDetails.getEndTime() != null) {
						endTime = libOrderDetails.getEndTime();
					}
					libOrderDetails.setEndTime(endTime);
				} else if ("C005".equals(libOrderDetails.getPriceType())) {
					number = number * 6;
					libOrderDetails.setEndTime(DateHelper.getMonthDate(beginTime, number));
				} else if ("C006".equals(libOrderDetails.getPriceType())) {
					number = number * 12;
					libOrderDetails.setEndTime(DateHelper.getMonthDate(beginTime, number));
				} else if ("C007".equals(libOrderDetails.getPriceType())) {
					libOrderDetails.setEndTime(DateHelper.getMonthDate(beginTime, 12));
					number = 12;
				} else if ("C008".equals(libOrderDetails.getPriceType())) {
					libOrderDetails.setEndTime(DateHelper.timeStitching(DateHelper.parseDate("2018-02-28", "yyyy-MM-dd"), "23:59:59"));
				} else if ("C015".equals(libOrderDetails.getPriceType())) {
					number = number * 3;
					libOrderDetails.setEndTime(DateHelper.getMonthDate(beginTime, number));
				} else if ("C018".equals(libOrderDetails.getPriceType())) {
					//暑假卡
					libOrderDetails.setEndTime(DateHelper.timeStitching(DateHelper.parseDate("2018-08-31", "yyyy-MM-dd"), "23:59:59"));
				}else if("C022".equals(libOrderDetails.getPriceType())){
					//按天计算
					libOrderDetails.setEndTime(DateUtil.getDateAfter(beginTime, number));
				}else if("C023".equals(libOrderDetails.getPriceType())){
					//软件服务（家长自批改服务）
					Date endTime = DateHelper.getMonthDate(beginTime, number);
					libOrderDetails.setEndTime(endTime);
				}
			}
			if (libOrderDetails.getExtraPrice() != null) {
				libOrderDetails.setPrice(libOrderDetails.getPrice().add(libOrderDetails.getExtraPrice()));
			}
			this.save(libOrderDetails);
			logger.info("支付成功后，添加作业吧销售订单" + libOrderDetails.getId());
			//新增作业吧服务数据
			if (StringUtil.isNotBlank(libOrderDetails.getVipId())) {
				libVipServiceService.saveLibVipServiceV4(libOrderDetails.getPriceSpecies(), libOrderDetails.getPriceType(), libOrderDetails.getVipId(), libOrderDetails.getStartTime(), libOrderDetails.getEndTime(), 0, libOrderDetails.getId());
            }
			tokenManager.createServiceCount("ZUOYB_SERVICE_" + libVip.getId() + "_" + libOrderDetails.getLibId(), "1");
			//更新优惠码的受益人
			if (StringUtil.isNotBlank(libOrderDetails.getCode())) {
				CodeExchange codeExchange = codeExchangeService.findByCode(libOrderDetails.getCode());
				if (codeExchange != null) {
					codeExchange.setUserId(libOrderDetails.getUserId());
					User user = userService.getById(libOrderDetails.getUserId());
					codeExchange.setUserName(user != null ? user.getName() : null);
					//解锁该优惠码
					codeExchange.setIsLock(0);
					codeExchangeService.save(codeExchange);
				}
			}
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存购卡信息异常");
		}
	}

	@Override
	public List<LibOrderDetails> findByVipIdAndPriceSpecies(String vipId, String priceSpecies) {
		return libOrderDetailsDao.findByVipIdAndPriceSpeciesAndOrderStatusOrderByCreateTimeDesc(vipId, priceSpecies, 1);
	}

	@Override
	public List<LibOrderDetails> findOrderDetailList(String vipId, String priceSpecies, int appType){
		return libOrderDetailsDao.findByVipIdAndPriceSpeciesAndOrderStatusAndAppTypeOrderByCreateTimeDesc(vipId, priceSpecies, 1, appType);
	}

}
