package com.game.business.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.game.business.domain.*;
import com.game.business.dto.AppUserAgentDTO;
import com.game.business.dto.AppUserDTO;
import com.game.business.service.IAppGameCommissionService;
import com.game.business.service.IAppGameService;
import com.game.business.service.IAppUserService;
import com.game.business.util.Md5Utils;
import com.game.business.vo.AppGameBettingDetailsCountVO;
import com.game.business.vo.AppGameCommissionVO;
import com.game.business.vo.AppUserAgentVO;
import com.game.business.vo.AppUserPAgentVO;
import com.game.common.annotation.Anonymous;
import com.game.common.core.domain.*;
import com.game.common.utils.SecurityUtils;
import com.game.common.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.game.common.annotation.Log;
import com.game.common.core.controller.BaseController;
import com.game.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.game.business.service.IAppUserAgentService;
import com.game.common.utils.poi.ExcelUtil;
import com.game.common.core.page.TableDataInfo;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 用户代理表Controller
 * 
 * @author game
 * @date 2024-06-25
 */
@RestController
@RequestMapping("/business/agent")
@Api(value = "AppUserAgentController", description = "用户代理表接口", tags = {"用户代理表接口"})
public class AppUserAgentController extends BaseController
{
    @Autowired
    private IAppUserAgentService appUserAgentService;

    @Autowired
    private IAppGameCommissionService appGameCommissionService;

    @Autowired
    private IAppGameService appGameService;

    @Autowired
    private IAppUserService appUserService;


    @PostMapping("/addAgent")
    @ApiOperation(value = "添加代理", notes = "添加代理")
    public HttpRet<AppUserAgentVO> addAgent(@RequestBody AppUserDTO appUserDTO)
    {
        appUserDTO.setUserId(SecurityUtils.getUserId());
        if(appUserService.getMobileCount(appUserDTO.getUserName())){
            return HttpRet.fail("用户手机号码已存在。");
        }

        AppUser appUser = getAppUser(appUserDTO.getUserName(), appUserDTO.getPassWord(), appUserDTO.getSmsRegion());

        appUserService.insertAppUser(appUser);

        AppUserAgent pUserAgent = new AppUserAgent();
        pUserAgent.setUserId(appUserDTO.getUserId());
        List<AppUserAgent> pList = appUserAgentService.selectAppUserAgentList(pUserAgent);

        if(pList == null || pList.isEmpty()){
            return HttpRet.fail("上级代理不存在或不是代理。");
        }

        AppUserAgent dbPuserAgent = pList.get(0);

        AppUserAgent appUserAgent = new AppUserAgent();
        appUserAgent.setTopId((dbPuserAgent.getTopId() == null || dbPuserAgent.getTopId() < 1) ? dbPuserAgent.getUserId() : dbPuserAgent.getTopId());
        appUserAgent.setPid(dbPuserAgent.getUserId());
        appUserAgent.setUserId(appUser.getUserid());
        appUserAgent.setAuditStatus("1");
        appUserAgent.setLiveRate(0.00);
        appUserAgent.setDividendGuaranteeRate(0.00);
        appUserAgent.setCreateTime(new Date());

        appUserAgentService.insertAppUserAgent(appUserAgent);

        //更新上级团队人数
        String subset =  dbPuserAgent.getSubset();
        if(StringUtils.isNotBlank(subset)){
            subset = subset.concat(",");
        }else{
            subset = "";
        }
        subset = subset.concat(String.valueOf(appUser.getUserid()));
        AppUserAgent updateUserAgent = new AppUserAgent();
        updateUserAgent.setId(dbPuserAgent.getId());
        updateUserAgent.setSubset(subset);
        appUserAgentService.updateAppUserAgent(updateUserAgent);

        AppUserAgentVO appUserAgentVO = new AppUserAgentVO();
        BeanUtils.copyProperties(appUserAgent, appUserAgentVO);
        appUserAgentVO.setUserId(appUser.getUserid());
        appUserAgentVO.setNickName(appUser.getUsername());
        appUserAgentVO.setAvatar("");

        List<AppGameCommissionVO> gameCommissionVOList = new ArrayList<>();
        List<AppGame> gameList = appGameService.selectAppGameList(new AppGame());
        if(gameList != null && !gameList.isEmpty()){
            for (int i = 0; i < gameList.size(); i++) {
                AppGame appGame = gameList.get(i);

                AppGameCommission appGameCommission = new AppGameCommission();
                appGameCommission.setUserId(appUserAgent.getUserId());
                appGameCommission.setPid(appUserAgent.getPid());
                appGameCommission.setGameId(appGame.getId());
                appGameCommission.setGameRate(0.00);

                if(appGameCommissionService.save(appGameCommission)){
                    AppGameCommissionVO appGameCommissionVO = new AppGameCommissionVO();
                    appGameCommissionVO.setId(appGameCommission.getId());
                    appGameCommissionVO.setPid(dbPuserAgent.getUserId());
                    appGameCommissionVO.setUserId(appUser.getUserid());
                    appGameCommissionVO.setGameRate(0.00);

                    appGameCommissionVO.setGameId(appGame.getId());
                    appGameCommissionVO.setGameName(appGame.getName());
                    appGameCommissionVO.setLogoUrl(appGame.getLogoUrl());
                    appGameCommissionVO.setGamePath(appGame.getGamePath());

                    gameCommissionVOList.add(appGameCommissionVO);
                }
            }
        }

        appUserAgentVO.setCommissions(gameCommissionVOList);

        return HttpRet.success("添加成功", appUserAgentVO);
    }


    @PostMapping("/updateConfig")
    @ApiOperation(value = "修改代理配置", notes = "修改代理配置")
    public HttpRet updateConfig(@RequestBody AppUserAgentDTO appUserAgent)
    {
        if(appUserAgent == null){
            return HttpRet.fail("代理数据为空。");
        }

        if(appUserAgent.getLiveRate() == null || appUserAgent.getLiveRate() > 100){
            return HttpRet.fail("直播佣金参数异常。");
        }

        if(appUserAgent.getDividendGuaranteeRate() == null || appUserAgent.getDividendGuaranteeRate() > 100){
            return HttpRet.fail("保底分红参数异常。");
        }

        AppUserAgent dbUserAgent = new AppUserAgent();
        BeanUtils.copyProperties(appUserAgent, dbUserAgent);
        dbUserAgent.setUserId(null);
        dbUserAgent.setPid(null);
        dbUserAgent.setTopId(null);
        dbUserAgent.setUpdateTime(new Date());
        appUserAgentService.updateAppUserAgent(dbUserAgent);

        if(appUserAgent.getCommissions() != null && !appUserAgent.getCommissions().isEmpty()){
            List<AppGameCommission> commissionList = appUserAgent.getCommissions();
            for(AppGameCommission commission : commissionList){
                if(commission.getId() == null){
                    if(commission.getGameId() == null){
                        continue;
                    }
                    commission.setPid(appUserAgent.getPid());
                    commission.setUserId(appUserAgent.getUserId());
                    appGameCommissionService.insertAppGameCommission(commission);
                }else{
                    commission.setUserId(null);
                    commission.setPid(null);
                    commission.setGameId(null);
                    appGameCommissionService.updateAppGameCommission(commission);
                }
            }
        }

        return  HttpRet.success("修改成功", appUserAgent);
    }

    /**
     * 获取代理成员设置
     */
    @PostMapping(value = "/getUserAgentByUserId")
    @ApiOperation(value = "获取代理配置", notes = "获取代理配置")
    public HttpRet<AppUserAgentVO> getUserAgentByUserId()
    {

        Long userId = SecurityUtils.getUserId();

        AppUserAgent userAgent = new AppUserAgent();
        userAgent.setUserId(userId);
        List<AppUserAgent> userAgents = appUserAgentService.selectAppUserAgentList(userAgent);

        if(userAgents == null || userAgents.isEmpty()){
            return HttpRet.fail("代理信息不存在。");
        }

        AppUserAgent appUserAgent = userAgents.get(0);

        AppUserAgentVO appUserAgentVO = new AppUserAgentVO();
        BeanUtils.copyProperties(appUserAgent, appUserAgentVO);

        AppGameCommission appGameCommission = new AppGameCommission();
        appGameCommission.setPid(appUserAgent.getPid());
        appGameCommission.setUserId(appUserAgent.getUserId());
        List<AppGameCommission> gameCommissions = appGameCommissionService.selectAppGameCommissionList(appGameCommission);
        Map<Long, List<AppGameCommission>> idGameMap;
        if(gameCommissions != null && !gameCommissions.isEmpty()){
            idGameMap = gameCommissions.stream().collect(Collectors.groupingBy(AppGameCommission::getGameId));
        }else{
            idGameMap = new HashMap<>();
        }

        List<AppGameCommissionVO> gameCommissionVOList = new ArrayList<>();

        List<AppGame> gameList = appGameService.selectAppGameList(new AppGame());
        if(gameList != null && !gameList.isEmpty()){
            for (int i = 0; i < gameList.size(); i++) {
                AppGame appGame = gameList.get(i);


                AppGameCommissionVO appGameCommissionVO = new AppGameCommissionVO();
                if(idGameMap.containsKey(appGame.getId())){
                    AppGameCommission gameCommission = idGameMap.get(appGame.getId()).get(0);
                    BeanUtils.copyProperties(gameCommission, appGameCommissionVO);
                }else{
                    appGameCommissionVO.setGameRate(0.00);
                }

                appGameCommissionVO.setGameId(appGame.getId());
                appGameCommissionVO.setGameName(appGame.getName());
                appGameCommissionVO.setLogoUrl(appGame.getLogoUrl());
                appGameCommissionVO.setGamePath(appGame.getGamePath());

                gameCommissionVOList.add(appGameCommissionVO);
            }
        }

        appUserAgentVO.setCommissions(gameCommissionVOList);

        return HttpRet.success("查询成功", appUserAgentVO);
    }

    /**
     * 获取代理成员设置
     */
    @PostMapping(value = "/getUserAgent")
    @ApiOperation(value = "获取代理成员设置", notes = "获取代理成员设置")
    public HttpRet<AppUserPAgentVO> getListByGameId(@RequestParam(name = "pid") Long pid, @RequestParam(name = "userId") Long userId)
    {

        AppUserPAgentVO appUserPAgentVO = new AppUserPAgentVO();

        AppUser appUser = appUserService.selectAppUserByUserid(userId);
        if(appUser == null ){
            return HttpRet.fail("用户信息不存在。");
        }

        AppUserAgent userAgent = new AppUserAgent();
        userAgent.setPid(pid);
        userAgent.setUserId(userId);
        List<AppUserAgent> userAgents = appUserAgentService.selectAppUserAgentList(userAgent);

        if(userAgents == null || userAgents.isEmpty()){
            return HttpRet.fail("代理信息不存在。");
        }

        AppUserAgent userPAgent = new AppUserAgent();
        userPAgent.setUserId(pid);
        List<AppUserAgent> userpAgents = appUserAgentService.selectAppUserAgentList(userPAgent);
        if(userpAgents == null || userpAgents.isEmpty()){
            return HttpRet.fail("上级代理信息不存在。");
        }

        AppUserAgentVO appUserAgentVO = new AppUserAgentVO();
        BeanUtils.copyProperties(userAgents.get(0), appUserAgentVO);
        appUserAgentVO.setUserId(appUser.getUserid());
        appUserAgentVO.setNickName(StringUtils.isEmpty(appUser.getNickname()) ? appUser.getUsername() : appUser.getNickname());
        appUserAgentVO.setAvatar(appUser.getAvatar());

        AppGameCommission appGameCommission = new AppGameCommission();
        appGameCommission.setPid(pid);
        appGameCommission.setUserId(userId);
        List<AppGameCommission> gameCommissions = appGameCommissionService.selectAppGameCommissionList(appGameCommission);
        Map<Long, List<AppGameCommission>> idGameMap;
        if(gameCommissions != null && !gameCommissions.isEmpty()){
            idGameMap = gameCommissions.stream().collect(Collectors.groupingBy(AppGameCommission::getGameId));
        }else{
            idGameMap = new HashMap<>();
        }

        AppUserAgentVO appUserpAgentVO = new AppUserAgentVO();
        BeanUtils.copyProperties(userpAgents.get(0), appUserpAgentVO);

        Map<Long, List<AppGameCommission>> idGamePMap = new HashMap<>();

        if(appUserpAgentVO.getPid() != null){
            AppGameCommission appGamePCommission = new AppGameCommission();
            appGamePCommission.setPid(appUserpAgentVO.getPid());
            appGamePCommission.setUserId(appUserpAgentVO.getUserId());
            List<AppGameCommission> gamePCommissions = appGameCommissionService.selectAppGameCommissionList(appGamePCommission);

            if(gamePCommissions != null && !gamePCommissions.isEmpty()){
                idGamePMap = gamePCommissions.stream().collect(Collectors.groupingBy(AppGameCommission::getGameId));
            }
        }

        if(appUserpAgentVO.getLiveRate() == null){
            appUserpAgentVO.setLiveRate(100.00);
        }
        if(appUserpAgentVO.getDividendGuaranteeRate() == null){
            appUserpAgentVO.setDividendGuaranteeRate(100.00);
        }

        List<AppGameCommissionVO> gameCommissionVOList = new ArrayList<>();
        List<AppGameCommissionVO> gamePCommissionVOList = new ArrayList<>();

        List<AppGame> gameList = appGameService.selectAppGameList(new AppGame());
        if(gameList != null && !gameList.isEmpty()){
            for (int i = 0; i < gameList.size(); i++) {
                AppGame appGame = gameList.get(i);


                AppGameCommissionVO appGameCommissionVO = new AppGameCommissionVO();
                if(idGameMap.containsKey(appGame.getId())){
                    AppGameCommission gameCommission = idGameMap.get(appGame.getId()).get(0);
                    BeanUtils.copyProperties(gameCommission, appGameCommissionVO);
                }else{
                    appGameCommissionVO.setGameRate(0.00);
                }

                appGameCommissionVO.setGameId(appGame.getId());
                appGameCommissionVO.setGameName(appGame.getName());
                appGameCommissionVO.setLogoUrl(appGame.getLogoUrl());
                appGameCommissionVO.setGamePath(appGame.getGamePath());

                gameCommissionVOList.add(appGameCommissionVO);

                AppGameCommissionVO appGamePCommissionVO = new AppGameCommissionVO();
                if(idGamePMap.containsKey(appGame.getId())){
                    AppGameCommission gameCommission = idGamePMap.get(appGame.getId()).get(0);
                    BeanUtils.copyProperties(gameCommission, appGamePCommissionVO);
                }else{
                    appGamePCommissionVO.setGameRate(100.00);
                }
                appGamePCommissionVO.setGameId(appGame.getId());

                gamePCommissionVOList.add(appGamePCommissionVO);
            }
        }

        appUserAgentVO.setCommissions(gameCommissionVOList);
        appUserPAgentVO.setAppUserAgent(appUserAgentVO);

        appUserpAgentVO.setCommissions(gamePCommissionVOList);
        appUserPAgentVO.setAppUserPAgent(appUserpAgentVO);

        return HttpRet.success("查询成功", appUserPAgentVO);
    }

    /**
     * 获取最小限制
     */
    @PostMapping(value = "/getUserAgentMin")
    @ApiOperation(value = "获取最小限制", notes = "获取最小限制")
    public HttpRet<AppUserAgentVO> getUserAgentMin(@RequestParam(name = "pid") Long pid, @RequestParam(name = "userId") Long userId)
    {

        AppUserAgent userAgent = new AppUserAgent();
        userAgent.setPid(pid);
        userAgent.setUserId(userId);
        List<AppUserAgent> userAgents = appUserAgentService.selectAppUserAgentList(userAgent);

        if(userAgents == null || userAgents.isEmpty()){
            return HttpRet.fail("代理信息不存在。");
        }

        AppUserAgent appUserAgent = userAgents.get(0);

        // 初始化代理的费率
        AppUserAgentVO appUserAgentVO = new AppUserAgentVO();
        appUserAgentVO.setDividendGuaranteeRate(0.00);
        appUserAgentVO.setLiveRate(0.00);

        // 设置最小的
        setUserAgentMinRate(appUserAgentVO, userId);

        List<AppGameCommissionVO> gameCommissionVOList = new ArrayList<>();

        // 初始化所有游戏的费率
        List<AppGame> gameList = appGameService.selectAppGameList(new AppGame());
        if(gameList != null && !gameList.isEmpty()){
            for (int i = 0; i < gameList.size(); i++) {
                AppGame appGame = gameList.get(i);

                AppGameCommissionVO appGameCommissionVO = new AppGameCommissionVO();
                appGameCommissionVO.setGameRate(0.00);
                appGameCommissionVO.setGameId(appGame.getId());

                setGameCommissionMinRate(appGameCommissionVO, userId);

                gameCommissionVOList.add(appGameCommissionVO);
            }
        }

        appUserAgentVO.setCommissions(gameCommissionVOList);

        return HttpRet.success("查询成功", appUserAgentVO);
    }

    /**
     * 新增用户
     * @return 用户id
     * @author jiang
     * @date 2021/9/25 16:28
     */
    public AppUser getAppUser(String userName, String password,String smsRegion) {
        AppUser curUser = appUserService.selectAppUserByUserid(SecurityUtils.getUserId());//操作人用户信息

        AppUser appUser = new AppUser();

        appUser.setSalt(RandomUtil.randomString(8));
        appUser.setPassword(Md5Utils.md5(Md5Utils.md5(password) + appUser.getSalt()));
        appUser.setUsername(RandomUtil.randomString(8));
        appUser.setMobile(userName);
        appUser.setNickname(appUser.getUsername());
        appUser.setSmsRegion(smsRegion);
        appUser.setPid(curUser.getUserid());
//        appUser.setInviteCode(curUser.getInviteCode());
        appUser.setInviteBindTime(new Date());
        appUser.setAgentFlag(1);
        appUser.setAvatar(null);
        appUser.setSex(0L);
        appUser.setSignature("这家伙很懒...");

        // 基础信息
//        appUser.setMobile(mobile);
        appUser.setRegType(0L);
        appUser.setOpenid(null);
        appUser.setRegisterIp("127.0.0.1");
        appUser.setRegType(0L);
        appUser.setCreateTime(new Date());
        appUser.setLoginType("1");

        appUser.setUserType(2L);
        appUser.setBirthday("1990-01-01");
        appUser.setStatus(0L);
        appUser.setDelFlag(0L);
        appUser.setIshot(1L);
        appUser.setIsRecommend(0L);
        appUser.setIssuper(1L);
        appUser.setRole(0L);
        appUser.setCity("墨西哥");
        appUser.setAddress("墨西哥");
        appUser.setLat(114.31);
        appUser.setLng(30.52);

        // 用户开关
        appUser.setGiftGlobalBroadcast(1L);
        appUser.setIsShowHomePage(1L);

        // 金币相关
        appUser.setCoin(0.00);
        appUser.setVotes(0.00);
        appUser.setAmount(0.00);
        appUser.setTotalAmount(0.00);
        appUser.setVotestotal(0.00);
        appUser.setTotalCharge(0.00);
        appUser.setTotalAmountCash(0.00);
        appUser.setTotalCash(0.00);
        appUser.setConsumption(0.00);

        // 等级积分相关
        appUser.setUserPoint(0L);
        appUser.setAnchorPoint(0L);
        appUser.setCharmPoint(0L);
        appUser.setUserGrade(1L);
        appUser.setAnchorGrade(1L);
        appUser.setWealthGrade(1L);
        appUser.setNobleGrade(0L);
        appUser.setCharmGrade(0L);

        appUser.setIsShowHomePage(1L);
        appUser.setIpaddr("墨西哥");
        appUser.setAppVersion(null);
        appUser.setAppVersionCode(null);
        appUser.setPhoneSystem(null);
        appUser.setPhoneFirm(null);
        appUser.setPhoneModel(null);
        appUser.setPhoneUuid(null);
        appUser.setSource(null);
        appUser.setIszombie(1L);
        appUser.setIszombiep(1L);

        return appUser;
    }

    public void setUserAgentMinRate(AppUserAgentVO appUserAgentVO, Long userId){

        AppUserAgent userAgent = new AppUserAgent();
        userAgent.setPid(userId);
        List<AppUserAgent> userAgents = appUserAgentService.selectAppUserAgentList(userAgent);

        if(userAgents == null || userAgents.isEmpty()){
            return;
        }

        // 排序
        List<AppUserAgent> sortLives = userAgents.stream().sorted(Comparator.comparing(AppUserAgent::getLiveRate)).collect(Collectors.toList());
        appUserAgentVO.setLiveRate(sortLives.get(0).getLiveRate());
        List<AppUserAgent> sortDividendGuarantee = userAgents.stream().sorted(Comparator.comparing(AppUserAgent::getDividendGuaranteeRate)).collect(Collectors.toList());
        appUserAgentVO.setLiveRate(sortDividendGuarantee.get(0).getDividendGuaranteeRate());
        setUserAgentMinRate(appUserAgentVO, userId);
    }


    private void setGameCommissionMinRate(AppGameCommissionVO appGameCommissionVO, Long userId){

        AppGameCommission appGameCommission = new AppGameCommission();
        appGameCommission.setGameId(appGameCommissionVO.getGameId());
        appGameCommission.setPid(userId);
        List<AppGameCommission> gameCommissions = appGameCommissionService.selectAppGameCommissionList(appGameCommission);

        if(gameCommissions == null || gameCommissions.isEmpty()){
            return;
        }

        // 排序
        List<AppGameCommission> sortGameCommissions = gameCommissions.stream().sorted(Comparator.comparing(AppGameCommission::getGameRate)).collect(Collectors.toList());
        appGameCommissionVO.setGameRate(sortGameCommissions.get(0).getGameRate());
        setGameCommissionMinRate(appGameCommissionVO, userId);
    }

    @PostMapping(value = "/updateSetting")
    @ApiOperation(value = "更新代理成员设置", notes = "更新代理成员设置")
    @PreAuthorize("@ss.hasPermi('business:user:updateSetting')")
    @Log(title = "用户代理设置-更新直播、分红待遇", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public R<String> updateSetting(@RequestBody AppUserAgent appUserAgent){
        AppUserAgent userAgent = appUserAgentService.selectInfo(appUserAgent.getUserId());
        if(null == userAgent){
            return R.fail("修改失败，代理信息不存在");
        }
        if(userAgent.getPid().doubleValue() == 0){
            return R.fail("顶级账号禁止修改");
        }
        //查询上级
        AppUserAgent superAgent = appUserAgentService.selectInfo(userAgent.getPid());
        if(1 == appUserAgent.getUpType().intValue() && superAgent.getDividendGuaranteeRate().doubleValue() < appUserAgent.getDividendGuaranteeRate().doubleValue()){
            return R.fail("修改失败，保底分红超过上级分红比例请先修改上级");
        }
        if(0 == appUserAgent.getUpType().intValue() && superAgent.getLiveRate().doubleValue() < appUserAgent.getLiveRate().doubleValue()){
            return R.fail("修改失败，直播分成超过上级分红比例请先修改上级");
        }
        //查询下级
        /*AppUserAgent queryAgent = new AppUserAgent();
        queryAgent.setPid(userAgent.getUserId());
        List<AppUserAgent> downAgents = appUserAgentService.selectAppUserAgentList(queryAgent);
        if(null != downAgents && downAgents.size() > 0){
            double dividendGuaranteeRate = downAgents.stream().mapToDouble(e->e.getDividendGuaranteeRate()).max().getAsDouble();
            if(appUserAgent.getDividendGuaranteeRate() < dividendGuaranteeRate){
                return R.fail("修改失败，保底分红超过最小可修改值：" + dividendGuaranteeRate);
            }
            double liveRate = downAgents.stream().mapToDouble(e->e.getLiveRate()).max().getAsDouble();
            if(appUserAgent.getLiveRate() < liveRate){
                return R.fail("修改失败，直播分成超过最小可修改值：" + liveRate);
            }
        }*/
        AppUserAgent updateAgent = new AppUserAgent();
        updateAgent.setId(userAgent.getId());
        if(appUserAgent.getUpType().intValue() == 0){
            updateAgent.setLiveRate(appUserAgent.getLiveRate());
        }else if(appUserAgent.getUpType().intValue() == 1){
            updateAgent.setDividendGuaranteeRate(appUserAgent.getDividendGuaranteeRate());
        }
        appUserAgentService.updateAppUserAgent(updateAgent);
        upRate(userAgent.getUserId(),appUserAgent.getUpType().intValue()==0?appUserAgent.getLiveRate():appUserAgent.getDividendGuaranteeRate(),appUserAgent.getUpType());
        return R.ok("修改成功");
    }

    private void upRate(Long userId,Double rate,Integer upType){
        double newRate = rate - 0.1;
        if(newRate < 0){
            newRate = 0.0;
        }
        //查询下级大于等于当前分红比例的用户
        List<AppUserAgent> downAgents = appUserAgentService.selectDownByRate(userId,rate,upType);
        if(null != downAgents && downAgents.size() > 0){
            for(AppUserAgent downAgent : downAgents){
                AppUserAgent updateAgent = new AppUserAgent();
                updateAgent.setId(downAgent.getId());
                if(0 == upType.intValue()){
                    updateAgent.setLiveRate(newRate);
                }else if(1 == upType.intValue()){
                    updateAgent.setDividendGuaranteeRate(newRate);
                }
                appUserAgentService.updateAppUserAgent(updateAgent);

                upRate(downAgent.getUserId(),newRate,upType);
            }
        }
    }
}
