package com.iamberry.wechat.service.relationship.Dao.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.relationship.WdRelation;
import com.iamberry.wechat.service.mapper.WdRelationMapper;
import com.iamberry.wechat.service.relationship.Dao.WdRelationDao;
/**
 * 微代理层级 dao 实现类
 * 2016年7月4日
 * @author Administrator
 *
 */
@Repository
public class WdRelationDaoImpl implements WdRelationDao{
	@Autowired
	private WdRelationMapper wdRelationMapper;
	/**
	 * 添加一个微代理层级
	 * 2016年7月4日
	 * @param wdRelation
	 * @return
	 */
	public Integer insertWdRelation(WdRelation wdRelation){
		return wdRelationMapper.insertWdRelation(wdRelation);
	}
	
	/**
	 * 根据用户openid 查找一个微代理层记录
	 * 2016年7月4日
	 * @param openid
	 * @return
	 */
	public WdRelation getWdRelationByOpenid(String openid){
		return wdRelationMapper.getWdRelationByOpenid(openid);
	}

	@Override
	public boolean insertWdrelation(Member fatherMember, Member member) {
		if(fatherMember == null || StringUtils.isEmpty(fatherMember.getUserOpenid())
				|| member == null || StringUtils.isEmpty(member.getUserOpenid())){
			return false;
		}
		WdRelation selectWdr = new WdRelation();
		selectWdr.setOpenid(member.getUserOpenid());
		selectWdr.setWdFirst(fatherMember.getUserId());
		
		WdRelation newWdr = new WdRelation();
		newWdr.setOpenid(member.getUserOpenid());
		WdRelation fatherWR = wdRelationMapper.getWdRelationByOpenid(fatherMember.getUserOpenid());
		newWdr.setWdFirst(fatherMember.getUserId());
		newWdr.setWdCount(1);
		if(fatherWR != null && fatherWR.getWdFirst() != null){
			newWdr.setWdSecond(fatherWR.getWdFirst());
			newWdr.setWdCount(2);
		}
		if(fatherWR != null && fatherWR.getWdSecond() != null){
			newWdr.setWdThird(fatherWR.getWdSecond());
			newWdr.setWdCount(3);
		}
		if(fatherWR != null && fatherWR.getWdThird() != null){
			newWdr.setWdFourth(fatherWR.getWdThird());
			newWdr.setWdCount(4);
		}
		Integer i = 0;
		//若已经存在关系则修改
		WdRelation wd = wdRelationMapper.selectWdRelationByOpenid(member.getUserOpenid());
		if(wd != null){	
			newWdr.setUpdateDate(new Date());
			newWdr.setStatus(1);
			i =	wdRelationMapper.updateWdRelation(newWdr);
		}else{
			i = wdRelationMapper.insertWdRelation(newWdr);
		}
		return i > 0 ? true : false;
	}

	@Override
	public int updateStatus(String openid) {
		// TODO Auto-generated method stub
		return wdRelationMapper.updateStatus(openid);
	}
	/**
	 * 修改用户微代理信息
	 * @param wdRelation
	 * @return
	 * @author LJK
	 * @time 2016年11月24日
	 */
	@Override
	public int updateWdRelation(WdRelation wdRelation) {
		// TODO Auto-generated method stub
		return wdRelationMapper.updateWdRelation(wdRelation);
	}
	
	
}
