package com.iamberry.wechat.service.member;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

import com.iamberry.wechat.core.entity.admin.FullReduction;
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.Page;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.service.ShopUtil;
import com.iamberry.wechat.service.home.dao.HomeServiceDao;
import com.iamberry.wechat.service.mapper.PlaceInfoMapper;
import com.iamberry.wechat.service.member.dao.MemberDao;
import com.iamberry.wechat.service.relationship.Dao.WdRelationDao;
import com.iamberry.wechat.service.system.dao.SystemDao;
import com.iamberry.wechat.tools.StaticInfo;

/**
 * 会员信息 service 实现
 * 2016年4月21日
 * @author Administrator
 *
 */
@Service
public class MemberServiceImpl implements MemberService {
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private PlaceInfoMapper placeInfoMapper;
	@Autowired
	public SystemDao systemDao;
	@Autowired
	private HomeServiceDao homeServiceDao;
	@Autowired
	private WdRelationDao wdRelationDao;
	@Autowired
	private RatFWLogger logger;
	/**
	 * 根据userid得到会员信息
	 * @param userId
	 * @return
	 */
	@Override
	public Member getMemberByUserId(Integer userId) {
		// TODO Auto-generated method stub
		return memberDao.getMemberByUserId(userId);
	}
	
	/**
	 * 根据 openid 查询一个member
	 * 2016年4月28日
	 * @author 穆再兴
	 * @return
	 */
	public Member getMemberByUserOpenId(String openid){
		return memberDao.getMemberByUserOpenId(openid);
	}
	@Override
	public Integer getCount() {
		return memberDao.getCount();
	}
	@Override
	public List<Member> getMemberByPage(Page page) {
		return memberDao.getMemberByPage(page);
	}
	/**
	 * 根据 userid 修改会员信息
	 * 2016年4月21日
	 * @author 穆再兴
	 * @param userId
	 * @return
	 */
	@Override
	public Integer updateMemberByUserId(Member member){
		return memberDao.updateMemberByUserId(member);
	}
	@Override
	public Integer updateUserUseIntegral(Member member) {
		// TODO Auto-generated method stub
		return memberDao.updateUserUseIntegral(member);
	}
	@Override
	public List<Member> selectUserIntegralByWechatProxyId(Page page) {
		// TODO Auto-generated method stub
		return memberDao.selectUserIntegralByWechatProxyId(page);
	}
	@Override
	public Member selectUserIdentityAndQrcodeByOpenId(String openid) {
		// TODO Auto-generated method stub
		return memberDao.selectUserIdentityAndQrcodeByOpenId(openid);
	}

	@Override
	public Member selectUserResAndIdSByOpenId(String openid) {
		// TODO Auto-generated method stub
		return memberDao.selectUserResAndIdSByOpenId(openid);
	}
	
	/**
	 * 根据 openid 修改用户可用金额
	 * 2016年5月4日
	 * @param member
	 * @return
	 */
	public Integer updateUserIncomeByOpenId(Member member){
		return memberDao.updateUserIncomeByOpenId(member);
	}

	@Override
	public boolean updateUserFlagByOpenId(String openId) {
		// TODO Auto-generated method stub
		return memberDao.updateUserFlagByOpenId(openId) >= 1 ? true : false;
	}
	
	/**
	 * 根据userid获取当前用户的“下线人数”和“已购买人数”
	 * 2016年5月11日
	 * @param openId
	 * @return
	 */
	public List<Integer> selectDownCountByUserId(Integer userId){
		return memberDao.selectDownCountByUserId(userId);
	}

	@Override
	public boolean buildChildUser(String shareOpenid, Member member,int userType,int orderType) {
		// TODO Auto-generated method stub
		if(StringUtils.isEmpty(shareOpenid) || member == null){	return false;}
		//用户点击自己分享的链接则不绑定
		if(shareOpenid.equals(member.getUserOpenid())){return false;}
		
		//绑定关系
		if(userType == 1){
			//绑定为微代理下线
			return bulidUser(member.getUserOpenid(), shareOpenid, 1, orderType);
		}else if(userType == 2){
			//需过滤可以发展下线的角色
			PlaceInfo placeInfo = placeInfoMapper.getOnePlaceInfo2(shareOpenid);
			//内容格式：商户层可以绑定关系的角色id:41,42	41 42 分别为可以绑定关系的角色id
			String str = systemDao.selectOneShopRuleById(121).getRuleDesc();
			String rolesStr = str.split(":")[1];
			String[] roleArr = rolesStr.split(",");
			if(placeInfo != null && 
					Arrays.asList(roleArr).contains(Integer.toString(placeInfo.getRoleId()))){
				//改商户存在并且为可以绑定关系的就是 则绑定为其下线
				return bulidUser(member.getUserOpenid(), placeInfo.getId(), 2, orderType);
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

	/**
	 * 为某个用户绑定关系
	 * @param nowUserOpenId 当前用户openid
	 * @param parent 父类ID，如果type=1,此ID为openid(字符串)，如果为2,此为代理商ID(数值)
	 * @param type type = 1 ： 属于微代理；type=2:属于代理商
	 * @return true ： 绑定成功， false：绑定失败
	 */
	private boolean bulidUser(String nowUserOpenId, Object parent, Integer type, int orderType) {
		// TODO Auto-generated method stub
		Member member = homeServiceDao.selectMemberInfoByOpenId(nowUserOpenId);
		if (!checkUserRelation(nowUserOpenId, member)) {	//当前用户不可以绑定关系 则返回
			return false;
		}
		
		// 绑定类型
		if (type.intValue() == 1) {	//微代理:parent:为openid
			if (parent.toString().equals(nowUserOpenId)) {//会员自己不能成为自己会员的下线
				return false;
			}
			//上级用户信息
    		Member parentInfo = homeServiceDao.selectMemberInfoByOpenId(parent.toString());
    		//只有购买商品时才判断用户是否发生过购买，租赁的不需要判断
    		if (orderType == 1) {
    			boolean isFlag = ShopUtil.isFlag(parentInfo);	//分享人可否发展下线
        		if(!isFlag){return false;}
    		}
    		
    		if(member != null && member.getUserIsFlag() != null){
    			//判断是否已经终身绑定，如果等于2表示已经终身绑定，不在往后执行
    			if(member.getUserIsFlag() == 2){
    				return false;
    			}
    			
    			member.setUserResType(2);
    			if(parentInfo.getTemplateId() != null){
    				member.setTemplateId(parentInfo.getTemplateId());
    			}
    			if(parentInfo.getUserDealers() != null){
    				member.setUserDealers(parentInfo.getUserDealers());
    			}
    		}
    		Integer i = homeServiceDao.updateUserResAndTypeByOpenid(member); // 更新
    		boolean flag = wdRelationDao.insertWdrelation(parentInfo, member);//插入微代理层关系
    		if(i.intValue() > 0 && flag){
    			logger.info(this,"--用户-->>" + member.getUserOpenid() + "<<--成为用户-->>"
    					+ parentInfo.getUserOpenid() + "<<--下线");
    			return true;
    		}
		} else if (type.intValue() == 2) {	//代理商:parent：为代理商ID
			Matcher match = StaticInfo.pattern.matcher(parent.toString());
	        if(!match.find()) {
	        	return false;
	        }
			PlaceInfo info = placeInfoMapper.selectPlaceInfobyId(Integer.parseInt(parent.toString()));
			if (info == null || nowUserOpenId.equals(info.getOpenid())) {//会员自己不能成为自己商户的下线
				return false; 
			}
			int gloadId = systemDao.selectOneShopRuleById(206).getRuleNum().intValue();
			if (gloadId == info.getId()) {
				return false;
			}
			if(info.getTemplateId() != 0){
				member.setTemplateId(info.getTemplateId());
			}
			if(info.getPlaceIds() != null){
				member.setUserDealers(info.getPlaceIds()); // bilud商户层关系
			}
			member.setUserResType(3);
    		Integer i = homeServiceDao.updateUserResAndTypeByOpenid(member); // 更新
    		// 修改微带表状态
    		wdRelationDao.updateStatus(member.getUserOpenid());
    		
    		if(i > 0){
    			return true;
    		}
		}
		return false;
	}
	
	/**
	 * 校验当前用户是否可以绑定关系
	 * true:更新用户绑定信息 	false：不能更新用户绑定信息
	 * 2016年11月16日
	 * mzx
	 * @param member
	 * @return
	 */
	private boolean checkUserRelation(String nowUserOpenId, Member member){
		boolean flag = false;
		if (member != null && member.getUserId() != null) {
			//当关注时、点击别人链接时都会覆盖原油的绑定关系，当用户购买商品后userisflag变为2并且不在被覆盖
			if (member.getUserIsFlag() != null && member.getUserIsFlag().intValue() == 1) {
				return true;
			} 
		} else {
			// 如果用户不存在，添加用户信息（openid、未关注、性别未知）
			member = new Member();
			member.setUserStatus(1); 					// 未关注
			member.setUserSex(0);
			member.setUserOpenid(nowUserOpenId);
			homeServiceDao.insertMemberInfo(member);
			flag = true; 								// 更新
		}
		return flag;
	}
	@Override
	public Map<String, Object> getDownInfoAndBuyedCount(Page page) {
		List<Member> list = memberDao.selectUserIntegralByWechatProxyId(page);
		
		List<Integer> countList = memberDao.selectDownCountByUserId(page.getTotalRecord());	//page.getTotalRecord 用户userid
		int downNum = 0;		//下线人数
		int buyedNum = 0;		//已购买人数
		if(countList.size() == 2){
			downNum = countList.get(0);
			buyedNum = countList.get(1);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("downNum", downNum);
		map.put("buyedNum", buyedNum);
		if(list.size()>0){
			map.put("beginNo", list.get(0).getUserId());
			map.put("endNo", list.get(list.size()-1).getUserId());
		}	
		map.put("list", list);
		return map;
	}

	@Override
	public boolean updateIsBaughtByOpenid(String openid, int userIsBaught) {
		// TODO Auto-generated method stub
		if(StringUtils.isEmpty(openid)){ return false; }
		Member member = memberDao.getMemberByUserOpenId(openid);
		if(member == null){	return false; }
		Integer i = 0;
		//若当前状态已经是要修改的状态 则不修改
		if(member.getUserIsBought() != null && member.getUserIsBought().intValue() != userIsBaught){
			member.setUserIsBought(userIsBaught);
			i = memberDao.updateIsBaughtByOpenid(member);
		}
		if(i != null && i.intValue() > 0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Integer addFullReduction(String openId) {
		return memberDao.addFullReduction(openId);
	}

	@Override
	public FullReduction getFullReduction(String openId) {
		return memberDao.getFullReduction(openId);
	}
}
