package com.iamberry.wechat.service.reback;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.PaperBean;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.flow.TemplateFlowInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.Order;
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.task.TaskModel;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.face.relationship.DealerRelationService;
import com.iamberry.wechat.face.relationship.WdRelationService;
import com.iamberry.wechat.service.mapper.OrderMapper;
import com.iamberry.wechat.service.mapper.RebackInfoMapper;
import com.iamberry.wechat.service.mapper.TemplateFlowInfoMapper;

/**
 * @description 返现表的操作
 * @author 欧阳明
 * @date 2016-05-25
 * 
 */
@Lazy(false)
@Service("rebackServicesImpl")
public class RebackServicesImpl implements RebackServices {

	@Autowired
	private RebackInfoMapper  rebackInfoMapper;
	@Autowired
	private MemberService memberService;
	@Autowired
	private SystemService  systemService;
	@Autowired
	private PlaceInfoService  placeInfoService;
	@Autowired
	private RatFWLogger logger;
	@Autowired
	private TemplateFlowInfoMapper templateFlowInfoMapper;
	@Autowired
	private DealerRelationService dealerRelationService;
	@Autowired
	private WdRelationService wdRelationService;
	@Autowired
	private OrderMapper orderMapper;
	
	/**
	 * 插入当个对象
	 */
	public int insert(RebackInfo rebackInfo) {
		return rebackInfoMapper.insert(rebackInfo);
	}

	/**
	 * 根据传递的条件进行对象的查询
	 */
	public List<RebackInfo> selectAll(RebackInfo reback) {
		return rebackInfoMapper.selectAll(reback);
	}

	/**
	 * 统计该查询条件下一共有多少条记录
	 */
	public int selectCount(RebackInfo reback) {
		return rebackInfoMapper.getAllCount(reback);
	}

	@Override
	public int update(RebackInfo reback) {
		return rebackInfoMapper.update(reback);
	}

	/**
	 * param rebackInfo 一定要带有orderid 
	 */
	public int updateStatus(RebackInfo reback) {
		return  rebackInfoMapper.updateStatus(reback);
	}

	/**
	 * 通过id获取对象
	 */
	public RebackInfo selectOneById(int id) {
		return rebackInfoMapper.getOneById(id);
	}

	/**
	 * 处理当个订单的返现记录的插入
	 * @param order
	 * @return
	 */
	public int loadSingleOrderReward(Order order) {
		//防止微信回调函数多次
		int alreadyin=rebackInfoMapper.alreadyIn(order.getSalesOrderid());
		if(alreadyin>0){
			logger.info("loadSingleOrderReward is been already load:"+order.getSalesOrderid());
		    return -1;
		}
		
		//购买产品的个数 （如果以后有不同的产品，这里是重点修改的地方）用于统计每一订单返现多少钱的
		//int productNums=rebackInfoMapper.getItemsProductNums(order.getSalesOrderid());
		List<Map> productTypeMap=orderMapper.getItemProdutTypeStatic(order.getSalesOrderid());
		
		
		//判断订单的会员来源：自己关注，微代理来源，分销商来源
		Member member=memberService.getMemberByUserOpenId(order.getSalesOpenid());
		Date date=new Date();
		
		if(member.getUserResType()==1){
//System.out.println("=====================自己关注，不返利=============");
			return 1; //自己关注的不返
		}else if(member.getUserResType()==3){
//System.out.println("=====================父级分销商，返利=============");
		    return drpReback(order,member,date,productTypeMap);
		}
		
//System.out.println("=====================微代理线路，返利=============");
		
		//获取微代理的层次
		WdRelation  wdRelation=wdRelationService.getWdRelationByOpenid(member.getUserOpenid());
		int cengci=wdRelation.getWdCount();
		if(cengci>2) cengci=2;
		//微代理来源
		int i=wdReback( order, member,date,productTypeMap,wdRelation);

		if(member.getUserDealers()==null){
			return 1;
		}
	    i=drpReback2(order,member,date,productTypeMap,cengci);
		return i;
	}
	
	
	/**
	 * 分销商的返利
	 * @author 欧阳明
	 * 
	 */
	public int drpReback(Order order,Member member,Date data , List<Map> productTypeMap){
		Integer placeInfoId=0;
		PlaceInfo placeInfo=null;
		int cengci=0;
		int isSuccess=0;
		Map<String,Object> templateFlowInfo=new HashMap();
		RebackInfo rebackInfo=new RebackInfo();
		
		//获取商户层的层次
		DealerRelation dealerRelation=
				dealerRelationService.getDealerRelationById(member.getUserDealers());
		//分销商来源 只返商户层的
			for(int i=0;i<6;i++){

				if(i==0){
					 placeInfoId=dealerRelation.getDealerSixth();
				}else if(i==1){
					placeInfoId=dealerRelation.getDealerFifth();
				}else if(i==2){
					placeInfoId=dealerRelation.getDealerFourth();
				}else if(i==3){
					placeInfoId=dealerRelation.getDealerThird();
				}else if(i==4){
					placeInfoId=dealerRelation.getDealerSecond();
				}else if(i==5){
					placeInfoId=dealerRelation.getDealerFirst();
				}
				if(placeInfoId==null){
					continue;
				}
				cengci=cengci+1;
				
				StringBuffer conditionProductType=new StringBuffer();
				Boolean flag=false;
				conditionProductType.append("(");
				for (Map map:productTypeMap) {
					if(!flag){
						conditionProductType.append(map.get("productType").toString());
					}else{
						conditionProductType.append(","+map.get("productType").toString());
					}
					flag=true;
				}
				conditionProductType.append(")");
				
				//提防出现重复的数据??
				placeInfo=placeInfoService.getPlaceInfoById(placeInfoId);
				
				templateFlowInfo.put("templateId", member.getTemplateId());
				templateFlowInfo.put("flowLevel", cengci);
				templateFlowInfo.put("flowType", 1);
				templateFlowInfo.put("flowRoleId", placeInfo.getRoleId());
				templateFlowInfo.put("flowProductType", conditionProductType.toString());
				
				//谨防出现重复的情况！
				List<TemplateFlowInfo> templateFlowInfos=templateFlowInfoMapper.getTemplateFlowInfos(templateFlowInfo);
				
				if(templateFlowInfos==null || templateFlowInfos.size()==0){
					logger.info("该角色在产品类型模板中找不到节点"+placeInfo.getRoleId());
					return 1;
				}
				
				
				Map<String,Integer> templateFlowInfosMap=new HashMap<String,Integer>();
				for(TemplateFlowInfo info:templateFlowInfos){
					templateFlowInfosMap.put(info.getFlowProductType().toString(), info.getFlowMoney());
				}
				
				int totalMoney=0;
				//计算返利的金额
				for (Map map:productTypeMap) {
					int  num=((BigDecimal) map.get("num")).intValue();
					int money=(int) templateFlowInfosMap.get(map.get("productType").toString());
					totalMoney=totalMoney+num*money;
				}
				
				rebackInfo.setFromOpenid(member.getUserOpenid());
				rebackInfo.setToOpenid(placeInfo.getOpenid());
				rebackInfo.setUserType(2);
				rebackInfo.setMoney(totalMoney);
				rebackInfo.setOrderId(order.getSalesOrderid());
				rebackInfo.setCreateDate(data);
				rebackInfo.setStatus(1);
				rebackInfo.setRoleId(placeInfo.getRoleId());
				rebackInfo.setUserId(placeInfoId);
				isSuccess=rebackInfoMapper.insert(rebackInfo);
			}
			return isSuccess;
	}
	
	
	
	/**
	 * 微代理的返利
	 * @author 欧阳明
	 * 
	 */
	public int wdReback(Order order,Member member,Date date ,List<Map> productTypeMap,WdRelation wdRelation ){
		
		int cengci=0;
		int isSuccess=0;
		Integer memeberId=0;
		Map templateFlowInfoMap=new HashMap();
		RebackInfo rebackInfo=new RebackInfo();
		
		int templateId=0;
		//获取微代理的层次
		//WdRelation  wdRelation=wdRelationService.getWdRelationByOpenid(member.getUserOpenid());
		
		//没有模板id的
		if(member.getTemplateId()==null){
			//获取默认templateId
			templateId=systemService.selectOneShopRuleById(120).getRuleNum().intValue();
		}else{
			templateId=member.getTemplateId();
		}

		//有模板id
		for(int i=0;i<4;i++){
			if(i==0){
				memeberId=wdRelation.getWdFirst();
			}else if(i==1){
				memeberId=wdRelation.getWdSecond();
			}else if(i==2){
				memeberId=wdRelation.getWdThird();
			}else if(i==3){
				memeberId=wdRelation.getWdFourth();
			}
			if(memeberId==null){
				continue;
			}
			cengci=cengci+1;
			
			templateFlowInfoMap.put("templateId", templateId);
			templateFlowInfoMap.put("flowLevel", cengci);
			templateFlowInfoMap.put("flowType", 2);
			
			StringBuffer conditionProductType=new StringBuffer();
			Boolean flag=false;
			conditionProductType.append("(");
			for (Map map:productTypeMap) {
				if(!flag){
					conditionProductType.append(map.get("productType").toString());
				}else{
					conditionProductType.append(","+map.get("productType").toString());
				}
				flag=true;
			}
			conditionProductType.append(")");
			
			templateFlowInfoMap.put("flowProductType", conditionProductType.toString());
			
			//获取所有产品类型的模板节点
			List<TemplateFlowInfo> templateFlowInfos=templateFlowInfoMapper.getTemplateFlowInfos(templateFlowInfoMap);
			if(templateFlowInfos==null || templateFlowInfos.size()==0){
				logger.info("该角色在产品类型模板中找不到节点,userId:"+member.getUserId());
				return 1;
			}
			Map<String,Integer> templateFlowInfosMap=new HashMap<String,Integer>();
			for(TemplateFlowInfo info:templateFlowInfos){
				templateFlowInfosMap.put(info.getFlowProductType().toString(), info.getFlowMoney());
			}
			
			int totalMoney=0;
			//计算返利的金额
			for (Map map:productTypeMap) {
				int  num=((BigDecimal) map.get("num")).intValue();
				int money=(int) templateFlowInfosMap.get(map.get("productType").toString());
				totalMoney=totalMoney+num*money;
			}

			Member member1=memberService.getMemberByUserId(memeberId);
			rebackInfo.setFromOpenid(member.getUserOpenid());
			rebackInfo.setToOpenid(member1.getUserOpenid());
			rebackInfo.setMoney(totalMoney);
			rebackInfo.setOrderId(order.getSalesOrderid());
			rebackInfo.setStatus(1);
			rebackInfo.setUserType(1);
			rebackInfo.setRoleId(99);
			rebackInfo.setUserId(memeberId);
			rebackInfo.setCreateDate(date);
			isSuccess=rebackInfoMapper.insert(rebackInfo);	
		}
		return isSuccess;	
	}
	
	
	
	/**
	 * 微代理的返利,上级有分销商的
	 * @author 欧阳明
	 * 
	 */
	public int drpReback2(Order order,Member member,Date data , List<Map> productTypeMap, int cengci){
		Integer placeInfoId=0;
		PlaceInfo placeInfo=null;
		int isSuccess=0;
		Map<String,Object> templateFlowInfo=new HashMap();
		RebackInfo rebackInfo=new RebackInfo();
		
		//获取商户层的层次
		DealerRelation dealerRelation=
				dealerRelationService.getDealerRelationById(member.getUserDealers());
		
		//分销商来源 只返商户层的
			for(int i=0;i<6;i++){

				if(i==0){
					 placeInfoId=dealerRelation.getDealerSixth();
				}else if(i==1){
					placeInfoId=dealerRelation.getDealerFifth();
				}else if(i==2){
					placeInfoId=dealerRelation.getDealerFourth();
				}else if(i==3){
					placeInfoId=dealerRelation.getDealerThird();
				}else if(i==4){
					placeInfoId=dealerRelation.getDealerSecond();
				}else if(i==5){
					placeInfoId=dealerRelation.getDealerFirst();
				}
				if(placeInfoId==null){
					continue;
				}
				cengci=cengci+1;
				
				StringBuffer conditionProductType=new StringBuffer();
				Boolean flag=false;
				conditionProductType.append("(");
				for (Map map:productTypeMap) {
					if(!flag){
						conditionProductType.append(map.get("productType").toString());
					}else{
						conditionProductType.append(","+map.get("productType").toString());
					}
					flag=true;
				}
				conditionProductType.append(")");
				
				//提防出现重复的数据??
				placeInfo=placeInfoService.getPlaceInfoById(placeInfoId);
				
				templateFlowInfo.put("templateId", member.getTemplateId());
				templateFlowInfo.put("flowLevel", cengci);
				templateFlowInfo.put("flowType", 1);
				templateFlowInfo.put("flowRoleId", placeInfo.getRoleId());
				templateFlowInfo.put("flowProductType", conditionProductType.toString());
				
				//谨防出现重复的情况！
				List<TemplateFlowInfo> templateFlowInfos=templateFlowInfoMapper.getTemplateFlowInfos(templateFlowInfo);
				
				if(templateFlowInfos==null || templateFlowInfos.size()==0){
					logger.info("该角色在产品类型模板中找不到节点"+placeInfo.getRoleId());
					return 1;
				}
				
				
				Map<String,Integer> templateFlowInfosMap=new HashMap<String,Integer>();
				for(TemplateFlowInfo info:templateFlowInfos){
					templateFlowInfosMap.put(info.getFlowProductType().toString(), info.getFlowMoney());
				}
				
				int totalMoney=0;
				//计算返利的金额
				for (Map map:productTypeMap) {
					int  num=((BigDecimal) map.get("num")).intValue();
					int money=(int) templateFlowInfosMap.get(map.get("productType").toString());
					totalMoney=totalMoney+num*money;
				}
				
				rebackInfo.setFromOpenid(member.getUserOpenid());
				rebackInfo.setToOpenid(placeInfo.getOpenid());
				rebackInfo.setUserType(2);
				rebackInfo.setMoney(totalMoney);
				rebackInfo.setOrderId(order.getSalesOrderid());
				rebackInfo.setRoleId(placeInfo.getRoleId());
				rebackInfo.setUserId(placeInfoId);
				rebackInfo.setCreateDate(data);
				rebackInfo.setStatus(1);
				isSuccess=rebackInfoMapper.insert(rebackInfo);
			}
			return isSuccess;
	}

	/**
	 * 从集合中遍历出模板节点中对应的钱
	 * @return
	 */
	public int  getMoneyFromTemplate(List<TemplateFlowInfo> templateInfos,
			int level,int flowType, int roleId ){
		if(flowType==1){	
			for(TemplateFlowInfo info:templateInfos){
				if(info.getFlowType()==1 && info.getFlowLevel()==level){
					return info.getFlowMoney();
				}
			}
		}
		for(TemplateFlowInfo info:templateInfos){
			if(info.getFlowType()==1 && info.getFlowRoleId()==roleId){
				return info.getFlowMoney();
			}
		}
		return 0;
	}

	@Override
	public List<TaskModel> getByDate(int productType, Date startDate,
			Date endDate, int count) {
		// TODO Auto-generated method stub
		PaperBean bean = new PaperBean();
		bean.setOtherInt(productType);
		bean.setBeginDate(startDate);
		bean.setEndDate(endDate);
		bean.setHid(count);
		return rebackInfoMapper.getByDate(bean);
	}
}
