package com.buy507.mall.portal.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.buy507.mall.common.api.CommonResult;
import com.buy507.mall.common.util.Constants;
import com.buy507.mall.mapper.*;
import com.buy507.mall.model.*;
import com.buy507.mall.portal.component.RedisLock;
import com.buy507.mall.portal.component.TeamMemberNumberHanderQueue;
import com.buy507.mall.portal.dao.PortalMemberDao;
import com.buy507.mall.portal.domain.*;
import com.buy507.mall.portal.service.InitDistributionService;
import com.buy507.mall.portal.service.PortalCommonService;
import com.buy507.mall.portal.service.RedisService;
import com.buy507.mall.portal.service.UmsMemberService;
import com.buy507.mall.portal.util.JwtTokenUtil;
import com.buy507.mall.portal.util.WeChatDecryptDataUtil;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员管理Service实现类
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
	
    @Autowired
    private UmsMemberMapper memberMapper;
    
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    
    @Autowired
    private UmsMemberService memberService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private RedisService redisService;
    
    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;
    
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private DmsTeamLevelMapper teamLevelMapper;
    
    @Autowired
    private DmsMemberTradeRecordMapper memberTradeRecordMapper;
    
    @Autowired
    private PortalMemberDao portalMemberDao;
    
    @Autowired
    private DmsTeamTotalConsumeMapper teamTotalConsumeMapper;
    
    @Autowired
    private OmsOrderMapper orderMapper;
    
    @Autowired
    private InitDistributionService initDistributionService;
    
    @Autowired
    private DmsMemberBankAccountMapper memberBankAccountMapper;
    
    @Autowired
    private DmsMemberWithdrawApplyMapper memberWithdrawApplyMapper;
    
    @Autowired
    private PortalCommonService commonService;
    
    @Autowired
    private DmsMemberTransferRecordMapper memberTransferRecordMapper;
    /**
     * 会员分成流水
     */
    @Resource
    private UmsMemberAccountTransactionMapper umsMemberAccountTransactionMapper;
    /**
     * 会员上下关系
     */
    @Resource
    private UmsMemberRelationTreeMapper umsMemberRelationTreeMapper;
    
    @Autowired
    private RedisLock redisLock;

    @Resource
    private UmsDevelopmentFundMapper umsDevelopmentFundMapper;
    
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    
    @Value("${wechat.loginUrl}")
    private String WECHAT_LOGIN_URL;
    
    @Value("${wechat.appId}")
    private String WECHAT_APPID;
    
    @Value("${wechat.secret}")
    private String WECHAT_SECRET;
    
    @Value("${wechat.grantType}")
    private String WECHAT_GRANT_TYPE;
    
    @Value("${aliyun.sms.api}")
    private String ALIYUN_SMS_API;
    
    @Value("${aliyun.sms.signName}")
    private String ALIYUN_SMS_SIGN_NAME;
    
    @Value("${aliyun.sms.templateCode}")
    private String ALIYUN_SMS_TEMPLATE_CODE;
    
    @Value("${aliyun.accessKeyId}")
    private String ALIYUN_ACCESS_KEY_ID;
    
    @Value("${aliyun.accessKeySecret}")
    private String ALIYUN_ACCESS_KEY_SECRET;
    
    
    @Autowired
    private RestTemplate restTemplate;


    @Override
    public UmsMember getByUsername(String username) {
    	UmsMemberExample example = new UmsMemberExample();
    	example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> members = memberMapper.selectByExample(example);
        if(members != null && !members.isEmpty()) {
        	return members.get(0);
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public CommonResult register(String telephone, String password, String authCode,String invitationCode) {

        //邀请码不为空
        if(StringUtils.isEmpty(invitationCode)){
            return CommonResult.failed("邀请码不为空");
        }

        UmsMemberExample queryMember = new UmsMemberExample();
        queryMember.createCriteria().andInvitationCodeEqualTo(invitationCode);
        //查询邀请人
        List<UmsMember> invitationMember = memberMapper.selectByExample(queryMember);
        if(invitationMember == null || invitationMember.isEmpty()){
            return CommonResult.failed("邀请码不正确");
        }

        //验证验证码
        if(!verifyAuthCode(authCode, telephone)){
            return CommonResult.failed("验证码错误");
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(telephone);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            return CommonResult.failed("该用户已经存在");
        }
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(telephone);
        umsMember.setPhone(telephone);
        umsMember.setPassword(passwordEncoder.encode(password));
        umsMember.setCreateTime(new Date());
        umsMember.setIntegration(0);
        umsMember.setGender(0); //性别：0->未知；1->男；2->女
        umsMember.setStatus(1); //会员状态 0 禁用	1启用
        umsMember.setGrowth(0); //成长值
        umsMember.setBalance(new BigDecimal(0));
        umsMember.setMemberLevel(MemberLevel.Member);
        umsMember.setStoreStatus(StoreStatus.No);
        String genCode = generateRandomString();


        //生成的邀请码不能有重复
        UmsMemberExample queryMember1 = new UmsMemberExample();
        queryMember1.createCriteria().andInvitationCodeEqualTo(genCode);
        List<UmsMember> invitationMember1 = memberMapper.selectByExample(queryMember1);
        if(!invitationMember1.isEmpty()){
            genCode = genCode + telephone.substring(telephone.length()-4);
        }

        umsMember.setInvitationCode(genCode);
        umsMember.setSourceType(1);//默认为线上会员

        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(0);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);


        if(!invitationMember.isEmpty()){
            //关联上级关系
            UmsMemberRelationTree newRelation = new UmsMemberRelationTree();
            newRelation.setMemberId(umsMember.getId());
            newRelation.setHigherLevelId(invitationMember.get(0).getId());
            umsMemberRelationTreeMapper.insert(newRelation);
        }
        //初始化会员分销相关表
        initDistributionService.initDistributionTable(umsMember.getId());
        return CommonResult.success(null, "注册成功");
    }


    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int STRING_LENGTH = 6;

    public static String generateRandomString() {
        StringBuilder sb = new StringBuilder(STRING_LENGTH);
        Random random = new Random();

        for (int i = 0; i < STRING_LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }

        return sb.toString();
    }
    
    @Override
    public Map<String, String>  login(String username, String password) {
        Map<String, String> tokenMap = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if(!passwordEncoder.matches(password, userDetails.getPassword())){
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            UmsMember member = ((MemberDetails) userDetails).getUmsMember();
            String token = jwtTokenUtil.generateToken(userDetails);
            tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            tokenMap.put("tokenHead", tokenHead);
            tokenMap.put("phone", member.getPhone() == null ? "" : member.getPhone());
            if(StringUtils.isEmpty(member.getPhone()) || StringUtils.isEmpty(member.getRealName())) {
                tokenMap.put("flag", "0");
            } else {
                tokenMap.put("flag", "1");
            }

            //insertLoginLog(username);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }



        return tokenMap;
    }
    
    @Override
	public Map<String, String> wechatLogin(WeChatLogin weChatLogin) {
    	
    	String url = WECHAT_LOGIN_URL + "?appid=" + WECHAT_APPID + "&secret=" 
    					+ WECHAT_SECRET + "&js_code=" + weChatLogin.getCode() + "&grant_type=" + WECHAT_GRANT_TYPE;
    	
    	String response = restTemplate.getForObject(url, String.class);
    	Map<String, String> object = new Gson().fromJson(response, HashMap.class);
    	String openId = object.get("openid");
    	if(!StringUtils.isEmpty(openId)) {
    		UmsMember member = memberService.getByUsername(openId);
    		if(!StringUtils.isEmpty(weChatLogin.getEncryptedData()) && !StringUtils.isEmpty(weChatLogin.getIv())) {
    			String sessionKey = object.get("session_key");
    			String decryptData = WeChatDecryptDataUtil.decrypt(sessionKey, weChatLogin.getIv(), weChatLogin.getEncryptedData());
    			
    			JsonObject jsonObject = new Gson().fromJson(decryptData, JsonObject.class);
    			
    			if(member == null) {
    				member = new UmsMember();
    				BigDecimal bigDecimal = new BigDecimal(0);
    				member.setUsername(openId);
    				member.setNickname(jsonObject.get("nickName") == null ? "" : jsonObject.get("nickName").getAsString());
    				member.setCreateTime(new Date());
    				member.setIntegration(0);
    				//性别：0->未知；1->男；2->女
    				if(StringUtils.isEmpty(jsonObject.get("gender"))) {
    					member.setGender(0);
    				} else {
    					member.setGender(Integer.valueOf(String.valueOf(jsonObject.get("gender"))));
    				}
    				member.setIcon(jsonObject.get("avatarUrl") == null ? "" : jsonObject.get("avatarUrl").getAsString());
    				member.setStatus(1); //会员状态 0 禁用	1启用
    				member.setGrowth(0); //成长值
    				member.setBalance(bigDecimal);
    				member.setFreeze(bigDecimal);
    				member.setMemberLevel(MemberLevel.Member);
    				member.setStoreStatus(StoreStatus.No);
    				
    				memberMapper.insert(member);
    				
    				if(weChatLogin.getMemberId() != null) {
    					UmsMember inviter = memberMapper.selectByPrimaryKey(weChatLogin.getMemberId());
    					if(inviter != null && !inviter.getId().equals(member.getId())) {
							DmsTeamLevel teamLevel = teamLevelMapper.selectOneByMemberId(member.getId());
							if(teamLevel == null) {
								teamLevel = new DmsTeamLevel();
								teamLevel.setMemberId(member.getId());
								teamLevel.setParentId(inviter.getId());
								teamLevelMapper.insert(teamLevel);
								
								/**
								 * 重新计算上级团队的团队成员数量
								 * 团队成员数量表
								 */
								TeamMemberNumberHanderQueue.addMemberToQueue(member);			
							}
    					}
    				}
    		        
    		        //初始化会员分销相关表
    				initDistributionService.initDistributionTable(member.getId());
    				
    			} else {
    				/*
    				member.setNickname(jsonObject.get("nickName") == null ? "" : jsonObject.get("nickName").getAsString());
    				//性别：0->未知；1->男；2->女
    				if(StringUtils.isEmpty(jsonObject.get("gender"))) {
    					member.setGender(0);
    				} else {
    					member.setGender(Integer.valueOf(String.valueOf(jsonObject.get("gender"))));
    				}
    				member.setIcon(jsonObject.get("avatarUrl") == null ? "" : jsonObject.get("avatarUrl").getAsString());
    				memberRepo.save(member);
    				*/
    			}
    		}
    		
    		if(member != null) {
    			String token = null;
		        //密码需要客户端加密后传递
		        try {
		            UserDetails userDetails = userDetailsService.loadUserByUsername(openId);
		            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
		            SecurityContextHolder.getContext().setAuthentication(authentication);
		            token = jwtTokenUtil.generateToken(userDetails);
		            LOGGER.info("member nickname and token: {}, {}", member.getNickname(), token);
		            
		            Map<String, String> tokenMap = new HashMap<>();
		            tokenMap.put("token", token);
		            tokenMap.put("tokenHead", tokenHead);
		            
		            tokenMap.put("phone", member.getPhone() == null ? "" : member.getPhone());
		            if(StringUtils.isEmpty(member.getPhone()) || StringUtils.isEmpty(member.getRealName())) {
		            	tokenMap.put("flag", "0");
		            } else {
		            	tokenMap.put("flag", "1");
		            }
		            
		            return tokenMap;
		        } catch (AuthenticationException e) {
		            LOGGER.warn("登录异常:{}", e.getMessage());
		        }
    		}
    		
    	}
		return null;
	}

    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for(int i=0;i<6;i++){
        	code.append(random.nextInt(10));
        }
        //验证码绑定手机号并存储到redis
        try {
			boolean flag = sendSms(telephone, code.toString());
			if(!flag) {
				return CommonResult.failed("操作频繁，请稍后再试");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResult.failed("获取验证码失败，请稍后再试");
		}
        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, code.toString());
        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);
        return CommonResult.success(null, "获取验证码成功");
    }
    
    private boolean sendSms(String telephone, String code) throws Exception {
    	DefaultProfile profile = DefaultProfile.getProfile("default", ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(ALIYUN_SMS_API);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("TemplateParam", "{\"code\":\""+ code +"\"}");
        request.putQueryParameter("RegionId", "default");
        request.putQueryParameter("PhoneNumbers", telephone);
        request.putQueryParameter("SignName", ALIYUN_SMS_SIGN_NAME);
        request.putQueryParameter("TemplateCode", ALIYUN_SMS_TEMPLATE_CODE);
        CommonResponse response = client.getCommonResponse(request);
        
        JsonObject jsonObject = new Gson().fromJson(response.getData(), JsonObject.class);
        LOGGER.debug(response.getData());
        if("OK".equals(jsonObject.get("Code").getAsString())) {
        	return true;
        }
        return false;
    }

    @Override
    public CommonResult updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(memberList)){
            return CommonResult.failed("该账号不存在");
        }
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            return CommonResult.failed("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        return CommonResult.success(null,"密码修改成功");
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = null;
        try {
        	memberDetails = (MemberDetails) auth.getPrincipal();
        	return memberDetails.getUmsMember();
		} catch (Exception e) {
			
		}
        return null;
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record=new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone){
        if(StringUtils.isEmpty(authCode)){
            return false;
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        return authCode.equals(realAuthCode);
    }

    @Override
	public MemberInfoResult  getMemberInfo() {
		UmsMember loginMember =  getCurrentMember();
		UmsMember member = memberMapper.selectByPrimaryKey(loginMember.getId());
		DmsTeamTotalConsume teamTotalConsume = teamTotalConsumeMapper.selectOneByMemberId(loginMember.getId());
		
		OmsOrderExample example = new OmsOrderExample();
		example.createCriteria().andMemberIdEqualTo(loginMember.getId());
		List<OmsOrder> orders = orderMapper.selectByExample(example);

        DateTime nowTime = DateTime.now();
        UmsMemberAccountTransactionExample accountTransactionExample = new UmsMemberAccountTransactionExample();

        //查询总收入
        BigDecimal totalIncome = BigDecimal.ZERO;
        accountTransactionExample.createCriteria()
                .andTransactionStateEqualTo(UmsMemberAccountTransaction.TRANSACTION_STATE_YES)
                .andMemberIdEqualTo(member.getId());

        List<UmsMemberAccountTransaction> totalList = umsMemberAccountTransactionMapper.selectByExample(accountTransactionExample);
        if(totalList!= null && !totalList.isEmpty()){
            Optional<BigDecimal> sum = totalList.stream().map(UmsMemberAccountTransaction::getRevenueAmount).reduce(BigDecimal :: add);
            // 检查 Optional 是否包含值
            if (sum.isPresent()) {
                totalIncome =  sum.get();
            }
        }

        //查询今天收入
        BigDecimal todayIncome = BigDecimal.ZERO;
        accountTransactionExample = new UmsMemberAccountTransactionExample();
        accountTransactionExample.createCriteria()
                .andTransferPaymentTimeBetween(DateUtil.beginOfDay(nowTime) ,nowTime)
                .andTransactionStateEqualTo(UmsMemberAccountTransaction.TRANSACTION_STATE_YES)
                .andMemberIdEqualTo(member.getId());
        List<UmsMemberAccountTransaction> todayIncomeList = umsMemberAccountTransactionMapper.selectByExample(accountTransactionExample);
        if(todayIncomeList!= null && !todayIncomeList.isEmpty()){
            Optional<BigDecimal> todaySum = todayIncomeList.stream().map(UmsMemberAccountTransaction::getRevenueAmount).reduce(BigDecimal :: add);
            // 检查 Optional 是否包含值
            if (todaySum.isPresent()) {
                todayIncome =  todaySum.get();
            }
        }


		MemberInfoResult result = new MemberInfoResult();
		result.setBalance(member.getBalance()); //余额
		result.setFreeze(member.getFreeze()); //冻结余额
		result.setCoupon(0);
        result.setTotalIncome(totalIncome.toString());
        result.setTodayIncome(todayIncome.toString());
		result.setNickname(member.getNickname() == null ? "" : member.getNickname());
		result.setHeadPicture(member.getIcon() == null ? "" :member.getIcon());
		result.setGender(member.getGender());
		result.setMemberLevel(member.getMemberLevel().getValue()-1);
		result.setMemberId(loginMember.getId());
		result.setRealName(member.getRealName());
		result.setDetailAddress(member.getDetailAddress());
        result.setSourceType(member.getSourceType());
		
		if(MemberLevel.Member.equals(member.getMemberLevel())) {
			result.setMemberLevelName("普通用户");
		} else if(MemberLevel.Consumer.equals(member.getMemberLevel())) {
			result.setMemberLevelName("vip会员");
		} else if(MemberLevel.Partner.equals(member.getMemberLevel())) {
			result.setMemberLevelName("店长");
		} else if(MemberLevel.Diamond.equals(member.getMemberLevel())) {
			result.setMemberLevelName("代理");
		} else if(MemberLevel.OneDiamond.equals(member.getMemberLevel())) {
			result.setMemberLevelName("市代");
		} else {
            result.setMemberLevelName("普通用户");
        }
		
		BigDecimal memberTotal = new BigDecimal(0);
		
		//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
		//会员总消费金额，显示会员所有已发货和已完成订单的数据
		for(OmsOrder order : orders) {
			if(order.getStatus() == 1 || order.getStatus() == 2 || order.getStatus() == 3) {
				memberTotal = memberTotal.add(order.getTotalAmount());
			}
		}
		
		//团队消费总金额 = 个人+团队
		result.setMemberTotalConsume(memberTotal);
		
		BigDecimal teamTotal = new BigDecimal(0);
		if(teamTotalConsume == null) {
			result.setTeamTotalConsume(memberTotal.add(teamTotal));
		} else {
			result.setTeamTotalConsume(memberTotal.add(teamTotalConsume.getValue()));
		}
		
		if(member.getGender() == 1) {
			result.setGenderName("男");
		} else if(member.getGender() == 2) {
			result.setGenderName("女");
		} else {
			result.setGenderName("保密");
		}
		
		result.setPhone(member.getPhone());
		
		//查询会员推荐人信息
		DmsTeamLevel teamLevel = teamLevelMapper.selectOneByMemberId(loginMember.getId());
		if(teamLevel != null) {
			result.setInviter(memberMapper.selectByPrimaryKey(teamLevel.getParentId()).getNickname());
		}

		return result;
	}
    
    @SuppressWarnings("rawtypes")
	public CommonResult updateMemberNickname(String nickname) {
    	//获取当前登录用户
    	UmsMember member = memberMapper.selectByPrimaryKey(memberService.getCurrentMember().getId());
    	while(true) {
			long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
			if(redisLock.lock(String.valueOf(member.getId()), String.valueOf(time))) {
				member = memberMapper.selectByPrimaryKey(member.getId());
				//修改用户资料
		    	member.setNickname(nickname);
		    	memberMapper.updateByPrimaryKey(member);
				redisLock.unlock(String.valueOf(member.getId()), String.valueOf(time));
				break;
			}
		}
    	return CommonResult.success(null, "修改成功");
    	
    }
    
    @SuppressWarnings("rawtypes")
	public CommonResult updateMemberGender(Integer gender) {
    	//获取当前登录用户
    	UmsMember user = memberService.getCurrentMember();
    	//修改用户资料
    	user.setGender(gender);
    	memberMapper.updateByPrimaryKey(user);
    	return CommonResult.success("用户性别修改成功");
    }
 
    @SuppressWarnings("rawtypes")
	public CommonResult updateMemberIcon(String icon) {
    	//获取当前登录用户
    	UmsMember user = memberService.getCurrentMember();
    	//修改用户资料
    	user.setIcon(icon);
    	memberMapper.updateByPrimaryKey(user);
    	return CommonResult.success("用户头像修改成功");
    }
    
    @SuppressWarnings("rawtypes")
	public CommonResult updateMemberPhone(String newPhone, String authCode) {
        //验证验证码
        if(!verifyAuthCode(authCode, newPhone)) {
            return CommonResult.failed("验证码错误");
        }
        
        //获取当前登录用户
    	UmsMember member = memberMapper.selectByPrimaryKey(memberService.getCurrentMember().getId());
        
    	UmsMemberExample example = new UmsMemberExample();
    	example.createCriteria().andPhoneEqualTo(newPhone);
    	
        //查询手机号码是否存在
        List<UmsMember> userPhones = memberMapper.selectByExample(example);
        UmsMember userPhone = null;
        if(userPhones != null && !userPhones.isEmpty()) {
        	userPhone = userPhones.get(0);
        }
        
        if(userPhone == null){
        	while(true) {
    			long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
    			if(redisLock.lock(String.valueOf(member.getId()), String.valueOf(time))) {
    				member = memberMapper.selectByPrimaryKey(member.getId());
    				//修改用户资料
    	        	member.setPhone(newPhone);
    	        	memberMapper.updateByPrimaryKey(member);
    				redisLock.unlock(String.valueOf(member.getId()), String.valueOf(time));
    				break;
    			}
    		}
	    	return CommonResult.success(null, "修改成功");
	    } else {
	    	return CommonResult.failed("该手机号已被使用");
    	}
    }
    
    /**
     * 修改真实姓名
     * @param realName
     * @return
     */
    @Override
	public CommonResult<String> updateRealName(String realName) {
    	
    	UmsMember currentMember = getCurrentMember();
		
		if(StringUtils.isEmpty(realName)) {
			return CommonResult.validateFailed("姓名不能为空");
		}
		
		while(true) {
			long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
			if(redisLock.lock(String.valueOf(currentMember.getId()), String.valueOf(time))) {
				UmsMember member = memberMapper.selectByPrimaryKey(currentMember.getId());
				member.setRealName(realName);
				memberMapper.updateByPrimaryKey(member);
				redisLock.unlock(String.valueOf(currentMember.getId()), String.valueOf(time));
				break;
			}
		}
		return CommonResult.success(null, "修改成功");
	}

    /**
     * 修改联系地址
     * @param
     * @return
     */
	@Override
	public CommonResult<String> updateAddress(String address) {
		UmsMember currentMember = getCurrentMember();
		
		if(StringUtils.isEmpty(address)) {
			return CommonResult.validateFailed("联系地址不能为空");
		}
		
		while(true) {
			long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
			if(redisLock.lock(String.valueOf(currentMember.getId()), String.valueOf(time))) {
				UmsMember member = memberMapper.selectByPrimaryKey(currentMember.getId());
				member.setDetailAddress(address);
				memberMapper.updateByPrimaryKey(member);
				redisLock.unlock(String.valueOf(currentMember.getId()), String.valueOf(time));
				break;
			}
		}
		return CommonResult.success(null, "修改成功");
	}


    @Override
    public CommonResult<String> updateSourceType(Integer sourceType) {
        UmsMember currentMember = getCurrentMember();
        if(sourceType != null) {
            return CommonResult.validateFailed("个人来源为空");
        }
        currentMember.setSourceType(sourceType);
        memberMapper.updateByPrimaryKeySelective(currentMember);
        return CommonResult.success(null, "修改成功");
    }


    /**
	 * 判空
	 * 
	 * @author hzh 2015-06-07 20:40
	 * */
	public static boolean isEmpty(Object value) {
		if (value == null) {
			return true;
		}
		if ("".equals(value.toString()) || "null".equals(value.toString())) {
			return true;
		}
		if (value.toString().trim().equals("")||value.toString().trim().equals("null")) {
			return true;
		}
		return false;
	}

	@Override
	public CommonResult shareInvite() {
        UmsMember member = memberMapper.selectByPrimaryKey(getCurrentMember().getId());
        Map<String, Object> result = new HashMap<>();
        result.put("inviteCode", member.getInvitationCode());
        result.put("inviteUrl", "http://49.233.215.129:688/#/pages/public/register?inviteCode="+member.getInvitationCode());
        return CommonResult.success(result);
	}

	/**
     * 查询账户明细
     * @return
     */
	@Override
	public List<AccountDetailResult> getAccountDetail(Integer pageSize, Integer pageNum) {
		UmsMember loginMember = getCurrentMember();
		PageHelper.startPage(pageNum, pageSize);
		List<DmsMemberTradeRecord> list = memberTradeRecordMapper.selectByMemberId(loginMember.getId());
		AccountDetailResult detailResult = null;
		List<AccountDetailResult> resultList = new ArrayList<>();
		for(DmsMemberTradeRecord tradeRecord : list) {
			detailResult = new AccountDetailResult();
			BeanUtils.copyProperties(tradeRecord, detailResult);
			
			//收支类型（0->收入；1->支出）
			if(detailResult.getType() == 0) {
				detailResult.setTypeName("收入");
			} else {
				detailResult.setTypeName("支出");
			}
			
			resultList.add(detailResult);
		}
		
		return resultList;
	}

	/**
     * 获取团队人员列表
     * @param memberId
     * @param pageSize
     * @param pageNum
     * @return
     */
	@Override
	public List<TeamMemberResult> getTeamList(Long memberId, Integer pageSize, Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		List<TeamMemberResult> list = portalMemberDao.selectMemberTeamList(memberId);
		UmsMember member = null;
		BigDecimal totalAmount = null;
		OmsOrderExample example = null;
		List<OmsOrder> orderList = null;
		for(TeamMemberResult result : list) {
			member = memberMapper.selectByPrimaryKey(result.getMemberId());
			//查询会员累计消费金额和下级团队累计消费金额
			totalAmount = new BigDecimal(0);
			example = new OmsOrderExample();
			example.createCriteria().andMemberIdEqualTo(member.getId());
			orderList = orderMapper.selectByExample(example);
			for(OmsOrder o : orderList) {
				//订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
				if(o.getStatus() == 1 || o.getStatus() == 2 || o.getStatus() == 3) {
					totalAmount = totalAmount.add(o.getTotalAmount());
				}
			}
			
			result.setTeamConsume(result.getTeamConsume().add(totalAmount));
		}
		
		return list;
	}

    /**
     * 获取提现申请列表
     * @param pageSize
     * @param pageNum
     * @return
     */
	@Override
	public List<MemberWithdrawApplyResult> getWithdrawApply(Integer pageSize, Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		UmsMember currentMember = getCurrentMember();
		List<MemberWithdrawApplyResult> list = portalMemberDao.selectMemberWithdrawApplyList(currentMember.getId());
		return list;
	}

    /**
     * 会员提现申请
     * @param applyParam
     * @return
     */
	@Override
	public CommonResult withdrawApply(WithdrawApplyParam applyParam) {
		
		UmsMember currentMember = getCurrentMember();
		DmsMemberBankAccount account = null;
		
		if(applyParam.getWithdrawType() == null) {
			return CommonResult.validateFailed("提现方式不能为空");
		}
		
		if(applyParam.getWithdrawType() == 0) { //支付宝
			if(StringUtils.isEmpty(applyParam.getRealName())) {
				return CommonResult.validateFailed("真实姓名不能为空");
			}
			
			if(StringUtils.isEmpty(applyParam.getAlipayAccount())) {
				return CommonResult.validateFailed("支付宝账号不能为空");
			}
		} else if(applyParam.getWithdrawType() == 1) { //微信
			if(StringUtils.isEmpty(applyParam.getWechatAccount())) {
				return CommonResult.validateFailed("微信账号不能为空");
			}
			
			if(StringUtils.isEmpty(applyParam.getWechatNickname())) {
				return CommonResult.validateFailed("微信昵称不能为空");
			}
		} else if(applyParam.getWithdrawType() == 2) { //银行卡
			if(StringUtils.isEmpty(applyParam.getBankAccountId())) {
				return CommonResult.validateFailed("银行信息无效");
			}
			
			account = memberBankAccountMapper.selectOneById(applyParam.getBankAccountId());
			if(account == null || !currentMember.getId().equals(account.getMemberId())) {
				return CommonResult.validateFailed("未查询到银行账户信息");
			}
			
		} else {
			return CommonResult.validateFailed("提现方式无效");
		}
		
		if(applyParam.getValue() <= 0) {
			return CommonResult.validateFailed("提现无效");
		}
		
		String withdrawMultipleStr = commonService.getDictionaryValue(Constants.D_WITHDRAW_MULTIPLE);
		double withdrawMultiple = Double.valueOf(withdrawMultipleStr);
		if(applyParam.getValue() % withdrawMultiple != 0) {
			return CommonResult.validateFailed("提现积分必须是" + withdrawMultipleStr + "的倍数");
		}
		
		BigDecimal withdraw = new BigDecimal(applyParam.getValue());
		
		UmsMember member = memberMapper.selectByPrimaryKey(currentMember.getId());
		//flag = -1,表示balance小于withdraw；flag = 0,表示balance等于withdraw；flag = 1,表示balance大于withdraw；
		int flag = member.getBalance().compareTo(withdraw);
		if(flag == -1) {
			return CommonResult.validateFailed("积分不足，不能提现");
		}
		
		while(true) {
			long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
			if(redisLock.lock(String.valueOf(currentMember.getId()), String.valueOf(time))) {
				member = memberMapper.selectByPrimaryKey(currentMember.getId());
				//flag = -1,表示balance小于withdraw；flag = 0,表示balance等于withdraw；flag = 1,表示balance大于withdraw；
				flag = member.getBalance().compareTo(withdraw);
				if(flag == -1) {
					return CommonResult.validateFailed("积分不足，不能提现");
				}
				member.setBalance(member.getBalance().subtract(withdraw)); //修改余额值
				member.setFreeze(member.getFreeze().add(withdraw)); //修改冻结值
				memberMapper.updateByPrimaryKey(member);
				redisLock.unlock(String.valueOf(currentMember.getId()), String.valueOf(time));
				break;
			}
		}
		
		Double dPoundagePercent = Double.valueOf(commonService.getDictionaryValue(Constants.D_WITHDRAW_POUNDAGE)) / 100;
		BigDecimal bPoundagePercent = new BigDecimal(dPoundagePercent);
		BigDecimal poundage = withdraw.multiply(bPoundagePercent);
		
		DmsMemberWithdrawApply apply = new DmsMemberWithdrawApply();
		
		//支付宝
		if(applyParam.getWithdrawType() == 0) {
			apply.setRealName(applyParam.getRealName());
			apply.setAlipayAccount(applyParam.getAlipayAccount());
		}
		
		//微信
		if(applyParam.getWithdrawType() == 1) {
			apply.setWechatAccount(applyParam.getWechatAccount());
			apply.setWechatNickname(applyParam.getWechatNickname());
		}
		
		if(applyParam.getWithdrawType() == 2) {
			apply.setAccountName(account.getAccountName());
			apply.setBankName(account.getBankName());
			apply.setBankCardNum(account.getBankCardNum());
			apply.setOpenBankAddress(account.getOpenBankAddress());
		}
		
		apply.setMemberId(currentMember.getId());
		apply.setValue(withdraw); //提现金额
		apply.setPoundage(poundage); //手续费
		apply.setActualValue(withdraw.subtract(poundage)); //扣除手续费后的实际提现金额
		apply.setWithdrawType(applyParam.getWithdrawType()); //提现方式(0: 支付宝; 1: 微信; 2: 银行卡)
		apply.setPaymentStatus(0); //付款状态：0->未打款；1->已打款；2->打款失败
		apply.setCreateTime(new Date());
		memberWithdrawApplyMapper.insert(apply);
		
		return CommonResult.success(null, "提现申请成功");
	}

	@Transactional
	@Override
	public CommonResult transfer(MemberTransferParam transferParam) {
		
		if(true) {
			return CommonResult.validateFailed("转账功能暂停使用");
		}
		
		if(StringUtils.isEmpty(transferParam.getPhone())) {
			return CommonResult.validateFailed("手机号不能为空");
		}
		if(transferParam.getValue() == null) {
			return CommonResult.validateFailed("转账积分不能为空");
		}
		if(transferParam.getValue() <= 0) {
			return CommonResult.validateFailed("转账积分无效");
		}
		BigDecimal transferValue = new BigDecimal(transferParam.getValue());
		UmsMember currentMember = getCurrentMember();
		
		UmsMemberExample example = new UmsMemberExample();
		example.createCriteria().andPhoneEqualTo(transferParam.getPhone());
		List<UmsMember> receiverMembers = memberMapper.selectByExample(example);
		UmsMember receiverMember = null;
		if(receiverMembers != null && !receiverMembers.isEmpty()) {
			receiverMember = receiverMembers.get(0);
		} else {
			return CommonResult.validateFailed("转入账户不存在");
		}
		
		if(receiverMember.getId().equals(currentMember.getId())) {
			return CommonResult.validateFailed("不能转给自己喔");
		}
		
		UmsMember member = memberMapper.selectByPrimaryKey(currentMember.getId());
		int flag = transferValue.compareTo(member.getBalance());
		//flag = -1,表示transferValue小于Balance；flag = 0,表示transferValue等于Balance；flag = 1,表示transferValue大于Balance；
		if(flag == 1) {
			return CommonResult.validateFailed("积分不足，无法转账");
		}
		
		while(true) {
			long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
			if(redisLock.lock(String.valueOf(currentMember.getId()), String.valueOf(time))) {
				member = memberMapper.selectByPrimaryKey(currentMember.getId());
				flag = transferValue.compareTo(member.getBalance());
				//flag = -1,表示transferValue小于Balance；flag = 0,表示transferValue等于Balance；flag = 1,表示transferValue大于Balance；
				if(flag == 1) {
					return CommonResult.validateFailed("积分不足，无法转账");
				}
				member.setBalance(member.getBalance().subtract(transferValue)); //修改余额值
				memberMapper.updateByPrimaryKey(member);
				redisLock.unlock(String.valueOf(currentMember.getId()), String.valueOf(time));
				break;
			}
		}
		
		while(true) {
			long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
			if(redisLock.lock(String.valueOf(receiverMember.getId()), String.valueOf(time))) {
				receiverMember = memberMapper.selectByExample(example).get(0);
				receiverMember.setBalance(receiverMember.getBalance().add(transferValue)); //修改余额值
				memberMapper.updateByPrimaryKey(receiverMember);
				redisLock.unlock(String.valueOf(receiverMember.getId()), String.valueOf(time));
				break;
			}
		}
		
		insertMemberTradeRecord(currentMember.getId(), ItemType.TransferAccount, 1, transferValue, "积分交易", "", null, null);
		insertMemberTradeRecord(receiverMember.getId(), ItemType.TransferAccount, 0, transferValue, "积分交易", "", null, null);
		
		DmsMemberTransferRecord transferRecord = new DmsMemberTransferRecord();
		transferRecord.setMemberId(currentMember.getId());
		transferRecord.setMemberNickname(member.getRealName());
		transferRecord.setReceiverId(receiverMember.getId());
		transferRecord.setReceiverNickname(receiverMember.getRealName());
		transferRecord.setReceiverPhone(transferParam.getPhone());
		transferRecord.setValue(transferValue);
		transferRecord.setCreateTime(new Date());
		
		memberTransferRecordMapper.insert(transferRecord);
		
		return CommonResult.success(null, "转账成功");
	}
	
	/**
	 * @param memberId 会员ID
	 * @param itemType 项目类型
	 * @param type 收支类型（0->收入；1->支出）
	 * @param value 值
	 * @param title 标题
	 * @param note 备注
	 * @param customerId 消费者会员ID
	 * @param orderId 订单ID
	 */
	private void insertMemberTradeRecord(Long memberId, ItemType itemType, int type, BigDecimal value, 
			String title, String note, Long customerId, Long orderId) {
		DmsMemberTradeRecord tradeRecord = new DmsMemberTradeRecord();
		tradeRecord.setMemberId(memberId);
		tradeRecord.setItemType(itemType);
		tradeRecord.setType(type); 
		tradeRecord.setValue(value);
		tradeRecord.setTitle(title);
		tradeRecord.setNote(note);
		tradeRecord.setCustomerId(customerId);
		tradeRecord.setOrderId(orderId);
		tradeRecord.setCreateTime(new Date());
		memberTradeRecordMapper.insert(tradeRecord);
	}

	/**
     * 获取会员转账记录
     * @param pageSize
     * @param pageNum
     * @return
     */
	@Override
	public List<MemberTransferResult> getTransferList(Integer pageSize, Integer pageNum) {
		PageHelper.startPage(pageNum, pageSize);
		UmsMember currentMember = getCurrentMember();
		return portalMemberDao.selectMemberTransferList(currentMember.getId());
	}

	/**
     * 注册完善个人资料
     * @param memberInfoParam
     * @return
     */
	@Override
	public CommonResult<String> firstSaveMemberInfo(FirstMemberInfoParam memberInfoParam) {
		
		//兼容历史数据，如果用户已经维护过手机号，不需要验证手机号和验证码
		UmsMember currentMember = getCurrentMember();
		
		UmsMember member = memberMapper.selectByPrimaryKey(currentMember.getId());
		
		if(StringUtils.isEmpty(memberInfoParam.getRealName())) {
			return CommonResult.validateFailed("姓名不能为空");
		}
		if(StringUtils.isEmpty(memberInfoParam.getDetailAddress())) {
			return CommonResult.validateFailed("联系地址不能为空");
		}
		
		if(StringUtils.isEmpty(member.getPhone())) {
			
			if(StringUtils.isEmpty(memberInfoParam.getPhone())) {
				return CommonResult.validateFailed("手机号码不能为空");
			}
			if(StringUtils.isEmpty(memberInfoParam.getAuthCode())) {
				return CommonResult.validateFailed("验证码不能为空");
			}
			 //验证验证码
	        if(!verifyAuthCode(memberInfoParam.getAuthCode(), memberInfoParam.getPhone())) {
	            return CommonResult.validateFailed("验证码错误");
	        }
	        
	        UmsMemberExample example = new UmsMemberExample();
			example.createCriteria().andPhoneEqualTo(memberInfoParam.getPhone());
			List<UmsMember> list = memberMapper.selectByExample(example);
			
			if(list == null || list.isEmpty()) {
				
				while(true) {
					long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
					if(redisLock.lock(String.valueOf(currentMember.getId()), String.valueOf(time))) {
						member = memberMapper.selectByPrimaryKey(currentMember.getId());
						
						member.setPhone(memberInfoParam.getPhone());
						member.setRealName(memberInfoParam.getRealName());
						member.setDetailAddress(memberInfoParam.getDetailAddress());
						
						memberMapper.updateByPrimaryKey(member);
						redisLock.unlock(String.valueOf(currentMember.getId()), String.valueOf(time));
						break;
					}
				}
				
			} else {
				return CommonResult.validateFailed("该手机号已被使用");	
			}
	        
		} else {
			while(true) {
				long time = System.currentTimeMillis() + RedisLock.TIMEOUT;
				if(redisLock.lock(String.valueOf(currentMember.getId()), String.valueOf(time))) {
					member = memberMapper.selectByPrimaryKey(currentMember.getId());
					
					member.setRealName(memberInfoParam.getRealName());
					member.setDetailAddress(memberInfoParam.getDetailAddress());
					
					memberMapper.updateByPrimaryKey(member);
					redisLock.unlock(String.valueOf(currentMember.getId()), String.valueOf(time));
					break;
				}
			}
		}
		
		return CommonResult.success(null, "保存成功");
	}

	/**
     * 根据手机号获取用户真实姓名
     * @param phone
     * @return
     */
	@Override
	public CommonResult<Map<String, String>> getRealName(String phone) {
		
		Map<String, String> result = new HashMap<>();
		UmsMemberExample example = new UmsMemberExample();
		example.createCriteria().andPhoneEqualTo(phone);
		List<UmsMember> list = memberMapper.selectByExample(example);
		if(list != null && !list.isEmpty()) {
			result.put("realName", list.get(0).getRealName());
		} else {
			result.put("realName", "");
		}
		result.put("phone", phone);
		return CommonResult.success(result);
	}

	/**
     * 个人团队信息查询
     * *************************************************/

    /**
     * 会员等级
     */
    @Resource
    private UmsMemberLevelMapper umsMemberLevelMapper;

    //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
    static List<Integer> ORDER_STATE = Lists.newArrayList(0, 4,5);

    @Override
    public CommonResult<Map<String, Object>> personalTeam() {
        Map<String, Object> result = new HashMap<>();
        UmsMember currentMember =  memberService.getCurrentMember(); //UmsMember currentMember = memberMapper.selectByPrimaryKey(2L); mcoo
        /**
         * 我的团队信息
         */
        result.put("usernickname", currentMember.getNickname());
        result.put("userId", currentMember.getId().toString());
        result.put("userAvatar ", currentMember.getIcon());
        UmsMemberLevel memberLevel = umsMemberLevelMapper.selectByPrimaryKey(currentMember.getMemberLevelId());
        result.put("userRole", memberLevel.getName());
        /**
         * 团队信息
         */
        UmsMemberRelationTreeExample umrtExample = new UmsMemberRelationTreeExample();
        umrtExample.createCriteria().andHigherLevelIdEqualTo(currentMember.getId());
        List<UmsMemberRelationTree>  memberRelationTreeList = umsMemberRelationTreeMapper.selectByExample(umrtExample);
        if(!memberRelationTreeList.isEmpty()){
            result.put("teamNumber", memberRelationTreeList.size());
           List<Long> teamIdList = memberRelationTreeList.stream().map(UmsMemberRelationTree::getMemberId).collect(Collectors.toList());
            OmsOrderExample orderExample = new OmsOrderExample();
            orderExample.createCriteria().andStatusNotIn(ORDER_STATE).andMemberIdIn(teamIdList);
            List<OmsOrder> memberOrderList = orderMapper.selectByExample(orderExample);
            if(!memberOrderList.isEmpty()){
                //总订单
                result.put("orderNumber", memberOrderList.size());
                Optional<BigDecimal> payAmountSum = memberOrderList.stream().map(OmsOrder::getPayAmount)
                        .reduce(BigDecimal::add);
                if(payAmountSum.isPresent()){
                    //总金额
                    result.put("orderAmount", payAmountSum);
                }
            }
            DateTime nowTime = DateTime.now();
            DateTime todayBegin  =  DateUtil.beginOfDay(nowTime);
            DateTime yesterday  =  DateUtil.beginOfDay(DateUtil.yesterday());
            DateTime sevenDay = DateUtil.offsetDay(nowTime, -7);
            DateTime firstDayOfMonth  =  DateUtil.beginOfMonth(nowTime);
            //今天
            Map<String, Object> todayInfo = this.getOrderInfoByDate(todayBegin, nowTime, currentMember, teamIdList);
            result.put("todayTeamNumber", todayInfo.get("teamNumber"));
            result.put("todayOrderNumber", todayInfo.get("orderNumber"));
            result.put("todayOrderAmount", todayInfo.get("orderAmount"));
            //昨天
            Map<String, Object> yesterdayInfo = this.getOrderInfoByDate(yesterday, nowTime, currentMember, teamIdList);//mcoo
            result.put("yesterdayTeamNumber", yesterdayInfo.get("teamNumber"));
            result.put("yesterdayOrderNumber", yesterdayInfo.get("orderNumber"));
            result.put("yesterdayOrderAmount", yesterdayInfo.get("orderAmount"));
            //近七天
            Map<String, Object> sevenDayInfo = this.getOrderInfoByDate(sevenDay, nowTime, currentMember, teamIdList);
            result.put("sevenDayTeamNumber", sevenDayInfo.get("teamNumber"));
            result.put("sevenDayOrderNumber", sevenDayInfo.get("orderNumber"));
            result.put("sevenDayOrderAmount", sevenDayInfo.get("orderAmount"));

            Map<String, Object> thisMonthInfo = this.getOrderInfoByDate(firstDayOfMonth, nowTime, currentMember, teamIdList);
            result.put("thisMonthTeamNumber", thisMonthInfo.get("teamNumber"));
            result.put("thisMonthOrderNumber", thisMonthInfo.get("orderNumber"));
            result.put("thisMonthOrderAmount", thisMonthInfo.get("orderAmount"));
        }

        /**
         * 上级信息
         */
        umrtExample = new UmsMemberRelationTreeExample();
        umrtExample.createCriteria().andMemberIdEqualTo(currentMember.getId());
        List<UmsMemberRelationTree>  upMemberRelationTreeList = umsMemberRelationTreeMapper.selectByExample(umrtExample);

        if(!upMemberRelationTreeList.isEmpty()){
            UmsMemberRelationTree urmt = upMemberRelationTreeList.get(0);
            if(urmt.getHigherLevelId() != null){
                UmsMember higherMember = memberMapper.selectByPrimaryKey(urmt.getHigherLevelId());
                result.put("inviternickname", higherMember.getNickname());
                result.put("inviterphone", higherMember.getPhone());
                result.put("inviterId", higherMember.getId().toString());
                result.put("inviterAvatar", higherMember.getIcon());
                UmsMemberLevel higherMemberLevel = umsMemberLevelMapper.selectByPrimaryKey(higherMember.getMemberLevelId());
                result.put("inviterrole", higherMemberLevel.getName());
            }
        }

        return CommonResult.success(result);
    }

    /**
     * 查询发展基金
     * @return
     */
    @Override
    public UmsDevelopmentFund getDevelopmentFund() {
        UmsDevelopmentFund developmentFund = new UmsDevelopmentFund();
        developmentFund = umsDevelopmentFundMapper.selectAll();
        return developmentFund;
    }

    private Map<String, Object> getOrderInfoByDate(DateTime begin, DateTime end, UmsMember currentMember, List<Long> teamIdList) {

        Map<String, Object> infoMap = new HashMap<>();

        UmsMemberRelationTreeExample umrtExample = new UmsMemberRelationTreeExample();
        umrtExample.createCriteria().andMemberIdEqualTo(currentMember.getId()).andCreateTimeBetween(begin, end);
        long  lowerCount = umsMemberRelationTreeMapper.countByExample(umrtExample);
        infoMap.put("teamNumber", lowerCount);
        OmsOrderExample orderExample = new OmsOrderExample();
        orderExample.createCriteria().andStatusNotIn(ORDER_STATE).andMemberIdIn(teamIdList).andPaymentTimeBetween(begin, end);
        List<OmsOrder> memberOrderList = orderMapper.selectByExample(orderExample);
        if(!memberOrderList.isEmpty()){
            //总订单
            infoMap.put("orderNumber", memberOrderList.size());
            Optional<BigDecimal> payAmountSum = memberOrderList.stream().map(OmsOrder::getPayAmount)
                    .reduce(BigDecimal::add);
            //总金额
            if(payAmountSum.isPresent()){
                infoMap.put("orderAmount", payAmountSum);
            }else {
                infoMap.put("orderAmount", "0.0");
            }

        }

        return infoMap;
    }


}
