package com.game.business.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.rmi.ServerException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.game.business.domain.*;
import com.game.business.dto.AppAgentEditDto;
import com.game.business.dto.AppAgentTeamDto;
import com.game.business.dto.AppUserTeamTranserDto;
import com.game.business.service.*;
import com.game.business.vo.AppAgentTeamVo;
import com.game.common.constant.AppSceneType;
import com.game.common.constant.finance.FinTranAddedInfo;
import com.game.common.constant.finance.FinTranType1;
import com.game.common.constant.finance.FinTranType3;
import com.game.common.constant.finance.TranCurrencyType;
import com.game.common.core.domain.HttpRet;
import com.game.common.utils.DateUtils;
import com.game.common.utils.MessageUtils;
import com.game.common.utils.SecurityUtils;
import com.game.common.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.game.business.mapper.AppUserAgentMapper;
import com.game.common.annotation.DataSource;
import com.game.common.enums.DataSourceType;

/**
 * 用户代理表Service业务层处理
 *
 * @author game
 * @date 2024-06-25
 */
@Service
public class AppUserAgentServiceImpl extends ServiceImpl<AppUserAgentMapper, AppUserAgent> implements IAppUserAgentService {

    @Autowired
    private AppUserAgentMapper appUserAgentMapper;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IAppGameCommissionService gameCommissionService;

    @Autowired
    private IAppGameService appGameService;

    @Autowired
    private IAppUserCountService appUserCountService;

    /**
     * 查询用户代理表
     *
     * @param id 用户代理表主键
     * @return 用户代理表
     */
    @Override
    public AppUserAgent selectAppUserAgentById(Long id) {
        return appUserAgentMapper.selectAppUserAgentById(id);
    }

    /**
     * 查询用户代理表列表
     *
     * @param appUserAgent 用户代理表
     * @return 用户代理表
     */
    @Override
    public List<AppUserAgent> selectAppUserAgentList(AppUserAgent appUserAgent) {
        return appUserAgentMapper.selectAppUserAgentList(appUserAgent);
    }

    /**
     * 新增用户代理表
     *
     * @param appUserAgent 用户代理表
     * @return 结果
     */
    @Override
    public int insertAppUserAgent(AppUserAgent appUserAgent) {
                appUserAgent.setCreateTime(DateUtils.getNowDate());
            return appUserAgentMapper.insertAppUserAgent(appUserAgent);
    }

    /**
     * 修改用户代理表
     *
     * @param appUserAgent 用户代理表
     * @return 结果
     */
    @Override
    public int updateAppUserAgent(AppUserAgent appUserAgent) {
                appUserAgent.setUpdateTime(DateUtils.getNowDate());
        return appUserAgentMapper.updateAppUserAgent(appUserAgent);
    }

    /**
     * 批量删除用户代理表
     *
     * @param ids 需要删除的用户代理表主键
     * @return 结果
     */
    @Override
    public int deleteAppUserAgentByIds(Long[] ids) {
        return appUserAgentMapper.deleteAppUserAgentByIds(ids);
    }

    /**
     * 删除用户代理表信息
     *
     * @param id 用户代理表主键
     * @return 结果
     */
    @Override
    public int deleteAppUserAgentById(Long id) {
        return appUserAgentMapper.deleteAppUserAgentById(id);
    }

    /**
     * 统计用户代理人数
     * */
    @Override
    public int countAgent(Long userId, String beginTime, String endTime) {
        LambdaQueryWrapper<AppUserAgent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUserAgent::getPid,userId);
        if(StringUtils.isNotBlank(beginTime)){
            queryWrapper.ge(AppUserAgent::getCreateTime,beginTime);
        }
        if(StringUtils.isNotBlank(endTime)){
            queryWrapper.le(AppUserAgent::getCreateTime,endTime);
        }
        queryWrapper.eq(AppUserAgent::getAuditStatus,"1");
        return appUserAgentMapper.selectCount(queryWrapper).intValue();
    }

    /**
     * 统计用户团队投注金额
     * */
    @Override
    public Double sumBetting(String beginTime,String endTime,Long pid) {
        return appUserAgentMapper.sumBetting(beginTime,endTime,pid);
    }

    @Override
    public HttpRet<Boolean> updateSetting(AppAgentEditDto editDto) {
        Long userId = SecurityUtils.getUserId();
        if(null != editDto.getUserId()){
            userId = editDto.getUserId();
        }
        LambdaQueryWrapper<AppUserAgent>  queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUserAgent::getUserId,userId);
        AppUserAgent userAgent = appUserAgentMapper.selectOne(queryWrapper);
        if(userAgent == null){
            return HttpRet.fail("当前用户不是代理无法进行设置");
        }
        if(null != editDto.getUserId() && !SecurityUtils.getUserId().equals(userAgent.getPid())){
            return HttpRet.fail("只能设置自己的下级代理");
        }
        if(!userAgent.getPid().equals(0L)){
            //当前用户有上级
            //查询上级代理设置
            LambdaQueryWrapper<AppUserAgent>  queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(AppUserAgent::getUserId,userId);
            AppUserAgent pUser = appUserAgentMapper.selectOne(queryWrapper2);
            if(null != editDto.getLiveRate() && editDto.getLiveRate().longValue() >= pUser.getLiveRate().longValue()){
                return HttpRet.fail("直播分成比例不能大于等于".concat(String.valueOf(pUser.getLiveRate())));
            }
            if(null != editDto.getDividendGuaranteeRate() && editDto.getDividendGuaranteeRate().longValue() >= pUser.getDividendGuaranteeRate().longValue()){
                return HttpRet.fail("保底分成比例不能大于等于".concat(String.valueOf(pUser.getLiveRate())));
            }
        }
        AppUserAgent update = new AppUserAgent();
        BeanUtils.copyProperties(editDto,update);
        update.setId(userAgent.getId());
        appUserAgentMapper.updateById(update);
        return HttpRet.success(MessageUtils.message("11022"),true);
    }

    @Override
    public List<AppAgentTeamVo> teamList(AppAgentTeamDto teamDto) {
        if(null == teamDto.getPid()) {
            teamDto.setPid(SecurityUtils.getUserId());
        }
        if(StringUtils.isBlank(teamDto.getBeginTime()) || StringUtils.isBlank(teamDto.getEndTime())){
            /*teamDto.setBeginTime(DateUtil.format(DateUtil.beginOfMonth(DateUtils.getNowDate()), "yyyy-MM-dd"));
            teamDto.setEndTime(DateUtil.format(DateUtil.endOfMonth(DateUtils.getNowDate()), "yyyy-MM-dd"));*/
            //默认查询当前周期
            Date now = DateUtils.getNowDate();
            int curDay = Integer.parseInt(DateUtil.format(now,"dd"));

            Date weekBegin = null;
            Date weekend = null;
            if(curDay <= 15){
                weekBegin = DateUtil.beginOfMonth(now);
                weekend = DateUtil.parse(DateUtil.format(now,"yyyy-MM-".concat("15").concat(" 23:59:59")),"yyyy-MM-dd HH:mm:ss");
            }else{
                weekBegin = DateUtil.parse(DateUtil.format(now,"yyyy-MM-".concat("15").concat(" 00:00:00")),"yyyy-MM-dd HH:mm:ss");
                weekend = DateUtil.endOfMonth(now);
            }
            teamDto.setBeginTime(DateUtil.format(weekBegin,"yyyy-MM-dd"));
            teamDto.setEndTime(DateUtil.format(weekend,"yyyy-MM-dd"));
        }
        List<AppAgentTeamVo> list = appUserAgentMapper.teamListNew(teamDto);
        if(null != list && list.size() > 0){
            list.forEach(e->{
                List<AppUserAgent> appUserAgentList = appUserAgentMapper.selectAllAgentList(e.getUserId(),null,null,null);
                if(null != appUserAgentList && appUserAgentList.size() > 0){
                    e.setTeamNum(appUserAgentList.size());
                }else{
                    e.setTeamNum(0);
                }
            });
            List<Long> ids = list.stream().map(e->{return e.getUserId();}).collect(Collectors.toList());
            //查询游戏分红比例
            List<AppGameCommission> gameCommissionList = gameCommissionService.getByIds(ids);
            List<AppGame> gameList = appGameService.selectAppGameList(new AppGame());
            if(null != gameCommissionList && gameCommissionList.size() > 0){
                Map<String,List<AppGameCommission>> map = gameCommissionList.stream().
                        collect(Collectors.groupingBy(j->String.valueOf(j.getUserId())));
                list.forEach(e->{
                    if(null != map.get(String.valueOf(e.getUserId()))){
                        List<AppGameCommission> commissionList = map.get(String.valueOf(e.getUserId()));
                        commissionList.forEach(commission->{
                            if(null == commission.getPid()){
                                commission.setPid(e.getPid());
                            }
                        });
                        e.setGameCommissionList(commissionList);
                    }else if(null != gameList && gameList.size() > 0){
                        e.setGameCommissionList(gameList.stream().map(j->{
                            AppGameCommission gameCommission = new AppGameCommission();
                            gameCommission.setUserId(e.getUserId());
                            gameCommission.setGameId(j.getId());
                            gameCommission.setGameName(j.getName());
                            gameCommission.setPid(e.getPid());
                            gameCommission.setGameRate(0.00);
                            return gameCommission;
                        }).collect(Collectors.toList()));
                    }
                    if(!teamDto.getPid().equals(e.getUserId())) {
                        //非当前用户则统计整条线用户数据
                        List<AppUserCount> appUserCountList = appUserCountService.getAppUserCountNew(e.getUserId(), teamDto.getBeginTime(), teamDto.getEndTime());
                        if (null != appUserCountList && appUserCountList.size() > 0) {
                            DecimalFormat df = new DecimalFormat("#.##");
                            //下注金额
                            e.setBettingAmount(BigDecimal.valueOf(appUserCountList.stream().mapToDouble(AppUserCount::getGameBetting).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                            //直播返点
                            e.setLiveCommission(BigDecimal.valueOf(appUserCountList.stream().mapToDouble(AppUserCount::getLiveCommission).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                            //游戏返点
                            e.setGameCommission(BigDecimal.valueOf(appUserCountList.stream().mapToDouble(j->
                                {
                                    return j.getGameCommission() - j.getLiveBettingCommission() + j.getRechargeCommission() + j.getWithdrawalCommission();
                                }
                            ).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                            //直播间下注返点
                            e.setLiveBettingCommission(BigDecimal.valueOf(appUserCountList.stream().mapToDouble(j->
                                {
                                    return j.getLiveBettingCommission();
                                }
                            ).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                            //盈亏
                            e.setGameAmount(BigDecimal.valueOf(appUserCountList.stream().mapToDouble(userCount -> {
                                return ((userCount.getGameWinAmount() - (userCount.getGameBetting() - userCount.getGameLoseAmount()))
                                        - userCount.getGameLoseAmount()) + userCount.getGameCommission() + userCount.getRechargeGive()
                                        + userCount.getRechargeCommission() + userCount.getWithdrawalCommission();
                            }).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                            //充值金额（由于统计的金额是扣除了手续费并且加上赠送金额的值 故这么计算出原始充值金额）
                            e.setRechargeAmount(BigDecimal.valueOf(appUserCountList.stream().mapToDouble(userCount -> {
                                return userCount.getRechargeAmount();
                            }).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                            //充值手续费
                            e.setRechargeCommission(BigDecimal.valueOf(appUserCountList.stream().mapToDouble(AppUserCount::getRechargeCommission).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                            //充值赠送金额
                            e.setRechargeGive(BigDecimal.valueOf(appUserCountList.stream().mapToDouble(AppUserCount::getRechargeGive).sum()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                        } else {
                            //下注金额
                            e.setBettingAmount(0.00);
                            //直播返点
                            e.setLiveCommission(0.00);
                            //游戏返点
                            e.setGameCommission(0.00);
                            //盈亏
                            e.setGameAmount(0.00);
                            //充值金额（由于统计的金额是扣除了手续费并且加上赠送金额的值 故这么计算出原始充值金额）
                            e.setRechargeAmount(0.00);
                            //充值手续费
                            e.setRechargeCommission(0.00);
                            //充值赠送金额
                            e.setRechargeGive(0.00);
                        }
                    }
                });
            }
        }
        return list;
    }

    @Override
    public HttpRet<String> transfer(AppUserTeamTranserDto transfer) {
        AppUser toAppUser = appUserService.selectAppUserByUserid(transfer.getToUserId());
        AppUser appUser = appUserService.selectAppUserByUserid(SecurityUtils.getUserId());
        if(null == toAppUser){
            return HttpRet.fail("受益用户不存在");
        }
        if(appUser.getDiamondCoin().longValue() < transfer.getMoney().longValue()){
            return HttpRet.fail("转账金额不足");
        }
        //当前用户扣减余额
        AppUser updateAppUser = new AppUser();
        updateAppUser.setUserid(appUser.getUserid());
        updateAppUser.setDiamondCoin(appUser.getDiamondCoin() - transfer.getMoney());
        FinTranAddedInfo addedInfo = FinTranAddedInfo.createTranInfo(appUser.getUserid(), 0, 0, AppSceneType.Scene_None, "");
        FinTranRecord tran = FinTranRecord.initFinTranRecordSomeParams(addedInfo, FinTranType3.TRANSFER_TO_TEAM_DiamondCoin, FinTranType1.U_Outcome_Balance, appUser);
        tran.setDiamondCoinChange(transfer.getMoney());
        tran.setAfterDiamondCoin(appUser.getDiamondCoin() + transfer.getMoney());
        tran.setCurrencyType(TranCurrencyType.Balance.getType());
        return null;
    }

    @Override
    public List<AppUserAgent> selectAllAgentList(Long pid, Long userId,String beginTime,String endTime) {
        List<AppUserAgent> list = appUserAgentMapper.selectAllAgentList(pid,userId,beginTime,endTime);
        if(null == list){
            list = new ArrayList<>();
        }
        return list;
    }

    @Override
    public AppUserAgent selectInfo(Long userId) {
        LambdaQueryWrapper<AppUserAgent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUserAgent::getUserId,userId);
        queryWrapper.eq(AppUserAgent::getAuditStatus,1);
        return appUserAgentMapper.selectOne(queryWrapper);
    }

}