package com.iamberry.wechat.handles.mq;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.channel.ChannelRebate;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.integral.IntegralConfig;
import com.iamberry.wechat.core.entity.integral.UseIntegral;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.NumberBacklogDto;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.report.Report;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.agentInfo.AgentPurchaseOrderService;
import com.iamberry.wechat.face.channel.ChannelRebateService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.integral.UseIntegralService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.report.ReportService;
import com.iamberry.wechat.service.ImberryConfig;
import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.SendMessageUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.core.entity.order.ProbationOrderDto;
import com.iamberry.wechat.core.entity.probation.ProbationAwardRelu;
import com.iamberry.wechat.core.entity.probation.ProbationNewLogs;
import com.iamberry.wechat.core.entity.task.TaskModel;
import com.iamberry.wechat.core.entity.task.WechatTask;
import com.iamberry.wechat.core.entity.task.WechatTaskLogs;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.face.order.ProbationShopOrderService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.face.task.WechatTaskService;
import com.iamberry.wechat.service.StaticCacheMemory;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.zk.SpringContextHolder;
/**
 * @author:何秀刚
 * @description: MQ模拟实现，每天最多处理1382400条
 * @createDate:2016年5月25日
 */
@Component(value="mqTask")
@Lazy(false)
public class MQTask implements InitializingBean {

	@Autowired
	private MQServiceProxy mQSerivce;
	@Autowired
	private RatFWLogger logger;
	@Autowired
	private WechatTaskService wechatTaskService;
	@Autowired
	private RebackServices rebackServices;
	@Autowired
	private ProbationShopOrderService probationShopOrderService;
	@Autowired
	private SendMessageUtil sendMessageUtil;
	@Autowired
	private CodeService codeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private AgentPurchaseOrderService agentPurchaseOrderService;
	@Autowired
	private UseIntegralService useIntegralService;
	@Autowired
	private AdminOrderService adminOrderService;
	@Autowired
	private CouponItemService couponItemService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private ReportService reportService;
	@Autowired
	private ChannelRebateService channelRebateService;

	private Lock lock = new ReentrantLock();

	@SuppressWarnings(value = {"unchecked", "rawtypes"})
	@Scheduled(cron = "0/30 * * * * ?")
	public void sendOrderService() {
		logger.info("------------task start-----------");
		// If the timer has not stopped, then the next time the timer can not start.
		lock.lock();
		
		try {
			// step 1, Gets the message that is not executed in the database.
			List<MQMessage> messages = mQSerivce.selectWaitHandlerMessage();
			if (messages == null || messages.size() <= 0) {
				return;
			}
			
			// step 2, Handle 10 messages at a time.
			for (MQMessage mqMessage : messages) {
				try {
					Object object = SpringContextHolder.getBean(mqMessage.getServiceHandlerObjectName());
					Class classes = object.getClass();
					Method method = classes.getMethod(mqMessage.getServiceHandlerMethodName(), MQMessage.class);
					if (method == null) {
						mqMessage.setServiceErrorMessage("Method is not defined:" + mqMessage.getServiceHandlerMethodName());
						mqMessage.setServiceStatus(2);
						continue;
					}
					// invoke Method.
					Object resultObject = method.invoke(object, mqMessage);
					if (!(resultObject instanceof Boolean)) {
						mqMessage.setServiceStatus(2);
						mqMessage.setServiceErrorMessage(mqMessage.getServiceHandlerObjectName() + "." + mqMessage.getServiceHandlerMethodName() + "()Return value is not type Boolean");
						continue;
					}
					if (!(Boolean) resultObject) {
						mqMessage.setServiceErrorMessage("invoke Method Error");
						mqMessage.setServiceStatus(2);
						continue;
					}
					mqMessage.setServiceStatus(1);
					continue;
				} catch (Exception e) {
					// TODO: handle exception
					mqMessage.setServiceErrorMessage(e.getMessage());
					mqMessage.setServiceStatus(2);
					continue;
				} finally {
					mqMessage.setServiceIsSend(1);
				}
			}
			
			// step 3, update Message status and serviceIsSend.
			mQSerivce.updateBatchMessage(messages);
			
			// step 4, is next ?
			if (messages.size() >= 10) {
				StaticCacheMemory.isStartTask = true;
				this.sendOrderService();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e, "MQ Task Error:" + e.getMessage());
		} finally {
			// reset lock
			lock.unlock();
		}
		logger.info("------------task invoke success-----------");
	}
	
	/**
	 * 订阅消息
	 */
	public void subscribeMessageQueue() {
	}
	
	// 强迫线程可见
	private volatile boolean oldState = true;
	
	/**
	 * 微信定期任务奖励-上个月的定时器
	 */
	@SuppressWarnings("deprecation")
//	@Scheduled(cron = "0/59 * * * * ?")
	public void oldMonthTask() {
		if (!oldState) {
			logger.info("线程正忙...");
			return;
		}
		oldState = false;
		try {
			// 判断上一个月的数据是否奖励完成
			logger.info("上一个月的定时奖励任务奖励...");
			// 当前时间
			Date nowDate = new Date();
			
			// 回到上一个月
			nowDate.setMonth(nowDate.getMonth() - 1);
			// 上一个月的结束时间  类似 ：2016-02-29 23:59:59
			Date oldMonthLastDay = DateTimeUtil.getLastDayOfYear(nowDate);
			// 上一个月的开始时间  类似 ：2016-02-01 00:00:00
			Date oldMonthFirstDay = DateTimeUtil.getFirstDayOfYear(nowDate);
			
			List<WechatTask> tasks = wechatTaskService.getRunTask(oldMonthFirstDay, oldMonthLastDay);
			if (tasks == null || tasks.size() == 0) {
				logger.info("暂时没有上一个月的任务奖励...");
				oldState = true;
				return;
			}
			// 获取在上一个月销售达到X台的数据
			for (WechatTask wechatTask : tasks) {
				List<TaskModel> models = rebackServices.getByDate(wechatTask.getTaskProductType(), oldMonthFirstDay, oldMonthLastDay, wechatTask.getTaskSalesNum());
				if (models == null || models.size() == 0) {
					logger.info("暂时没有人完成上一个月的任务" + wechatTask.getTaskId() + "奖励...");
					continue;
				}
				// 达到的用户是否已经领取奖励
				for (TaskModel taskModel : models) {
					WechatTaskLogs logs = new WechatTaskLogs();
					logs.setLogsTaskId(wechatTask.getTaskId());
					logs.setLogsUserOpenId(taskModel.getOpenID());
					Integer logsID = wechatTaskService.getByTaskIdAndOpenId(logs);
					if (logsID != null) {
						// 如果当前用户已经领取了奖励，那么跳过
						continue;
					}
					// 若用没有领取，那么奖励
					try {
						wechatTaskService.handlerTask(taskModel.getOpenID(), wechatTask.getTaskMoney(), wechatTask.getTaskId(), wechatTask.getTaskProductType());
					} catch (Exception e) {
						logger.error(this, "对:" + taskModel.getOpenID() + ",奖励失败!error:" + e.getMessage());
					}
				}
			}
		} catch (Exception e) {
			logger.error(this, "发生异常,奖励失败!error:" + e.getMessage());
		} finally {
			// 归还锁
			oldState = true;
		}
	}

	// 强迫线程可见
	private volatile boolean nowState = true;
	/**
	 * 微信定期任务奖励-本月的定时器
	 */
//	@Scheduled(cron = "0/59 * * * * ?")
	public void nowMonthTask() {
		if (!nowState) {
			logger.info("线程正忙...");
			return;
		}
		nowState = false;
		
		try {
			// 判断本月是否有奖励数据
			logger.info("本月的定时奖励任务奖励...");
			// 当前时间
			Date nowDate = new Date();
			
			// 上一个月的结束时间  类似 ：2016-02-29 23:59:59
			Date oldMonthLastDay = DateTimeUtil.getLastDayOfYear(nowDate);
			// 上一个月的开始时间  类似 ：2016-02-01 00:00:00
			Date oldMonthFirstDay = DateTimeUtil.getFirstDayOfYear(nowDate);
			
			List<WechatTask> tasks = wechatTaskService.getRunTask(oldMonthFirstDay, oldMonthLastDay);
			if (tasks == null || tasks.size() == 0) {
				logger.info("暂时没有本月的任务奖励...");
				nowState = true;
				return;
			}
			// 获取在上一个月销售达到X台的数据
			for (WechatTask wechatTask : tasks) {
				List<TaskModel> models = rebackServices.getByDate(wechatTask.getTaskProductType(), oldMonthFirstDay, oldMonthLastDay, wechatTask.getTaskSalesNum());
				if (models == null || models.size() == 0) {
					logger.info("暂时没有人完成本月的任务" + wechatTask.getTaskId() + "奖励...");
					continue;
				}
				// 达到的用户是否已经领取奖励
				for (TaskModel taskModel : models) {
					WechatTaskLogs logs = new WechatTaskLogs();
					logs.setLogsTaskId(wechatTask.getTaskId());
					logs.setLogsUserOpenId(taskModel.getOpenID());
					Integer logsID = wechatTaskService.getByTaskIdAndOpenId(logs);
					if (logsID != null) {
						// 如果当前用户已经领取了奖励，那么跳过
						continue;
					}
					// 若用没有领取，那么奖励
					try {
						wechatTaskService.handlerTask(taskModel.getOpenID(), wechatTask.getTaskMoney(), wechatTask.getTaskId(), wechatTask.getTaskProductType());
					} catch (Exception e) {
						logger.error(this, "对:" + taskModel.getOpenID() + ",奖励失败!error:" + e.getMessage());
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(this, "发生异常:" + e.getMessage());
		} finally {
			nowState = true;
		}
	}
	
	public void afterPropertiesSet() throws Exception {
	}
	
	/**
	 * 试用订单短信推送服务（满足XX天奖励XX奖励）
	 */
//	@Scheduled(cron = "0 0 */1 * * ?")//每小时执行一次
	public void probationRewardPush(){
		logger.info("------------执行推送满足奖励条件用户 start-----------"); 
		//查询奖励推送规则
		List<ProbationAwardRelu> reluList = probationShopOrderService.selectProbationAwardRelu(); 
		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(reluList!=null && !reluList.isEmpty()){
			for(ProbationAwardRelu awardRelu : reluList){
				//查询所有待支付订单
				List<ProbationOrderDto> orderDtoList = probationShopOrderService.selectProbationStartOrder();
				if(orderDtoList!=null && !orderDtoList.isEmpty()){
					for(ProbationOrderDto orderDto : orderDtoList ){
						//计算总试用期限(小时)
						Long totalDate = (orderDto.getProbationEndTime().getTime() - orderDto.getProbationStartTime().getTime()) / 1000 / 60 / 60;
						//计算试用剩余期限(小时)
						Long remainingDate = (orderDto.getProbationEndTime().getTime() - new Date().getTime()) / 1000 / 60 / 60;
						//暂停时间
						/*Long pauseDate = 0l;
						if(orderDto.getProbationPauseStartTime() != null && orderDto.getProbationPauseEndTime() != null){
							pauseDate =	(orderDto.getProbationPauseEndTime().getTime() - orderDto.getProbationPauseStartTime().getTime()) / 1000 / 60 / 60;
						}*/
						//实际试用时间 (总试用时间 - 试用剩余期限 - 暂停时间)
 						Long actualProbationDate = totalDate - remainingDate - orderDto.getProbationPauseTotalLength() / 1000 / 60 / 60;
						//奖励奖品天数转换为小时
						Long awardDate = Long.valueOf(awardRelu.getAwardNum()) * 24;
						//奖励条件时间 - 实际试用时间  （大于23小时或者小于26小时则推送）
						if( awardDate -actualProbationDate > 23 && awardDate -actualProbationDate < 26 ){
							ProbationNewLogs probationNewLogs =	probationShopOrderService.selectProbationNewLogsByOrderId(orderDto.getProbationOrderid());
							//添加日志信息
							ProbationNewLogs newLogs = new ProbationNewLogs();
							newLogs.setLogsPorderid(orderDto.getProbationOrderid());
							newLogs.setLogsTime(awardRelu.getAwardNum());
							newLogs.setLogsCreateTime(new Date());
							if(probationNewLogs == null){
								//推送操作
								sendMessageUtil.probationPush(awardRelu.getAwardInfo(), 
										orderDto.getProductName(), 
										orderDto.getProbationOrderid(), 
										formatter.format(orderDto.getProbationStartTime()), 
										formatter.format(
												new Date(
														orderDto.getProbationStartTime().getTime() + 
														(awardRelu.getAwardNum() * 24 + orderDto.getProbationPauseTotalLength()) * 60 * 60 * 1000)), 
										awardRelu.getAwardInfoTwo(), 
										orderDto.getProbationOpenid(), 
										ResultInfo.TRY_ORDER_DETAIL+"?orderId="+orderDto.getProbationOrderid());
								//添加日志
								probationShopOrderService.insertProbationLogs(newLogs);
								//发送短信给收货人
								if(StringUtils.isNotEmpty(orderDto.getProbationReceiveTel())){
									codeService.sendTextToUser(orderDto.getProbationReceiveTel(), 6);
								}
							}else if(probationNewLogs.getLogsTime() < awardRelu.getAwardNum()){
								//执行推送
								sendMessageUtil.probationPush(
										awardRelu.getAwardInfo(), 
										orderDto.getProductName(), 
										orderDto.getProbationOrderid(), 
										formatter.format(orderDto.getProbationStartTime()), 
										formatter.format(
												new Date(orderDto.getProbationStartTime().getTime() 
														+ (awardRelu.getAwardNum() * 24 + orderDto.getProbationPauseTotalLength()) * 60 * 60 * 1000)),
										awardRelu.getAwardInfoTwo(), 
										orderDto.getProbationOpenid(), 
										ResultInfo.TRY_ORDER_DETAIL+"?orderId="+orderDto.getProbationOrderid());
								//修改日志
								probationShopOrderService.updatePauseLogsDate(newLogs);
								//发送短信给收货人
								if(StringUtils.isNotEmpty(orderDto.getProbationReceiveTel())){
									codeService.sendTextToUser(orderDto.getProbationReceiveTel(), awardRelu.getAwardNum().intValue());
								}
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 保持百胜系统cookie的活性（每分钟执行一次）
	 */
	@SuppressWarnings(value = {"unchecked", "rawtypes"})
	@Scheduled(cron = "0 0/1 * * * ?")
	public void selectEfastOrder() {
		try{
			//获取cookie值
			ShopSystemRule rule =  systemService.selectOneShopRuleById(244);
			String phone = "13590159563";
			String url = NameUtils.getConfig("efast_order_url") + phone;
			Map<String,String> params = new HashMap<String,String>();
			String cookie = rule.getRuleDesc();
			//查询百胜订单信息
			String str = HttpClient431Util.doGet(params,url,null,null,cookie);
		} catch(Exception e) {
			System.out.println("------------请求百胜接口失败-------------");
		}

	}

	/**
	 * 电动牙刷商城更换刷头提示（每小时执行一次）
	 */
	/*@SuppressWarnings(value = {"unchecked", "rawtypes"})
	@Scheduled(cron = "0 0 0/1 * * ?")
	public void updateToothHint() {
		//获取更换刷头时间间隔
		ShopSystemRule rule =  systemService.selectOneShopRuleById(245);
		List<OrderHint> list = new ArrayList<OrderHint>();
		OrderHint orderHint = new OrderHint();
		orderHint.setHintTime(new Date());
		orderHint.setHintStatus(1);
		//根据时间和状态获取需要提示的
		List<OrderHint> orderList = agentPurchaseOrderService.listOrderHint(orderHint);
		if (orderList == null || orderList.size() == 0) {
			return;
		}
		for (int i = 0;i < orderList.size();i++) {
			OrderHint order = orderList.get(i);
			Calendar cl = Calendar.getInstance();
			cl.setTime(order.getHintTime());
			cl.add(Calendar.MONTH, +rule.getRuleNum().intValue());
			OrderHint hint = new OrderHint();
			hint.setHintTime(cl.getTime());
			hint.setHintId(order.getHintId());
			hint.setHintNum(1);
			list.add(hint);
			//更换牙刷刷头提示
			sendMessageUtil.updateToothHint("上朵电动牙刷商城", "上朵电动牙刷","您的牙刷已使用三个月，请及时更换刷头!", "上朵电动牙刷商城", order.getUserOpenId(),NameUtils.getConfig("WECHAT_UPDATE_TOOTH_HINT")+order.getHintId());
		}
		//批量修改更换刷头信息
		int num = agentPurchaseOrderService.updateOrderHintList(list);
	}*/


	/**
	 * 待入账积分更改为已入账积分（每小时执行一次）
	 */
	@SuppressWarnings(value = {"unchecked", "rawtypes"})
	@Scheduled(cron = "0 0 0/1 * * ?")
//	@Scheduled(cron = "0 0/3 * * * ?")//每三分钟执行一次
	public void updateIntegralStayToAlready() {
		useIntegralService.updateIntegralStayToAlready();
	}

	/**
	 * 待处理订单提醒（每天下午2:50点，短信提醒益霜、上朵运营一次（15814645335、13472545449）
	 */
	@SuppressWarnings(value = {"unchecked", "rawtypes"})
	/*@Scheduled(cron = "0 0/3 * * * ?")//每三分钟执行一次*/
	@Scheduled(cron = "0 50 14 * * ?")//每天下午2点50分执行一次
	public void pendingOrderReminder() {
		//查询待发货事项、申请退款订单、申请退货订单、申请换货订单 的数量
		NumberBacklogDto numberBacklogDto = adminOrderService.selectNumberBacklog();
		Integer num = (numberBacklogDto.getExchange()+numberBacklogDto.getReturnGoods()+numberBacklogDto.getReturnRefund()+numberBacklogDto.getSendTheGoods());
		String text = MessageFormat.format(ImberryConfig.PENDING_ORDER_REMINDER, num);
		if(num > 0){
			codeService.informShipping("18001923600", text);
			codeService.informShipping("18271840547", text);
			codeService.informShipping("13922874118", text);
		}
	}


	/**
	 * 每天0点统计上朵领取优惠券信息
	 *
	 * 领券人数：
	 * 使用券人数：
	 * 注册人数：
	 */
	@SuppressWarnings(value = {"unchecked", "rawtypes"})
	//	@Scheduled(cron = "0 0/3 * * * ?")//每三分钟执行一次
	@Scheduled(cron = "0 0 0 * * ?")		//每天0点触发
	public void report() {
		logger.info("统计上朵领取优惠券信息");
		Report report = new Report();
		//获取需要查询的优惠券类型的id
		String ids = systemService.selectOneShopRuleById(256).getRuleDesc();
		String[] newIds = ids.split(",");
		if(newIds == null){
			return;
		}
		Integer[] couponIds = new Integer[newIds.length];
		for (int i=0;i<newIds.length;i++) {
			couponIds[i] = Integer.valueOf(newIds[i]);
		}
		CouponItem couponItem = new CouponItem();
		couponItem.setCouponIds(couponIds);
		Integer number = couponItemService.allCouponItemNumber(couponItem);
		report.setReportCouponNumber(number);

		couponItem.setCouponUseStatus(2);
		number = couponItemService.allCouponItemNumber(couponItem);
		report.setReportCouponUseNumber(number);

		number = memberService.getRegisteredNumber();
		report.setReportRegisteredNumber(number);

		Integer flag = reportService.save(report);
	}

	/**
	 * 生日福利
	 * 每天0点为当天生日的人送积分
	 */
	@SuppressWarnings(value = {"unchecked", "rawtypes"})
//	@Scheduled(cron = "0 0/2 * * * ?")	//每三分钟执行一次
	@Scheduled(cron = "0 0 9 * * ?")	//每天9点触发
	public void birthday() {
		logger.info("生日福利定时任务");
		IntegralConfig integralConfig = useIntegralService.getIntegralConfigById(16);
		Integer integral = integralConfig.getIntegralConfigNumber();
		Integer configId = integralConfig.getIntegralConfigId();
		Member memeber  = new Member();
		memeber.setUserBirthDate(new Date());
		memeber.setUserIdentity(1);		//userIdentity
		/*查询当天生日的人*/
		List<Member> memberList =  memberService.getBirthday(memeber);
		for (Member m :memberList) {
			UseIntegral ui = new UseIntegral();
			ui.setUserOpenId(m.getUserOpenid());
			ui.setConfigId(16);
			ui.setIntegralCreateTime(new Date());
			List<UseIntegral>  useIntegralList = useIntegralService.getUseIntegralList(ui);
			if(useIntegralList == null || useIntegralList.size() < 1){
				memberService.updaterIntegral(m.getUserId(),1,configId,integral,"生日福利赠送积分");
			}
		}
	}


	/**
	 * 上朵分销返利定时任务
	 * 每天1点
	 */
	@SuppressWarnings(value = {"unchecked", "rawtypes"})
//	@Scheduled(cron = "0 0/2 * * * ?")	//每三分钟执行一次
	@Scheduled(cron = "0 0 1 * * ?")	//每天1点触发
	public void channelRebate() {
		logger.info("上朵分销返利任务开始");
		ChannelRebate channelRebate = new ChannelRebate();
		channelRebate.setRebackStatus(1);
		List<ChannelRebate> channelRebateList = channelRebateService.listChannelRebate(channelRebate);
		Integer num = Integer.valueOf(systemService.selectOneShopRuleById(258).getRuleNum().intValue());		//10
		logger.info("上朵分销返利订单处理时间为："+num + "天");
		for (ChannelRebate cr:channelRebateList) {
			Order order = adminOrderService.getShopOrderByOrderId(cr.getSalesOrderid());
			Integer status = order.getSalesStatus();
			//状态  0：取消订单  1：待支付  2：已支付、待发货  3：退款申请中  4：已退款  5：已发货  6：申请退货中  7：退货中  8：订单退货，订单关闭  9：换货中  10：换货完成 11：申请换货中 12：订单完成
			if(status == 5 ||   status == 9 || status == 10 ||  status == 11 ||  status == 12){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(order.getSalesCreateDate());
				calendar.add(Calendar.DATE, num);
				if(calendar.getTime().getTime() < new Date().getTime()){	//如果订单时间+10天 小于 当前时间，那么表示该返利状态更改为已返利（2）
					ChannelRebate newCr = new ChannelRebate();
					newCr.setRebateId(cr.getRebateId());
					newCr.setRebackStatus(2);
					//newCr.setRebackTime(new Date());
					Integer flag = channelRebateService.update(newCr);
					if(flag > 0){
						logger.info("上朵分销返利成功，订单号为："+cr.getSalesOrderid()+"--返利id为："+cr.getRebateId());
					}else{
						logger.info("上朵分销返利失败，订单号为："+cr.getSalesOrderid()+"--返利id为："+cr.getRebateId());
					}
				}
			}else{
//				if(status > 2){
//					logger.info("上朵分销返利记录，订单号为："+cr.getSalesOrderid()+"--返利id为："+cr.getRebateId()+"==订单状态为："+status);
//				}
			}
		}
		logger.info("上朵分销返利任务结束");
	}



}
