package com.czg.service.market.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.czg.account.entity.ShopInfo;
import com.czg.account.entity.ShopUser;
import com.czg.account.entity.UserInfo;
import com.czg.account.service.ShopInfoService;
import com.czg.account.service.ShopUserService;
import com.czg.account.service.UserInfoService;
import com.czg.constant.TableValueConstant;
import com.czg.exception.CzgException;
import com.czg.market.dto.MkDistributionUserDTO;
import com.czg.market.dto.MkDistributionWithdrawFlowDTO;
import com.czg.market.entity.*;
import com.czg.market.service.*;
import com.czg.market.vo.DistributionCenterShopVO;
import com.czg.market.vo.DistributionCenterTopVO;
import com.czg.market.vo.InviteUserVO;
import com.czg.market.vo.MkDistributionConfigVO;
import com.czg.order.dto.MkDistributionPayDTO;
import com.czg.order.entity.OrderInfo;
import com.czg.market.service.OrderInfoService;
import com.czg.order.service.OrderPaymentService;
import com.czg.sa.StpKit;
import com.czg.service.market.enums.OrderStatusEnums;
import com.czg.service.market.mapper.MkDistributionUserMapper;
import com.czg.utils.AssertUtil;
import com.czg.utils.CzgRandomUtils;
import com.czg.utils.FunUtils;
import com.czg.utils.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分销员表 服务层实现。
 *
 * @author ww
 * @since 2025-10-27
 */
@Slf4j
@Service
public class MkDistributionUserServiceImpl extends ServiceImpl<MkDistributionUserMapper, MkDistributionUser> implements MkDistributionUserService {

    @Resource
    private MkDistributionConfigService mkDistributionConfigService;
    @Resource
    private MkDistributionLevelConfigService levelConfigService;
    @Resource
    private MkDistributionAmountFlowService distributionAmountFlowService;
    @Resource
    private MkDistributionFlowService distributionFlowService;
    @Resource
    private MkDistributionWithdrawFlowService withdrawFlowService;
    @Resource
    private MkDistributionDeliverService distributionDeliverService;
    @Resource
    private ShopUserInviteService shopUserInviteService;

    @Resource
    private AppWxServiceImpl appWxService;

    @DubboReference
    private ShopUserService shopUserService;
    @DubboReference
    private UserInfoService userInfoService;
    @DubboReference
    private OrderPaymentService orderPaymentService;
    @Resource
    private OrderInfoService orderInfoService;
    @DubboReference
    private ShopInfoService shopInfoService;

    @Override
    public Map<String, Object> centerUser(Long userId) {
        DistributionCenterTopVO centerTopVO = null;
        try {
            QueryWrapper totalIncomeSumQueryWrapper = new QueryWrapper();
            totalIncomeSumQueryWrapper.select("sum(total_income) as totalIncome,sum(pending_income) as pendingIncome,sum(withdrawn_income) as cashOutAmount");
            totalIncomeSumQueryWrapper.eq(MkDistributionUser::getUserId, userId);
            totalIncomeSumQueryWrapper.eq(MkDistributionUser::getIsDel, 0);
            centerTopVO = getOneAs(totalIncomeSumQueryWrapper, DistributionCenterTopVO.class);
        } catch (Exception e) {
            log.error("查询用户中心数据失败", e);
        }
        // 封装顶部收益数据
        UserInfo userInfo = userInfoService.getById(userId);
        Map<String, Object> result = new HashMap<>(5);
        result.put("totalIncome", centerTopVO == null ? 0.0 : centerTopVO.getTotalIncome());
        result.put("pendingIncome", centerTopVO == null ? 0.0 : centerTopVO.getPendingIncome());
        result.put("cashOutAmount", userInfo.getDistributionAmount());

        result.put("activates", activates(userId, 1, 5));
        result.put("unActivates", unActivates(userId, 1, 3));
        return result;
    }

    @Override
    public Page<DistributionCenterShopVO> activates(Long userId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<DistributionCenterShopVO> activates = mapper.selectMyDistributionShops(userId);
        return PageUtil.convert(new PageInfo<>(activates));
    }

    @Override
    public Page<DistributionCenterShopVO> unActivates(Long userId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<DistributionCenterShopVO> unActivates = mapper.selectUnDistributionShops(userId);
        for (DistributionCenterShopVO unActivate : unActivates) {
            if (unActivate.getOrderCount() == 1) {
                unActivate.setLabelContent("在本店下单过");
            } else if (unActivate.getShopUser() == 1) {
                unActivate.setLabelContent("曾进入过店铺");
            }
//            else if("manual".equals(unActivate.getOpenType())){
//                unActivate.setLabelContent("manual手动开通");，
//            }

        }
        return PageUtil.convert(new PageInfo<>(unActivates));
    }


    @Override
    public Map<String, Object> centerConfig(Long userId, Long shopId) {
        Map<String, Object> result = new HashMap<>();
        ShopInfo shopInfo = shopInfoService.getById(shopId);
        AssertUtil.isNull(shopInfo, "店铺不存在");
        result.put("shopName", shopInfo.getShopName());
        result.put("parentName", "");
        result.put("parentPhone", "");
        ShopUser shopUser = shopUserService.getShopUserInfo(shopId, userId);
        AssertUtil.isNull(shopUser, "店铺用户不存在");
        UserInfo userInfo = userInfoService.getById(shopUser.getUserId());
        result.put("cashOutAmount", userInfo.getDistributionAmount() == null ? 0.0 : userInfo.getDistributionAmount());
        ShopUserInvite shopUserInvite = shopUserInviteService.getOneByShopIdAndShopUserId(shopId, shopUser.getId());
        if (shopUserInvite != null && shopUserInvite.getDistributionUserId() != null) {
            MkDistributionUser mkDistributionUser = getMkDistributionUserByIdAndShopId(shopUserInvite.getDistributionUserId(), shopId);
            AssertUtil.isNull(mkDistributionUser, "上级分销员不存在");
            ShopUser shopUserParent = shopUserService.getById(mkDistributionUser.getId());
            result.put("parentName", shopUserParent.getNickName());
            result.put("parentPhone", shopUserParent.getPhone());
        }
        MkDistributionUser mkDistributionUser = getMkDistributionUserByIdAndShopId(shopUser.getId(), shopId);
        MkDistributionConfigVO mkDistributionConfigVO = mkDistributionConfigService.detail(shopId);
        if (mkDistributionUser != null) {
            Map<String, Object> distributionUser = new HashMap<>();
            distributionUser.put("distributionId", mkDistributionUser.getId());
            distributionUser.put("inviteCode", mkDistributionUser.getInviteCode());
            distributionUser.put("consumeAmount", mkDistributionUser.getConsumeAmount());
            distributionUser.put("status", mkDistributionUser.getStatus() == 9);
            distributionUser.put("totalIncome", mkDistributionUser.getTotalIncome());
            distributionUser.put("pendingIncome", mkDistributionUser.getPendingIncome());
            distributionUser.put("isAssignLevel", mkDistributionUser.getIsAssignLevel());

            if (mkDistributionUser.getDistributionLevelId() != null) {
                List<MkDistributionLevelConfig> levelConfigList = mkDistributionConfigVO.getLevelConfigList();
                boolean isNextLevel = false;
                for (MkDistributionLevelConfig levelConfig : levelConfigList) {
                    if ("invite".equals(mkDistributionConfigVO.getUpgradeType()) && isNextLevel) {
                        distributionUser.put("nextLevelGap", levelConfig.getInviteCount() - mkDistributionUser.getInviteCount());
                        break;
                    }
                    if (levelConfig.getId().equals(mkDistributionUser.getDistributionLevelId())) {
                        distributionUser.put("level", levelConfig.getLevel());
                        distributionUser.put("levelName", levelConfig.getName());
                        distributionUser.put("levelOneCommission", levelConfig.getLevelOneCommission());
                        isNextLevel = true;
                    }
                }
            } else {
                distributionUser.put("level", 0);
                distributionUser.put("levelName", "无");
            }
            result.put("distributionUser", distributionUser);
        } else {
            result.put("config", mkDistributionConfigVO);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getInviteCode(Long shopId, Long shopUserId) {
        ShopUser shopUser = shopUserService.getById(shopUserId);
        AssertUtil.isNull(shopUser, "店铺用户不存在");
        MkDistributionConfigVO mkDistributionConfigVO = mkDistributionConfigService.detail(shopId);
        if (mkDistributionConfigVO == null || mkDistributionConfigVO.getIsEnable() == 0) {
            throw new CzgException("店铺分销功能未开启");
        }
        if (!"auto".equals(mkDistributionConfigVO.getOpenType())) {
            throw new CzgException("该店铺不可自行成为分销员");
        }
        MkDistributionUser mkDistributionUser = getMkDistributionUserByIdAndShopId(shopUser.getId(), shopId);
        if (mkDistributionUser == null) {
            mkDistributionUser = new MkDistributionUser();
            mkDistributionUser.setId(shopUser.getId());
            mkDistributionUser.setShopId(shopId);
            mkDistributionUser.setOpeningMethod("自主申请");
            mkDistributionUser = addDistributionUser(mkDistributionUser);
        }
        return mkDistributionUser.getInviteCode();
    }

    @Override
    public void realNameAuth(UserInfo userInfo) {
        AssertUtil.isTrue(!IdcardUtil.isValidCard(userInfo.getIdCard()), "身份证号格式错误");
        UserInfo newUserInfo = new UserInfo();
        newUserInfo.setId(userInfo.getId());
        newUserInfo.setRealName(userInfo.getRealName());
        newUserInfo.setIdCard(userInfo.getIdCard());
        userInfoService.updateById(newUserInfo);
    }

    @Override
    @GlobalTransactional
    public void bindInviteUser(MkDistributionUserDTO param) {
        ShopUser shopUser = shopUserService.getById(param.getId());
        AssertUtil.isNull(shopUser, "店铺用户不存在");
        ShopUserInvite shopUserInvite = shopUserInviteService.getOneByShopIdAndShopUserId(param.getShopId(), shopUser.getId());
        if (shopUserInvite != null && shopUserInvite.getDistributionUserId() != null) {
            throw new CzgException("店铺用户已绑定分销员");
        }
        MkDistributionUser parent = getOne(QueryWrapper.create().eq(MkDistributionUser::getInviteCode, param.getInviteCode()));
        AssertUtil.isNull(parent, "邀请人不存在");
        if (!parent.getShopId().equals(param.getShopId())) {
            throw new CzgException("邀请人不是本店铺的分销员");
        }
        if (parent.getId().equals(shopUser.getId())) {
            throw new CzgException("不能绑定自己为上级");
        }
        if (parent.getStatus() == 9) {
            throw new CzgException("绑定失败该邀请人分销身份已被取消");
        }
        ShopUser parentShopUser = shopUserService.getById(parent.getId());
        AssertUtil.isNull(parentShopUser, "邀请人不存在");
        ShopUserInvite parentShopUserInvite = shopUserInviteService.getOneByShopIdAndShopUserId(param.getShopId(), parentShopUser.getId());
        if (parentShopUserInvite != null && parentShopUserInvite.getDistributionUserId() != null && parentShopUserInvite.getDistributionUserId().equals(shopUser.getId())) {
            throw new CzgException("存在绑定关系，不可绑定");
        }
        if (parentShopUserInvite != null && parentShopUserInvite.getDistributionUserParentId() != null && parentShopUserInvite.getDistributionUserParentId().equals(shopUser.getId())) {
            throw new CzgException("存在绑定关系，不可绑定");
        }
        //更新自己的上级
        ShopUserInvite newShopUserInvite = new ShopUserInvite();
        newShopUserInvite.setShopId(param.getShopId());
        newShopUserInvite.setShopUserId(shopUser.getId());
        newShopUserInvite.setDistributionUserId(parentShopUser.getId());
        newShopUserInvite.setDistributionUserParentId(parentShopUserInvite == null ? null : parentShopUserInvite.getDistributionUserParentId());
        newShopUserInvite.setInviteTime(LocalDateTime.now());
        shopUserInviteService.save(newShopUserInvite);
        if (parentShopUserInvite != null && parentShopUserInvite.getDistributionUserParentId() != null) {
            //更新自己的下级 的上级的上级 为自己的上级
            ShopUserInvite childShopUserInvite = new ShopUserInvite();
            childShopUserInvite.setDistributionUserParentId(parentShopUser.getId());
            shopUserInviteService.update(childShopUserInvite, QueryWrapper.create().eq(ShopUserInvite::getDistributionUserId, shopUser.getId()));
        }

        MkDistributionUser newDistributionUser = new MkDistributionUser();
        newDistributionUser.setId(parent.getId());
        newDistributionUser.setInviteCount(parent.getInviteCount() + 1);
        MkDistributionConfig mkDistributionConfig = mkDistributionConfigService.getOne(QueryWrapper.create()
                .eq(MkDistributionConfig::getShopId, parent.getShopId()));
        if ("自主申请".equals(parent.getOpeningMethod()) && parent.getStatus() == 0 && mkDistributionConfig != null) {
            if (newDistributionUser.getInviteCount() >= mkDistributionConfig.getInviteCount()) {
                ShopUser parentShopUser1 = new ShopUser();
                parentShopUser1.setId(parentShopUser.getId());
                parentShopUser1.upDistributionShop(param.getShopId(), 1);
                shopUserService.updateById(parentShopUser1);
            }
        }
        if (mkDistributionConfig != null && !"not_upgrade".equals(mkDistributionConfig.getUpgradeType()) && parent.getIsAssignLevel() == 0) {
            if ("invite".equals(mkDistributionConfig.getUpgradeType())) {
                if (mkDistributionConfig.getInviteConsume() == 1) {
                    long count = orderInfoService.count(QueryWrapper.create()
                            .eq(OrderInfo::getUserId, shopUser.getUserId())
                            .eq(OrderInfo::getShopId, parent.getShopId())
                            .eq(OrderInfo::getStatus, OrderStatusEnums.DONE.getCode()));
                    if (count < 1) {
                        throw new CzgException("绑定失败,被邀请人需要成功支付一笔订单");
                    }
                }
                MkDistributionLevelConfig levelConfig = levelConfigService.getOne(QueryWrapper.create()
                        .eq(MkDistributionLevelConfig::getShopId, parent.getShopId())
                        .le(MkDistributionLevelConfig::getInviteCount, newDistributionUser.getInviteCount())
                        .orderBy(MkDistributionLevelConfig::getId).desc().limit(1));
                if (levelConfig != null) {
                    newDistributionUser.setDistributionLevelId(levelConfig.getId());
                    newDistributionUser.setDistributionLevelName(levelConfig.getName());
                    newDistributionUser.setStatus(1);
                }
            } else if ("cost".equals(mkDistributionConfig.getUpgradeType())) {
                costUpgradeLevel(parent.getId(), parent.getShopId());
            }
        }
        update(newDistributionUser, QueryWrapper.create().eq(MkDistributionUser::getId, parent.getId())
                .eq(MkDistributionUser::getShopId, parent.getShopId()));
    }

    @Override
    public void costUpgradeLevelBefore(Long userId, Long shopId) {
        ShopUser shopUser = shopUserService.getShopUserInfo(shopId, userId);
        costUpgradeLevel(shopUser.getId(), shopId);
        ShopUserInvite shopUserInvite = shopUserInviteService.getOneByShopIdAndShopUserId(shopId, shopUser.getId());
        if (shopUserInvite != null && shopUserInvite.getDistributionUserId() != null) {
            costUpgradeLevel(shopUserInvite.getDistributionUserId(), shopId);
        }
    }


    /**
     * 分销员：按消费金额升级等级
     */
    public void costUpgradeLevel(Long shopUserId, Long shopId) {
        MkDistributionUser distributionUser = getMkDistributionUserByIdAndShopId(shopUserId, shopId);
        if (distributionUser == null || distributionUser.getIsAssignLevel() == 1) {
            return;
        }
        MkDistributionConfig mkDistributionConfig = mkDistributionConfigService.getOne(QueryWrapper.create()
                .eq(MkDistributionConfig::getShopId, distributionUser.getShopId()));
        if (mkDistributionConfig == null || !"cost".equals(mkDistributionConfig.getUpgradeType())) {
            return;
        }
        BigDecimal totalAmount = mapper.getOrderConsumeAmountByList(shopId, distributionUser.getId());
        BigDecimal ownTotalAmount = mapper.getOrderConsumeAmountById(shopId, distributionUser.getUserId());
        totalAmount = totalAmount.add(ownTotalAmount);
        MkDistributionLevelConfig levelConfig = levelConfigService.getOne(QueryWrapper.create()
                .eq(MkDistributionLevelConfig::getShopId, distributionUser.getShopId())
                .le(MkDistributionLevelConfig::getCostAmount, totalAmount)
                .gt(MkDistributionLevelConfig::getId, distributionUser.getDistributionLevelId())
                .orderBy(MkDistributionLevelConfig::getId).desc().limit(1));
        MkDistributionUser newDistributionUser = new MkDistributionUser();
        newDistributionUser.setId(shopUserId);
        newDistributionUser.setConsumeAmount(totalAmount);
        if (levelConfig != null) {
            if (totalAmount.compareTo(levelConfig.getCostAmount()) >= 0) {
                newDistributionUser.setId(shopUserId);
                newDistributionUser.setDistributionLevelId(levelConfig.getId());
                newDistributionUser.setDistributionLevelName(levelConfig.getName());
            }
        }
        update(newDistributionUser, QueryWrapper.create().eq(MkDistributionUser::getId, shopUserId)
                .eq(MkDistributionUser::getShopId, shopId));

    }

    @Override
    public Page<MkDistributionUserDTO> getDistributionUser(MkDistributionUserDTO param) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(MkDistributionUser::getId, param.getId());
        queryWrapper.eq(MkDistributionUser::getShopId, param.getShopId());
        queryWrapper.ne(MkDistributionUser::getStatus, 0);
        queryWrapper.eq(MkDistributionUser::getDistributionLevelId, param.getDistributionLevelId());
        queryWrapper.ge(MkDistributionUser::getCreateTime, param.getStartTime());
        queryWrapper.le(MkDistributionUser::getCreateTime, param.getEndTime());
        queryWrapper.orderBy(MkDistributionUser::getCreateTime).desc();
        Page<MkDistributionUserDTO> page = pageAs(new Page<>(param.getPage(), param.getSize()), queryWrapper, MkDistributionUserDTO.class);
        Map<Long, ShopUser> shopUserMap = new HashMap<>();
        if (CollUtil.isNotEmpty(page.getRecords())) {
            if (param.getId() != null) {
                shopUserMap.put(param.getId(), shopUserService.getById(param.getId()));
            } else {
                Set<Long> shopUserIds = page.getRecords().stream()
                        .map(MkDistributionUserDTO::getId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toSet());
                shopUserMap = shopUserService.list(QueryWrapper.create().in(ShopUser::getId, shopUserIds))
                        .stream().collect(Collectors.toMap(ShopUser::getId, shopUser -> shopUser));
            }
            for (MkDistributionUserDTO record : page.getRecords()) {
                ShopUser shopUser = shopUserMap.get(record.getId());
                if (shopUser == null || shopUser.getId() == null) {
                    continue;
                }
                record.setHeadImg(shopUser.getHeadImg());
                record.setShopUserName(shopUser.getNickName());
                record.setShopUserPhone(shopUser.getPhone());
            }
        }
        return page;
    }

    @Override
    public Page<InviteUserVO> getInviteUser(Long id, Long shopId, Long shopUserId, Long distributionLevelId, Integer page, Integer size) {
        return shopUserService.getInviteUser(id, shopId, shopUserId, distributionLevelId, page, size);
    }

    @Override
    @GlobalTransactional
    public MkDistributionUser addDistributionUser(MkDistributionUser param) {
        AssertUtil.isNull(param.getShopId(), "店铺ID不能为空");
        AssertUtil.isNull(param.getOpeningMethod(), "开通方式不能为空");
        AssertUtil.isNull(param.getId(), "店铺用户ID不能为空");
        ShopUser shopUser = shopUserService.getById(param.getId());
        AssertUtil.isNull(shopUser, "店铺用户ID不能为空");
        MkDistributionUser distributionUser = getMkDistributionUserByIdAndShopId(param.getId(), param.getShopId());
        if (distributionUser != null && distributionUser.getStatus() != 0) {
            throw new CzgException("该用户已是分销员,不可重复添加");
        }
        MkDistributionConfig config = mkDistributionConfigService.getOne(
                QueryWrapper.create().eq(MkDistributionConfig::getShopId, param.getShopId())
                        .eq(MkDistributionConfig::getIsEnable, 1));
        AssertUtil.isNull(config, "店铺未配置分销");
        param.setStatus(0);
        param.setInviteCount(0);
        if (!"自主申请".equals(param.getOpeningMethod()) || config.getInviteCount() == 0) {
            initLevel(config, param);
        }
        if (distributionUser != null) {
            distributionUser.setOpeningMethod("手动添加");
            distributionUser.setDistributionLevelId(param.getDistributionLevelId());
            distributionUser.setDistributionLevelName(param.getDistributionLevelName());
            distributionUser.setStatus(1);
            update(distributionUser, QueryWrapper.create().eq(MkDistributionUser::getId, param.getId())
                    .eq(MkDistributionUser::getShopId, param.getShopId()));
        } else {
            if ("手动添加".equals(param.getOpeningMethod())) {
                param.setStatus(1);
            }
            param.setId(param.getId());
            param.setUserId(shopUser.getUserId());
            param.setInviteCode(CzgRandomUtils.randomString(10));
            save(param);
        }
        ShopUser shopUser2 = new ShopUser();
        shopUser2.setId(shopUser.getId());
        if (param.getStatus() == 0) {
            shopUser2.upDistributionShop(param.getShopId(), 0);
        } else {
            shopUser2.upDistributionShop(param.getShopId(), 1);
        }
        shopUserService.updateById(shopUser2);
        return param;
    }

    @Override
    public void updateDistributionUserById(MkDistributionUserDTO param) {
        AssertUtil.isNull(param.getId(), "分销员ID不能为空");
        MkDistributionUser distributionUser = BeanUtil.toBean(param, MkDistributionUser.class);
        update(distributionUser, QueryWrapper.create().eq(MkDistributionUser::getId, param.getId())
                .eq(MkDistributionUser::getShopId, param.getShopId()));
    }

    @Override
    public void resetDistributionUserLevel(MkDistributionUserDTO param) {
        AssertUtil.isNull(param.getId(), "分销员ID不能为空");
        MkDistributionUser distributionUser = getMkDistributionUserByIdAndShopId(param.getId(), param.getShopId());
        AssertUtil.isNull(distributionUser, "分销员不存在");
        AssertUtil.isTrue(distributionUser.getIsAssignLevel() == 0, "分销员并未指定等级,不可重置");
        MkDistributionConfig config = mkDistributionConfigService.getOne(
                QueryWrapper.create().eq(MkDistributionConfig::getShopId, param.getShopId())
                        .eq(MkDistributionConfig::getIsEnable, 1));
        AssertUtil.isNull(config, "店铺未配置分销");
        initLevel(config, distributionUser);
        MkDistributionUser newDistributionUser = new MkDistributionUser();
        newDistributionUser.setId(distributionUser.getId());
        newDistributionUser.setIsAssignLevel(0);
        newDistributionUser.setDistributionLevelId(distributionUser.getDistributionLevelId());
        newDistributionUser.setDistributionLevelName(distributionUser.getDistributionLevelName());
        newDistributionUser.setConsumeAmount(distributionUser.getConsumeAmount());
        update(newDistributionUser, QueryWrapper.create().eq(MkDistributionUser::getId, distributionUser.getId())
                .eq(MkDistributionUser::getShopId, distributionUser.getShopId()));
    }


    @Override
    public void initLevel(MkDistributionConfig config, MkDistributionUser distributionUser) {
        MkDistributionLevelConfig levelConfig = new MkDistributionLevelConfig();
        if ("not_upgrade".equals(config.getUpgradeType())) {
            levelConfig = levelConfigService.getOne(QueryWrapper.create()
                    .eq(MkDistributionLevelConfig::getShopId, config.getShopId())
                    .orderBy(MkDistributionLevelConfig::getId).asc().limit(1));
        } else if ("invite".equals(config.getUpgradeType())) {
            levelConfig = levelConfigService.getOne(QueryWrapper.create()
                    .eq(MkDistributionLevelConfig::getShopId, config.getShopId())
                    .le(MkDistributionLevelConfig::getInviteCount, distributionUser.getInviteCount())
                    .orderBy(MkDistributionLevelConfig::getInviteCount).desc().limit(1));
        } else if ("cost".equals(config.getUpgradeType())) {
            BigDecimal totalAmount = mapper.getOrderConsumeAmountByList(config.getShopId(), distributionUser.getId());
            BigDecimal ownTotalAmount = mapper.getOrderConsumeAmountById(config.getShopId(), distributionUser.getUserId());
            totalAmount = totalAmount.add(ownTotalAmount);
            levelConfig = levelConfigService.getOne(QueryWrapper.create()
                    .eq(MkDistributionLevelConfig::getShopId, distributionUser.getShopId())
                    .le(MkDistributionLevelConfig::getCostAmount, totalAmount)
                    .orderBy(MkDistributionLevelConfig::getId).desc().limit(1));
            distributionUser.setConsumeAmount(totalAmount);
        }
        if (levelConfig != null) {
            distributionUser.setDistributionLevelId(levelConfig.getId());
            distributionUser.setDistributionLevelName(levelConfig.getName());
            distributionUser.setStatus(1);
        } else {
            distributionUser.setDistributionLevelId(0L);
            distributionUser.setDistributionLevelName("无等级");
        }
        distributionUser.setIsAssignLevel(0);
    }

    @Override
    public void deleteDistributionUser(Long id, Long shopId) {
        AssertUtil.isNull(id, "分销员ID不能为空");
        MkDistributionUser distributionUser = new MkDistributionUser();
        distributionUser.setIsDel(1);
        update(distributionUser, QueryWrapper.create().eq(MkDistributionUser::getId, id)
                .eq(MkDistributionUser::getShopId, shopId));
    }


    @Override
    public Boolean cashPayOrder(long adminId, MkDistributionPayDTO payParam) {
        ShopInfo shopInfo = shopInfoService.getById(payParam.getShopId());
        AssertUtil.isNull(shopInfo, "店铺不存在");
        BigDecimal amount = shopInfoService.updateAmount(shopInfo.getId(), payParam.getAmount());
        Long mainShopId = shopInfoService.getMainIdByShopId(shopInfo.getId());

        distributionAmountFlowService.save(new MkDistributionAmountFlow()
                .setType(payParam.getAmount().compareTo(BigDecimal.ZERO) < 0 ? TableValueConstant.DistributionAmountFlow.Type.MANUAL_SUB.getCode() :
                        TableValueConstant.DistributionAmountFlow.Type.MANUAL_RECHARGE.getCode())
                .setMainShopId(mainShopId).setShopId(shopInfo.getId()).setAmount(amount).setChangeAmount(payParam.getAmount())
                .setRemark(payParam.getRemark()).setOpAccount(StpKit.USER.getAccount()));
        return true;
    }

    @Override
    public void open(Long shopUserId, BigDecimal amount, Long shopId, Long sourceId) {
        ShopUser shopUserInfo = shopUserService.getById(shopUserId);
        Long mainShopId = shopInfoService.getMainIdByShopId(shopId);
//        BigDecimal finalAmount = shopInfoService.updateAmount(shopId, amount);
        distributionAmountFlowService.save(new MkDistributionAmountFlow()
                .setType(TableValueConstant.DistributionAmountFlow.Type.OPEN.getCode())
                .setMainShopId(mainShopId).setShopId(shopId).setAmount(amount).setChangeAmount(amount).setSourceId(sourceId)
                .setRemark("分销员购买"));
        try {
            addDistributionUser(new MkDistributionUser().setShopId(shopId)
                    .setUserId(shopUserInfo.getUserId())
                    .setId(shopUserInfo.getId()).setOpeningMethod("付费开通"));
        } catch (Exception e) {
            log.error("分销员开通失败", e);
        }
    }


    @Override
    public void rechargeCallBack(Long shopId, BigDecimal amount, Long paymentId) {
        Long mainShopId = shopInfoService.getMainIdByShopId(shopId);
        BigDecimal finalAmount = shopInfoService.updateAmount(shopId, amount);
        distributionAmountFlowService.save(new MkDistributionAmountFlow()
                .setType(TableValueConstant.DistributionAmountFlow.Type.SELF_RECHARGE.getCode())
                .setMainShopId(mainShopId).setShopId(shopId).setAmount(finalAmount).setChangeAmount(amount).setSourceId(paymentId)
                .setRemark("自助充值"));
    }


    @GlobalTransactional
    protected void deepReward(ShopUser orderSourceShopUser, MkDistributionLevelConfig parentLevel, MkDistributionConfigVO config,
                              MkDistributionUser currentDistributionUser, BigDecimal amount, Long sourceId, String type, String orderNo, Integer currentLevel) {
        if (currentLevel > 2) {
            return;
        }
        // 当前分销员
        AssertUtil.isNull(currentDistributionUser, "分销员不存在");
        AssertUtil.isTrue(currentDistributionUser.getStatus() != 1, "分销员未开启");

//        ShopUser currentShopUser = shopUserService.getById(currentDistributionUser.getId());
        ShopUserInvite currentShopUser = shopUserInviteService.getOneByShopIdAndShopUserId(config.getShopId(), currentDistributionUser.getId());
        MkDistributionLevelConfig level = levelConfigService.getById(currentDistributionUser.getDistributionLevelId());

        // 校验剩余分成比例
        BigDecimal finalCommission = parentLevel == null ? level.getLevelOneCommission() : level.getLevelOneCommission().subtract(parentLevel.getLevelOneCommission());
        if (finalCommission.compareTo(BigDecimal.ZERO) <= 0) {
            log.info("当前分销员: {}, 分销等级: {}, 剩余比例: {}, 不参与分销", currentDistributionUser.getId(), level.getId(), finalCommission);
            return;
        }

        // 上上级分销员
        if (currentShopUser != null && currentShopUser.getDistributionUserId() != null) {
            MkDistributionUser parent = getMkDistributionUserByIdAndShopId(currentShopUser.getDistributionUserId(), config.getShopId());
            try {
                deepReward(orderSourceShopUser, level, config, parent, amount, sourceId, type, orderNo, currentLevel + 1);
            } catch (Exception e) {
                log.warn("分销奖励失败: {}", e.getMessage());
            }
        }

        AssertUtil.isNull(level, "分销等级不存在");
        log.info("当前分销员: {}, 上级分销员: {}, 分销等级: {}", currentDistributionUser.getId(), currentShopUser == null ? null : currentShopUser.getDistributionUserId(), level.getId());

        if (config.getRewardCount() != null && config.getRewardCount() > 0) {
            long count = distributionFlowService.count(new QueryWrapper()
                    .eq(MkDistributionFlow::getShopId, config.getShopId()).eq(MkDistributionFlow::getShopUserId, currentDistributionUser.getId()));
            if (count >= config.getRewardCount()) {
                log.info("分销员{}已达到奖励次数上限, 次数: {}", currentDistributionUser.getId(), config.getRewardCount());
                return;
            }else {
                log.info("分销员奖励次数: {}", count);
            }
        }

        // 店铺信息
        BigDecimal rewardAmount;
//        if (currentLevel == 1) {
//            rewardAmount = amount.multiply(level.getLevelOneCommission().divide(BigDecimal.valueOf(100), RoundingMode.DOWN));
//        } else {
//            rewardAmount = amount.multiply(level.getLevelTwoCommission().divide(BigDecimal.valueOf(100), RoundingMode.DOWN));
//        }
        rewardAmount = amount.multiply(finalCommission.divide(BigDecimal.valueOf(100), RoundingMode.DOWN));

        // 延时发放时间
        LocalDateTime delayTime = config.getSettlementDay() == null || config.getSettlementDay() == 0 ? null : DateUtil.offsetDay(DateUtil.date(), config.getSettlementDay()).toLocalDateTime();

        // 用户分账明细
        ShopUser shopUser = shopUserService.getById(currentDistributionUser.getId());
        MkDistributionFlow mkDistributionFlow = new MkDistributionFlow().setShopUserId(currentDistributionUser.getId())
                .setShopId(currentDistributionUser.getShopId()).setDistributionUserId(currentDistributionUser.getId())
                .setUserId(shopUser.getUserId())
                .setNickName(shopUser.getNickName()).setSourceShopUserId(orderSourceShopUser.getId()).setSourceNickName(orderSourceShopUser.getNickName())
                .setCommission(finalCommission).setParentCommission(parentLevel != null ? parentLevel.getLevelOneCommission() : null)
                .setLevelId(currentDistributionUser.getDistributionLevelId()).setLevel(currentLevel == 1 ? 1 : 2).setOrderNo(orderNo)
                .setSourceId(sourceId).setAmount(amount).setType(type)
                .setRewardAmount(rewardAmount).setBillNo(IdUtil.simpleUUID());

        if (delayTime == null) {
            mkDistributionFlow.setStatus(TableValueConstant.DistributionFlow.Status.SUCCESS.getCode());
            distributionFlowService.save(mkDistributionFlow);
            log.info("即时分销开始");
            try {
                updateShopInfoAmount(currentDistributionUser.getShopId(), rewardAmount.negate(), sourceId, TableValueConstant.DistributionAmountFlow.Type.SUB, "分销扣除");
                updateIncome(BigDecimal.ZERO, rewardAmount, BigDecimal.ZERO, currentDistributionUser.getId(), shopUser.getUserId(), shopUser.getId(), config.getShopId(), currentLevel == 1 ? 1 : 2);
            } catch (Exception e) {
                mkDistributionFlow.setStatus(TableValueConstant.DistributionFlow.Status.PENDING.getCode());
                updateIncome(rewardAmount, BigDecimal.ZERO, BigDecimal.ZERO, currentDistributionUser.getId(), shopUser.getUserId(), shopUser.getId(), config.getShopId(), currentLevel == 1 ? 1 : 2);
                distributionFlowService.updateById(mkDistributionFlow);
            }
        } else {
            mkDistributionFlow.setDeliverTime(delayTime);
            mkDistributionFlow.setStatus(TableValueConstant.DistributionFlow.Status.PENDING.getCode());
            distributionFlowService.save(mkDistributionFlow);
            log.info("延时分销开始");
            updateIncome(rewardAmount, BigDecimal.ZERO, BigDecimal.ZERO, currentDistributionUser.getId(), shopUser.getUserId(), shopUser.getId(), config.getShopId(), currentLevel == 1 ? 1 : 2);
        }
    }

    @Override
    public BigDecimal updateShopInfoAmount(Long shopId, BigDecimal changeAmount, Long sourceId, TableValueConstant.DistributionAmountFlow.Type type, String remark) {
        BigDecimal finalAmount = shopInfoService.updateAmount(shopId, changeAmount);
        distributionAmountFlowService.save(new MkDistributionAmountFlow()
                .setType(type.getCode())
                .setShopId(shopId).setAmount(finalAmount).setChangeAmount(changeAmount).setSourceId(sourceId)
                .setRemark(remark));
        return finalAmount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refund(Long orderId, String orderNo) {
        long count = distributionFlowService.count(new QueryWrapper().eq(MkDistributionFlow::getOrderNo, orderNo).eq(MkDistributionFlow::getStatus, TableValueConstant.DistributionFlow.Status.PENDING.getCode()));
        if (count >= 1) {
            log.warn("此分销已经退款");
            return;
        }
        distributionFlowService.list(new QueryWrapper().eq(MkDistributionFlow::getOrderNo, orderNo).ne(MkDistributionFlow::getStatus, TableValueConstant.DistributionFlow.Status.REFUND.getCode())).forEach(item -> {
            MkDistributionFlow refundFlow = BeanUtil.copyProperties(item, MkDistributionFlow.class);
            refundFlow.setStatus(TableValueConstant.DistributionFlow.Status.REFUND.getCode());
            refundFlow.setSourceId(item.getId());
            refundFlow.setId(null);
            refundFlow.setCreateTime(DateUtil.date().toLocalDateTime());
            refundFlow.setUpdateTime(DateUtil.date().toLocalDateTime());
            if (TableValueConstant.DistributionFlow.Status.PENDING.getCode().equals(item.getStatus())) {
                item.setStatus(TableValueConstant.DistributionFlow.Status.SUCCESS.getCode());
                updateIncome(item.getRewardAmount().negate(), BigDecimal.ZERO, BigDecimal.ZERO, item.getDistributionUserId(), item.getUserId(), item.getShopUserId(), item.getShopId(), item.getLevel());
                distributionFlowService.updateById(item);
            } else {
                // 执行扣款
                updateIncome(BigDecimal.ZERO, item.getRewardAmount().negate(), BigDecimal.ZERO, item.getDistributionUserId(), item.getUserId(), item.getShopUserId(), item.getShopId(), item.getLevel());
                updateShopInfoAmount(item.getShopId(), item.getRewardAmount(), orderId, TableValueConstant.DistributionAmountFlow.Type.REFUND, "分销回退");
            }
            distributionFlowService.save(refundFlow);
        });
    }

    @Override
    public void distribute(Long sourceId, String orderNo, BigDecimal amount, Long sourceUserId, Long shopId, String type) {
        MkDistributionDeliver deliver = new MkDistributionDeliver().setSourceId(sourceId).setOrderNo(orderNo).setShopId(shopId).setType(type).setStatus("success");
        FunUtils.safeRunVoid(() -> {
            AssertUtil.isTrue(amount.compareTo(BigDecimal.ZERO) == 0, "分销金额不能为0");
            MkDistributionConfigVO config = mkDistributionConfigService.detail(shopId);
            AssertUtil.isTrue(config.getIsEnable() != 1, "分销未开启");
            // 当前用户上级分销员
            ShopUser sourceShopUserInfo = shopUserService.getShopUserInfo(shopId, sourceUserId);
            if (sourceShopUserInfo == null) {
                return;
            }
            ShopUserInvite sourceInviteUser = shopUserInviteService.getOneByShopIdAndShopUserId(shopId, sourceShopUserInfo.getId());
            if (sourceInviteUser.getDistributionUserId() == null) {
                return;
            }
            log.info("开始分销, 当前来源用户: {}, shopId: {}, 邀请人id: {}", sourceUserId, shopId, sourceInviteUser.getDistributionUserId());

            MkDistributionUser distributionUser = getMkDistributionUserByIdAndShopId(sourceInviteUser.getDistributionUserId(), shopId);
            deepReward(sourceShopUserInfo, null, config, distributionUser, amount, sourceId, type, orderNo, 1);
        });
        distributionDeliverService.save(deliver);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateIncome(BigDecimal pendingIncome, BigDecimal receivedIncome, BigDecimal withdrawIncome, Long id, Long userId, Long shopUserId, Long shopId, Integer isOne) {
        // 用户收益信息
        shopUserService.updateOneOrTwoAmount(shopUserId, shopId, receivedIncome, isOne);
        // 用户可提现余额
        userInfoService.updateDistributionAmount(userId, receivedIncome);
        //分销员余额
        boolean flag = mapper.updateIncome(pendingIncome, receivedIncome, withdrawIncome, id, shopId);
        if (!flag) {
            throw new CzgException("操作失败");
        }
    }

    static void main() {
        BigDecimal amount = new BigDecimal("0.18");
        BigDecimal fee = amount.multiply(BigDecimal.valueOf(0.08)).setScale(2, RoundingMode.UP);
        BigDecimal finalAmount = amount.subtract(fee);
        System.out.println(finalAmount);
        System.out.println(fee);
    }

    @Override
    public Boolean withdraw(long userId, MkDistributionWithdrawFlowDTO withdrawFlowDTO) {
        UserInfo userInfo = userInfoService.getById(userId);
        if (userInfo.getDistributionAmount().subtract(withdrawFlowDTO.getAmount()).compareTo(BigDecimal.ZERO) < 0) {
            throw new CzgException("可提现金额不足");
        }

        if (StrUtil.isBlank(userInfo.getIdCard())) {
            throw new CzgException("请先实名认证");
        }

        BigDecimal fee = withdrawFlowDTO.getAmount().multiply(BigDecimal.valueOf(0.08)).setScale(2, RoundingMode.UP);
        BigDecimal finalAmount = withdrawFlowDTO.getAmount().subtract(fee);

        MkDistributionWithdrawFlow withdrawFlow = new MkDistributionWithdrawFlow().setUserId(userId)
                .setAmount(finalAmount).setServiceFee(fee).setBillNo(IdUtil.simpleUUID()).setStatus(TableValueConstant.DistributionWithdrawFlow.Status.PENDING.getCode());
        JSONObject jsonObject = appWxService.transferBalance(userInfo.getWechatOpenId(), userInfo.getRealName(), finalAmount, "提现", withdrawFlow.getBillNo());
        withdrawFlow.setPackageInfo(jsonObject.getString("package_info"));
        // 扣减余额
        userInfoService.updateDistributionAmount(userId, withdrawFlowDTO.getAmount().negate());
        return withdrawFlowService.save(withdrawFlow);
    }

    @Override
    public Map<String, Object> withdrawDetail(long userId, Long id) {
        MkDistributionWithdrawFlow flow = withdrawFlowService.getOne(new QueryWrapper().eq(MkDistributionWithdrawFlow::getId, id).eq(MkDistributionWithdrawFlow::getUserId, userId));
        AssertUtil.isNull(flow, "提现记录不存在");
        AssertUtil.isTrue(TableValueConstant.DistributionWithdrawFlow.Status.FINISH.getCode().equals(flow.getStatus()), "已经提现");

        return Map.of(
                "mchId", appWxService.config.mchId,
                "appId", appWxService.config.appId,
                "package", flow.getPackageInfo()
        );
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void withdrawNotify(String outBillNo, String state, String failReason) {
        MkDistributionWithdrawFlow flow = withdrawFlowService.getOne(new QueryWrapper().eq(MkDistributionWithdrawFlow::getBillNo, outBillNo));
        AssertUtil.isNull(flow, "提现记录不存在");
        switch (state) {
            case "SUCCESS":
                flow.setStatus(TableValueConstant.DistributionWithdrawFlow.Status.FINISH.getCode());
                break;
            case "FAIL":
                flow.setStatus(TableValueConstant.DistributionWithdrawFlow.Status.FAIL.getCode());
            case "CANCELLED":
                flow.setStatus(TableValueConstant.DistributionWithdrawFlow.Status.FAIL.getCode());
                // 扣减余额
                userInfoService.updateDistributionAmount(flow.getUserId(), flow.getAmount().add(flow.getServiceFee()));
                break;

        }
        flow.setFailReason(failReason);
        withdrawFlowService.updateById(flow);
    }

    @Override
    public MkDistributionUser getMkDistributionUserByIdAndShopId(Long shopUserId, Long shopId) {
        return getOne(new QueryWrapper().eq(MkDistributionUser::getId, shopUserId).eq(MkDistributionUser::getShopId, shopId));
    }
}
