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

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.ssj.bean.sys.lesson.domain.LessonService;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.push.domain.Miniprogram;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.sales.domain.LibOrderDetails;
import com.ssj.bean.weixin.sales.domain.LibOrderRefunds;
import com.ssj.bean.weixin.sales.domain.LibStaffing;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.weixin.sales.dao.LibOrderRefundsDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.WxUtil;
import com.ssj.service.conch.teacher.service.ITzybService;
import com.ssj.service.sys.lesson.service.LessonServiceService;
import com.ssj.service.sys.sort.service.SortService;
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.order.service.PayB2CService;
import com.ssj.service.weixin.payment.service.WeiXinPayB2CService;
import com.ssj.service.weixin.problem.service.CnAreaService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibOrderDetailsService;
import com.ssj.service.weixin.sales.service.LibOrderRefundsService;
import com.ssj.service.weixin.sales.service.LibStaffingService;
import com.ssj.service.weixin.sales.service.LibVipCodeService;
import com.ssj.service.weixin.sales.service.LibVipServiceService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.service.weixin.zuoyb.service.ZuoybDayService;


/** 
 * @author  ZhangCaibao 
 * @version 2017年5月2日 下午3:34:08 
 * 类说明 
 */
@Service(version="1.0")
@Transactional
public class LibOrderRefundsServiceImpl extends BaseServiceImpl<LibOrderRefunds, String> implements  LibOrderRefundsService{

	@Autowired
	private LibOrderRefundsDao  libOrderRefundsDao;


	@Autowired
	private LibOrderDetailsService libOrderDetailsService;
	
	@Autowired
	private OrderService orderService;
	
   @Autowired
   private ILibVipService vipService;
   
   @Autowired
	private ILibJoinService joinService;
   @Autowired
   private LibStaffingService libStaffingService;
   /**
    * 退款日志记录
    */
   @Autowired
   private LibOrderRefundsService libOrderRefundsService;
   
   @Autowired
   private SortService  sortService;
   
   @Autowired
   private UserService  userService;
   
   @Autowired
   private PayB2CService  payB2CService;
   
   @Autowired
	private PushTemplateService  pushTemplateService;
   
   @Autowired
   private WeiXinPayB2CService  weiXinPayB2CService;
   @Autowired
   private LibVipCodeService  libVipCodeService;
   @Autowired
   private LibVipServiceService  libVipServiceService;
   
   @Autowired
   private TokenManager  tokenManager; 

	@Autowired
	private CnAreaService cnAreaService;

	@Autowired
	private LessonServiceService lessonServiceService;
	
	@Autowired
	private ITzybService zybService;
	
	 @Autowired
	 private ZuoybDayService zuoybDayService;
	 
	@Override
	public PagingAndSortingRepository<LibOrderRefunds, String> getDao() {
		return libOrderRefundsDao;
	}
	@Override
	public LibOrderRefunds findByLibIdCount(String libId,String initiateUserId,Integer step,String orderDetailsId) {
		return libOrderRefundsDao.findByLibIdCount(libId, initiateUserId, step,orderDetailsId);
	}
	@Override
	public void updateStatVoid(String orderDetailsId, Integer statVoid) {
		libOrderRefundsDao.updateStatVoid(orderDetailsId, statVoid);
	}
	@Override
	public LibOrderRefunds findRefundByDetailId(String orderDetailsId, int statVoid) {
		
		return libOrderRefundsDao.findRefundByDetailId(orderDetailsId,statVoid);
	}

	public LibOrderRefunds findByLessonServiceId (String lsId){
		return libOrderRefundsDao.findByOrderDetailsIdAndStatVoid(lsId, 1); //查询有效的退款流程
	}
	@Override
	public LibOrderRefunds apply(LibOrderDetails libOrderDetails,String type,String openId,String childName) {
		//发送消息模板
				LibOrderRefunds libOrderRefunds =this.findByLibIdCount(libOrderDetails.getLibId(), libOrderDetails.getUserId(), 1,libOrderDetails.getId());
				if(libOrderRefunds ==null ){
					libOrderRefunds = new LibOrderRefunds();
					libOrderRefunds.setInitiateTime(new Date());
					libOrderRefunds.setLibId(libOrderDetails.getLibId());
					libOrderRefunds.setInitiateUserId(libOrderDetails.getUserId());
					libOrderRefunds.setAcceptRole(type);
					libOrderRefunds.setStep(1);
					libOrderRefunds.setStat(0);
					libOrderRefunds.setStatVoid(1);
					libOrderRefunds.setInitiateOpenId(openId);
					libOrderRefunds.setOrderDetailsId(libOrderDetails.getId());
					if("s_cd".equals(type)){
						libOrderRefunds.setTotalStep(4);
					}else{
						libOrderRefunds.setTotalStep(5);
					}
					this.save(libOrderRefunds);
					//发送消息模板给销售
					libOrderDetailsService.sendReviewTemplate(libOrderRefunds.getId(), 
							userService.getAccount(libOrderDetails.getSalesUserId()),childName,libOrderDetails.getDetails(),
							libOrderDetails.getPrice());
				}
		return libOrderRefunds;
	}
	@Override
	public ResponseEntity saveOrderRefundsTwo(BigDecimal price,
			String refundsStat, String refundsReason, String id, String type,
			Integer stat, String reason,String openId) {
		ResponseEntity response = new ResponseEntity();
		LibOrderRefunds  libOrderRefunds =libOrderRefundsService.getById(id);
		LibOrderDetails  libOrderDetails  =libOrderDetailsService.getById(libOrderRefunds.getOrderDetailsId());
		LibVip  libVip = vipService.getById(libOrderDetails.getVipId()!=null ? libOrderDetails.getVipId() :"-1" );
		libOrderRefunds.setPrice(price);
		libOrderRefunds.setRefundsStat(refundsStat);
		libOrderRefunds.setRefundsReason(refundsReason);
		libOrderRefunds.setType(type);
		libOrderRefunds.setStat(stat);
		libOrderRefunds.setReviewTime(new Date());
		libOrderRefunds.setReason(reason);
		libOrderRefunds.setAuditorOpenId(openId);
		libOrderRefundsService.save(libOrderRefunds);
		if(stat == 1){
			LibOrderRefunds orderRefunds = new  LibOrderRefunds();
			orderRefunds.setInitiateTime(libOrderRefunds.getInitiateTime());
			orderRefunds.setLibId(libOrderRefunds.getLibId());
			orderRefunds.setInitiateUserId(libOrderRefunds.getInitiateUserId());
			orderRefunds.setOrderDetailsId(libOrderRefunds.getOrderDetailsId());
			orderRefunds.setPrice(libOrderRefunds.getPrice());
			orderRefunds.setRefundsStat(libOrderRefunds.getRefundsStat());
			orderRefunds.setRefundsReason(libOrderRefunds.getRefundsReason());
			orderRefunds.setTotalStep(libOrderRefunds.getTotalStep());
			orderRefunds.setType(libOrderRefunds.getType());
			orderRefunds.setInitiateOpenId(libOrderRefunds.getInitiateOpenId());
			orderRefunds.setStatVoid(1);
			//发送消息模板 判断 发送给馆长或区域总监
			orderRefunds.setStat(0);
			orderRefunds.setStep(libOrderRefunds.getStep()+1);
			//判断该管是不是有CD
			Integer count=libStaffingService.fingByCDcount(libOrderRefunds.getLibId());
			
			//当前操作员是馆长，那么就发送给区域总监
			if("s_cd".equals(libOrderRefunds.getAcceptRole())){
				//TbLibJoin  tbLibJoin=joinService.getById(libOrderRefunds.getLibId());
				//orderRefunds.setAcceptRole(organizationService.getParentCodeByOrgCode(tbLibJoin.getOrgCode()));
				orderRefunds.setAcceptRole("SSJ-SSJ-CW");
			}else{
				if(count>0){
					orderRefunds.setAcceptRole("s_cd");
				}else{
					//TbLibJoin  tbLibJoin=joinService.getById(libOrderRefunds.getLibId());
					//orderRefunds.setAcceptRole(organizationService.getParentCodeByOrgCode(tbLibJoin.getOrgCode()));
					//审核后发送给财务
					orderRefunds.setAcceptRole("SSJ-SSJ-CW");
				}
			}
			libOrderRefundsService.save(orderRefunds);
			//发送消息模板给上一级
		    if("s_cd".equals(libOrderRefunds.getAcceptRole())){
		    	//推送给财务
		    	String url ="/weixin/libOrder/applyFives_"+orderRefunds.getId()+".html";
		    	libOrderDetailsService.sendSuperiorTemplate(url, orderRefunds.getAcceptRole(), orderRefunds.getAcceptRole(),orderRefunds.getId(),libVip.getChildName(),libOrderRefunds.getPrice());
		    	
		    }else{
		    	if(count>0){
		    		//推送给馆长
		    		String url ="/weixin/libOrder/applyThree_"+orderRefunds.getId()+".html";
		    		libOrderDetailsService.sendSuperiorTemplate(url, orderRefunds.getLibId(), orderRefunds.getAcceptRole(),orderRefunds.getId(),libVip.getChildName(),libOrderRefunds.getPrice());
		    	}else{
		    		//推送给财务
			    	String url ="/weixin/libOrder/applyFives_"+orderRefunds.getId()+".html";
			    	libOrderDetailsService.sendSuperiorTemplate(url, orderRefunds.getAcceptRole(), orderRefunds.getAcceptRole(),orderRefunds.getId(),libVip.getChildName(),libOrderRefunds.getPrice());
			    	
		    	}
		    }
		  
		}else{
			// 拒绝用户 发送通知给用户 让用户从新发起 （包括下级直到 用户）
			//把之前的记录全部设置为拒绝状态
			libOrderRefundsService.updateStatVoid(libOrderRefunds.getOrderDetailsId(), 2);
			libOrderDetailsService.sendRefuseTemplate(id, libOrderRefunds.getInitiateOpenId(),reason);
		}
		  //修改推送
	//    pushTemplateService.updateObjectId(id);
		response.success("获取成功");
		return response;
	}
	@Override
	public ResponseEntity saveOrderRefundsThree(String id, Integer stat,
			String reason,String openId) {
		ResponseEntity response = new ResponseEntity();
		LibOrderRefunds  libOrderRefunds =libOrderRefundsService.getById(id);
		libOrderRefunds.setReviewTime(new Date());
		libOrderRefunds.setStat(stat);
		libOrderRefunds.setReason(reason);
		libOrderRefunds.setAuditorOpenId(openId);
		libOrderRefundsService.save(libOrderRefunds);
		
		if(stat ==1){
			LibOrderRefunds orderRefunds = new  LibOrderRefunds();
			orderRefunds.setInitiateTime(libOrderRefunds.getInitiateTime());
			orderRefunds.setLibId(libOrderRefunds.getLibId());
			orderRefunds.setInitiateUserId(libOrderRefunds.getInitiateUserId());
			orderRefunds.setOrderDetailsId(libOrderRefunds.getOrderDetailsId());
			orderRefunds.setPrice(libOrderRefunds.getPrice());
			orderRefunds.setRefundsStat(libOrderRefunds.getRefundsStat());
			orderRefunds.setRefundsReason(libOrderRefunds.getRefundsReason());
			orderRefunds.setTotalStep(libOrderRefunds.getTotalStep());
			orderRefunds.setType(libOrderRefunds.getType());
			orderRefunds.setInitiateOpenId(libOrderRefunds.getInitiateOpenId());
			orderRefunds.setStatVoid(1);
			//发送消息模板 判断 发送给馆长或区域总监
			orderRefunds.setStat(0);
			orderRefunds.setStep(libOrderRefunds.getStep()+1);
			//当前操作员是馆长，那么就发送给区域总监
			//TbLibJoin  tbLibJoin=joinService.getById(libOrderRefunds.getLibId());
			//orderRefunds.setAcceptRole(organizationService.getParentCodeByOrgCode(tbLibJoin.getOrgCode()));
			//当前操作员是馆长，那么就发送给财务
			orderRefunds.setAcceptRole("SSJ-SSJ-CW");
			libOrderRefundsService.save(orderRefunds);
			//推送给财务
			String url ="/weixin/libOrder/applyFives_"+orderRefunds.getId()+".html";
	    	LibOrderDetails  libOrderDetails =libOrderDetailsService.getById(libOrderRefunds.getOrderDetailsId());
			LibVip  libVip = vipService.getById(libOrderDetails.getVipId()!=null ? libOrderDetails.getVipId() :"-1" );
	    	libOrderDetailsService.sendSuperiorTemplate(url, orderRefunds.getAcceptRole(), orderRefunds.getAcceptRole(),orderRefunds.getId(),libVip.getChildName(),libOrderRefunds.getPrice());
			//发送消息模板给上级，发送给区域经理
		}else{
			// 拒绝用户 发送通知给用户 让用户从新发起 （包括下级直到 用户）
						//把之前的记录全部设置为拒绝状态。
			libOrderDetailsService.sendSubordinateTemplate(libOrderRefunds.getInitiateOpenId(), libOrderRefunds.getLibId(), libOrderRefunds.getOrderDetailsId(), id,reason);
			libOrderRefundsService.updateStatVoid(libOrderRefunds.getOrderDetailsId(), 2);
		}
	//	  pushTemplateService.updateObjectId(id);
		
		response.success("获取成功");
		return response;
	}
	@Override
	public ResponseEntity saveOrderRefundsFour(String id, Integer stat,
			String reason, String openId) {
		ResponseEntity response = new ResponseEntity();
		LibOrderRefunds  libOrderRefunds =libOrderRefundsService.getById(id);
		libOrderRefunds.setReviewTime(new Date());
		libOrderRefunds.setStat(stat);
		libOrderRefunds.setReason(reason);
		libOrderRefunds.setAuditorOpenId(openId);
		libOrderRefundsService.save(libOrderRefunds);
		if(stat ==1){
			LibOrderRefunds orderRefunds = new  LibOrderRefunds();
			orderRefunds.setInitiateTime(libOrderRefunds.getInitiateTime());
			orderRefunds.setLibId(libOrderRefunds.getLibId());
			orderRefunds.setInitiateUserId(libOrderRefunds.getInitiateUserId());
			orderRefunds.setOrderDetailsId(libOrderRefunds.getOrderDetailsId());
			orderRefunds.setPrice(libOrderRefunds.getPrice());
			orderRefunds.setRefundsStat(libOrderRefunds.getRefundsStat());
			orderRefunds.setRefundsReason(libOrderRefunds.getRefundsReason());
			orderRefunds.setTotalStep(libOrderRefunds.getTotalStep());
			orderRefunds.setType(libOrderRefunds.getType());
			orderRefunds.setInitiateOpenId(libOrderRefunds.getInitiateOpenId());
			orderRefunds.setStatVoid(1);
			//发送消息模板 判断 发送给馆长或区域总监
			orderRefunds.setStat(0);
			orderRefunds.setStep(libOrderRefunds.getStep()+1);
			//区域总监审核后发送给财务
			orderRefunds.setAcceptRole("SSJ-SSJ-CW");
			libOrderRefundsService.save(orderRefunds);
			//发送消息模板给上级，发送给财务总监
			
			String url ="/weixin/libOrder/applyFives_"+orderRefunds.getId()+".html";
			LibOrderDetails  libOrderDetails =libOrderDetailsService.getById(libOrderRefunds.getOrderDetailsId());
			LibVip  libVip = vipService.getById(libOrderDetails.getVipId()!=null ? libOrderDetails.getVipId() :"-1" );
	    	libOrderDetailsService.sendSuperiorTemplate(url, orderRefunds.getAcceptRole(), orderRefunds.getAcceptRole(),orderRefunds.getId(),libVip.getChildName(),libOrderRefunds.getPrice());
	    	
		}else{
			// 拒绝用户 发送通知给用户 让用户从新发起 （包括下级直到 用户）
						//把之前的记录全部设置为拒绝状态。
			libOrderDetailsService.sendSubordinateTemplate(libOrderRefunds.getInitiateOpenId(), libOrderRefunds.getLibId(), libOrderRefunds.getOrderDetailsId(), id,reason);
			libOrderRefundsService.updateStatVoid(libOrderRefunds.getOrderDetailsId(), 2);
		}
		// pushTemplateService.updateObjectId(id);
		response.success("获取成功");
		return response;
	}
	@Override
	public ResponseEntity saveOrderRefundsFives(String id, Integer stat,
			String reason, String openId) {
		ResponseEntity response = new ResponseEntity();
		try {
		//	pushTemplateService.updateObjectId(id);
			LibOrderRefunds  libOrderRefunds =libOrderRefundsService.getById(id);
			libOrderRefunds.setReviewTime(new Date());
			libOrderRefunds.setStat(stat);
			libOrderRefunds.setReason(reason);
			libOrderRefunds.setAuditorOpenId(openId);
			libOrderRefundsService.save(libOrderRefunds);
			if(stat ==1){
				 //写入一条记录，保存定时器定时处理
				LibOrderDetails libOrderDetails =libOrderDetailsService.getById(libOrderRefunds.getOrderDetailsId());
				//payB2CService.savePayB2C(libOrderRefunds.getInitiateUserId(), libOrderDetails.getOrderNo(), libOrderRefunds.getPrice(), libOrderRefunds.getInitiateOpenId());
				//发送模板给发起人
				libOrderDetailsService.sendAgreeTemplate(id, libOrderRefunds.getInitiateOpenId());
				//把vip卡service 设置为无效
				libVipServiceService.updateVipServiceStat(libOrderRefunds.getOrderDetailsId());
				weiXinPayB2CService.refund(libOrderDetails.getOrderId(), libOrderRefunds.getInitiateUserId(), libOrderRefunds.getPrice());
				
			}else{
				// 拒绝用户 发送通知给用户 让用户从新发起 （包括下级直到 用户）
				//把之前的记录全部设置为拒绝状态。
				libOrderDetailsService.sendSubordinateTemplate(libOrderRefunds.getInitiateOpenId(), libOrderRefunds.getLibId(), libOrderRefunds.getOrderDetailsId(), id,reason);
				libOrderRefundsService.updateStatVoid(libOrderRefunds.getOrderDetailsId(), 2);
			}
			 response.success("保存成功");
		} catch (Exception e) {
			response.failure("打款失败");
		}
		return response;
	}
	@Override
	public ResponseEntity saveOneRefundsZj(String id, Integer stat,
			String reason, String userId) {

		ResponseEntity response = new ResponseEntity();
		try {
			//pushTemplateService.updateObjectId(id);
			LibOrderRefunds  libOrderRefunds =libOrderRefundsService.getById(id);
			//看是否是财务在审核
			LibStaffing staffing = libStaffingService.findByUserIdAndType(userId, "SSJ-SSJ");
			if(staffing == null){
				response.failure("不是城市总监不能审核！");
				return response;
			}
			libOrderRefunds.setReviewTime(new Date());
			libOrderRefunds.setReason(reason);
			LessonService lessonService = lessonServiceService.getById(libOrderRefunds.getOrderDetailsId());
			//退费文描
			StringBuffer sb = new StringBuffer();
			String surplusPriceStr = null;
			//如果有试听课
			if(lessonService.getIsListenTest() == 1) {
				//总课次
				int courseCount = lessonService.getCourseCount()-1;
				//消课次数
				int finishCount = (lessonService.getCurrentCount() > 1) ? lessonService.getCurrentCount() - 2 : 0;
				//总付费
	            BigDecimal sumPrice = lessonService.getPrice().multiply(new BigDecimal(courseCount));
	            //消耗费用(不带上试听课的费用)
	            BigDecimal usePrice = lessonService.getPrice().multiply(new BigDecimal(finishCount));
	            //剩余金额
	            BigDecimal surplusPrice = sumPrice.subtract(usePrice);
	            surplusPriceStr = surplusPrice.toString();
	            sb.append("付费").append(sumPrice.toString()).append("元，").append("(含试听课)");
	            sb.append("消课").append(finishCount).append("次，");
	            sb.append("消耗共计").append(usePrice.toString()).append("元，");
	            sb.append("剩余").append(surplusPriceStr).append("元。");
			}else {
				//总课次
				int courseCount = lessonService.getCourseCount();
				//消课次数
				int finishCount = lessonService.getCurrentCount() - 1;
				//总付费
	            BigDecimal sumPrice = lessonService.getPrice().multiply(new BigDecimal(courseCount));
	            //消耗费用
	            BigDecimal usePrice = lessonService.getPrice().multiply(new BigDecimal(finishCount));
	            //剩余金额
	            BigDecimal surplusPrice = sumPrice.subtract(usePrice);
	            surplusPriceStr = surplusPrice.toString();
	            sb.append("付费").append(sumPrice.toString()).append("元，");
	            sb.append("消课").append(finishCount).append("次，");
	            sb.append("消耗共计").append(usePrice.toString()).append("元，");
	            sb.append("剩余").append(surplusPriceStr).append("元。");
			}
			   //查询退款信息
			 Map<String, Object> serviceInfo = zybService.findRefundsInfo(libOrderRefunds.getOrderDetailsId());
			if(stat ==1){
				   //城市总监通过，发送模板通知给财务总监
				   libOrderRefunds.setAcceptRole("SSJ-SSJ-CW");
				   LibStaffing staffing2 = libStaffingService.findOnebyLibIdAndType("SSJ-SSJ-CW", "SSJ-SSJ-CW");
				   User cwuser = userService.getById(staffing2.getUserId());
				   Map<String,String> data =new HashMap<String, String>();
		            String template_id_short="OPENTM415783002";
		            //尊敬的XX老师您好，XX校长的XX家长向您发起一笔课程退款申请，xx校长、XX城市总监已通过申请，请及时处理！
		            data.put("first", "尊敬的"+staffing2.getName()+"老师您好，"+serviceInfo.get("master_name")+"校长的"+serviceInfo.get("parent_name")+"家长向您发起一笔课程退款申请，"+serviceInfo.get("master_name")+"校长、"+staffing.getName()+"城市总监已通过申请，请及时处理！");
		            data.put("keyword1", lessonService.getGrade()+lessonService.getCourseName());
		            data.put("keyword2", surplusPriceStr);
		            data.put("keyword3", sb.toString());
		            data.put("remark", "点击查看退款详情。");
		            //如果是同意则跳H5页面 拒绝跳小程序
		            SendTemplateShort sendTemplateShort = null;
	            	String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/oneToOneAuditCw_"+id+".html";
	            	sendTemplateShort=new SendTemplateShort(cwuser.getAccount(), template_id_short, url, data);
		            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				
			}else{
			
				//将一对一辅导表退款中的状态改为status=1
				lessonService.setStatus(1);
				lessonServiceService.save(lessonService);
				//拒绝审核
				libOrderRefunds.setStat(2);
				libOrderRefunds.setReviewTime(new Date());
				//stat_void置为失效
				libOrderRefunds.setStatVoid(2);
				
				//城市总监拒绝 发送给用户和校长
				//尊敬的XX校长您好，您发起的XX家长课程退款申请已被城市总监拒绝，如有疑问，请与之联系。
				Map<String,String> data =new HashMap<String, String>();
	            String template_id_short="OPENTM415783002";
	            data.put("first", "尊敬的"+serviceInfo.get("master_name")+"校长您好，您发起的"+serviceInfo.get("parent_name")+"家长课程退款申请已被城市总监拒绝，如有疑问，请与之联系。");
	            data.put("keyword1", lessonService.getGrade()+lessonService.getCourseName());
	            data.put("keyword2", surplusPriceStr);
	            data.put("keyword3", sb.toString());
	            data.put("remark", "点击查看退款详情。");
	            //如果是同意则跳H5页面 拒绝跳小程序
	            SendTemplateShort sendTemplateShort = null;
            	String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/oneOrderJuJue_"+id+".html";
            	sendTemplateShort=new SendTemplateShort(libOrderRefunds.getAuditorOpenId(), template_id_short, url, data, 3, 10);
	            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				//亲爱的XX家长您好，您的退款申请未通过，如有疑问，请联系XX校长。
	            data.clear();
	            data.put("first", "亲爱的"+serviceInfo.get("parent_name")+"家长您好，您的退款申请未通过，如有疑问，请联系"+serviceInfo.get("master_name")+"校长");
	            data.put("keyword1", lessonService.getGrade()+lessonService.getCourseName());
	            data.put("keyword2", surplusPriceStr);
	            data.put("keyword3", sb.toString());
	            data.put("remark", "点击查看退款详情。");
	            Miniprogram miniprogram =new  Miniprogram();
	            miniprogram.setAppid(WxUtil.map.get("jzdAppId"));
	            miniprogram.setPagepath("pages/my_order/my_order?type=24&idx=2");
            	sendTemplateShort=new SendTemplateShort(libOrderRefunds.getInitiateOpenId(), template_id_short, null, data, miniprogram);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
			}
			libOrderRefundsService.save(libOrderRefunds);
			 response.success("保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			response.failure("保存失败");
		}
		return response;
	
	}
	@Override
	public ResponseEntity saveOneRefundsCw(String id, Integer stat,
			String reason, String userId) {

		ResponseEntity response = new ResponseEntity();
		try {
			LibOrderRefunds  libOrderRefunds =libOrderRefundsService.getById(id);
			//看是否是财务在审核
			LibStaffing staffing = libStaffingService.findByUserIdAndType(userId, "SSJ-SSJ-CW");
			if(staffing == null){
				response.failure("不是财务不能审核！");
				return response;
			}
			libOrderRefunds.setReviewTime(new Date());
			libOrderRefunds.setReason(reason);
			LessonService lessonService = lessonServiceService.getById(libOrderRefunds.getOrderDetailsId());
			//退费文描
			StringBuffer sb = new StringBuffer();
			String surplusPriceStr = null;
			//如果有试听课
			if(lessonService.getIsListenTest() == 1) {
				//总课次
				int courseCount = lessonService.getCourseCount()-1;
				//消课次数
				int finishCount = (lessonService.getCurrentCount() > 1) ? lessonService.getCurrentCount() - 2 : 0;
				//总付费
	            BigDecimal sumPrice = lessonService.getPrice().multiply(new BigDecimal(courseCount));
	            //消耗费用(不带上试听课的费用)
	            BigDecimal usePrice = lessonService.getPrice().multiply(new BigDecimal(finishCount));
	            //剩余金额
	            BigDecimal surplusPrice = sumPrice.subtract(usePrice);
	            surplusPriceStr = surplusPrice.toString();
	            sb.append("付费").append(sumPrice.toString()).append("元，").append("(含试听课)");
	            sb.append("消课").append(finishCount).append("次，");
	            sb.append("消耗共计").append(usePrice.toString()).append("元，");
	            sb.append("剩余").append(surplusPriceStr).append("元。");
			}else {
				//总课次
				int courseCount = lessonService.getCourseCount();
				//消课次数
				int finishCount = lessonService.getCurrentCount() - 1;
				//总付费
	            BigDecimal sumPrice = lessonService.getPrice().multiply(new BigDecimal(courseCount));
	            //消耗费用
	            BigDecimal usePrice = lessonService.getPrice().multiply(new BigDecimal(finishCount));
	            //剩余金额
	            BigDecimal surplusPrice = sumPrice.subtract(usePrice);
	            surplusPriceStr = surplusPrice.toString();
	            sb.append("付费").append(sumPrice.toString()).append("元，");
	            sb.append("消课").append(finishCount).append("次，");
	            sb.append("消耗共计").append(usePrice.toString()).append("元，");
	            sb.append("剩余").append(surplusPriceStr).append("元。");
			}
			   //查询退款信息
			 Map<String, Object> serviceInfo = zybService.findRefundsInfo(libOrderRefunds.getOrderDetailsId());
			if(stat ==1){
				   //城市总监通过，发送模板通知给财务总监
				libOrderRefunds.setStat(1);
				//最近审核时间
				libOrderRefunds.setReviewTime(new Date());
				libOrderRefundsService.save(libOrderRefunds);
				//删除zyb_dayy 退费未上课反馈的一对一任务;
				zuoybDayService.deleteByVipIdAndType(lessonService.getVipId(),lessonService.getId(),3);
				
				//调用退款接口
				payB2CService.refundPayB2C(libOrderRefunds.getInitiateUserId(), lessonService.getOrderNo(), 
						libOrderRefunds.getPrice(), libOrderRefunds.getCardName(), libOrderRefunds.getCardNum(),
						libOrderRefunds.getCardBank(), libOrderRefunds.getSubbranch());
				
			}else{
			
				//将一对一辅导表退款中的状态改为status=1
				lessonService.setStatus(1);
				lessonServiceService.save(lessonService);
				//拒绝审核
				libOrderRefunds.setStat(2);
				libOrderRefunds.setReviewTime(new Date());
				//stat_void置为失效
				libOrderRefunds.setStatVoid(2);
				
				//财务拒绝 发送给城市总监用户和校长
				//尊敬的XX校长您好，您发起的XX家长课程退款申请已被财务拒绝，如有疑问，请与之联系。
				//尊敬的XX城市总监您好，XX校长的XX家长课程退款申请已被财务拒绝，如有疑问，请与之联系。
				//亲爱的XX家长您好，您的退款申请未通过，如有疑问，请联系XX校长。
				LibStaffing staffing2 = libStaffingService.findOnebyLibIdAndType("SSJ-SSJ", "SSJ-SSJ");
				Map<String,String> data =new HashMap<String, String>();
	            String template_id_short="OPENTM415783002";
	            
	            data.put("first", "尊敬的"+staffing2.getName()+"城市总监您好，"+serviceInfo.get("master_name")+"校长的"+serviceInfo.get("parent_name")+"家长课程退款申请已被财务拒绝，如有疑问，请与之联系。");
	            data.put("keyword1", lessonService.getGrade()+lessonService.getCourseName());
	            data.put("keyword2", surplusPriceStr);
	            data.put("keyword3", sb.toString());
	            data.put("remark", "点击查看退款详情。");
	            //如果是同意则跳H5页面 拒绝跳小程序
	            User zjuser = userService.getById(staffing2.getUserId());
	            SendTemplateShort sendTemplateShort = null;
            	String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/oneOrderJuJue_"+id+".html";
            	sendTemplateShort=new SendTemplateShort(zjuser.getAccount(), template_id_short, url, data);
	            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
	            
	            data.clear();
	            data.put("first", "尊敬的"+serviceInfo.get("master_name")+"校长您好，您发起的"+serviceInfo.get("parent_name")+"家长课程退款申请已被财务拒绝，如有疑问，请与之联系。");
	            data.put("keyword1", lessonService.getGrade()+lessonService.getCourseName());
	            data.put("keyword2", surplusPriceStr);
	            data.put("keyword3", sb.toString());
	            data.put("remark", "点击查看退款详情。");
	            //如果是同意则跳H5页面 拒绝跳小程序
            	url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libOrder/oneOrderJuJue_"+id+".html";
            	sendTemplateShort=new SendTemplateShort(libOrderRefunds.getAuditorOpenId(), template_id_short, url, data, 3, 10);
	            pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
				//亲爱的XX家长您好，您的退款申请未通过，如有疑问，请联系XX校长。
	            data.clear();
	            data.put("first", "亲爱的"+serviceInfo.get("parent_name")+"家长您好，您的退款申请未通过，如有疑问，请联系"+serviceInfo.get("master_name")+"校长");
	            data.put("keyword1", lessonService.getGrade()+lessonService.getCourseName());
	            data.put("keyword2", surplusPriceStr);
	            data.put("keyword3", sb.toString());
	            data.put("remark", "点击查看退款详情。");
	            Miniprogram miniprogram =new  Miniprogram();
	            miniprogram.setAppid(WxUtil.map.get("jzdAppId"));
	            miniprogram.setPagepath("pages/my_order/my_order?type=24&idx=2");
            	sendTemplateShort=new SendTemplateShort(libOrderRefunds.getInitiateOpenId(), template_id_short, null, data, miniprogram);
				pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
			}
			libOrderRefundsService.save(libOrderRefunds);
			 response.success("保存成功");
		} catch (Exception e) {
			response.failure("审核失败");
		}
		return response;
	
	}

}
