package com.kxs.stat.biz.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.constant.CommonConstants;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.AssertUtil;
import com.kxs.common.core.util.R;
import com.kxs.common.core.util.RetOps;
import com.kxs.common.core.util.TotalDateUtil;
import com.kxs.common.mybatis.handler.MonthTableNameHandler;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.product.api.feign.RemoteKxsProductService;
import com.kxs.product.api.model.KxsBrand;
import com.kxs.stat.api.dto.statUser.StatUserGetMyTradeDTO;
import com.kxs.stat.api.dto.statUser.StatUserGetTradeDetailDTO;
import com.kxs.stat.api.dto.statUser.StatUserGetUserStatByDayOrMonthDTO;
import com.kxs.stat.api.dto.statUser.StatUserGetUserTradeListDTO;
import com.kxs.stat.api.model.*;
import com.kxs.stat.api.vo.ShdTradeAmtVO;
import com.kxs.stat.api.vo.TotalTradeAmtVO;
import com.kxs.stat.api.vo.myUser.*;
import com.kxs.stat.api.vo.statUser.*;
import com.kxs.stat.biz.constant.enums.TotalTypeEnum;
import com.kxs.stat.biz.mapper.*;
import com.kxs.stat.biz.service.KxsUserActTradeService;
import com.kxs.stat.biz.service.KxsUserNewTradeService;
import com.kxs.stat.biz.service.KxsUserTradeService;
import com.kxs.user.api.dto.kxsapp.IntegralStatDTO;
import com.kxs.user.api.feign.RemoteKxsUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 个人交易统计总表(KxsUserTrade)表服务实现类
 *
 * @author 系统
 * @since 2024-05-07 17:25:06
 */
@Service("kxsUserTradeService")
@RequiredArgsConstructor
@Slf4j
public class KxsUserTradeServiceImpl extends ServiceImpl<KxsUserTradeMapper, KxsUserTrade> implements KxsUserTradeService {
    private final RemoteKxsUserService remoteKxsUserService;
    private final RemoteKxsProductService remoteKxsProductService;

    private final PlatformTransactionManager platformTransactionManager;

    private final KxsUserActTradeService kxsUserActTradeService;
    private final KxsUserActTradeMapper kxsUserActTradeMapper;

    private final KxsLkbTradeMapper kxsLkbTradeMapper;

    private final KxsUserLogoutTradeMapper kxsUserLogoutTradeMapper;

    private final KxsUserNewTradeService kxsUserNewTradeService;
    private final KxsUserNewTradeMapper kxsUserNewTradeMapper;

    private final KxsZlbTradeMapper kxsZlbTradeMapper;
    private final static String PREFIX_TABLE_NAME = CommonConstants.USER_TABLE_PREFIX;

    private final static String PREFIX_TABLE_NAME_AFTER = CommonConstants.USER_TABLE_AFTER_PREFIX;
    private final static String PREFIX_TABLE_NAME_BEFORE = CommonConstants.USER_TABLE_BEFORE_PREFIX;


    private final static String PREFIX_TABLE_NAME_TEMP = "kxs_user_trade_temp_";
    private final KxsUserGdTradeMapper kxsUserGdTradeMapper;
    private final KxsLkbActTradeMapper kxsLkbActTradeMapper;

    private  Map<Integer, KxsBrand> brandsMap;

    @Override
    @Async
    public void getUserTradeList(String para) {
        //拼接表名
        String thisMoth;
        //如果定时任务传了参数就使用定时任务的参数
        if (StrUtil.isNotBlank(para)) {
            thisMoth = para;
        } else {
            thisMoth = LocalDateTimeUtil.format(LocalDate.now(), DatePattern.SIMPLE_MONTH_PATTERN);
        }

        String version = LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_FORMATTER);
        //计算增量的pos交易
//        String tableName = PREFIX_TABLE_NAME + "after_" + thisMoth;
        String tableName = PREFIX_TABLE_NAME + thisMoth;
        String tempTableName = PREFIX_TABLE_NAME_TEMP + thisMoth;

        int batchSize = 20;
        TransactionTemplate template = new TransactionTemplate(platformTransactionManager);
        template.execute(status -> {
            //创建临时表
            baseMapper.createTemporaryShdTable(tempTableName);

            //查询pos交易
            Cursor<ShdTradeAmtVO> kxsUserTrades = baseMapper.getUserTradeList(tableName);
            for (ShdTradeAmtVO kxsUserTrade : kxsUserTrades) {
                ShdTradeAmtVO shdTradeAmtVO = baseMapper.getTempShdTableData(tempTableName, kxsUserTrade.getUserId());
                if (shdTradeAmtVO == null) {
                    shdTradeAmtVO = new ShdTradeAmtVO();
                    shdTradeAmtVO.setUserId(kxsUserTrade.getUserId());
                    shdTradeAmtVO.setPosAmt(kxsUserTrade.getPosAmt());
                    baseMapper.insertTempShdTableData(tempTableName, shdTradeAmtVO);
                } else {
                    shdTradeAmtVO.setPosAmt(shdTradeAmtVO.getPosAmt());
                    baseMapper.updateTempShdTableData(tempTableName, shdTradeAmtVO);
                }

            }
            //查询lkb交易
            Cursor<KxsLkbTrade> lkbTrades = kxsLkbTradeMapper.getUserTradeMonthList(thisMoth);
            for (KxsLkbTrade lkbTrade : lkbTrades) {
                ShdTradeAmtVO shdTradeAmtVO = baseMapper.getTempShdTableData(tempTableName, lkbTrade.getUserId());
                if (shdTradeAmtVO == null) {
                    shdTradeAmtVO = new ShdTradeAmtVO();
                    shdTradeAmtVO.setUserId(lkbTrade.getUserId());
                    shdTradeAmtVO.setLkbAmt(lkbTrade.getTradeAmt());
                    //活动交易 * 4加入
                    if (lkbTrade.getActTradeAmt() != null) {
                        shdTradeAmtVO.setLkbActAmt(lkbTrade.getActTradeAmt().multiply(BigDecimal.valueOf(4)));
                    }
                    baseMapper.insertTempShdTableData(tempTableName, shdTradeAmtVO);
                } else {
                    shdTradeAmtVO.setLkbAmt(lkbTrade.getTradeAmt());
                    //活动交易 * 4加入
                    if (lkbTrade.getActTradeAmt() != null) {
                        shdTradeAmtVO.setLkbActAmt(lkbTrade.getActTradeAmt().multiply(BigDecimal.valueOf(4)));
                    }
                    baseMapper.updateTempShdTableData(tempTableName, shdTradeAmtVO);
                }
            }
            //查询广电交易数据
            Cursor<KxsUserActTrade> kxsUserActTrades = kxsUserActTradeMapper.getUserTradeMonthList(thisMoth);
            for (KxsUserActTrade kxsUserActTrade : kxsUserActTrades) {
                //总激活数
                int actNum = kxsUserActTrade.getActNum();
                //查询注销的广电卡
                KxsUserLogoutTrade kxsUserLogoutTrade = kxsUserLogoutTradeMapper.selectOne(Wrappers.<KxsUserLogoutTrade>lambdaQuery()
                        .eq(KxsUserLogoutTrade::getUserId, kxsUserActTrade.getUserId())
                        .eq(KxsUserLogoutTrade::getTotalType, TotalTypeEnum.TEAM.getType()).last("limit 1"));
                //总激活数 减去注销的卡 = 实际激活总数
                if (kxsUserLogoutTrade != null) {
                    actNum = actNum - kxsUserLogoutTrade.getLogoutNum();
                }
                ShdTradeAmtVO shdTradeAmtVO = baseMapper.getTempShdTableData(tempTableName, kxsUserActTrade.getUserId());
                if (shdTradeAmtVO == null) {
                    shdTradeAmtVO = new ShdTradeAmtVO();
                    shdTradeAmtVO.setUserId(kxsUserActTrade.getUserId());
                    //广电卡 * 10000加入
                    shdTradeAmtVO.setGdAmt(NumberUtil.mul(actNum, CommonConstants.GD_CARDINAL_NUMBER));
                    baseMapper.insertTempShdTableData(tempTableName, shdTradeAmtVO);
                } else {
                    //广电卡 * 10000加入
                    shdTradeAmtVO.setGdAmt(NumberUtil.mul(actNum, CommonConstants.GD_CARDINAL_NUMBER));
                    baseMapper.updateTempShdTableData(tempTableName, shdTradeAmtVO);
                }
            }

            Cursor<ShdTradeAmtVO> shdTradeAmtVOList = baseMapper.getTempShdTableList(tempTableName);
            List<IntegralStatDTO> batch = new ArrayList<>();
            for (ShdTradeAmtVO kxsUserTrade : shdTradeAmtVOList) {
                //pos交易额 + 来客吧非活动交易额
                BigDecimal totalAmount = BigDecimal.ZERO;
                if (kxsUserTrade.getPosAmt() != null) {
                    totalAmount = totalAmount.add(kxsUserTrade.getPosAmt());
                }
                if (kxsUserTrade.getLkbAmt() != null) {
                    totalAmount = totalAmount.add(kxsUserTrade.getLkbAmt());
                }
                if (kxsUserTrade.getGdAmt() != null) {
                    totalAmount = totalAmount.add(kxsUserTrade.getGdAmt());
                }
                if (kxsUserTrade.getLkbActAmt() != null) {
                    totalAmount = totalAmount.add(kxsUserTrade.getLkbActAmt());
                }
                if (totalAmount.compareTo(CommonConstants.MAX_TOTAL_AMT) >= 0) {
                    IntegralStatDTO integralStatDTO = new IntegralStatDTO();
                    integralStatDTO.setTradeMonth(thisMoth);
                    integralStatDTO.setUserId(Long.valueOf(kxsUserTrade.getUserId()));
                    integralStatDTO.setTotalAmount(totalAmount);
                    integralStatDTO.setVersion(Long.valueOf(version));
                    batch.add(integralStatDTO);
                    log.info("用户{}交易额达标：{}", kxsUserTrade.getUserId(), totalAmount);
                }
                if (batch.size() >= batchSize) {
                    remoteKxsUserService.integralStat(batch, SecurityConstants.FROM_IN);
                    batch.clear();
                }
            }
            // 处理最后一批数据
            if (!batch.isEmpty()) {
                remoteKxsUserService.integralStat(batch, SecurityConstants.FROM_IN);
            }
            return null;
        });

        baseMapper.removeTempTable(tempTableName);
    }

    @Override
    public BigDecimal getStatAmount(String month) {
        //拼接表名
        String tableName = PREFIX_TABLE_NAME + month;
        return baseMapper.getStatAmount(tableName);
    }

    @Override
    public R getUserStatByDayOrMonth(StatUserGetUserStatByDayOrMonthDTO param) {
        Long userId = param.getUserId();
        Integer type = param.getType();
        LocalDate now = LocalDate.now();
        List<Integer> times;
        StatUserGetUserStatByDayOrMonthVO statUserGetUserStatByDayOrMonthVO = new StatUserGetUserStatByDayOrMonthVO();
        if (type == 0) {
            times = TotalDateUtil.getDayList(now.minusDays(1), 7);
        } else if (type == 1) {
            //近半年
            times = TotalDateUtil.getMonthList(now.minusDays(1), 6);
        } else {
            return R.failed("类型错误");
        }

        //交易趋势图
        List<TrendVO> trendVOList = setTradeTrend(userId, times, type, TotalTypeEnum.TEAM.getType());
        statUserGetUserStatByDayOrMonthVO.setTradeTrend(trendVOList);

        //交易占比
        List<PercentVO> percentVOList = setTradeTotalAndPercent(userId, times, type);
        statUserGetUserStatByDayOrMonthVO.setTradePercent(percentVOList);

        //激活商户占比
        List<MchActPercentVO> mchActPercentList = kxsUserActTradeMapper.getMchActTimePercent(userId, times, type, TotalTypeEnum.TEAM.getType());
        mchActPercentList.forEach(item -> item.setName(getBrandMap().get(item.getBrandId()).getName()));
        statUserGetUserStatByDayOrMonthVO.setActMchPercent(mchActPercentList);

        //新增激活商户趋势图
        List<TrendVO> addMchTrendList = kxsUserActTradeService.getAddActMchTrend(userId, times, type, TotalTypeEnum.TEAM.getType(), getBrandMap());
        statUserGetUserStatByDayOrMonthVO.setMchAddTrend(addMchTrendList);

        //新增创客趋势图
        List<UserAddTrendVO> userAddTrendVOList = kxsUserNewTradeService.getAddUserTrend(userId, times, type, TotalTypeEnum.TEAM.getType());
        statUserGetUserStatByDayOrMonthVO.setUserAddTrend(userAddTrendVOList);

        return R.ok(statUserGetUserStatByDayOrMonthVO);
    }

    @Override
    public R getUserTrend(Integer totalType, Integer type) {

        Long userId = SecurityUtils.getUser().getId();
        LocalDate now = LocalDate.now();
        List<Integer> times;
        StatUserGetUserStatByDayOrMonthVO statUserGetUserStatByDayOrMonthVO = new StatUserGetUserStatByDayOrMonthVO();
        if (type == 0) {
            times = TotalDateUtil.getDayList(now.minusDays(1), 7);
        } else if (type == 1) {
            //近半年
            times = TotalDateUtil.getMonthList(now.minusDays(1), 6);
        } else {
            return R.failed("类型错误");
        }

        //交易趋势图
        List<TrendVO> trendVOList = setTradeTrend(userId, times, type, totalType);
        statUserGetUserStatByDayOrMonthVO.setTradeTrend(trendVOList);

        //新增激活商户趋势图
        List<TrendVO> addMchTrendList = kxsUserActTradeService.getAddActMchTrend(userId, times, type, totalType, brandsMap);
        statUserGetUserStatByDayOrMonthVO.setMchAddTrend(addMchTrendList);

        //新增创客趋势图
        List<UserAddTrendVO> userAddTrendVOList = kxsUserNewTradeService.getAddUserTrend(userId, times, type, totalType);
        statUserGetUserStatByDayOrMonthVO.setUserAddTrend(userAddTrendVOList);

        return R.ok(statUserGetUserStatByDayOrMonthVO);
    }

    @Override
    public R getHomeAmount(Long userId) {
        LocalDate now = LocalDate.now();
        Integer month = TotalDateUtil.getMonthNumber(now);
        Integer today = TotalDateUtil.getDateNumber(now);
        //拼接表名
        String tableName = PREFIX_TABLE_NAME + month;
        //今日交易额
        StatUserGetHomeAmoutVO statUserGetHomeAmoutVO = new StatUserGetHomeAmoutVO();

        //获取团队日总交易额
        BigDecimal amountToDay = getAmountToDayOrMonth(userId, today, tableName, TotalTypeEnum.TEAM.getType());
        statUserGetHomeAmoutVO.setAmountToDay(amountToDay);

        //获取团队月总交易额
        BigDecimal amountMonth = getAmountToDayOrMonth(userId, month, tableName, TotalTypeEnum.TEAM.getType());
        statUserGetHomeAmoutVO.setAmountMonth(amountMonth);

        //获取今日新增用户
        statUserGetHomeAmoutVO.setUserAddToDay(kxsUserNewTradeMapper.selectToDayOrMonthCount(userId, today, TotalTypeEnum.TEAM.getType()));
        //获取本月新增用户
        statUserGetHomeAmoutVO.setUserAddMonth(kxsUserNewTradeMapper.selectToDayOrMonthCount(userId, month, TotalTypeEnum.TEAM.getType()));

        //获取今日新增商户
        statUserGetHomeAmoutVO.setMerchantAddToDay(kxsUserActTradeMapper.getUserActByDayOrMonthCount(userId, today, TotalTypeEnum.SELF.getType()));

        //获取本月新增商户
        statUserGetHomeAmoutVO.setMerchantAddMonth(kxsUserActTradeMapper.getUserActByDayOrMonthCount(userId, month, TotalTypeEnum.TEAM.getType()));
        return R.ok(statUserGetHomeAmoutVO);
    }

    @Override
    public R getMyTrade(StatUserGetMyTradeDTO param) {
        Long userId = SecurityUtils.getUser().getId();
        param.setUserId(userId);
        Integer month = param.getMonth();
        Integer totalType = param.getType();
        //拼接表名
        String tableName = CommonConstants.USER_TABLE_PREFIX + param.getMonth();
        StatUserGetMyTradeVO statUserGetMyTradeVO = new StatUserGetMyTradeVO();
        //总交易
        BigDecimal totalAmount = BigDecimal.ZERO;
        //获取pos交易额
        KxsUserTrade kxsUserPosTrade = baseMapper.getMyPosOrCloudTrade(param, tableName, 0, userId, null);
        if (kxsUserPosTrade != null) {
            BigDecimal proBDirectTradeAmt = kxsUserPosTrade.getProBDirectTradeAmt();//稳定期B贷记卡
            BigDecimal proADirectTradeAmt = kxsUserPosTrade.getProADirectTradeAmt();//稳定期A贷记卡
            BigDecimal proDirectTradeAmt = kxsUserPosTrade.getProDirectTradeAmt();//稳定期贷记卡
            BigDecimal helpDirectTradeAmt = kxsUserPosTrade.getHelpDirectTradeAmt();//扶持期贷记卡交易额


            BigDecimal proBDebitTradeAmt = kxsUserPosTrade.getProBDebitTradeAmt();//稳定期B借记卡
            BigDecimal proADebitTradeAmt = kxsUserPosTrade.getProADebitTradeAmt();//稳定期A借记卡
            BigDecimal proDebitTradeAmt = kxsUserPosTrade.getProDebitTradeAmt();//稳定期借记卡
            BigDecimal helpDebitTradeAmt = kxsUserPosTrade.getHelpDebitTradeAmt();//扶持期借记卡

            //pos借记卡
            BigDecimal posDebitAmount = BigDecimal.ZERO.add(proBDebitTradeAmt).add(proADebitTradeAmt).add(proDebitTradeAmt).add(helpDebitTradeAmt);
            //贷记卡
            BigDecimal posCreditAmount = BigDecimal.ZERO.add(proBDirectTradeAmt).add(proADirectTradeAmt).add(proDirectTradeAmt).add(helpDirectTradeAmt);

            statUserGetMyTradeVO.setPosDebitAmount(posDebitAmount);//Pos借记卡
            statUserGetMyTradeVO.setPosCreditAmount(posCreditAmount);//Pos贷记卡

            totalAmount = totalAmount.add(posDebitAmount).add(posCreditAmount);
        }
        //获取云闪付交易额
        KxsUserTrade kxsUserCloudTrade = baseMapper.getMyPosOrCloudTrade(param, tableName, 1, userId, "");
        if (kxsUserCloudTrade != null) {
            BigDecimal cloudAmount = BigDecimal.ZERO.add(kxsUserCloudTrade.getProBDirectTradeAmt())
                    .add(kxsUserCloudTrade.getProADirectTradeAmt())
                    .add(kxsUserCloudTrade.getProDirectTradeAmt())
                    .add(kxsUserCloudTrade.getHelpDirectTradeAmt())
                    .add(kxsUserCloudTrade.getProBDebitTradeAmt())
                    .add(kxsUserCloudTrade.getProADebitTradeAmt())
                    .add(kxsUserCloudTrade.getProDebitTradeAmt())
                    .add(kxsUserCloudTrade.getHelpDebitTradeAmt());
            statUserGetMyTradeVO.setCloudAmount(cloudAmount);
            totalAmount = totalAmount.add(cloudAmount);
        }


        //助力宝交易额
        TotalTradeAmtVO totalTradeAmtVO = kxsZlbTradeMapper.getZlbTrade(userId, month, totalType);
        if (totalTradeAmtVO != null) {
            BigDecimal zlbAmt = BigDecimal.ZERO;
            zlbAmt = totalTradeAmtVO.getZlbAmt();
            statUserGetMyTradeVO.setZlbAmount(zlbAmt);//助力宝
            totalAmount = totalAmount.add(zlbAmt);
        }

        //来客吧交易额
        totalTradeAmtVO = kxsLkbTradeMapper.getLkbTrade(userId, month, totalType);
        if (totalTradeAmtVO != null) {
            BigDecimal lkbActAmt = totalTradeAmtVO.getLkbActAmt();
            BigDecimal lkbAmt = totalTradeAmtVO.getLkbAmt();
            statUserGetMyTradeVO.setLkbActivityAmount(lkbActAmt);//来客吧活动
            statUserGetMyTradeVO.setLkbAmount(lkbAmt);//来客吧非活动
            totalAmount = totalAmount.add(lkbActAmt).add(lkbAmt);
        }

        //广电话费
        totalTradeAmtVO = kxsUserGdTradeMapper.getGdTrade(userId, month, totalType);
        if (totalTradeAmtVO != null) {
            BigDecimal gdAmount = totalTradeAmtVO.getGdAmount();

            statUserGetMyTradeVO.setGdTelephoneCharge(gdAmount);
            totalAmount = totalAmount.add(gdAmount);
        }

        //广电交易额
        totalTradeAmtVO = kxsUserGdTradeMapper.getGdActCount(userId, month, totalType);
        if (totalTradeAmtVO != null) {
            Integer gdCount = totalTradeAmtVO.getGdCount();
            //广电激活量 * 10000
            BigDecimal gdActivityAmount = BigDecimal.ZERO.add(new BigDecimal(gdCount * CommonConstants.GD_TO_PRICE));
            //广电活动
            statUserGetMyTradeVO.setGdActivityAmount(gdActivityAmount);

            totalAmount = totalAmount.add(gdActivityAmount);
        }




        //获取指定月新增用户
        Integer userAddMonth = kxsUserNewTradeMapper.selectToDayOrMonthCount(userId, month, TotalTypeEnum.TEAM.getType());
        statUserGetMyTradeVO.setUserAddCount(userAddMonth);

        //总用户
        Long totalUserCount = kxsUserNewTradeMapper.selectCount(Wrappers.<KxsUserNewTrade>lambdaQuery()
                .eq(KxsUserNewTrade::getUserId, userId)
                .eq(KxsUserNewTrade::getTotalType, totalType));
        statUserGetMyTradeVO.setTotalUserCount(totalUserCount);

        //获取累计全部激活商户
        Long merchantAddMonth = kxsUserActTradeMapper.selectCount(Wrappers.<KxsUserActTrade>lambdaQuery()
                .eq(KxsUserActTrade::getUserId, userId)
                .eq(KxsUserActTrade::getTotalType, totalType));
        statUserGetMyTradeVO.setActivateMerchantCount(merchantAddMonth != null ? merchantAddMonth : 0);//商户总激活

        //获取当月全部激活码牌
        Long signCount = kxsLkbActTradeMapper.selectCount(Wrappers.<KxsLkbActTrade>lambdaQuery()
                        .eq(KxsLkbActTrade::getUserId, userId)
                .eq(KxsLkbActTrade::getTotalType, totalType)
                .eq(KxsLkbActTrade::getTradeMonth, month));
        statUserGetMyTradeVO.setActivateSignCount(signCount != null ? signCount : 0);//码牌

        //存量激活广电卡
        Long simCount = kxsUserActTradeMapper.selectCount(Wrappers.<KxsUserActTrade>lambdaQuery()
                .eq(KxsUserActTrade::getUserId, userId)
                .eq(KxsUserActTrade::getBrandId, 14)
                .eq(KxsUserActTrade::getTotalType, totalType));
        statUserGetMyTradeVO.setActivateSIMCount(simCount != null ? simCount : 0);//存量激活sim卡
        //当月激活广电卡
        Long simToMonthCount = kxsUserActTradeMapper.selectCount(Wrappers.<KxsUserActTrade>lambdaQuery()
                .eq(KxsUserActTrade::getUserId, userId)
                .eq(KxsUserActTrade::getBrandId, 14)
                .eq(KxsUserActTrade::getTradeMonth, month)
                .eq(KxsUserActTrade::getTotalType, totalType));
        statUserGetMyTradeVO.setActivateSIMToMonthCount(simToMonthCount != null ? simToMonthCount : 0);

        statUserGetMyTradeVO.setTotalAmount(totalAmount);

        statUserGetMyTradeVO.setType(param.getType());
        return R.ok(statUserGetMyTradeVO);
    }

    @Override
    public R getUserTradeStatList(StatUserGetUserTradeListDTO param) {
        String month = param.getMonth();//查询月
        Integer totalType = param.getTotalType();//查询类型 0个人 1团队
        Long userId = param.getUserId();
        Integer getType = param.getGetType();//获取类型 1获取月 2获取半年
        Integer tradeType = param.getTradeType();//1获取增量 2获取存量 3获取全部
        LocalDate now = LocalDate.now();
        String tableName = "";
        List<String> times = new ArrayList<>();
        if (tradeType.equals(3)) {//获取全部
            tableName = PREFIX_TABLE_NAME; //全部
            if (getType.equals(2)) {//查询近半年
                ArrayList<StatUserGetUserTradeStatListVO> statUserGetUserTradeStatListVOS = getStatUserGetUserTradeStatListVOSByMonth(month, totalType, userId, getType, now, times, tableName, tradeType);
                return R.ok(statUserGetUserTradeStatListVOS);
            } else if (getType.equals(1)) {//查询月详细
                ArrayList<StatUserGetUserTradeStatListVO> statUserGetUserTradeStatListVOS = getUserGetUserTradeStatListVOSByDay(month, totalType, userId, getType, now, times, tableName, tradeType);
                return R.ok(statUserGetUserTradeStatListVOS);
            }
        } else if (tradeType.equals(2)) {
            tableName = PREFIX_TABLE_NAME_BEFORE; //存量
            if (getType.equals(2)) {//查询近半年
                ArrayList<StatUserGetUserTradeStatListVO> statUserGetUserTradeStatListVOS = getStatUserGetUserTradeStatListVOSByMonth(month, totalType, userId, getType, now, times, tableName, tradeType);
                return R.ok(statUserGetUserTradeStatListVOS);
            } else if (getType.equals(1)) {//查询月详细
                ArrayList<StatUserGetUserTradeStatListVO> statUserGetUserTradeStatListVOS = getUserGetUserTradeStatListVOSByDay(month, totalType, userId, getType, now, times, tableName, tradeType);
                return R.ok(statUserGetUserTradeStatListVOS);
            }
        } else if (tradeType.equals(1)) {
            tableName = PREFIX_TABLE_NAME_AFTER; //增量
            if (getType.equals(2)) {//查询近半年
                ArrayList<StatUserGetUserTradeStatListVO> statUserGetUserTradeStatListVOS = getStatUserGetUserTradeStatListVOSByMonth(month, totalType, userId, getType, now, times, tableName, tradeType);
                return R.ok(statUserGetUserTradeStatListVOS);
            } else if (getType.equals(1)) {//查询月详细
                ArrayList<StatUserGetUserTradeStatListVO> statUserGetUserTradeStatListVOS = getUserGetUserTradeStatListVOSByDay(month, totalType, userId, getType, now, times, tableName, tradeType);
                return R.ok(statUserGetUserTradeStatListVOS);
            }
        }
        return R.ok();

    }

    @Override
    public R getTradeDetail(StatUserGetTradeDetailDTO param) {
        Integer totalType = param.getTotalType();//0:个人 1:计奖
        Integer month = param.getDate();//该参数有效获取月份格式yyyyMM   日格式yyyyMMdd
        Integer getType = param.getGetType();// 1获取日详情 2获取月详情
        Integer tradeType = param.getTradeType();//1获取增量 2获取存量 3获取全部
        Long userId = param.getUserId();//用户id
        if (userId == null || userId == 0) {
            userId = SecurityUtils.getUser().getId();
        }
        Integer brandId = param.getBrandId();//品牌id

        String tableName;
        switch (tradeType) {
            case 1 -> tableName = CommonConstants.USER_TABLE_AFTER_PREFIX + month;
            case 2 -> tableName = CommonConstants.USER_TABLE_BEFORE_PREFIX + month;
            case 3 -> tableName = CommonConstants.USER_TABLE_PREFIX + month;
            default -> throw new GlobalCustomerException("参数错误");
        }


        StatUserGetTradeDetailVO statUserGetTradeDetailVO = new StatUserGetTradeDetailVO();
        statUserGetTradeDetailVO.setDate(month);//交易时间
        statUserGetTradeDetailVO.setBrandId(brandId);//品牌

        //扶持期
        StatUserTradeVo statUserTradeVo = new StatUserTradeVo();
        //稳定期
        StatUserTradeVo proStatUserTradeVo = new StatUserTradeVo();
        //稳定期A
        StatUserTradeVo proAstatUserTradeVo = new StatUserTradeVo();
        //稳定期B
        StatUserTradeVo proBstatUserTradeVo = new StatUserTradeVo();

        //pos交易
        KxsUserTrade kxsUserTradePos = baseMapper.getAllUserTradeSum(userId, month, getType, 0, brandId, totalType, tableName);
        if (kxsUserTradePos != null) {
            statUserTradeVo.setDirectTradeAmt(kxsUserTradePos.getHelpDirectTradeAmt());//扶持期贷记卡
            statUserTradeVo.setDebitTradeAmt(kxsUserTradePos.getHelpDebitTradeAmt());//扶持期借记卡
            statUserTradeVo.setDebitCapTradeAmt(kxsUserTradePos.getHelpDebitCapTradeAmt());//扶持期借记卡封顶交易额
            statUserTradeVo.setDebitCapNum(kxsUserTradePos.getHelpDebitCapNum());//扶持期借记卡封顶交易笔数
            BigDecimal helpNotCapTrade = kxsUserTradePos.getHelpDebitTradeAmt().subtract(kxsUserTradePos.getHelpDebitCapTradeAmt());//非封顶交易额
            statUserTradeVo.setCloudTrade(helpNotCapTrade);//扶持期非封顶借记卡交易额
            statUserTradeVo.setPosTrade(kxsUserTradePos.getHelpDirectTradeAmt().add(kxsUserTradePos.getHelpDebitTradeAmt()));//交易总和

            proStatUserTradeVo.setDirectTradeAmt(kxsUserTradePos.getProDirectTradeAmt());//稳定期贷记卡
            proStatUserTradeVo.setDebitTradeAmt(kxsUserTradePos.getProDebitTradeAmt());//稳定期借记卡
            proStatUserTradeVo.setDebitCapTradeAmt(kxsUserTradePos.getProDebitCapTradeAmt());//稳定期借记卡封顶交易额
            proStatUserTradeVo.setDebitCapNum(kxsUserTradePos.getProDebitCapNum());//稳定期借记卡封顶交易笔数
            BigDecimal proNotCapTrade = kxsUserTradePos.getProDebitTradeAmt().subtract(kxsUserTradePos.getProDebitCapTradeAmt());//非封顶交易额
            proStatUserTradeVo.setCloudTrade(proNotCapTrade);//稳定期非封顶借记卡交易额
            proStatUserTradeVo.setPosTrade(kxsUserTradePos.getProDirectTradeAmt().add(kxsUserTradePos.getProDebitTradeAmt()));//交易总和

            proAstatUserTradeVo.setDirectTradeAmt(kxsUserTradePos.getProADirectTradeAmt());//稳A贷记
            proAstatUserTradeVo.setDebitTradeAmt(kxsUserTradePos.getProADebitTradeAmt());//稳A借记
            proAstatUserTradeVo.setDebitCapTradeAmt(kxsUserTradePos.getProADebitCapTradeAmt());//稳定期A借记卡封顶交易额
            proAstatUserTradeVo.setDebitCapNum(kxsUserTradePos.getProADebitCapNum());//稳定期A借记卡封顶交易笔数
            BigDecimal proANotCapTrade = kxsUserTradePos.getProADebitTradeAmt().subtract(kxsUserTradePos.getProADebitCapTradeAmt());//非封顶交易额
            proAstatUserTradeVo.setCloudTrade(proANotCapTrade);//稳定期b非封顶借记卡交易额
            proAstatUserTradeVo.setPosTrade(kxsUserTradePos.getProADirectTradeAmt().add(kxsUserTradePos.getProADebitTradeAmt()));//交易总和

            proBstatUserTradeVo.setDirectTradeAmt(kxsUserTradePos.getProBDirectTradeAmt());//稳定期B借记卡
            proBstatUserTradeVo.setDebitTradeAmt(kxsUserTradePos.getProBDebitTradeAmt());//稳定期B贷记卡
            proBstatUserTradeVo.setDebitCapTradeAmt(kxsUserTradePos.getProBDebitCapTradeAmt());//稳定期B借记卡封顶交易额
            proBstatUserTradeVo.setDebitCapNum(kxsUserTradePos.getProBDebitCapNum());//稳定期B借记卡封顶交易笔数
            BigDecimal proBNotCapTrade = kxsUserTradePos.getProBDebitTradeAmt().subtract(kxsUserTradePos.getProBDebitCapTradeAmt());//稳定期b非封顶交易额
            proBstatUserTradeVo.setCloudTrade(proBNotCapTrade);//稳定期b非封顶借记卡交易额
            proBstatUserTradeVo.setPosTrade(kxsUserTradePos.getProBDirectTradeAmt().add(kxsUserTradePos.getProBDebitTradeAmt()));//交易总和
        }
        //云闪付
        KxsUserTrade kxsUserTradeCloud = baseMapper.getAllUserTradeSum(userId, month, getType, 1, brandId, totalType, tableName);
        if (kxsUserTradeCloud != null) {
            BigDecimal helpTrade = kxsUserTradeCloud.getHelpDebitCapTradeAmt().add(kxsUserTradeCloud.getHelpDirectTradeAmt());//计算扶持期云闪付交易额
            statUserTradeVo.setCloudTrade(helpTrade);//扶持期云闪付交易额

            BigDecimal proTrade = kxsUserTradeCloud.getProDebitCapTradeAmt().add(kxsUserTradeCloud.getProDirectTradeAmt());//计算稳定期云闪付交易额
            proStatUserTradeVo.setCloudTrade(proTrade);//稳定期云闪付交易额

            BigDecimal proATrade = kxsUserTradeCloud.getProADebitCapTradeAmt().add(kxsUserTradeCloud.getProADirectTradeAmt());//计算稳定期b云闪付交易额
            proAstatUserTradeVo.setCloudTrade(proATrade);//稳定期A云闪付交易额

            BigDecimal proBTrade = kxsUserTradeCloud.getProBDebitCapTradeAmt().add(kxsUserTradeCloud.getProBDirectTradeAmt());//计算稳定期a云闪付交易额
            proBstatUserTradeVo.setCloudTrade(proBTrade);//稳定期B云闪付交易额
        }
        statUserGetTradeDetailVO.setHelpDirectTradeAmt(statUserTradeVo);
        statUserGetTradeDetailVO.setProDirectTradeAmt(proStatUserTradeVo);
        statUserGetTradeDetailVO.setProADirectTradeAmt(proAstatUserTradeVo);
        statUserGetTradeDetailVO.setProBDirectTradeAmt(proBstatUserTradeVo);

        return R.ok(statUserGetTradeDetailVO);
    }


    private ArrayList<StatUserGetUserTradeStatListVO> getUserGetUserTradeStatListVOSByDay(String month, Integer totalType, Long userId, Integer getType, LocalDate now, List<String> times, String tableName, Integer tradeType) {
        //校验时间格式是yyyyMM
        AssertUtil.isyyyyMM(month);
        //判断month是否是本月  否则获取月份中全部日日期
        int year = Integer.parseInt(month.substring(0, 4));
        int monthOfYear = Integer.parseInt(month.substring(4, 6));
        // 判断给定的月份字符串是否表示当前月份
        boolean isCurrentMonth = year == now.getYear() && monthOfYear == now.getMonthValue();
        // 如果是当前月份，则生成本月到今天的日期字符串
        if (isCurrentMonth) {
            LocalDate firstDayOfMonth = now.withDayOfMonth(1);
            for (LocalDate date = firstDayOfMonth; !date.isAfter(now); date = date.plusDays(1)) {
                times.add(date.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            }
        } else {
            // 如果不是当前月份，则生成整个月的日期字符串
            LocalDate firstDayOfMonth = LocalDate.of(year, monthOfYear, 1);
            int daysInMonth = firstDayOfMonth.lengthOfMonth();
            for (int day = 1; day <= daysInMonth; day++) {
                LocalDate date = firstDayOfMonth.withDayOfMonth(day);
                times.add(date.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            }
        }
        //拼接表名
        String lastTableName = tableName + month;
        ArrayList<StatUserGetUserTradeStatListVO> statUserGetUserTradeStatListVOS = new ArrayList<>();
        //构造查询Dto
        StatUserGetMyTradeDTO statUserGetMyTradeDTO = new StatUserGetMyTradeDTO();
        statUserGetMyTradeDTO.setMonth(Integer.valueOf(month));
        statUserGetMyTradeDTO.setType(totalType);
        for (int i = times.size() - 1; i >= 0; i--) {
            String time = times.get(i);
            //查询交易额
            KxsUserTrade myPosTrade = null;
            try {
                //此处存在不存在表  跳过报错视为无数据
                myPosTrade = baseMapper.getMyPosOrCloudTrade(statUserGetMyTradeDTO, lastTableName, 0, userId, time);
            } catch (Exception e) {
                log.info(e.getMessage());
            }
            if (myPosTrade == null) {
                myPosTrade = new KxsUserTrade();
            }
            StatUserGetUserTradeStatListVO statUserGetUserTradeStatListVO = getMonthTrade(totalType, userId, getType, statUserGetMyTradeDTO, myPosTrade, month, time, tableName, tradeType);
            statUserGetUserTradeStatListVO.setTime(time);
            statUserGetUserTradeStatListVOS.add(statUserGetUserTradeStatListVO);
        }
        return statUserGetUserTradeStatListVOS;

    }

    private ArrayList<StatUserGetUserTradeStatListVO> getStatUserGetUserTradeStatListVOSByMonth(String month, Integer totalType, Long userId, Integer getType, LocalDate now, List<String> times, String tableName, Integer tradeType) {
        //近半年
        for (int i = 0; i < 6; i++) {
            // 计算过去半年每月月份
            LocalDate currentDay = now.minusMonths(i);
            // 将LocalDate转换为字符串
            String currentDateString = LocalDateTimeUtil.format(currentDay, DatePattern.SIMPLE_MONTH_PATTERN);
            times.add(currentDateString);
        }
        //获取交易额
        //构造查询Dto
        StatUserGetMyTradeDTO statUserGetMyTradeDTO = new StatUserGetMyTradeDTO();
        statUserGetMyTradeDTO.setMonth(Integer.valueOf(month));
        statUserGetMyTradeDTO.setType(totalType);
        ArrayList<StatUserGetUserTradeStatListVO> statUserGetUserTradeStatListVOS = new ArrayList<>();
        //查询进半年需要循环查询不同的表
        for (int i = times.size() - 1; i >= 0; i--) {
            String time = times.get(i);
            try {
                //拼接表名  因有可能查询不存在的表导致报错我们try包裹视为无数据
                String lastTableName = tableName + time;
                //查询交易额
                KxsUserTrade myPosTrade = baseMapper.getMyPosOrCloudTrade(statUserGetMyTradeDTO, lastTableName, 0, userId, "");
                if (myPosTrade == null) {
                    myPosTrade = new KxsUserTrade();
                }
                StatUserGetUserTradeStatListVO statUserGetUserTradeStatListVO = getMonthTrade(totalType, userId, getType, statUserGetMyTradeDTO, myPosTrade, month, time, tableName, tradeType);
                statUserGetUserTradeStatListVO.setTime(time);
                statUserGetUserTradeStatListVOS.add(statUserGetUserTradeStatListVO);
            } catch (Exception e) {
                log.info(e.getMessage());
            }
        }
        return statUserGetUserTradeStatListVOS;
    }

    private StatUserGetUserTradeStatListVO getMonthTrade(Integer totalType, Long userId, Integer getType, StatUserGetMyTradeDTO statUserGetMyTradeDTO, KxsUserTrade kxsUserTrade, String month, String date, String tableName, Integer tradeType) {
        BigDecimal helpDirectTradeAmt = kxsUserTrade.getHelpDirectTradeAmt() == null ? BigDecimal.ZERO : kxsUserTrade.getHelpDirectTradeAmt();//扶贷
        BigDecimal helpDebitTradeAmt = kxsUserTrade.getHelpDebitTradeAmt() == null ? BigDecimal.ZERO : kxsUserTrade.getHelpDebitTradeAmt();//扶借

        BigDecimal proDirectTradeAmt = kxsUserTrade.getProDirectTradeAmt() == null ? BigDecimal.ZERO : kxsUserTrade.getProDirectTradeAmt();//稳贷
        BigDecimal proDebitTradeAmt = kxsUserTrade.getProDebitTradeAmt() == null ? BigDecimal.ZERO : kxsUserTrade.getProDebitTradeAmt();//稳借

        BigDecimal proADirectTradeAmt = kxsUserTrade.getProADirectTradeAmt() == null ? BigDecimal.ZERO : kxsUserTrade.getProADirectTradeAmt();//稳A贷
        BigDecimal proADebitTradeAmt = kxsUserTrade.getProADebitTradeAmt() == null ? BigDecimal.ZERO : kxsUserTrade.getProADebitTradeAmt();//稳A借

        BigDecimal proBDebitTradeAmt = kxsUserTrade.getProBDebitTradeAmt() == null ? BigDecimal.ZERO : kxsUserTrade.getProBDebitTradeAmt();//稳B借
        BigDecimal proBDirectTradeAmt = kxsUserTrade.getProBDirectTradeAmt() == null ? BigDecimal.ZERO : kxsUserTrade.getProBDirectTradeAmt();//稳B贷

        BigDecimal totalAmount = BigDecimal.ZERO;

        StatUserGetUserTradeStatListVO statUserGetUserTradeStatListVO = new StatUserGetUserTradeStatListVO();
        BigDecimal debitPos = helpDebitTradeAmt.add(proDebitTradeAmt).add(proADebitTradeAmt).add(proBDebitTradeAmt);
        BigDecimal diretPos = helpDirectTradeAmt.add(proDirectTradeAmt).add(proADirectTradeAmt).add(proBDirectTradeAmt);
        //pos机交易额
        statUserGetUserTradeStatListVO.setPosDebitAmount(debitPos);
        statUserGetUserTradeStatListVO.setPosCreditAmount(diretPos);
        totalAmount = totalAmount.add(debitPos).add(diretPos);
        //拼接表名
        tableName = tableName + month;
        KxsUserTrade myCloudTrade = null;
        try {
            //存在表不存在的月份,跳过报错视为无数据  查询云闪付
            myCloudTrade = baseMapper.getMyPosOrCloudTrade(statUserGetMyTradeDTO, tableName, 1, userId, getType == 1 ? date : null);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        if (myCloudTrade == null) {
            myCloudTrade = new KxsUserTrade();
        }
        BigDecimal helpDirectTradeAmtCloud = myCloudTrade.getHelpDirectTradeAmt() == null ? BigDecimal.ZERO : myCloudTrade.getHelpDirectTradeAmt();//扶贷
        BigDecimal helpDebitTradeAmtCloud = myCloudTrade.getHelpDebitTradeAmt() == null ? BigDecimal.ZERO : myCloudTrade.getHelpDebitTradeAmt();//扶借

        BigDecimal proDirectTradeAmtCloud = myCloudTrade.getProDirectTradeAmt() == null ? BigDecimal.ZERO : myCloudTrade.getProDirectTradeAmt();//稳贷
        BigDecimal proDebitTradeAmtCloud = myCloudTrade.getProDebitTradeAmt() == null ? BigDecimal.ZERO : myCloudTrade.getProDebitTradeAmt();//稳借

        BigDecimal proADirectTradeAmtCloud = myCloudTrade.getProADirectTradeAmt() == null ? BigDecimal.ZERO : myCloudTrade.getProADirectTradeAmt();//稳A贷
        BigDecimal proADebitTradeAmtCloud = myCloudTrade.getProADebitTradeAmt() == null ? BigDecimal.ZERO : myCloudTrade.getProADebitTradeAmt();//稳A借

        BigDecimal proBDebitTradeAmtCloud = myCloudTrade.getProBDebitTradeAmt() == null ? BigDecimal.ZERO : myCloudTrade.getProBDebitTradeAmt();//稳B借
        BigDecimal proBDirectTradeAmtCloud = myCloudTrade.getProBDirectTradeAmt() == null ? BigDecimal.ZERO : myCloudTrade.getProBDirectTradeAmt();//稳B贷
        BigDecimal posAmount = helpDirectTradeAmtCloud
                .add(helpDebitTradeAmtCloud)
                .add(proDirectTradeAmtCloud)
                .add(proDebitTradeAmtCloud)
                .add(proADirectTradeAmtCloud)
                .add(proADebitTradeAmtCloud)
                .add(proBDebitTradeAmtCloud)
                .add(proBDirectTradeAmtCloud);
        //云闪付交易额
        statUserGetUserTradeStatListVO.setCloudAmunt(posAmount);
        totalAmount = totalAmount.add(posAmount);

        if (!tradeType.equals(2)) {//存量不存在以下数据
            //助力宝交易额
            TotalTradeAmtVO TotalTradeAmtVO = kxsZlbTradeMapper.getZlbTrade(userId, Integer.valueOf(date), totalType);
            TotalTradeAmtVO = TotalTradeAmtVO == null ? new TotalTradeAmtVO() : TotalTradeAmtVO;


            BigDecimal zlbAmt = TotalTradeAmtVO.getZlbAmt() == null ? BigDecimal.ZERO : TotalTradeAmtVO.getZlbAmt();
            statUserGetUserTradeStatListVO.setZlbAmount(zlbAmt);
            totalAmount = totalAmount.add(zlbAmt);

            //来客吧交易额
            TotalTradeAmtVO = kxsLkbTradeMapper.getLkbTrade(userId, Integer.valueOf(date), totalType);
            TotalTradeAmtVO = TotalTradeAmtVO == null ? new TotalTradeAmtVO() : TotalTradeAmtVO;

            BigDecimal lkbActAmt = TotalTradeAmtVO.getLkbActAmt() == null ? BigDecimal.ZERO : TotalTradeAmtVO.getLkbActAmt();
            statUserGetUserTradeStatListVO.setLkbActivityAmount(lkbActAmt);
            totalAmount = totalAmount.add(lkbActAmt);


            BigDecimal lkbAmt = TotalTradeAmtVO.getLkbAmt() == null ? BigDecimal.ZERO : TotalTradeAmtVO.getLkbAmt();
            statUserGetUserTradeStatListVO.setLkbAmount(lkbAmt);
            totalAmount = totalAmount.add(lkbAmt);
            //广电话费
            TotalTradeAmtVO = kxsUserGdTradeMapper.getGdTrade(userId, Integer.valueOf(date), totalType);
            TotalTradeAmtVO = TotalTradeAmtVO == null ? new TotalTradeAmtVO() : TotalTradeAmtVO;

            BigDecimal gdAmount = TotalTradeAmtVO.getGdAmount() == null ? BigDecimal.ZERO : TotalTradeAmtVO.getGdAmount();
            statUserGetUserTradeStatListVO.setGdTelephoneCharge(gdAmount);
            totalAmount = totalAmount.add(gdAmount);

            if (tradeType.equals(3)) {//广电获取全部
                //广电激活量
                if (getType == 1) {
                    TotalTradeAmtVO = kxsUserGdTradeMapper.getGdActAllCount(userId, Integer.valueOf(date), totalType);
                } else {
                    TotalTradeAmtVO = kxsUserGdTradeMapper.getGdActAllCount(userId, Integer.valueOf(date), totalType);
                }
                TotalTradeAmtVO = TotalTradeAmtVO == null ? new TotalTradeAmtVO() : TotalTradeAmtVO;

                BigDecimal gdActAmt = BigDecimal.valueOf(TotalTradeAmtVO.getGdCount() != null ? TotalTradeAmtVO.getGdCount() * 10000 : 0);
                statUserGetUserTradeStatListVO.setGdActivityAmount(gdActAmt);
            }
            if (tradeType.equals(1)) {//广电获取增量  只获取当前时间
                //广电激活量
                TotalTradeAmtVO = kxsUserGdTradeMapper.getGdActCount(userId, Integer.valueOf(date), totalType);
                TotalTradeAmtVO = TotalTradeAmtVO == null ? new TotalTradeAmtVO() : TotalTradeAmtVO;

                BigDecimal gdActAmt = BigDecimal.valueOf(TotalTradeAmtVO.getGdCount() != null ? TotalTradeAmtVO.getGdCount() * 10000 : 0);
                statUserGetUserTradeStatListVO.setGdActivityAmount(gdActAmt);
            }
        }
        //总额
        statUserGetUserTradeStatListVO.setTotalAmount(totalAmount);

        //查询各品牌交易总额
        List<StatUserBrandTradeVO> statUserBrandTradeVOS = baseMapper.getStatUserBrandTradeVOS(userId, getType, tableName, totalType, date);
        statUserGetUserTradeStatListVO.setProductList(statUserBrandTradeVOS);
        return statUserGetUserTradeStatListVO;
    }

    /**
     * 获取天或月的交易金额
     *
     * @param userId    用户 ID
     * @param date      日期
     * @param tableName 表名
     * @param totalType 0个人 1团队
     * @return {@link BigDecimal}
     */
    private BigDecimal getAmountToDayOrMonth(Long userId, Integer date, String tableName, Integer totalType) {

        BigDecimal amount = BigDecimal.ZERO;
        //pos交易
        TotalTradeAmtVO totalTradeAmtVO = baseMapper.getPosTrade(userId, tableName, date, totalType);
        if (totalTradeAmtVO != null) {
            amount = amount.add(totalTradeAmtVO.getPosAmt());
        }
        //来客吧交易额
        totalTradeAmtVO = kxsLkbTradeMapper.getLkbTrade(userId, date, totalType);
        if (totalTradeAmtVO != null) {
            amount = amount.add(totalTradeAmtVO.getLkbAmt());
            amount = amount.add(totalTradeAmtVO.getLkbActAmt());
        }
        //助力宝交易额
        totalTradeAmtVO = kxsZlbTradeMapper.getZlbTrade(userId, date, totalType);
        if (totalTradeAmtVO != null) {
            amount = amount.add(totalTradeAmtVO.getZlbAmt());
        }
        //广电交易额
        totalTradeAmtVO = kxsUserGdTradeMapper.getGdActCount(userId, date, totalType);
        if (totalTradeAmtVO != null) {
            Integer gdCount = totalTradeAmtVO.getGdCount();
            //广电激活量 * 10000
            amount = amount.add(new BigDecimal(gdCount * CommonConstants.GD_TO_PRICE));
        }
        //广电话费
        totalTradeAmtVO = kxsUserGdTradeMapper.getGdTrade(userId, date, totalType);
        if (totalTradeAmtVO != null) {
            amount = amount.add(totalTradeAmtVO.getGdAmount());
        }
        return amount;
    }


    /**
     * 创客交易品牌占比
     *
     * @param userId 用户 ID
     * @param times  时间区间
     * @param type   类型
     * @return {@link List}<{@link PercentVO}>
     */
    private List<PercentVO> setTradeTotalAndPercent(Long userId, List<Integer> times, Integer type) {

        List<PercentVO> percentVOList = new ArrayList<>();
        if (type == 0) {
            //近7天
            for (Integer day : times) {
                Integer month = TotalDateUtil.getMonthNumber(LocalDateTimeUtil.parseDate(String.valueOf(day), DatePattern.PURE_DATE_PATTERN));
                List<PercentVO> userTradeTotal = baseMapper.getUserTradeDayTotal(CommonConstants.USER_TABLE_PREFIX + month, userId, day, TotalTypeEnum.TEAM.getType());
                percentVOList.addAll(userTradeTotal);
            }
            return percentVOList.stream()
                    .peek(item -> item.setName(getBrandMap().get(item.getBrandId()).getName()))
                    .collect(Collectors.toMap(PercentVO::getBrandId, a -> a, (o1, o2) -> {
                        o1.setTradeAmt(o1.getTradeAmt().add(o2.getTradeAmt()));
                        return o1;
                    })).values().stream().toList();

        } else {
            //近半年
            for (Integer month : times) {
                List<PercentVO> userTradeTotal = baseMapper.getUserTradeMonthTotal(CommonConstants.USER_TABLE_PREFIX + month, userId, TotalTypeEnum.TEAM.getType());
                percentVOList.addAll(userTradeTotal);
            }
            return percentVOList.stream()
                    .peek(item -> item.setName(getBrandMap().get(item.getBrandId()).getName()))
                    .collect(Collectors.toMap(PercentVO::getBrandId, a -> a, (o1, o2) -> {
                        o1.setTradeAmt(o1.getTradeAmt().add(o2.getTradeAmt()));
                        return o1;
                    })).values().stream().toList();

        }
    }

    /**
     * 创客交易趋势图
     *
     * @param userId 用户 ID
     * @param times  时间区间
     * @param type   类型
     * @return {@link List}<{@link TrendVO}>
     */
    private List<TrendVO> setTradeTrend(Long userId, List<Integer> times, Integer type, Integer totalType) {

        MonthTableNameHandler.setData(MonthTableNameHandler.getThisMoth());
        List<TrendVO> trendVOList = new ArrayList<>();
        LinkedHashMap<Integer, List<TrendTimesVO>> tradeTrend = new LinkedHashMap<>();
        if (type == 0) {
            //近7天交易趋势图
            for (Integer day : times) {
                Integer month = TotalDateUtil.getMonthNumber(LocalDateTimeUtil.parseDate(String.valueOf(day), DatePattern.PURE_DATE_PATTERN));
                //每个月表统计查询出来后再合并进map里
                List<TrendTimesVO> monthTradeTrend = baseMapper.getUserTradeDayTrend(CommonConstants.USER_TABLE_PREFIX + month, userId, day, totalType);
                tradeTrend.put(day, monthTradeTrend);
            }
        }else{
            //近半年

            for (Integer month : times) {
                //每个月表统计查询出来后再合并进map里
                List<TrendTimesVO> monthTradeTrend = baseMapper.getUserTradeMonthTrend(CommonConstants.USER_TABLE_PREFIX + month, userId, totalType);
                tradeTrend.put(month, monthTradeTrend);
            }
        }
        initUserTrend(trendVOList, tradeTrend);

        return trendVOList;
    }

    private void initUserTrend(List<TrendVO> trendVOList, LinkedHashMap<Integer, List<TrendTimesVO>> tradeTrend) {
        //全部交易额
        TrendVO trendVO = new TrendVO();
        trendVO.setName("全部");
        LinkedList<Map<String, Object>> allAmt = new LinkedList<>();
        for (Integer date : tradeTrend.keySet()) {
            List<TrendTimesVO> trendTimesList = tradeTrend.get(date);
            //当前月份的所有总和
            BigDecimal totalAmt = trendTimesList.stream().map(TrendTimesVO::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            allAmt.addFirst(MapUtil.<String, Object>builder().put("time", date).put("tradeAmt", totalAmt).build());
        }
        trendVO.setTimes(allAmt);
        trendVOList.add(trendVO);
        //各品牌交易额
        for (Integer brandId : getBrandMap().keySet()) {
            TrendVO trendBrandVO = new TrendVO();
            trendBrandVO.setName(getBrandMap().get(brandId).getName());
            LinkedList<Map<String, Object>> brandAmt = new LinkedList<>();
            for (Integer date : tradeTrend.keySet()) {
                List<TrendTimesVO> trendTimesList = tradeTrend.get(date);
                BigDecimal totalAmt = trendTimesList.stream().filter(item -> Objects.equals(brandId, item.getBrandId())).map(TrendTimesVO::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                brandAmt.addFirst(MapUtil.<String, Object>builder().put("time", date).put("tradeAmt", totalAmt).build());
            }
            trendBrandVO.setTimes(brandAmt);
            trendVOList.add(trendBrandVO);
        }
    }


    private Map<Integer, KxsBrand> getBrandMap() {
        if (brandsMap == null) {
            R<List<KxsBrand>> brandRes = remoteKxsProductService.loadByAllBrand();
            List<KxsBrand> brands = RetOps.of(brandRes)
                    .getData()
                    .orElseThrow(() -> new GlobalCustomerException("获取品牌列表为空"));
            brandsMap = brands.stream().collect(Collectors.toMap(KxsBrand::getId, Function.identity()));
        }
        return brandsMap;

    }
}

