package cn.wisenergy.service.app.impl;

import cn.wisenergy.mapper.*;
import cn.wisenergy.model.app.*;
import cn.wisenergy.model.enums.TradeRecordEnum;
import cn.wisenergy.service.app.AerialDeliveryUserService;
import cn.wisenergy.service.app.UserLevelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author zw
 * @ Description: 用户升级功能业务实现
 * @ Author     : zw
 * @ Date       : 2021/2/24 17:06
 */
@Service
@Slf4j
public class UserLevelServiceImpl extends ServiceImpl<UsersMapper, User> implements UserLevelService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RecommendUserMapper recommendUserMapper;

    @Autowired
    private TeamUserInfoMapper teamUserInfoMapper;

    @Autowired
    private TradeRecordMapper tradeRecordMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private TeamPerformanceMapper teamPerformanceMapper;

    @Autowired
    private CultivatingPrizeMapper cultivatingPrizeMapper;

    @Autowired
    private CultivatingPrizeInfoMapper cultivatingPrizeInfoMapper;

    @Autowired
    private AerialDeliveryUserService aerialDeliveryUserService;

    @Autowired
    private OrderMapper orderMapper;

    //系统推荐人邀请码
    private static final String sysInviteCode1 = "1";
    private static final String sysInviteCode2 = "88888888";

    //获取订单
    @XxlJob(value = "userLevelUpjobhandler")
    @Override
    public void userLevelUp() {
        //1.获取数据库订单数据
        log.info("------------------------用户升级开始----------------------------------");
        List<OrderInfo> ordersByLevelStatus = orderMapper.getByLevelStatus(0);
        for (OrderInfo orderInfo : ordersByLevelStatus) {
            String userId = orderInfo.getUserId();
            userLevelUpgrade(userId);
            //当前订单升级状态置为1
            orderInfo.setLevelStatus(1);
            orderMapper.updateById(orderInfo);
        }
        log.info("-------------------------用户升级结束--------------------------------------");
    }

    @Override
    @Transactional
    public void userLevelUpgrade(String userId) {
        //当前用户对象
        User user = usersMapper.getByUserId(userId);
        //当前用户直推表对象
        RecommendUser recommendUser = recommendUserMapper.getByUserId(userId);
        //当前用户团队信息表对象
        TeamUserInfo teamUserInfoMapperByUserId = teamUserInfoMapper.getByUserId(userId);
        //当前用户等级
        Integer userLevel = user.getUserLevel();
        //当前用户的累计消费
        BigDecimal performanceByUserid = new BigDecimal(0);
        if (userLevel == 0){
            //计算当前用户业绩
            performanceByUserid = orderMapper.getPerformanceByUserid(userId);
            if (null == performanceByUserid) {
                performanceByUserid = new BigDecimal(0);
            }
        }
        //当前用户的推荐人邀请码
        String beInvitedCode = user.getBeInvitedCode();
        //
        String inviteUserId = "";
        RecommendUser inviteRecommendUser = new RecommendUser();
        //若当前用户的推荐人邀请码是  “1” 时 则当前用户没有邀请人
        if (!sysInviteCode1.equals(beInvitedCode) && !sysInviteCode2.equals(beInvitedCode)) {
            //通过当前用户推荐人邀请码获取邀请人的userId
            User byBeInvitedCode = usersMapper.getByBeInvitedCode(beInvitedCode);
            if (null != byBeInvitedCode) {
                inviteUserId = byBeInvitedCode.getUserId();
                //邀请人的直推用户信息
                inviteRecommendUser = recommendUserMapper.getByUserId(inviteUserId);
            }
        }
        //用户等级升级为幼苗 1
        //若当前用户等级为0（普通用户）且跨境额度（业绩消费金额）>= 3980 进行升级0-->1
        //todo:根据业绩去计算  查一次表获取业绩
        if (userLevel == 0 && performanceByUserid.intValue() >= 3980) {
            user.setUserLevel(1);
            usersMapper.updateById(user);
            //同步accountInfo 和TeamPerformance 的用户等级
            accountAndTeamPerformanceUserLevelUpdate(userId);
            //用户推荐人邀请码为 1 时 该用户没有邀请人
            if (sysInviteCode1.equals(beInvitedCode) || sysInviteCode2.equals(beInvitedCode)) {
                return;
            } else {
                //推荐人直推信息表数据维护
                //若邀请人直推用户信息中的普通用户数量为0是则不用变化，否则普通用户数量-1
                if (inviteRecommendUser.getNormalUserNum() == 0) {
                    inviteRecommendUser.setNormalUserNum(inviteRecommendUser.getNormalUserNum());
                } else {
                    //普通用户-1
                    inviteRecommendUser.setNormalUserNum(inviteRecommendUser.getNormalUserNum() - 1);
                }
                //邀请人直推用户信息中的幼苗用户数量为+1
                inviteRecommendUser.setSeedlingNum(inviteRecommendUser.getSeedlingNum() + 1);
                recommendUserMapper.updateById(inviteRecommendUser);
                //团队用户表数据维护
//                teamUserInfoNormalToSeed(inviteUserId);
                aerialDeliveryUserService.teamDataNotRecommend(userId,inviteUserId);
                //上级用户获得幼苗等级的培育奖
                int level = 1;
                cultivatingPrizeToInvitedUser(userId, inviteUserId, level);
                //用户升级成功时，进行邀请人等级自查是否达到升级条件
                userLevelUpgrade(inviteUserId);
            }

        }
        //用户等级升级为青铜树 2
        //当前用户等级为幼苗用户（1）时 且当前用户直推人数中幼苗等级>=5人<20人时
        if (userLevel == 1 && recommendUser.getSeedlingNum() >= 3
                             && recommendUser.getSeedlingNum() < 15) {
            //用户升级成功
            user.setUserLevel(2);
            usersMapper.updateById(user);
            //同步accountInfo 和TeamPerformance 的用户等级
            accountAndTeamPerformanceUserLevelUpdate(userId);
            //用户被邀请码为 1 时 该用户没有邀请人
            if (sysInviteCode1.equals(beInvitedCode) || sysInviteCode2.equals(beInvitedCode)) {
                return;
            } else {
                //若邀请人直推用户信息中的幼苗用户数量为0是则不用变化，否则幼苗用户数量-1
                if (inviteRecommendUser.getSeedlingNum() == 0) {
                    inviteRecommendUser.setSeedlingNum(inviteRecommendUser.getSeedlingNum());
                } else {
                    //幼苗用户-1
                    inviteRecommendUser.setSeedlingNum(inviteRecommendUser.getSeedlingNum() - 1);
                }
                //邀请人直推用户信息中的青铜树用户数量为+1
                inviteRecommendUser.setBronzeTreeNum(inviteRecommendUser.getBronzeTreeNum() + 1);
                recommendUserMapper.updateById(inviteRecommendUser);
                //团队用户表数据维护
//                teamUserInfoSeedToBronze(inviteUserId);
                aerialDeliveryUserService.teamDataNotRecommend(userId,inviteUserId);
                //上级用户获得幼苗等级的培育奖
                int level = 2;
                cultivatingPrizeToInvitedUser(userId, inviteUserId, level);
                //用户升级成功时，进行邀请人等级自查是否达到升级条件
                userLevelUpgrade(inviteUserId);
            }
        }
        //用户等级升级为白银树 3
        if (userLevel == 2 && recommendUser.getSeedlingNum() >= 15
                            && recommendUser.getSeedlingNum() < 20) {
            user.setUserLevel(3);
            usersMapper.updateById(user);
            //同步accountInfo 和TeamPerformance 的用户等级
            accountAndTeamPerformanceUserLevelUpdate(userId);
            //用户被邀请码为 1 时 该用户没有邀请人
            if (sysInviteCode1.equals(beInvitedCode) || sysInviteCode2.equals(beInvitedCode)) {
                return;
            } else {
                //推荐人直推信息表数据维护
                //若邀请人直推用户信息中的青铜树用户数量为0是则不用变化，否则青铜树用户数量-1
                if (inviteRecommendUser.getBronzeTreeNum() == 0) {
                    inviteRecommendUser.setBronzeTreeNum(inviteRecommendUser.getBronzeTreeNum());
                } else {
                    //青铜树用户-1
                    inviteRecommendUser.setBronzeTreeNum(inviteRecommendUser.getBronzeTreeNum() - 1);
                }
                //邀请人直推用户信息中的白银用户数量 + 1
                inviteRecommendUser.setSilverTreeNum(inviteRecommendUser.getSilverTreeNum() + 1);
                recommendUserMapper.updateById(inviteRecommendUser);
                //团队用户表数据维护
//                teamUserInfoBronzeToSilver(inviteUserId);
                aerialDeliveryUserService.teamDataNotRecommend(userId,inviteUserId);
                //上级用户获得幼苗等级的培育奖
                int level = 3;
                cultivatingPrizeToInvitedUser(userId, inviteUserId, level);
                //用户升级成功时，进行邀请人等级自查是否达到升级条件
                userLevelUpgrade(inviteUserId);
            }

        }
        //用户等级升级为黄金树 4
        //:todo 条件:团队中青铜树数量>=20
        if (userLevel == 3 && recommendUser.getSeedlingNum() >= 20
                && recommendUser.getSilverTreeNum() >= 2
                && teamUserInfoMapperByUserId.getSeedlingNum() >= 30
                && teamUserInfoMapperByUserId.getBronzeTreeNum() >= 20) {
            user.setUserLevel(4);
            usersMapper.updateById(user);
            //同步accountInfo 和TeamPerformance 的用户等级
            accountAndTeamPerformanceUserLevelUpdate(userId);
            //用户被邀请码为 1 时 该用户没有邀请人
            if (sysInviteCode1.equals(beInvitedCode) || sysInviteCode2.equals(beInvitedCode)) {
                return;
            } else {
                //推荐人直推信息表数据维护
                //若邀请人直推用户信息中的白银树用户数量为0是则不用变化，否则白银树用户数量-1
                if (inviteRecommendUser.getSilverTreeNum() == 0) {
                    inviteRecommendUser.setSilverTreeNum(inviteRecommendUser.getSilverTreeNum());
                } else {
                    //白银树用户-1
                    inviteRecommendUser.setSilverTreeNum(inviteRecommendUser.getSilverTreeNum() - 1);
                }
                //邀请人直推用户信息中的黄金用户数量 + 1
                inviteRecommendUser.setGoldTreeNum(inviteRecommendUser.getGoldTreeNum() + 1);
                recommendUserMapper.updateById(inviteRecommendUser);
                //团队用户表数据维护
//                teamUserInfoSilverToGoldTree(inviteUserId);
                aerialDeliveryUserService.teamDataNotRecommend(userId,inviteUserId);
                //上级用户获得幼苗等级的培育奖
                int level = 4;
                cultivatingPrizeToInvitedUser(userId, inviteUserId, level);
                //用户升级成功时，进行邀请人等级自查是否达到升级条件
                userLevelUpgrade(inviteUserId);
            }
        }
        //用户等级级升级为农场主 5
        //:todo 条件:团队中白银树数量>=40
        if (userLevel == 4 && recommendUser.getSeedlingNum() >= 30
                && recommendUser.getGoldTreeNum() >= 2
                && teamUserInfoMapperByUserId.getSeedlingNum() >=70
                && teamUserInfoMapperByUserId.getSilverTreeNum() >= 40) {
            user.setUserLevel(5);
            usersMapper.updateById(user);
            //同步accountInfo 和TeamPerformance 的用户等级
            accountAndTeamPerformanceUserLevelUpdate(userId);
            //用户被邀请码为 1 时 该用户没有邀请人
            if (sysInviteCode1.equals(beInvitedCode) || sysInviteCode2.equals(beInvitedCode)) {
                return;
            } else {
                //推荐人直推信息表数据维护
                //若邀请人直推用户信息中的黄金树用户数量为0是则不用变化，否则黄金树用户数量-1
                if (inviteRecommendUser.getGoldTreeNum() == 0) {
                    inviteRecommendUser.setGoldTreeNum(inviteRecommendUser.getGoldTreeNum());
                } else {
                    //黄金树用户-1
                    inviteRecommendUser.setGoldTreeNum(inviteRecommendUser.getGoldTreeNum() - 1);
                }
                //邀请人直推用户信息中的农场主用户数量 + 1
                inviteRecommendUser.setGoldTreeNum(inviteRecommendUser.getFarmerNum() + 1);
                recommendUserMapper.updateById(inviteRecommendUser);
                //团队用户表数据维护
//                teamUserInfoGoldTreeToFarmer(inviteUserId);
                aerialDeliveryUserService.teamDataNotRecommend(userId,inviteUserId);
                //上级用户获得幼苗等级的培育奖
                int level = 5;
                cultivatingPrizeToInvitedUser(userId, inviteUserId, level);
                //用户升级成功时，进行邀请人等级自查是否达到升级条件
                userLevelUpgrade(inviteUserId);
            }
        }

        //用户等级升级为森林之星 6
        if (userLevel == 5 && recommendUser.getSeedlingNum() >= 40
                && recommendUser.getFarmerNum() >= 2
                && teamUserInfoMapperByUserId.getSeedlingNum() >=80
                && teamUserInfoMapperByUserId.getSilverTreeNum() >= 70
                && teamUserInfoMapperByUserId.getGoldTreeNum() >= 30) {
            user.setUserLevel(6);
            usersMapper.updateById(user);
            //同步accountInfo 和TeamPerformance 的用户等级
            accountAndTeamPerformanceUserLevelUpdate(userId);
            //用户被邀请码为 1 时 该用户没有邀请人
            if (sysInviteCode1.equals(beInvitedCode) || sysInviteCode2.equals(beInvitedCode)) {
                return;
            } else {
                //推荐人直推信息表数据维护
                //若邀请人直推用户信息中的农场主用户数量为0是则不用变化，否则农场主用户数量-1
                if (inviteRecommendUser.getFarmerNum() == 0) {
                    inviteRecommendUser.setFarmerNum(inviteRecommendUser.getFarmerNum());
                } else {
                    //农场主用户-1
                    inviteRecommendUser.setFarmerNum(inviteRecommendUser.getFarmerNum() - 1);
                }
                //邀请人直推用户信息中的森林之星用户数量 + 1
                inviteRecommendUser.setForestStartNum(inviteRecommendUser.getForestStartNum() + 1);
                recommendUserMapper.updateById(inviteRecommendUser);
                //团队用户表数据维护
//                teamUserInfoFarmerToForestStart(inviteUserId);
                aerialDeliveryUserService.teamDataNotRecommend(userId,inviteUserId);
                //上级用户获得幼苗等级的培育奖
                int level = 6;
                cultivatingPrizeToInvitedUser(userId, inviteUserId, level);
                //用户升级成功时，进行邀请人等级自查是否达到升级条件
                userLevelUpgrade(inviteUserId);
            }
        }
        //用户等级升级为西田森合伙人 7
        //:todo 条件:团队中白银树数量>=90 && 条件:团队中黄金树数量>=50 条件:团队中农场主数量>=30
        if (userLevel == 6 && recommendUser.getSeedlingNum() >= 50
                && recommendUser.getForestStartNum() >= 2
                && teamUserInfoMapperByUserId.getSeedlingNum() >= 100
                && teamUserInfoMapperByUserId.getSilverTreeNum() >= 90
                && teamUserInfoMapperByUserId.getGoldTreeNum() >= 50
                && teamUserInfoMapperByUserId.getFarmerNum() >= 30) {
            user.setUserLevel(7);
            usersMapper.updateById(user);
            //同步accountInfo 和TeamPerformance 的用户等级
            accountAndTeamPerformanceUserLevelUpdate(userId);
            //用户被邀请码为 1 时 该用户没有邀请人
            if (sysInviteCode1.equals(beInvitedCode) || sysInviteCode2.equals(beInvitedCode)) {
                return;
            } else {
                //推荐人直推信息表数据维护
                //若邀请人直推用户信息中的森林之星用户数量为0是则不用变化，否则森林之星用户数量-1
                if (inviteRecommendUser.getForestStartNum() == 0) {
                    inviteRecommendUser.setForestStartNum(inviteRecommendUser.getForestStartNum());
                } else {
                    //森林之星用户-1
                    inviteRecommendUser.setForestStartNum(inviteRecommendUser.getForestStartNum() - 1);
                }
                //邀请人直推用户信息中的西田森合伙人用户数量 + 1
                inviteRecommendUser.setPartnerNum(inviteRecommendUser.getPartnerNum() + 1);
                recommendUserMapper.updateById(inviteRecommendUser);
                //团队用户表数据维护
//                teamUserInfoForestStartToPartner(inviteUserId);
                aerialDeliveryUserService.teamDataNotRecommend(userId,inviteUserId);
                //上级用户获得幼苗等级的培育奖
                int level = 7;
                cultivatingPrizeToInvitedUser(userId, inviteUserId, level);
                //用户升级成功时，进行邀请人等级自查是否达到升级条件
                userLevelUpgrade(inviteUserId);
            }
        }
    }

    /**
     * 团队用户表数据维护(森林之星用户升级至西田森合伙人用户时)
     *
     * @param inviteUserId 邀请人userid
     */
    private void teamUserInfoForestStartToPartner(String inviteUserId) {
        //邀请人的团队信息表对象
        TeamUserInfo teamNumInfoBuyId = teamUserInfoMapper.getByUserId(inviteUserId);
        //邀请人的用户表对象
        User byUserId = usersMapper.getByUserId(teamNumInfoBuyId.getUserId());

        String beinvitedCodeUserId = "";
        String inviteCode = byUserId.getBeInvitedCode();
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            //通过邀请人的用户信息获取邀请人的推荐人邀请码
            beinvitedCodeUserId = usersMapper.getByBeInvitedCode(inviteCode).getUserId();
        }
        //通过邀请人的用户信息获取邀请人的推荐人邀请码
        //String beinvitedCodeUserId = usersMapper.getByBeInvitedCode(byUserId.getBeInvitedCode()).getUserId();
        //邀请人团队信息表中森林之星用户数量 = 0 时，森林之星用户数量不用变化，否则森林之星用户数量 - 1
        if (teamNumInfoBuyId.getForestStartNum() == 0) {
            teamNumInfoBuyId.setForestStartNum(teamNumInfoBuyId.getForestStartNum());
        } else {
            //森林之星用户数量 - 1
            teamNumInfoBuyId.setForestStartNum(teamNumInfoBuyId.getForestStartNum() - 1);
        }
        //西田森合伙人用户数量 + 1
        teamNumInfoBuyId.setPartnerNum(teamNumInfoBuyId.getPartnerNum() + 1);
        teamUserInfoMapper.updateById(teamNumInfoBuyId);
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            return;
        }
        teamUserInfoForestStartToPartner(beinvitedCodeUserId);
    }

    /**
     * 团队用户表数据维护(农场主用户升级至森林之星用户时)
     *
     * @param inviteUserId 邀请人userid
     */
    private void teamUserInfoFarmerToForestStart(String inviteUserId) {
        //邀请人的团队信息表对象
        TeamUserInfo teamNumInfoBuyId = teamUserInfoMapper.getByUserId(inviteUserId);
        //邀请人的用户表对象
        User byUserId = usersMapper.getByUserId(teamNumInfoBuyId.getUserId());

        String beinvitedCodeUserId = "";
        String inviteCode = byUserId.getBeInvitedCode();
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            //通过邀请人的用户信息获取邀请人的推荐人邀请码
            beinvitedCodeUserId = usersMapper.getByBeInvitedCode(inviteCode).getUserId();
        }
        //通过邀请人的用户信息获取邀请人的推荐人邀请码
        //String beinvitedCodeUserId = usersMapper.getByBeInvitedCode(byUserId.getBeInvitedCode()).getUserId();
        //邀请人团队信息表中农场主用户数量 = 0 时，农场主用户数量不用变化，否则农场主用户数量 - 1
        if (teamNumInfoBuyId.getFarmerNum() == 0) {
            teamNumInfoBuyId.setFarmerNum(teamNumInfoBuyId.getFarmerNum());
        } else {
            //农场主用户数量 - 1
            teamNumInfoBuyId.setFarmerNum(teamNumInfoBuyId.getFarmerNum() - 1);
        }
        //森林之星用户数量 + 1
        teamNumInfoBuyId.setForestStartNum(teamNumInfoBuyId.getForestStartNum() + 1);
        teamUserInfoMapper.updateById(teamNumInfoBuyId);
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            return;
        }
        //递归向上修改团队用户信息表
        teamUserInfoFarmerToForestStart(beinvitedCodeUserId);
    }

    /**
     * 团队用户表数据维护(黄金树用户升级至农场主用户时)
     *
     * @param inviteUserId 邀请人userid
     */
    private void teamUserInfoGoldTreeToFarmer(String inviteUserId) {
        //邀请人的团队信息表对象
        TeamUserInfo teamNumInfoBuyId = teamUserInfoMapper.getByUserId(inviteUserId);
        //邀请人的用户表对象
        User byUserId = usersMapper.getByUserId(teamNumInfoBuyId.getUserId());

        String beinvitedCodeUserId = "";
        String inviteCode = byUserId.getBeInvitedCode();
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            //通过邀请人的用户信息获取邀请人的推荐人邀请码
            beinvitedCodeUserId = usersMapper.getByBeInvitedCode(inviteCode).getUserId();
        }
        //通过邀请人的用户信息获取邀请人的推荐人邀请码
        // String beinvitedCodeUserId = usersMapper.getByBeInvitedCode(byUserId.getBeInvitedCode()).getUserId();
        //邀请人团队信息表中黄金树用户数量 = 0 时，黄金树用户数量不用变化，否则黄金树用户数量 - 1
        if (teamNumInfoBuyId.getGoldTreeNum() == 0) {
            teamNumInfoBuyId.setGoldTreeNum(teamNumInfoBuyId.getGoldTreeNum());
        } else {
            //黄金树用户数量 - 1
            teamNumInfoBuyId.setGoldTreeNum(teamNumInfoBuyId.getGoldTreeNum() - 1);
        }
        //农场主数量 + 1
        teamNumInfoBuyId.setFarmerNum(teamNumInfoBuyId.getFarmerNum() + 1);
        teamUserInfoMapper.updateById(teamNumInfoBuyId);
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            return;
        }
        //递归向上修改团队用户信息表
        teamUserInfoGoldTreeToFarmer(beinvitedCodeUserId);
    }

    /**
     * 团队用户表数据维护(白银树用户升级至黄金树用户时)
     *
     * @param inviteUserId 邀请人userid
     */
    private void teamUserInfoSilverToGoldTree(String inviteUserId) {
        //邀请人的团队信息表对象
        TeamUserInfo teamNumInfoBuyId = teamUserInfoMapper.getByUserId(inviteUserId);
        //邀请人的用户表对象
        User byUserId = usersMapper.getByUserId(teamNumInfoBuyId.getUserId());

        String beinvitedCodeUserId = "";
        String inviteCode = byUserId.getBeInvitedCode();
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            //通过邀请人的用户信息获取邀请人的推荐人邀请码
            beinvitedCodeUserId = usersMapper.getByBeInvitedCode(inviteCode).getUserId();
        }
        //通过邀请人的用户信息获取邀请人的推荐人邀请码
        //String beinvitedCodeUserId = usersMapper.getByBeInvitedCode(byUserId.getBeInvitedCode()).getUserId();
        //邀请人团队信息表中白银树用户数量 = 0 时，白银树用户数量不用变化，否则白银树用户数量 - 1
        if (teamNumInfoBuyId.getSilverTreeNum() == 0) {
            teamNumInfoBuyId.setSilverTreeNum(teamNumInfoBuyId.getSilverTreeNum());
        } else {
            //白银树用户数量 - 1
            teamNumInfoBuyId.setSilverTreeNum(teamNumInfoBuyId.getSilverTreeNum() - 1);
        }
        //黄金树用户数量 - 1
        teamNumInfoBuyId.setGoldTreeNum(teamNumInfoBuyId.getGoldTreeNum() + 1);
        teamUserInfoMapper.updateById(teamNumInfoBuyId);
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            return;
        }
        //递归向上修改团队用户信息表
        teamUserInfoSilverToGoldTree(beinvitedCodeUserId);
    }

    /**
     * 团队用户表数据维护(青铜树用户升级至白银树用户时)
     *
     * @param inviteUserId 邀请人userid
     */
    private void teamUserInfoBronzeToSilver(String inviteUserId) {
        //邀请人的团队信息表对象
        TeamUserInfo teamNumInfoBuyId = teamUserInfoMapper.getByUserId(inviteUserId);
        //邀请人的用户表对象
        User byUserId = usersMapper.getByUserId(teamNumInfoBuyId.getUserId());

        String beinvitedCodeUserId = "";
        String inviteCode = byUserId.getBeInvitedCode();
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            //通过邀请人的用户信息获取邀请人的推荐人邀请码
            beinvitedCodeUserId = usersMapper.getByBeInvitedCode(inviteCode).getUserId();
        }
        //通过邀请人的用户信息获取邀请人的推荐人邀请码
        //String beinvitedCodeUserId = usersMapper.getByBeInvitedCode(byUserId.getBeInvitedCode()).getUserId();
        //邀请人团队信息表中青铜树用户数量 = 0 时，青铜树用户数量不用变化，否则青铜树用户数量 - 1
        if (teamNumInfoBuyId.getBronzeTreeNum() == 0) {
            teamNumInfoBuyId.setBronzeTreeNum(teamNumInfoBuyId.getBronzeTreeNum());
        } else {
            //青铜树用户数量 - 1
            teamNumInfoBuyId.setBronzeTreeNum(teamNumInfoBuyId.getBronzeTreeNum() - 1);
        }
        //白银树用户数量+1
        teamNumInfoBuyId.setSilverTreeNum(teamNumInfoBuyId.getSilverTreeNum() + 1);
        teamUserInfoMapper.updateById(teamNumInfoBuyId);
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            return;
        }
        //递归向上修改团队用户信息表
        teamUserInfoBronzeToSilver(beinvitedCodeUserId);
    }

    /**
     * 团队用户表数据维护(幼苗用户升级至青铜用户时)
     *
     * @param inviteUserId 邀请人userid
     */
    private void teamUserInfoSeedToBronze(String inviteUserId) {
        //邀请人的团队信息表对象
        TeamUserInfo teamNumInfoBuyId = teamUserInfoMapper.getByUserId(inviteUserId);
        //邀请人的用户表对象
        User byUserId = usersMapper.getByUserId(teamNumInfoBuyId.getUserId());

        String beinvitedCodeUserId = "";
        String inviteCode = byUserId.getBeInvitedCode();
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            //通过邀请人的用户信息获取邀请人的推荐人邀请码
            beinvitedCodeUserId = usersMapper.getByBeInvitedCode(inviteCode).getUserId();
        }
        //通过邀请人的用户信息获取邀请人的推荐人邀请码
        //String beinvitedCodeUserId = usersMapper.getByBeInvitedCode(byUserId.getBeInvitedCode()).getUserId();
        //邀请人团队信息表中幼苗用户数量 = 0 时，幼苗用户数量不用变化，否则幼苗用户数量 - 1
        if (teamNumInfoBuyId.getSeedlingNum() == 0) {
            teamNumInfoBuyId.setSeedlingNum(teamNumInfoBuyId.getSeedlingNum());
        } else {
            //幼苗用户数量-1
            teamNumInfoBuyId.setSeedlingNum(teamNumInfoBuyId.getSeedlingNum() - 1);
        }
        //邀请人的团队用户信息表中青铜树数量 + 1
        teamNumInfoBuyId.setBronzeTreeNum(teamNumInfoBuyId.getBronzeTreeNum() + 1);
        teamUserInfoMapper.updateById(teamNumInfoBuyId);
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            return;
        }
        //递归向上修改团队用户信息表
        teamUserInfoSeedToBronze(beinvitedCodeUserId);
    }

    /**
     * 团队用户表数据维护(普通用户升级至幼苗用户时)
     *
     * @param inviteUserId 邀请人userid
     */
    private void teamUserInfoNormalToSeed(String inviteUserId) {
        //邀请人的团队信息表对象
        TeamUserInfo teamNumInfoBuyId = teamUserInfoMapper.getByUserId(inviteUserId);
        //邀请人的用户表对象
        User intiveUserByUserId = usersMapper.getByUserId(teamNumInfoBuyId.getUserId());

        String beinvitedCodeUserId = "";
        //邀请人的推荐人邀请码
        String inviteCode = intiveUserByUserId.getBeInvitedCode();
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            //通过邀请人的用户信息获取邀请人的推荐人邀请码
            User byBeInvitedCode = usersMapper.getByBeInvitedCode(inviteCode);
            if (null != byBeInvitedCode) {
                beinvitedCodeUserId = byBeInvitedCode.getUserId();
            }
        }
        if (teamNumInfoBuyId.getNormalUserNum() == 0) {
            teamNumInfoBuyId.setNormalUserNum(teamNumInfoBuyId.getNormalUserNum());
        } else {
            //普通用户数量-1
            teamNumInfoBuyId.setNormalUserNum(teamNumInfoBuyId.getNormalUserNum() - 1);
        }
        //邀请人的团队用户信息表中幼苗数量 + 1
        //第一波用户是谁邀请的
        teamNumInfoBuyId.setSeedlingNum(teamNumInfoBuyId.getSeedlingNum() + 1);
        teamUserInfoMapper.updateById(teamNumInfoBuyId);
        if (!sysInviteCode1.equals(inviteUserId) || !sysInviteCode2.equals(inviteUserId)) {
            return;
        }
        //递归向上修改团队用户信息表
        if (!"".equals(beinvitedCodeUserId)) {
            teamUserInfoNormalToSeed(beinvitedCodeUserId);
        }
    }

    /**
     * 培育奖给到上级用户
     *
     * @param userId       当前用户id
     * @param inviteUserId 上级用户id
     * @param level        当前用户升级后的等级
     */
    public void cultivatingPrizeToInvitedUser(String userId, String inviteUserId, int level) {
        //当前用户的培育奖记录
        CultivatingPrizeInfo cultivatingPrizeInfo = cultivatingPrizeInfoMapper.getOneByUserId(userId);
        //判断当前用户等级
        if (1 == level) {
            //获取等级对应的培育奖记录状态
            int seedling = cultivatingPrizeInfo.getSeedling();
            //用户等级对应的培育奖金额
            BigDecimal cultivatingPrize = cultivatingPrizeMapper.getcultivatingPrizeByUserLevel(level).getCultivatingPrize();
            if (0 == seedling) {
                //1、判断推荐人的等级是否大与当前用户等级
                User inviteUser = usersMapper.getByUserId(inviteUserId);
                int inviteUserLevel = inviteUser.getUserLevel();
                if (null != inviteUser) {
                    if (inviteUserLevel > level) {
                        //2.交易流水新增一条数据
                        TradeRecord tradeRecord = new TradeRecord();
                        tradeRecord.setUserId(inviteUserId);
                        tradeRecord.setMoney(cultivatingPrize);
                        tradeRecord.setTradeNo(null);
                        tradeRecord.setStatus(0);
                        tradeRecord.setTradeType(TradeRecordEnum.CULTIVATING_PRIZE.getCode());
                        tradeRecordMapper.add(tradeRecord);

                        //3.修改培育奖记录状态 ==1
                        seedling = 1;
                        cultivatingPrizeInfo.setSeedling(seedling);
                        cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                    } else {
                        //3.修改培育奖记录状态 ==2
                        seedling = 2;
                        cultivatingPrizeInfo.setSeedling(seedling);
                        cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                    }

                }
            }
        } else if (2 == level) {
            //培育奖记录状态
            int bronzeTree = cultivatingPrizeInfo.getBronzeTree();
            //用户等级对应的培育奖金额
            BigDecimal cultivatingPrize = cultivatingPrizeMapper.getcultivatingPrizeByUserLevel(level).getCultivatingPrize();

            if (0 == bronzeTree) {
                //1、判断推荐人的等级是否大与当前用户等级
                User inviteUser = usersMapper.getByUserId(inviteUserId);
                if (null != inviteUser) {
                    int inviteUserLevel = inviteUser.getUserLevel();
                    if (inviteUserLevel > level) {
                        //2.交易流水新增一条数据
                        TradeRecord tradeRecord = new TradeRecord();
                        tradeRecord.setUserId(inviteUserId);
                        tradeRecord.setMoney(cultivatingPrize);
                        tradeRecord.setTradeNo(null);
                        tradeRecord.setStatus(0);
                        tradeRecord.setTradeType(TradeRecordEnum.CULTIVATING_PRIZE.getCode());
                        tradeRecordMapper.add(tradeRecord);

                        //3.修改培育奖记录状态 ==1
                        bronzeTree = 1;
                        cultivatingPrizeInfo.setBronzeTree(bronzeTree);
                        cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                    } else {
                        //3.修改培育奖记录状态 ==2
                        bronzeTree = 2;
                        cultivatingPrizeInfo.setBronzeTree(bronzeTree);
                        cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                    }

                }
            }
        } else if (3 == level) {
            //获取当前等级的培育奖状态
            int silverTree = cultivatingPrizeInfo.getSilverTree();
            //用户等级对应的培育奖金额
            BigDecimal cultivatingPrize = cultivatingPrizeMapper.getcultivatingPrizeByUserLevel(level).getCultivatingPrize();

            if (0 == silverTree) {
                //1、判断推荐人的等级是否大与当前用户等级
                User inviteUser = usersMapper.getByUserId(inviteUserId);
                if (null != inviteUser) {
                    int inviteUserLevel = inviteUser.getUserLevel();
                    if (inviteUserLevel > level) {
                        //2.交易流水新增一条数据
                        TradeRecord tradeRecord = new TradeRecord();
                        tradeRecord.setUserId(inviteUserId);
                        tradeRecord.setMoney(cultivatingPrize);
                        tradeRecord.setTradeNo(null);
                        tradeRecord.setStatus(0);
                        tradeRecord.setTradeType(TradeRecordEnum.CULTIVATING_PRIZE.getCode());
                        tradeRecordMapper.add(tradeRecord);

                        //3.修改培育奖记录状态 ==1
                        silverTree = 1;
                        cultivatingPrizeInfo.setBronzeTree(silverTree);
                        cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                    } else {
                        //3.修改培育奖记录状态 ==2
                        silverTree = 2;
                        cultivatingPrizeInfo.setBronzeTree(silverTree);
                        cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                    }
                }
            }
        } else if (4 == level) {
            int goldTree = cultivatingPrizeInfo.getGoldTree();
            //用户等级对应的培育奖金额
            BigDecimal cultivatingPrize = cultivatingPrizeMapper.getcultivatingPrizeByUserLevel(level).getCultivatingPrize();

            if (0 == goldTree) {
                //上级用户
                User inviteUser = usersMapper.getByUserId(inviteUserId);
                if (null != inviteUser) {
                    //2.交易流水新增一条数据
                    TradeRecord tradeRecord = new TradeRecord();
                    tradeRecord.setUserId(inviteUserId);
                    tradeRecord.setMoney(cultivatingPrize);
                    tradeRecord.setTradeNo(null);
                    tradeRecord.setStatus(0);
                    tradeRecord.setTradeType(TradeRecordEnum.CULTIVATING_PRIZE.getCode());
                    tradeRecordMapper.add(tradeRecord);

                    //3.修改培育奖记录状态 ==1
                    goldTree = 1;
                    cultivatingPrizeInfo.setGoldTree(goldTree);
                    cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                } else {
                    //3.修改培育奖记录状态 ==2
                    goldTree = 2;
                    cultivatingPrizeInfo.setGoldTree(goldTree);
                    cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                }
            }
        } else if (5 == level) {
            int farmer = cultivatingPrizeInfo.getFarmer();
            //用户等级对应的培育奖金额
            BigDecimal cultivatingPrize = cultivatingPrizeMapper.getcultivatingPrizeByUserLevel(level).getCultivatingPrize();

            if (0 == farmer) {
                //上级用户
                User inviteUser = usersMapper.getByUserId(inviteUserId);
                if (null != inviteUser) {
                    //2.交易流水新增一条数据
                    TradeRecord tradeRecord = new TradeRecord();
                    tradeRecord.setUserId(inviteUserId);
                    tradeRecord.setMoney(cultivatingPrize);
                    tradeRecord.setTradeNo(null);
                    tradeRecord.setStatus(0);
                    tradeRecord.setTradeType(TradeRecordEnum.CULTIVATING_PRIZE.getCode());
                    tradeRecordMapper.add(tradeRecord);

                    //3.修改培育奖记录状态 ==1
                    farmer = 1;
                    cultivatingPrizeInfo.setGoldTree(farmer);
                    cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                } else {
                    //3.修改培育奖记录状态 ==2
                    farmer = 2;
                    cultivatingPrizeInfo.setGoldTree(farmer);
                    cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                }
            }
        } else if (6 == level) {
            int forestStart = cultivatingPrizeInfo.getForestStart();
            //用户等级对应的培育奖金额
            BigDecimal cultivatingPrize = cultivatingPrizeMapper.getcultivatingPrizeByUserLevel(level).getCultivatingPrize();

            if (0 == forestStart) {
                //上级用户
                User inviteUser = usersMapper.getByUserId(inviteUserId);
                if (null != inviteUser) {
                    //2.交易流水新增一条数据
                    TradeRecord tradeRecord = new TradeRecord();
                    tradeRecord.setUserId(inviteUserId);
                    tradeRecord.setMoney(cultivatingPrize);
                    tradeRecord.setTradeNo(null);
                    tradeRecord.setStatus(0);
                    tradeRecord.setTradeType(TradeRecordEnum.CULTIVATING_PRIZE.getCode());
                    tradeRecordMapper.add(tradeRecord);

                    //3.修改培育奖记录状态 ==1
                    forestStart = 1;
                    cultivatingPrizeInfo.setGoldTree(forestStart);
                    cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                } else {
                    //3.修改培育奖记录状态 ==2
                    forestStart = 2;
                    cultivatingPrizeInfo.setGoldTree(forestStart);
                    cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                }
            }
        } else if (7 == level) {
            int partner = cultivatingPrizeInfo.getPartner();
            //用户等级对应的培育奖金额
            BigDecimal cultivatingPrize = cultivatingPrizeMapper.getcultivatingPrizeByUserLevel(level).getCultivatingPrize();

            if (0 == partner) {
                //上级用户
                User inviteUser = usersMapper.getByUserId(inviteUserId);
                if (null != inviteUser) {
                    //2.交易流水新增一条数据
                    TradeRecord tradeRecord = new TradeRecord();
                    tradeRecord.setUserId(inviteUserId);
                    tradeRecord.setMoney(cultivatingPrize);
                    tradeRecord.setTradeNo(null);
                    tradeRecord.setStatus(0);
                    tradeRecord.setTradeType(TradeRecordEnum.CULTIVATING_PRIZE.getCode());
                    tradeRecordMapper.add(tradeRecord);

                    //3.修改培育奖记录状态 ==1
                    partner = 1;
                    cultivatingPrizeInfo.setGoldTree(partner);
                    cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                } else {
                    //3.修改培育奖记录状态 ==2
                    partner = 2;
                    cultivatingPrizeInfo.setGoldTree(partner);
                    cultivatingPrizeInfoMapper.updateById(cultivatingPrizeInfo);
                }
            }
        }
    }

    //同步accountInfo 和TeamPerformance 的用户等级
    public void accountAndTeamPerformanceUserLevelUpdate(String userId){

        User userByUserId = usersMapper.getUserByUserId(userId);

        if (null != userByUserId){
            int userLevel = userByUserId.getUserLevel();
            AccountInfo accountInfoByUserId = accountMapper.getByUserId(userId);
            accountInfoByUserId.setUserLevel(userLevel);
            TeamPerformance teamPerformanceByUserId = teamPerformanceMapper.getByUserId(userId);
            teamPerformanceByUserId.setUserLevel(userLevel);

            accountMapper.edit(accountInfoByUserId);
            teamPerformanceMapper.edit(teamPerformanceByUserId);
        }
    }
}

