package com.iamberry.wechat.service.order;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.iamberry.wechat.core.entity.order.NumberBacklogDto;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.drp.PlaceLogs;
import com.iamberry.wechat.core.entity.flow.TemplateFlowInfo;
import com.iamberry.wechat.core.entity.member.CashLog;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.order.OrderItem;
import com.iamberry.wechat.core.entity.order.OrderRebackMoney;
import com.iamberry.wechat.core.entity.reback.RebackInfo;
import com.iamberry.wechat.core.entity.relationship.DealerRelation;
import com.iamberry.wechat.core.entity.relationship.WdRelation;
import com.iamberry.wechat.core.entity.rewards.RewardsLog;
import com.iamberry.wechat.core.entity.rewards.RewardsRank;
import com.iamberry.wechat.core.entity.rewards.SalesLog;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.service.mapper.RebackInfoMapper;
import com.iamberry.wechat.service.mapper.RewardsMapper;
import com.iamberry.wechat.service.mapper.SalesLogMapper;
import com.iamberry.wechat.service.mapper.TemplateFlowInfoMapper;
import com.iamberry.wechat.service.member.dao.CashLogDao;
import com.iamberry.wechat.service.order.dao.AdminOrderDao;
import com.iamberry.wechat.service.relationship.Dao.DealerRelationDao;
import com.iamberry.wechat.service.relationship.Dao.WdRelationDao;
import com.iamberry.wechat.tools.ResultInfo;


@Service
public class AdminOrderServiceImpl implements AdminOrderService {

	@Autowired
	private AdminOrderDao adminOrderDao;
	
	@Autowired
	private CashLogDao cashLogDao;

	
//	@Autowired
//	private WxService wxService;
	
	@Autowired
	private RebackInfoMapper  rebackInfoMapper;
	
	@Autowired
	private DealerRelationDao dealerRelationDao;
	
	@Autowired
	private WdRelationDao wdRelationDao;
	
	@Autowired
	private TemplateFlowInfoMapper templateFlowInfoMapper;
	
	@Autowired
	private RatFWLogger logger;
	
	@Autowired
	private SalesLogMapper salesLogMapper;
	
	@Autowired
	private RewardsMapper rewardsMapper;
	
	/**
	 * 根据订单编号，获取该订单的返利信息
	 * @param orderId  订单编号
	 * @return List<OrderRebackMoney> 返利信息
	 */
	public List<OrderRebackMoney> selectOrderRebackByOrderId(String orderId){
		return this.adminOrderDao.selectOrderRebackByOrderId(orderId);

	}
	
	public List<Order> selectShopOrder(Order order) {
		// TODO Auto-generated method stub
		order.getPage().initRecordBegin();
		Date endDate=null;
		/*if(order.getBeginDate()!=null){
			try {
				endDate=new Date(DateTimeUtil.getDayEnd(order.getBeginDate()));
			} catch (ParseException e) {
				endDate=DateTimeUtil.addDay(order.getBeginDate(), 1);
				e.printStackTrace();
			}
			order.setEndDate(endDate);
		}*/
		return this.adminOrderDao.selectShopOrder(order);
	}

	
	public List<Order> selectShopOrderByOrderId(Order order) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.selectShopOrderByOrderId(order);
	}

	
	public Order getShopOrderByOrderId(String orderId) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.getShopOrderByOrderId(orderId);
	}

	
	public List<OrderItem> getShopOrderItemByOrderId(String orderId) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.getShopOrderItemByOrderId(orderId);
	}

	
	public Integer selectShopOrderCount(Order order) {
		// TODO Auto-generated method stub
		 int count = this.adminOrderDao.selectShopOrderCount(order);
		 return	count = count % order.getPage().getPageSize() == 0? count/order.getPage().getPageSize():(count/order.getPage().getPageSize())+1;
	}

	
	public Order selectOrderStatusByOrderId(String orderId) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.selectOrderStatusByOrderId(orderId);
	}

	
	public boolean updateOrderStatusByOrderId(Order order) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.updateOrderStatusByOrderId(order)>= 1 ? true : false;
	}

	
	public boolean deliverOrderByOrderId(Order order) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.deliverOrderByOrderId(order) >= 1 ? true : false;
	}

	
	public Integer updateOrderDeliver(Order order) {
		// TODO Auto-generated method stub
		return adminOrderDao.updateOrderDeliver(order);
	}

	
	public boolean updateOrderAdminRemarkByOrderId(String remark,
			String orderId, Integer remarkColor) {
		// TODO Auto-generated method stub
		Order order = new Order();
		order.setSalesAdminRemark(remark);
		order.setSalesColorType(remarkColor);
		order.setSalesOrderid(orderId);
		return this.adminOrderDao.updateOrderAdminRemarkByOrderId(order) >= 1 ? true : false;
	}

	
	public List<Order> selectOrderByIntegral(Order order) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.selectOrderByIntegral(order);
	}

	
	public void updateOrderIntegral(Order order, ShopSystemRule shopSystemRule) {
		// TODO Auto-generated method stub
		//（微代理，自己奖励积分公式：购买台数*每台奖励积分数）
		logger.info("——返利过程:返利start,订单号:" + order.getSalesOrderid() + "——");
		if (null == order) {
			return;
		}
		if (null == order.getSalesOpenid() || "".equals(order.getSalesOpenid())) {
			logger.info("——返利过程:此订单的openId为空,订单号:" + order.getSalesOrderid() + "——");
			return;
		}
		
		Member member = this.adminOrderDao.getUserByOpenId(order.getSalesOpenid());
		if (null == member) {
			logger.info("——返利过程:没有查到该用户,订单号:" + order.getSalesOrderid() + "——");
			return;
		}
		
		//修改订单是否入账的状态，将未入账变为已入账
		this.adminOrderDao.updateOrderIntegral(order.getSalesOrderid());
		
		//将返利表中待入账改为已入账
		RebackInfo rabackInfo = new RebackInfo();
		rabackInfo.setOrderId(order.getSalesOrderid());
		rabackInfo.setStatus(2);
		rebackInfoMapper.updateStatus(rabackInfo);
		
		//查询是否有微代理返利
		WdRelation wdRelation = wdRelationDao.getWdRelationByOpenid(order.getSalesOpenid());
		
		//一个订单中可能有多个产品，每个产品可能有一个单独的返利类型，所以需要循环判断产品类型，根据数量返利
		if (null != order.getOrderItemList() && order.getOrderItemList().size() > 0) {
			for (OrderItem orderItem : order.getOrderItemList()) {
				//将order重新封装，使根据产品返利更清晰，每次封装只封装一个产品类型
				List<OrderItem> orderItemList = new ArrayList<OrderItem>();
				orderItemList.add(orderItem);
				Order orderInfo = new Order();
				orderInfo.setSalesOrderid(order.getSalesOrderid());
				orderInfo.setSalesOpenid(order.getSalesOpenid());
				orderInfo.setItemSum(orderItem.getItemNum());
				orderInfo.setOrderItemList(orderItemList);

				//如果没有模板id，则是自己关注
				if ((null == member.getTemplateId() || "".equals(member.getTemplateId())) && member.getUserResType().intValue() != 3) {
					//如果是第一层级，则微代理返利表为空，不需要返利
					if (wdRelation == null) {
						return;
					}
					//获取返利模板id
					int templateId = shopSystemRule.getRuleNum().intValue();
					member.setTemplateId(templateId);
					//微代理返利
					this.agencyRebate(wdRelation, member, orderInfo);
				} else {
					int levelSum = 0;
					if (wdRelation != null && null != member.getTemplateId() && !"".equals(member.getTemplateId())) {
						//微代理返利
						this.agencyRebate(wdRelation, member, orderInfo);
						levelSum = wdRelation.getWdCount();
					}
					//查询商户层
					if (null != member.getUserDealers() && !"".equals(member.getUserDealers())) {
						DealerRelation dealerRelation = dealerRelationDao.getDealerRelationById(member.getUserDealers());
						if (dealerRelation != null) {
							this.commercialRebate(dealerRelation, member, orderInfo, levelSum);
						}
					}
				}
				logger.info("——返利过程:返利end,订单号:" + order.getSalesOrderid() + "——");
			}
		} else {
			logger.info("——返利过程:此订单的订单项为空,订单号:" + order.getSalesOrderid() + "——");
			return;
		}
		
		
	}
	
	//给微代理返利
	public void agencyRebate(WdRelation wdRelation,Member member, Order order) {
		int itemSum = order.getItemSum();
		//判断返利第一层级是否为空，如果不为空则返利
		if (null != wdRelation.getWdFirst() && !"".equals(wdRelation.getWdFirst())) {
			//根据订单所购买的产品，判断是都达到销售奖励数量，如果达到则计算应当奖励多少金额,该奖励只适用于直接上下级关系
			Integer rewardsMoney = getRewardsMoney(order, wdRelation.getWdFirst(), itemSum);
			this.updateAgencyRebate(order, wdRelation.getWdFirst(), member.getTemplateId(), 1, 2, itemSum, 1, 4, rewardsMoney);
		}
		//判断返利第二层级是否为空，如果不为空则返利
		if (null != wdRelation.getWdSecond() && !"".equals(wdRelation.getWdSecond())) {
			this.updateAgencyRebate(order, wdRelation.getWdSecond(), member.getTemplateId(), 2, 2, itemSum, 1, 4, null);
		}
		//判断返利第三层级是否为空，如果不为空则返利
		if (null != wdRelation.getWdThird() && !"".equals(wdRelation.getWdThird())) {
			this.updateAgencyRebate(order, wdRelation.getWdThird(), member.getTemplateId(), 3, 2, itemSum, 1, 4, null);
		}
		//判断返利第四层级是否为空，如果不为空则返利
		if (null != wdRelation.getWdFourth() && !"".equals(wdRelation.getWdFourth())) {
			this.updateAgencyRebate(order, wdRelation.getWdFourth(), member.getTemplateId(), 4, 2, itemSum, 1, 4, null);
		}
	}
	
	//修改微代理返利
	public void updateAgencyRebate(Order order, int superiorId, int templateId, int flowLevel, 
			int flowType,int itemSum,int type,int resType, Integer rewardsMoney) {
		//获取订单项的产品类型id
		OrderItem orderItem = order.getOrderItemList().get(0);
		Integer productType = orderItem.getItemProductType();
		//获取返利金额
		Integer money = getRebateMoney(templateId, flowLevel, flowType, null, productType);
		if (money == null) {
			logger.info("——返利过程中没有查到该用户的返利金额,订单号:" + order.getSalesOrderid() + "——");
		} else if (money <= 0) {
			return;
		}
		//添加返利金额
		String openId = this.updateUserInfo(superiorId, money, itemSum, rewardsMoney);
		//将该操作添加到微代理返利金额记录表中
		this.addUserCashLogs(openId, money, type, order, resType, itemSum,rewardsMoney);
		//只给直接上级推送信息
		if (flowLevel == 1) {
			//返现后给用户推送微信消息
			this.wxMessage(openId, order.getSalesOrderid(), money, itemSum, ResultInfo.INDEX_PAGE);
		}
	}
	
	//根据订单所购买的产品，判断是都达到销售奖励数量，如果达到则计算应当奖励多少金额
	public Integer getRewardsMoney(Order order, Integer userId, int itemSum) {
		Integer rewardsMoney = null;
		//获取订单项的产品类型id
		OrderItem orderItem = order.getOrderItemList().get(0);
		Integer productType = orderItem.getItemProductType();
		//根据推荐人id查询该推荐人
		Member referUser = this.adminOrderDao.getUserByUserRefereeid(userId);
		if (null != productType && null != referUser && null != referUser.getUserOpenid() && !"".equals(referUser.getUserOpenid())) {
			boolean isNull = false;
			SalesLog salesLog = new SalesLog();
			salesLog.setSalesProductType(productType);
			salesLog.setSalesUserOpenId(referUser.getUserOpenid());
			//查询购买人直接上线是否卖出过该类型商品
			salesLog = salesLogMapper.getSalesInfo(salesLog);
			//查询该类型商品的销售奖励信息
			RewardsRank rewardsRank = new RewardsRank();
			rewardsRank.getProductType().setTypeId(productType);
			if (null == salesLog) {
				rewardsRank.setRankNum(0);
			} else {
				rewardsRank.setRankNum(salesLog.getSalesNum());
			}
			SalesLog salesLogInfo = new SalesLog();
			salesLogInfo.setSalesUserOpenId(referUser.getUserOpenid());
			salesLogInfo.setSalesProductType(productType);
			salesLogInfo.setSalesNum(itemSum);
			
			if (null == salesLog) {
				salesLogMapper.insertSalesLog(salesLogInfo);
				salesLog = salesLogInfo;
				isNull = true;
			}
			
			rewardsMoney = computeRewardsMoney(isNull, salesLog, rewardsRank, itemSum, referUser, productType);
			if (!isNull) {
				//如果销售记录表中有数据，则修改销售数量
				salesLogMapper.updateSalesLog(salesLogInfo);
			}
		}
		return rewardsMoney;
	}
	
	//计算销售奖励金额
	public Integer computeRewardsMoney(boolean isNull, SalesLog salesLog, RewardsRank rewardsRank, 
			int itemSum, Member referUser, Integer productType) {
		Integer rewardsMoney = null;
		int sum = 0;
		RewardsLog rewardsLog = new RewardsLog();
		List<RewardsRank> rewardList = rewardsMapper.getRankByRankProductType(rewardsRank);
		RewardsRank rewardsMax = rewardsMapper.getMaxRankByProductType(rewardsRank);
		if (null == rewardList || rewardList.size() <= 0) {
			if (null == rewardsMax) {
				return rewardsMoney;
			}
			rewardList = new ArrayList<RewardsRank>();
			rewardList.add(rewardsMax);
		} else {
			if (null != rewardsMax) {
				rewardList.add(0,rewardsMax);
			}
		}
		//循环销售奖励任务，一个个匹配是否满足该销售奖励数量
		for (int i = 0;i < rewardList.size();i++) {
			RewardsRank rewards = rewardList.get(i);
			RewardsRank rewards2 = null;
			Integer rankNum = rewards.getRankNum();
			Integer rankNum2 = null;
			if (i +1 < rewardList.size()) {
				rewards2 = rewardList.get(i + 1);
				rankNum2 = rewards2.getRankNum();
			}
			//判断购买订单用户的直接上线之前卖出的该类型商品+这次用户购买的该类型商品数量之和是否大于等于奖励数量
			if (null == rankNum) {
				return rewardsMoney;
			}
			int salesNum = 0;
			//判断之前该商品的销售数量是否为空如果是，则总数等于该次购买的数量，如果不为空，则总数等于之前销售数量+该次购买数量
			if (isNull && sum == 0) {
				salesNum = salesLog.getSalesNum().intValue();
			} else {
				salesNum = salesLog.getSalesNum().intValue() + itemSum;
			}
			
			if (salesNum >= rankNum.intValue()) {
				int differenceNum = 0;
				if (null == rankNum2 || (null != rankNum2 && salesNum < rankNum2.intValue())) {
					//当卖出个该商品数量大于等于销售奖励数量时计算这次应该奖励多少个商品，共多少金额
					differenceNum = salesNum - rankNum.intValue();
					//判断差值是否大于等于这次销售数量，如果大于等于，则按这次销售数量奖励，如果小于，则按差值奖励
					if (differenceNum  >= itemSum) {
						//当之前的销售数量大于销售奖励数量的时候,奖励的个数为这次购买的个数，如果小于，则奖励个数等于这次购买的数量加1
						if (null != rewardsMoney) {
							rewardsMoney += itemSum * rewards.getRankMoney().intValue();
						} else {
							rewardsMoney = itemSum * rewards.getRankMoney().intValue();
						}
						rewardsLog.setLogsNum(itemSum);
						rewardsLog.setLogsDesc("订单购买了"+ itemSum + "个商品,奖励了" + itemSum + "个商品");
					} else {
						if (null != rewardsMoney) {
							rewardsMoney += (differenceNum + 1) * rewards.getRankMoney().intValue();
						} else {
							rewardsMoney = (differenceNum + 1) * rewards.getRankMoney().intValue();
						}
						rewardsLog.setLogsNum(differenceNum + 1);
						rewardsLog.setLogsDesc("订单购买了"+ itemSum + "个商品,奖励了" + (differenceNum + 1) + "个商品");
					}
				} else if (null != rankNum2 && salesNum >= rankNum2.intValue()) {
					differenceNum = rankNum2.intValue() - rankNum.intValue();
					//判断差值是否大于等于这次销售数量，如果大于等于，则按这次销售数量奖励，如果小于，则按差值奖励
					if (differenceNum  >= itemSum) {
						//当之前的销售数量大于销售奖励数量的时候,奖励的个数为这次购买的个数，如果小于，则奖励个数等于这次购买的数量加1
						if (null != rewardsMoney) {
							rewardsMoney += (rankNum2.intValue() - salesLog.getSalesNum() - 1) * rewards.getRankMoney().intValue();
						} else {
							rewardsMoney = (rankNum2.intValue() - salesLog.getSalesNum() - 1) * rewards.getRankMoney().intValue();
						}
						rewardsLog.setLogsNum(rankNum2.intValue() - salesLog.getSalesNum() - 1);
						rewardsLog.setLogsDesc("订单购买了"+ itemSum + "个商品,奖励了" + (rankNum2.intValue() - salesLog.getSalesNum() - 1) + "个商品");
						itemSum = itemSum - (rankNum2.intValue() - salesLog.getSalesNum() - 1);
						salesLog.setSalesNum(salesLog.getSalesNum().intValue() + (rankNum2.intValue() - salesLog.getSalesNum() - 1));
					} else {
						if (null != rewardsMoney) {
							rewardsMoney += differenceNum * rewards.getRankMoney().intValue();
						} else {
							rewardsMoney = differenceNum * rewards.getRankMoney().intValue();
						}
						rewardsLog.setLogsNum(differenceNum);
						rewardsLog.setLogsDesc("订单购买了"+ itemSum + "个商品,奖励了" + differenceNum + "个商品");
						itemSum = salesNum - (rankNum2.intValue() - 1);
						salesLog.setSalesNum(rankNum2.intValue() - 1);
						sum = 1;
					}
				}
				rewardsLog.setLogsRankId(rewards.getRankId());
				rewardsLog.setLogsUserOpenId(referUser.getUserOpenid());
				rewardsLog.setLogsProductType(productType);
				rewardsLog.setLogsMoney(rewards.getRankMoney().intValue());
				
				//将该奖励插入奖励记录表
				rewardsMapper.insertRewardsLog(rewardsLog);
			}
		}
		return rewardsMoney;
	}
	
	//根据条件获取返利金额
	public int getRebateMoney(int templateId, int flowLevel, int flowType, Integer flowRoleId, Integer productType) {
		TemplateFlowInfo templateFlowInfo = new TemplateFlowInfo();
		templateFlowInfo.setTemplateId(templateId);
		templateFlowInfo.setFlowLevel(flowLevel);
		templateFlowInfo.setFlowType(flowType);
		templateFlowInfo.setFlowProductType(productType);
		if (flowRoleId != null) {
			templateFlowInfo.setFlowRoleId(flowRoleId);
		}
		//查询返利节点表金额
		templateFlowInfo = templateFlowInfoMapper.getTemplateFlowInfo(templateFlowInfo);
		if (null == templateFlowInfo) {
			return 0;
		} else {
			return templateFlowInfo.getFlowMoney();
		}
	}
	
	//商户层返利
	public void updateCommercialRebate(int templateId, int flowLevel, int flowType, int itemSum, 
			int placeId, int type, int resType, Order order) {
		//获取订单项的产品类型id
		OrderItem orderItem = order.getOrderItemList().get(0);
		Integer productType = orderItem.getItemProductType();
		//根据id获取渠道信息
		PlaceInfo placeInfo = adminOrderDao.getOnePlaceInfo(placeId);
		//获取返利金额
		Integer money = this.getRebateMoney(templateId, flowLevel, flowType,placeInfo.getRoleId(),productType);
		if (money == null) {
			logger.info("——返利过程中没有查到该用户的返利金额,订单号:" + order.getSalesOrderid() + "——");
		} else if (money <= 0) {
			return;
		}
		//添加返利金额
		this.updatePlaceInfo(placeId, money, itemSum);
		//将该操作添加到线下返利金额记录表中
		this.addPlaceLogs(placeId, money, type, order, resType, itemSum);
		if (flowLevel == 1) {
			//返现后给用户推送微信消息
			this.wxMessage(placeInfo.getOpenid(), order.getSalesOrderid(), money, order.getItemSum(), ResultInfo.DRP_INDEX_PAGE);
		}
	}
	
	//商户层返利
	public void commercialRebate(DealerRelation dealerRelation, Member member, Order order, int levelSum) {
		int itemSum = order.getItemSum();
		int flowLevel = dealerRelation.getDealerCount() + levelSum;
		//判断返利第一层级是否为空，如果不为空则返利
		if (null != dealerRelation.getDealerFirst() && !"".equals(dealerRelation.getDealerFirst())) {
			this.updateCommercialRebate(member.getTemplateId(), flowLevel, 1, itemSum, dealerRelation.getDealerFirst(), 1, 1, order);
		}
		//判断返利第二层级是否为空，如果不为空则返利
		if (null != dealerRelation.getDealerSecond() && !"".equals(dealerRelation.getDealerSecond())) {
			this.updateCommercialRebate(member.getTemplateId(), flowLevel - 1, 1, itemSum, dealerRelation.getDealerSecond(), 1, 1, order);
		}
		//判断返利第三层级是否为空，如果不为空则返利
		if (null != dealerRelation.getDealerThird() && !"".equals(dealerRelation.getDealerThird())) {
			this.updateCommercialRebate(member.getTemplateId(), flowLevel - 2, 1, itemSum, dealerRelation.getDealerThird(), 1, 1, order);
		}
		//判断返利第四层级是否为空，如果不为空则返利
		if (null != dealerRelation.getDealerFourth() && !"".equals(dealerRelation.getDealerFourth())) {
			this.updateCommercialRebate(member.getTemplateId(), flowLevel - 3, 1, itemSum, dealerRelation.getDealerFourth(), 1, 1, order);
		}
		//判断返利第五层级是否为空，如果不为空则返利
		if (null != dealerRelation.getDealerFifth() && !"".equals(dealerRelation.getDealerFifth())) {
			this.updateCommercialRebate(member.getTemplateId(), flowLevel - 4, 1, itemSum, dealerRelation.getDealerFifth(), 1, 1, order);
		}
		//判断返利第六层级是否为空，如果不为空则返利
		if (null != dealerRelation.getDealerSixth() && !"".equals(dealerRelation.getDealerSixth())) {
			this.updateCommercialRebate(member.getTemplateId(), flowLevel - 5, 1, itemSum, dealerRelation.getDealerSixth(), 1, 1, order);
		}
	}
	
	//修改用户可用金额信息
	public String updateUserInfo(int userId, double num, int itemSum, Integer rewardsMoney) {
		//根据推荐人id查询该推荐人
		Member referUser = this.adminOrderDao.getUserByUserRefereeid(userId);
		if (referUser != null) {
			//微代理对象
			Member agentMember = new Member();
			//微代理奖励金额
			int agentIntegral = 0;
			//计算微代理奖励金额，如果有销售奖励，则加上该奖励金额
			if (null != rewardsMoney) {
				agentIntegral = (int)(itemSum * num) + rewardsMoney.intValue();
			} else {
				agentIntegral = (int)(itemSum * num);
			}
			agentMember.setUserIncome(agentIntegral);
			agentMember.setUserId(userId);
			//给微代理奖励金额
			this.adminOrderDao.updateUserByUserId(agentMember);
			return referUser.getUserOpenid();
		}
		return "";
	}
	
	//封装在用户现金记录表中插入一条数据
	public void addUserCashLogs(String openid, double num, int type, Order order, int resType,int itemSum, Integer rewardsMoney) {
		CashLog cashLog = new CashLog();
		cashLog.setCashLogsOpenid(openid);
		//如果存在销售奖励金额，则添加
		if (null == rewardsMoney) {
			cashLog.setCashLogsNum((int)(num*itemSum));
		} else {
			cashLog.setCashLogsNum((int)(num*itemSum) + rewardsMoney.intValue());
		}
		
		cashLog.setCashLogsType(type);
		String rebateOrder = rebateOrderTemplate(order.getSalesOpenid(),order.getSalesOrderid(),
				openid,String.valueOf(cashLog.getCashLogsNum()));
		cashLog.setCashLogsIntroduction(rebateOrder);
		cashLog.setCashLogsResType(resType);
		cashLog.setCashLogsCreateDate(new Date());
		cashLog.setCashLogsOrderid(order.getSalesOrderid());
		this.cashLogDao.addCashLog(cashLog);
	}
	
	//修改线下渠道的返利金额
	public void updatePlaceInfo(int placeId, double num, int itemSum) {
		PlaceInfo placeInfo = new PlaceInfo();
		placeInfo.setId(placeId);
		placeInfo.setAmount((int)(num*itemSum));
		//修改金额
		this.adminOrderDao.updatePlaceInfo(placeInfo);
	}
	
	//封装在线下代理现金记录表中插入一条数据
	public void addPlaceLogs(int placeId, double num, int type, Order order, int resType, int itemSum) {
		try {
			PlaceLogs placeLogs = new PlaceLogs();
			placeLogs.setPlaceId(placeId);
			placeLogs.setNums((int)(num*itemSum));
			placeLogs.setType(type);
			String rebateOrder = rebateOrderTemplate(order.getSalesOpenid(),order.getSalesOrderid(),
					String.valueOf(placeLogs.getPlaceId()),String.valueOf(placeLogs.getNums()));
			placeLogs.setIntroduction(rebateOrder);
			placeLogs.setResType(resType);
			placeLogs.setCreateDate(new Date());
			this.adminOrderDao.insertPlaceLogs(placeLogs);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 返现后给用户推送微信消息
	 * create date 2016年5月17日
	 * @param openid
	 * @param orderid
	 * @param money
	 * @param url
	 */
	public void wxMessage(String openid,String orderid,double num, int itemSum,String url){
		double money = num * itemSum / 100;
		if(StringUtils.isNotEmpty(openid) || money > 0){
			try {
				String temp = ResultInfo.REWARDSREMINDTEMP;
				temp = temp.replaceFirst("firstValueIamberry", ResultInfo.REWARDSHASMESSAGE)
					.replaceFirst("orderValueIamberry", orderid)
					.replaceFirst("moneyValueIamberry", "￥" + new Double(money).toString())
					.replaceFirst("remarkValueIamberry", ResultInfo.INTOSHOP);
//				wxService.rewardsRemind(temp, openid, url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 构建简介模板
	 * @param str1   用户openid
	 * @param str2	orderid
	 * @param str3	返利对象openid或是id
	 * @param str4	多少钱
	 * @return
	 */
	public String rebateOrderTemplate(String str1, String str2, String str3, String str4) {
		String rebateOrder = ResultInfo.rebateOrderText;
		try {
			if (null != rebateOrder && !"".equals(rebateOrder)) {
				rebateOrder = rebateOrder.replace("{1}", str1);
				rebateOrder = rebateOrder.replace("{2}", str2);
				rebateOrder = rebateOrder.replace("{3}", str3);
				rebateOrder = rebateOrder.replace("{4}", str4);
			}
			return rebateOrder;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	
	@Override
	public Integer getOrderNum(Order order) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.getOrderNum(order);
	}

	@Override
	public ShopSystemRule getReluByRid(int rId) {
		// TODO Auto-generated method stub
		return this.adminOrderDao.getReluByRid(rId);
	}

	@Override
	public String selectSalesOpenIdByOrderId(String orderId) {
		// TODO Auto-generated method stub
		return adminOrderDao.selectSalesOpenIdByOrderId(orderId);
	}

	@Override
	public List<Order> getOrderByCreateTime(Order order) {
		// TODO Auto-generated method stub
		return adminOrderDao.getOrderByCreateTime(order);
	}
	@Override
	public List<Order> getOrderByCreateTimeAndFiveMinutes(Order order) {
		// TODO Auto-generated method stub
		return adminOrderDao.getOrderByCreateTimeAndFiveMinutes(order);
	}
	
	@Override
	public Integer updateOrderByOrderId(List<String> list) {
		// TODO Auto-generated method stub
		return adminOrderDao.updateOrderByOrderId(list);
	}

	@Override
	public Integer updateOrderStatusByOrderIdAndToStatus(Order order) {
		// TODO Auto-generated method stub
		return adminOrderDao.updateOrderStatusByOrderIdAndToStatus(order);
	}

	@Override
	public List<OrderItem> getItemsNumByOrderId(String orderId) {
		// TODO Auto-generated method stub
		return adminOrderDao.getItemsNumByOrderId(orderId);
	}

	@Override
	public List<Order> getOrderList(Order order) {
		// TODO Auto-generated method stub
		return adminOrderDao.getOrderList(order);
	}

	@Override
	public Integer updateOrderListStatus(List<Order> list) {
		// TODO Auto-generated method stub
		return adminOrderDao.updateOrderListStatus(list);
	}

	@Override
	public NumberBacklogDto selectNumberBacklog() {
		return adminOrderDao.selectNumberBacklog();
	}
	@Override
	public List<Order> getOrderListToExcel(Order order) {
		return adminOrderDao.getOrderListToExcel(order);
	}

	@Override
	public List<Order> cancelOrderList(Order order) {
		return adminOrderDao.cancelOrderList(order);
	}

	@Override
	public Integer cancelOrder(String salesOrderid) {
		return adminOrderDao.cancelOrder(salesOrderid);
	}
}
