package com.hzs.member.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.*;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.achieve.ext.CuMemberRetailSExt;
import com.hzs.common.domain.member.base.*;
import com.hzs.common.domain.member.detail.CuMemberGrade;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.member.empty.CuMemberEmptyCode;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.sale.wares.BdWaresAuthority;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.domain.system.config.BdTradeWhiteConfig;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.service.ICuMemberAccountService;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.base.param.UpdatePlaceParentPetitionParam;
import com.hzs.member.base.dto.*;
import com.hzs.member.base.mapper.CuMemberMapper;
import com.hzs.member.base.param.*;
import com.hzs.member.base.service.*;
import com.hzs.member.base.vo.*;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import com.hzs.member.empty.service.ICuMemberEmptyCodeService;
import com.hzs.member.handlebusiness.dto.AnalysisBusinessAppealParam;
import com.hzs.member.handlebusiness.vo.BusinessMemberVO;
import com.hzs.member.handlebusiness.vo.HandleBusinessVO;
import com.hzs.member.marketnews.param.MarketNewsParam;
import com.hzs.member.marketnews.vo.UserInvestmentVo;
import com.hzs.member.share.param.ShareRegisterParam;
import com.hzs.retail.member.param.ShareRetailMemberParam;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CountryDTO;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.IServiceChargeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.config.dto.ServiceChargeDTO;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.BusinessLogDTO;
import com.hzs.system.sys.dto.LoginUser;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 会员 服务实现类
 */
@Service
@Slf4j
public class CuMemberServiceImpl extends ServiceImpl<CuMemberMapper, CuMember> implements ICuMemberService {

    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    ICountryServiceApi iCountryServiceApi;
    @DubboReference
    IServiceChargeServiceApi iServiceChargeServiceApi;
    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    IApprovalServiceApi iApprovalServiceApi;
    @DubboReference
    IAwardsServiceApi iAwardsServiceApi;

    @Autowired
    private ICuMemberRegisterService memberRegisterService;
    @Autowired
    private ICuMemberAccountService memberAccountService;
    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ICuMemberEmptyCodeService iCuMemberEmptyCodeService;
    @Autowired
    private ICuSettleCountryDetailedService iCuSettleCountryDetailedService;
    @Autowired
    private ICuMemberBusinessService cuMemberBusinessService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Boolean saveMember(CuMember cuMember) {
        boolean save = false;
        try {
            if (cuMember.getIsMakerGift() == null) {
                cuMember.setIsMakerGift(EYesNo.NO.getIntValue());
            }
            if (baseMapper.insertCuMember(cuMember) > 0) {
                save = true;
            }
        } catch (Exception e) {
            log.error("saveMember error: {}", e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }
        return save;
    }

    @Override
    public Integer queryCuMemberByPkMember(Long pkReference) {
        LambdaQueryWrapper<CuMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMember::getPkParent, pkReference);
        queryWrapper.eq(CuMember::getCategory, ECategory.NORMAL.getValue());
        queryWrapper.eq(CuMember::getPayStatus, EPayStatus.PAID.getValue());
        List<Integer> customerList = new ArrayList<>();
        customerList.add(ECustomerType.NORMAL.getValue());
        customerList.add(ECustomerType.EMPTY_ORDER.getValue());
        customerList.add(ECustomerType.FANS.getValue());
        queryWrapper.in(CuMember::getCustomerType, customerList);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count == null ? 0 : count;
    }

    @Override
    public CuMemberExt getMemberById(Long memberId) {
        return baseMapper.queryLoginMember(null, memberId);
    }

    @Override
    public CuMemberExt getMemberByCode(String memberCode) {
        return baseMapper.queryLoginMember(memberCode, null);
    }

    @Override
    public List<CuMemberExt> getMemberInfoByCondition(CuMember cuMember) {
        return baseMapper.queryMemberInfoByCondition(cuMember);
    }

    @Override
    public CuMember getMember(String memberCode) {
        return baseMapper.queryLoginMember(memberCode, null);
    }

    @Override
    public CuMember getMember(Long pkId) {
        return baseMapper.queryLoginMember(null, pkId);
    }

    @Override
    public CuMember queryMember(String memberCode) {
        return baseMapper.queryLoginMember(memberCode, null);
    }

    @Override
    public CuMember queryMember(Long pkMember) {
        return baseMapper.queryLoginMember(null, pkMember);
    }

    @Override
    public boolean checkLowerMember(Long pkMember) {
        LambdaQueryWrapper<CuMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMember::getPkParent, pkMember)
                .or()
                .eq(CuMember::getPkPlaceParent, pkMember);
        return this.count(queryWrapper) > 0;
    }

    @Override
    public List<CuMemberExt> queryPlaceSponsorOnUmbrella(Long memberId, String memberCode, String phone) {
        return baseMapper.selectPlaceSponsorOnUmbrella(memberId, memberCode, phone);
    }

    @Override
    public List<CuMemberExt> selectPlaceSponsorUnderUmbrellaByCondition(Long memberId, List<CuMemberExt> cuMemberExtList) {
        return baseMapper.selectPlaceSponsorUnderUmbrellaByCondition(memberId, cuMemberExtList);
    }

    @Override
    public List<CuMemberExt> queryPlaceSponsorUnderUmbrella(Long memberId, String... placeParent) {
        if (placeParent != null && placeParent.length > 0) {
            return baseMapper.selectPlaceSponsorUnderUmbrellaByCode(memberId, placeParent[0]);
        } else {
            return baseMapper.selectPlaceSponsorUnderUmbrella(memberId);
        }
    }

    @Override
    public CuMemberExt queryPlaceSponsorLastLeft(Long memberId, Integer placeDept) {
        CuMemberExt cuMemberExt = baseMapper.selectPlaceSponsorLastLeft(memberId, placeDept);
        if (placeDept == EPlaceDept.LEFT_DEPT.getValue()) {
            return cuMemberExt;
        } else {
            // 1判断是否存在极右极左 至少2层推荐
            // 2不存在查询code是否存在第二部门安置人 1层推荐
            // 3不存在 code就是右区的极左极下 没有推荐
            if (cuMemberExt == null) {
                // 2023.11.28 添加 category(10) 查询条件，待激活、死活也占点位，查询也需要算上
                List<CuMemberExt> cuMemberExtList = baseMapper.queryMemberInfoByCondition(
                        CuMember.builder().pkPlaceParent(memberId).placeDept(placeDept).category(10).build());
                if (Collections.isEmpty(cuMemberExtList)) {
                    CuMember member = getMember(memberId);
                    return BeanUtil.copyProperties(member, CuMemberExt.class);
                }
                return cuMemberExtList.get(0);
            }
        }
        return cuMemberExt;
    }

    @Override
    public List<CuMemberExt> queryBloodKinshipOnUmbrella(Long memberId) {
        return baseMapper.selectBloodKinshipOnUmbrella(memberId);
    }

    @Override
    public List<CuMemberExt> queryBloodKinshipUnderUmbrella(Long memberId) {
        return baseMapper.selectBloodKinshipUnderUmbrella(memberId);
    }

    @Override
    public CuMember createMemberIdAndCode(CuMember cuMember) {
        cuMember.setMemberCode(createUserNameByPremix(cuMember.getPkSettleCountry(), MagicNumberConstants.OLD_DIGIT));
        cuMember.setPkId(baseMapper.createMemberId());
        // 生成主键
        return cuMember;
    }

    @Override
    public CuMember createRegisterMemberCode(CuMember cuMember) {
        String memberCode = createUserNameByPremix(cuMember.getPkSettleCountry(), MagicNumberConstants.OLD_DIGIT);
        cuMember.setMemberCode(memberCode);
        cuMember.setPkId(baseMapper.createMemberId());
        // 注册订单有待支付的话，生成的编号需要占用住
        iCuMemberEmptyCodeService.saveData(memberCode, cuMember.getPkSettleCountry(), MagicNumberConstants.PK_ADMIN);
        return cuMember;
    }

    @Override
    public List<RetailMemberVO> retailMemberList(RetailMemberVO retailMemberVO) {
        return baseMapper.retailMemberList(retailMemberVO);
    }

    @Override
    public List<CuMemberVO> realCuMemberByCondition(CuMemberVO memberParam) {
        return baseMapper.realCuMemberByCondition(memberParam);
    }

    @Override
    public CuMember createEmptyOrderMember(CuMemberExt member) {
        try {
            CuMember cuMember = createMemberIdAndCode(member);
            // 根据推荐编号查询推荐人
            CuMember parentMember = getMember(member.getParent());
            cuMember.setPkParent(parentMember.getPkId());
            // 根据安置编号查询安置人
            CuMember placeParentMember = getMember(member.getPlaceParent());
            cuMember.setPkPlaceParent(placeParentMember.getPkId());
            // 生成用户
            saveMember(cuMember);
            // 生成回填金额
            if (member.getLockAccount4() != null) {
                CuMemberAccount cuMemberAccount = new CuMemberAccount();
                cuMemberAccount.setLockAccount4(member.getLockAccount4());
                cuMemberAccount.setPkMember(cuMember.getPkId());
                Boolean b = memberAccountService.updateMemberAccount(cuMemberAccount, member.getPkCreator());
                if (!b) {
                    return null;
                }
            }
            //   会员注册信息
            saveMemberRegister(cuMember);
            return cuMember;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }

    }

    /**
     * 会员注册信息
     */
    public void saveMemberRegister(CuMember cuMember) {
        CuMemberRegister cuMemberRegister = BeanUtil.copyProperties(cuMember, CuMemberRegister.class);
        cuMemberRegister.setPkCreator(cuMember.getPkCreator());
        cuMemberRegister.setCreationTime(DateUtils.currentDateTime());
        cuMemberRegister.setPkCountry(SecurityUtils.getPkCountry());
        cuMemberRegister.setPkMember(cuMember.getPkId());
        memberRegisterService.save(cuMemberRegister);
    }

    @Override
    public List<UpdateCodeVO> puCodeList(UpdateCodeVO updateCodeVO) {
        return baseMapper.puCodeList(updateCodeVO);
    }

    @Override
    public List<ZeroElementRevokeVO> zeroList(ZeroElementRevokeVO zeroElementRevokeVO) {
        return baseMapper.zeroList(zeroElementRevokeVO);
    }

    @Override
    public List<ZeroElementRevokeDTO> zeroByBusinessList(AnalysisBusinessAppealParam analysisBusinessAppealParam) {
        //查询日志
        List<ZeroElementRevokeDTO> zeoList = new ArrayList<>();
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, analysisBusinessAppealParam.getBusinessNo());
        queryWrapper.eq(CuMemberServiceLog::getApproveStatus, EApproveStatus.ALREADY_SUBMIT.getValue());
        List<CuMemberServiceLog> memberServiceLogList = memberServiceLogService.list(queryWrapper);
        for (CuMemberServiceLog cs : memberServiceLogList) {
            ZeroElementRevokeDTO zero = JSONObject.parseObject(cs.getNewValue(), ZeroElementRevokeDTO.class);
            long timestamp = Long.parseLong(zero.getCreationTime());
            Date date = new Date(timestamp);
            zero.setCreationTime(DateUtils.parseDateTimeToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
            zeoList.add(zero);
        }
        return zeoList;
    }

    /**
     * @description: 查询会员变更前信息
     * @author: zhang jing
     * @date: 2023/7/17 12:18
     * @param: [updateCodeVO]
     * @return: com.hzs.member.base.vo.UpdateCodeVO
     **/
    @Override
    public UpdateCodeVO specialBusinessQuery(UpdateCodeVO updateCodeVO) {
        return baseMapper.specialBusinessQuery(updateCodeVO);
    }


    /**
     * @description: 批量修改会员编号
     * @author: zhang jing
     * @date: 2022/12/30 14:20
     * @param: [updateCodeVOList]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpdateCodeVO updateCode(UpdateCodeVO updateCode) {

        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        updateCode.setApprovalBusiness(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        for (UpdateCodeVO uc : updateCode.getUpdateCodeVOList()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setEditType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            memberLog.setOldValue(uc.getMemberCode());
            memberLog.setNewValue(uc.getMemberCodeNew());
            memberLog.setPkCreator(updateCode.getPkCreator());
            memberLog.setCreationTime(updateCode.getCreationTime());
            memberLog.setBusinessNo(code);
            memberLog.setPkCountry(updateCode.getPkCountry());
            memberLog.setProcessType(updateCode.getProcessType());
            memberLog.setApproveNumber(uc.getChangeNumber());
            //免签呈;免签呈免支付
            if (updateCode.getProcessType() == EProcessType.AVOIDSIGNING.getValue()
                    || updateCode.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
                //修改会员编号
                CuMember member = new CuMember();
                member.setPkId(uc.getPkId());
                member.setMemberCode(uc.getMemberCodeNew());
                member.setPkModified(updateCode.getPkCreator());
                member.setModifiedTime(updateCode.getCreationTime());
                baseMapper.updateById(member);
                //组装日志数据
                BusinessLogDTO businessLog = BusinessLogDTO.builder()
                        .businessType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue())
                        .businessCode(code)
                        .pkMember(uc.getPkId())
                        .content(EApprovalBusiness.CHANGE_MEMBER_CODE.getLabel() + "：变更前编号 " + uc.getMemberCode() + "变更后 " + uc.getMemberCodeNew())
                        .pkCreator(updateCode.getPkCreator())
                        .pkCountry(updateCode.getPkCountry())
                        .freeSignFlag(true).build();
                dtoList.add(businessLog);
            }
        }
        //扣钱
        if (updateCode.getProcessType().equals(EProcessType.AVOIDSIGNING.getValue())) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(updateCode.getPkCountry());
            businessCommissionDTO.setMemberAmountDTOList(updateCode.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);

        return updateCode;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZeroElementRevokeVO zeroRevokeBusiness(ZeroElementRevokeVO zero) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());
        zero.setApprovalBusiness(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
        // 封装修改结算国业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        for (ZeroElementRevokeVO zo : zero.getZeroVOList()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(zo.getPkId());
            memberLog.setEditType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
            memberLog.setOldValue(JSONObject.toJSONString(zo));
            memberLog.setNewValue(JSONObject.toJSONString(zo));
            memberLog.setPkCreator(zero.getPkCreator());
            memberLog.setCreationTime(zero.getCreationTime());
            memberLog.setBusinessNo(code);
            memberLog.setPkCountry(zero.getPkCountry());
            memberLog.setProcessType(zero.getProcessType());
            memberLog.setApproveNumber(zo.getChangeNumber());
            //免签呈;免签呈免支付
            if (zero.getProcessType() == EProcessType.AVOIDSIGNING.getValue()
                    || zero.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
                //校验会员是否存在推荐或安置
                CuMember member = new CuMember();
                member.setPkId(zo.getPkId());
                member.setPkModified(zero.getPkCreator());
                member.setModifiedTime(zero.getCreationTime());
                if (this.checkLowerMember(zo.getPkId())) {
                    //设为死点
                    member.setCategory(ECategory.DEAD_POINT.getValue());
                    baseMapper.updateById(member);
                } else {
                    //删除
                    LambdaUpdateWrapper<CuMember> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.set(CuMember::getMemberCode, CommonUtil.deleteMemberCode(zo.getMemberCode()));
                    updateWrapper.set(CuMember::getDelFlag, EDelFlag.DELETE.getValue());
                    updateWrapper.set(CuMember::getModifiedTime, zero.getCreationTime());
                    updateWrapper.set(CuMember::getPkModified, zero.getPkCreator());
                    updateWrapper.eq(CuMember::getPkId, zo.getPkId());
                    baseMapper.update(null, updateWrapper);
                }
            }
            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue())
                    .businessCode(code)
                    .pkMember(zo.getPkId())
                    .content(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getLabel() + "：撤单后会员编号 " + CommonUtil.deleteMemberCode(zo.getMemberCode()))
                    .pkCreator(zero.getPkCreator())
                    .pkCountry(zero.getPkCountry())
                    .freeSignFlag(true).build();
            dtoList.add(businessLog);
        }
        //扣钱
        if (zero.getProcessType().equals(EProcessType.AVOIDSIGNING.getValue())) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(zero.getPkCountry());
            businessCommissionDTO.setMemberAmountDTOList(zero.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
            businessCommissionDTO.setPkAccount(zero.getZeroVOList().get(0).getPkAccount());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.ZERO_ELEMENT_REVOKE_MONEY));
            }
        }
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return zero;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZeroElementRevokeVO zeroPetition(ZeroElementRevokeVO zeroElementRevokeVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());
        // 封装修改结算国业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();

        LoginUser loginUser = userTokenService.getLoginUser();
        for (ZeroElementRevokeVO zero : zeroElementRevokeVO.getZeroVOList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(zero.getPkId());
            memberLog.setPkCreator(zeroElementRevokeVO.getPkCreator());
            memberLog.setCreationTime(zeroElementRevokeVO.getCreationTime());
            memberLog.setPkCountry(zeroElementRevokeVO.getPkCountry());
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
            memberLog.setOldValue(JSONObject.toJSONString(zero));
            memberLog.setNewValue(JSONObject.toJSONString(zero));
            memberLog.setApproveNumber(zero.getChangeNumber());
            memberLog.setSingleAmount(zero.getCost());
            memberLog.setProcessType(zero.getProcessType());
            memberServiceLogService.save(memberLog);
            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue())
                    .businessCode(code)
                    .pkMember(zero.getPkId())
                    .content(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getLabel() + "：撤单后会员编号 " + CommonUtil.deleteMemberCode(zero.getMemberCode()))
                    .pkCreator(zeroElementRevokeVO.getPkCreator())
                    .pkCountry(zeroElementRevokeVO.getPkCountry())
                    .freeSignFlag(false).build();
            dtoList.add(businessLog);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.ZERO_ELEMENT_REVOKE)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(zeroElementRevokeVO.getSignType()))
                .remark(zeroElementRevokeVO.getRemark())
                .pkMemberList(zeroElementRevokeVO.getPkMemberList())
                .userIdList(zeroElementRevokeVO.getUserIdList())
                .sendIdList(zeroElementRevokeVO.getSendIdList())
                .fileList(zeroElementRevokeVO.getFileList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.ZERO_ELEMENT_REVOKE_PETITION);
        }
        //扣钱
        if (zeroElementRevokeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkCountry(zeroElementRevokeVO.getPkCountry());
            businessCommissionDTO.setPkAccount(zeroElementRevokeVO.getZeroVOList().get(0).getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(zeroElementRevokeVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.ZERO_ELEMENT_REVOKE_MONEY));
            }
        }
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return zeroElementRevokeVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpdateCodeVO petition(UpdateCodeVO updateCodeVO) {

        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (UpdateCodeVO uc : updateCodeVO.getUpdateParentParamList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setPkCreator(updateCodeVO.getPkCreator());
            memberLog.setCreationTime(updateCodeVO.getCreationTime());
            memberLog.setPkCountry(updateCodeVO.getPkCountry());
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            memberLog.setOldValue(uc.getMemberCode());
            memberLog.setNewValue(uc.getMemberCodeNew());
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setSingleAmount(uc.getCost());
            memberLog.setProcessType(updateCodeVO.getProcessType());
            memberServiceLogService.save(memberLog);
            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue())
                    .businessCode(code)
                    .pkMember(uc.getPkId())
                    .content(EApprovalBusiness.CHANGE_MEMBER_CODE.getLabel() + "：变更前编号 " + uc.getMemberCode() + "变更后 " + uc.getMemberCodeNew())
                    .pkCreator(updateCodeVO.getPkCreator())
                    .pkCountry(updateCodeVO.getPkCountry())
                    .freeSignFlag(false).build();
            dtoList.add(businessLog);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.CHANGE_MEMBER_CODE)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(updateCodeVO.getSignType()))
                .remark(updateCodeVO.getRemark())
                .pkMemberList(updateCodeVO.getPkMemberList())
                .userIdList(updateCodeVO.getUserIdList())
                .sendIdList(updateCodeVO.getSendIdList())
                .fileList(updateCodeVO.getFileList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.MEMBER_UPDATE_PETITION);
        }
        //扣钱
        if (updateCodeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkCountry(updateCodeVO.getPkCountry());
            businessCommissionDTO.setPkAccount(updateCodeVO.getUpdateParentParamList().get(0).getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(updateCodeVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }

        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return updateCodeVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpdateSettleCountryVO petition(UpdateSettleCountryVO upseCountryVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (UpdateSettleCountryVO uc : upseCountryVO.getUpstcyVOList()) {
            // 修改审核状态
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setPkCountry(pkCountry);
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            memberLog.setOldValue(uc.getPkSettleCountry().toString());
            memberLog.setNewValue(uc.getNewPkSettleCountry().toString());
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setSingleAmount(uc.getCost());
            memberLog.setProcessType(upseCountryVO.getProcessType());
            memberServiceLogService.save(memberLog);

            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue())
                    .businessCode(code)
                    .pkMember(uc.getPkId())
                    .content(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getLabel() + "：变更前结算国 " + uc.getShortName() + " 变更后 " + uc.getShortName2())
                    .pkCreator(userID)
                    .pkCountry(pkCountry)
                    .freeSignFlag(false).build();
            dtoList.add(businessLog);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.UPDATE_SETTLE_COUNTRY)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(upseCountryVO.getSignType()))
                .remark(upseCountryVO.getRemark())
                .pkMemberList(upseCountryVO.getPkMemberList())
                .userIdList(upseCountryVO.getUserIdList())
                .sendIdList(upseCountryVO.getSendIdList())
                .fileList(upseCountryVO.getFileList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.UPDATE_SETTLE_PETITION);
        }
        //扣钱
        if (upseCountryVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkAccount(upseCountryVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(upseCountryVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_SETTLE_MONEY));
            }
        }
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return upseCountryVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpPolicyCurrencyVO petition(UpPolicyCurrencyVO policyCurrencyVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        LoginUser loginUser = userTokenService.getLoginUser();
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        for (UpPolicyCurrencyVO plc : policyCurrencyVO.getPlculist()) {
            // 修改审核状态
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(plc.getPkMember());
            memberLog.setPkCreator(policyCurrencyVO.getPkCreator());
            memberLog.setCreationTime(policyCurrencyVO.getCreationTime());
            memberLog.setPkCountry(policyCurrencyVO.getPkCountry());
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
            memberLog.setNewValue(JSONObject.toJSONString(plc));
            memberLog.setApproveNumber(plc.getChangeNumber());
            memberLog.setSingleAmount(plc.getCost());
            memberLog.setProcessType(plc.getProcessType());
            memberLog.setBusinessScope(policyCurrencyVO.getBusinessScope());
            memberServiceLogService.save(memberLog);
            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue())
                    .businessCode(code)
                    .pkMember(plc.getPkId())
                    .content(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getLabel() + "：政策币业务： " + plc.getEnableStatusVal() +
                            " 政策币扣款比比例(%)： " + (plc.getDeductMoney() == null ? BigDecimal.ZERO : plc.getDeductMoney()) +
                            " 政策币转账： " + (plc.getDeductMoney() == null ? "" : plc.getTransferVal()) +
                            " 业务范围： " + (plc.getDeductMoney() == null ? "" : plc.getBusinessScopeVal()))
                    .pkCreator(policyCurrencyVO.getPkCreator())
                    .pkCountry(policyCurrencyVO.getPkCountry())
                    .freeSignFlag(false).build();
            dtoList.add(businessLog);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.POLICY_CURRENCY_YES_NO)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(policyCurrencyVO.getSignType()))
                .remark(policyCurrencyVO.getRemark())
                .pkMemberList(policyCurrencyVO.getPkMemberList())
                .userIdList(policyCurrencyVO.getUserIdList())
                .sendIdList(policyCurrencyVO.getSendIdList())
                .fileList(policyCurrencyVO.getFileList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.POLICY_CURRENCY_PETITION);
        }
        //扣钱
        if (policyCurrencyVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkCountry(policyCurrencyVO.getPkCountry());
            businessCommissionDTO.setPkAccount(policyCurrencyVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(policyCurrencyVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.POLICY_CURRENCY_MONEY));
            }
        }
        if (CollectionUtil.isNotEmpty(dtoList)) {
            //发送MQ到操作日志
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                    dtoList);
        }
        return policyCurrencyVO;
    }

    /**
     * @description: 特殊业务-零元撤单-审核通过/驳回
     * @author: zhang jing
     * @date: 2023/1/6 16:37
     * @param: [updateCodeVO]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean zeroByBusinessNo(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        LambdaUpdateWrapper<CuMemberServiceLog> updateWrapper = new LambdaUpdateWrapper<>();
        //审核通过
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
            updateWrapper.set(CuMemberServiceLog::getApproveStatus, EApproveStatus.FINISH.getValue());
            //查询日志
            LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
            queryWrapper.eq(CuMemberServiceLog::getApproveStatus, EApproveStatus.ALREADY_SUBMIT.getValue());
            List<CuMemberServiceLog> memberServiceLogList = memberServiceLogService.list(queryWrapper);
            for (CuMemberServiceLog cs : memberServiceLogList) {
                ZeroElementRevokeVO zero = JSONObject.parseObject(cs.getNewValue(), ZeroElementRevokeVO.class);
                //校验会员是否存在推荐或安置
                CuMember member = new CuMember();
                member.setPkId(zero.getPkId());
                member.setPkModified(userID);
                member.setModifiedTime(date);
                if (this.checkLowerMember(zero.getPkId())) {
                    //设为死点
                    member.setCategory(ECategory.DEAD_POINT.getValue());
                    baseMapper.updateById(member);
                } else {
                    //删除
                    LambdaUpdateWrapper<CuMember> updateWrapper1 = new LambdaUpdateWrapper<>();
                    updateWrapper1.set(CuMember::getDelFlag, EDelFlag.DELETE.getValue());
                    updateWrapper1.set(CuMember::getPkModified, userID);
                    updateWrapper1.set(CuMember::getModifiedTime, date);
                    updateWrapper1.eq(CuMember::getPkId, zero.getPkId());
                    updateWrapper1.set(CuMember::getMemberCode, CommonUtil.deleteMemberCode(zero.getMemberCode()));
                    baseMapper.update(null, updateWrapper1);
                }
            }
        }
        //驳回
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.REJECTED.getValue()) {
            Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
            updateWrapper.set(CuMemberServiceLog::getApproveStatus, EApproveStatus.REJECTED.getValue());
            LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
            List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                //查询扣费金额，账户信息
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                if (null == serviceChargeDTOR.getData() ||
                        null == serviceChargeDTOR.getData().getPkAccount()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                }
                for (CuMemberServiceLog msl : list) {
                    if (StringUtils.isNotNull(msl.getSingleAmount()) && msl.getSingleAmount().compareTo(BigDecimal.ONE) > 0) {
                        MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                        memberAmountDTO.setPkMember(msl.getPkMember());
                        memberAmountDTO.setTradeAmount(msl.getSingleAmount());
                        memberAmountDTOList.add(memberAmountDTO);
                    }
                }
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    //退款
                    BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                    businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                    businessCommissionDTO.setTradeType(EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue());
                    Boolean result = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                    if (!result) {
                        throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                    }
                }
            }

        }
        updateWrapper.set(CuMemberServiceLog::getPkModified, userID);
        updateWrapper.set(CuMemberServiceLog::getModifiedTime, date);
        updateWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
        memberServiceLogService.update(updateWrapper);

        return true;
    }

    /**
     * @description: 特殊业务-修改会员编号-审核通过
     * @author: zhang jing
     * @date: 2023/1/6 16:37
     * @param: [updateCodeVO]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCodeByBusinessNo(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        UpdateCodeVO updateCodeVO = new UpdateCodeVO();
        updateCodeVO.setBusinessNo(approvalBusinessResultDTO.getBusinessCode());
        updateCodeVO.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
        queryWrapper.eq(CuMemberServiceLog::getApproveStatus, EApproveStatus.ALREADY_SUBMIT.getValue());
        List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        if (CollectionUtil.isNotEmpty(list)) {
            for (CuMemberServiceLog memberLog : list) {
                ////审核通过 修改审核状态,累加修改次数
                memberLog.setPkModified(userID);
                memberLog.setModifiedTime(date);
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.updateById(memberLog);
                //修改会员编号
                CuMember member = new CuMember();
                member.setPkId(memberLog.getPkMember());
                member.setMemberCode(memberLog.getNewValue());
                member.setPkModified(userID);
                member.setModifiedTime(date);
                baseMapper.updateById(member);
            }
        }
        return true;
    }

    /**
     * @description: 政策币签呈-审核通过-驳回
     * @author: zhang jing
     * @date: 2023/5/10 18:02
     * @param: [approvalBusinessResultDTO]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean upPolicyCurrencyProcess(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();

        LambdaUpdateWrapper<CuMemberServiceLog> updateWrapper = new LambdaUpdateWrapper<>();
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
            updateWrapper.set(CuMemberServiceLog::getApproveStatus, EApproveStatus.FINISH.getValue());
        }
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.REJECTED.getValue()) {
            Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
            updateWrapper.set(CuMemberServiceLog::getApproveStatus, EApproveStatus.REJECTED.getValue());
            LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
            List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                //查询扣费金额，账户信息
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                if (null == serviceChargeDTOR.getData() ||
                        null == serviceChargeDTOR.getData().getPkAccount()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                }
                for (CuMemberServiceLog msl : list) {
                    if (StringUtils.isNotNull(msl.getSingleAmount()) && msl.getSingleAmount().compareTo(BigDecimal.ONE) > 0) {
                        MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                        memberAmountDTO.setPkMember(msl.getPkMember());
                        memberAmountDTO.setTradeAmount(msl.getSingleAmount());
                        memberAmountDTOList.add(memberAmountDTO);
                    }
                }
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    //退款
                    BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                    businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                    businessCommissionDTO.setTradeType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
                    Boolean result = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                    if (!result) {
                        throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                    }
                }
            }

        }
        updateWrapper.set(CuMemberServiceLog::getPkModified, userID);
        updateWrapper.set(CuMemberServiceLog::getModifiedTime, date);
        updateWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
        memberServiceLogService.update(updateWrapper);
        return true;
    }

    /**
     * @description: 删除政策币业务审核
     * @author: zhang jing
     * @date: 2024/4/24 15:19
     * @param: [approvalBusinessResultDTO]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delPolicyCurrencyProcess(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
        //查询政策币数据列表
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
        LambdaUpdateWrapper<CuMemberServiceLog> updateWrapper = new LambdaUpdateWrapper<>();
        List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            //处理审核驳回
            if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.REJECTED.getValue()) {
                updateWrapper.set(CuMemberServiceLog::getApproveStatus, EApproveStatus.REJECTED.getValue());
                //查询扣费金额，账户信息
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                if (null == serviceChargeDTOR.getData() ||
                        null == serviceChargeDTOR.getData().getPkAccount()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                }
                for (CuMemberServiceLog msl : list) {
                    if (StringUtils.isNotNull(msl.getSingleAmount()) && msl.getSingleAmount().compareTo(BigDecimal.ZERO) > 0) {
                        MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                        memberAmountDTO.setPkMember(msl.getPkMember());
                        memberAmountDTO.setTradeAmount(msl.getSingleAmount());
                        memberAmountDTOList.add(memberAmountDTO);
                    }
                }
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    //退款
                    BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                    businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                    businessCommissionDTO.setTradeType(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
                    Boolean result = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                    if (!result) {
                        throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                    }
                }
            }
            //审核通过则删除政策币业务
            if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
                for (CuMemberServiceLog msl : list) {
                    UpPolicyCurrencyVO up = JSONObject.parseObject(msl.getNewValue(), UpPolicyCurrencyVO.class);
                    LambdaUpdateWrapper<CuMemberServiceLog> updateWrapper1 = new LambdaUpdateWrapper<>();
                    updateWrapper1.set(CuMemberServiceLog::getPkModified, userID);
                    updateWrapper1.set(CuMemberServiceLog::getModifiedTime, date);
                    updateWrapper1.set(CuMemberServiceLog::getDelFlag, EDelFlag.DELETE.getValue());
                    updateWrapper1.eq(CuMemberServiceLog::getPkId, up.getPkId());
                    memberServiceLogService.update(updateWrapper1);
                }
                updateWrapper.set(CuMemberServiceLog::getApproveStatus, EApproveStatus.FINISH.getValue());
            }
            updateWrapper.set(CuMemberServiceLog::getPkModified, userID);
            updateWrapper.set(CuMemberServiceLog::getModifiedTime, date);
            updateWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
            memberServiceLogService.update(updateWrapper);
        } else {
            throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_ERROR));
        }

        return true;
    }

    /**
     * @description: 特殊业务-修改会员编号-审核驳回
     * @author: zhang jing
     * @date: 2023/1/7 9:16
     * @param: [updateCodeVO]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCodeReject(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        UpdateCodeVO updateCodeVO = new UpdateCodeVO();
        updateCodeVO.setBusinessNo(approvalBusinessResultDTO.getBusinessCode());
        Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
        updateCodeVO.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
        updateCodeVO.setPkAccount(pkCountry);
        List<UpdateCodeVO> updateCodeVOList = baseMapper.puCodeAllList(updateCodeVO);
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(updateCodeVOList)) {
            //查询扣费金额，账户信息
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            serviceChargeDTO.setPkCountry(pkCountry);
            R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            if (null == serviceChargeDTOR.getData() ||
                    null == serviceChargeDTOR.getData().getPkAccount()) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
            }
            for (UpdateCodeVO uc : updateCodeVOList) {
                //审核驳回
                CuMemberServiceLog memberLog = new CuMemberServiceLog();
                memberLog.setPkId(uc.getServiceLogId());
                memberLog.setPkModified(userID);
                memberLog.setModifiedTime(date);
                memberLog.setApproveNumber(uc.getChangeNumber() - 1);
                memberLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
                memberServiceLogService.updateById(memberLog);
                if (StringUtils.isNotNull(uc.getCost())) {
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(uc.getPkId());
                    memberAmountDTO.setTradeAmount(uc.getCost());
                    memberAmountDTOList.add(memberAmountDTO);
                }
            }
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //退款
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                businessCommissionDTO.setPkCountry(pkCountry);
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                businessCommissionDTO.setTradeType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
                Boolean result = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                if (!result) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                }
            }
        }
        return true;
    }

    /**
     * 修改安置信息
     *
     * @param placeParentParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updatePlaceParent(PlaceParentParam placeParentParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (UpdatePlaceParentParam updatePlaceParentParam : placeParentParam.getUpdatePlaceParentList()) {
            CuMember member = this.getMemberByCode(updatePlaceParentParam.getMemberCode());
            updatePlaceParentParam.setPkMember(member.getPkId());
            // 安置编号
            CuMember placeParent = this.getMemberById(member.getPkPlaceParent());
            //添加修改记录表数据
            String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(member.getPkId());
            memberLog.setEditType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            // 变更前信息
            UpdatePlaceVo oldUpdatePlaceVo = new UpdatePlaceVo();
            oldUpdatePlaceVo.setPlaceDept(member.getPlaceDept());
            oldUpdatePlaceVo.setPlaceMemberCode(placeParent.getMemberCode());
            memberLog.setOldValue(JSONUtil.toJsonStr(oldUpdatePlaceVo));
            // 变更后信息
            UpdatePlaceVo newUpdatePlaceVo = new UpdatePlaceVo();
            if ("安置右区".equals(updatePlaceParentParam.getEditNewPlaceDeptStr())) {
                updatePlaceParentParam.setEditNewPlaceDept(EPlaceDept.RIGHT_DEPT.getValue());
            } else if ("安置左区".equals(updatePlaceParentParam.getEditNewPlaceDeptStr())) {
                updatePlaceParentParam.setEditNewPlaceDept(EPlaceDept.LEFT_DEPT.getValue());
            }
            newUpdatePlaceVo.setPlaceDept(updatePlaceParentParam.getEditNewPlaceDept());
            newUpdatePlaceVo.setPlaceMemberCode(updatePlaceParentParam.getEditNewPlaceMemberCode());
            memberLog.setNewValue(JSONUtil.toJsonStr(newUpdatePlaceVo));
            memberLog.setPkCreator(loginUser.getUserId());
            memberLog.setCreationTime(DateUtils.currentDateTime());
            memberLog.setBusinessNo(code);
            memberLog.setPkCountry(pkCountry);
            memberLog.setProcessType(placeParentParam.getProcessType());
            memberLog.setApproveNumber(updatePlaceParentParam.getChangeNumber());

            if (placeParentParam.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    placeParentParam.getProcessType() == EProcessType.DOUBLEAVOID.getValue()
            ) {
                // 免签/全免
                //  TODO 免签提交修改安置
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
                editPlaceParent(placeParentParam.getUpdatePlaceParentList(), false);
            } else if (placeParentParam.getProcessType() == EProcessType.AVOIDPAY.getValue() ||
                    placeParentParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()
            ) {
                // 免付/确认
                // 免支付 需签呈+支付
                //生成签呈
                Set<Long> memberSet = new HashSet<>();
                memberSet.add(loginUser.getUserId());
                memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
                memberServiceLogService.save(memberLog);
                ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.CU_MEMBER_PLACE_PARENT)
                        .businessCode(code)
                        .signType(ESignType.getEnumByValue(placeParentParam.getSignType()))
                        .remark(placeParentParam.getRemark()).pkMemberList(memberSet).userIdList(placeParentParam.getUserIdList()).build();
                R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
                if (!submit.isSuccess()) {
                    log.error("====" + submit.getData());
                    throw new RuntimeException(ConfigMsgConstants.MEMBER_UPDATE_PLACE_PARENT);
                }
            }
            //发送日志
            try {
                sendPlaceParentLog(placeParentParam, loginUser, EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue(), code);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (placeParentParam.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                placeParentParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setPkAccount(placeParentParam.getUpdatePlaceParentList().get(0).getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(placeParentParam.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_PLACE_MONEY));
            }
        }

        return null;
    }

    /**
     * 发送日志
     *
     * @param placeParentParam
     */
    public void sendPlaceParentLog(PlaceParentParam placeParentParam, LoginUser loginUser, Integer businessType, String code) {

        for (UpdatePlaceParentParam updatePlaceParentParam : placeParentParam.getUpdatePlaceParentList()) {
            StringBuilder str = new StringBuilder();
            String oldValue = updatePlaceParentParam.getOldValue();
            if (StringUtils.isNotBlank(oldValue)) {
                if (JSONUtil.isTypeJSON(oldValue)) {
                    JSONObject oldJson = JSONObject.parseObject(oldValue);
                    String placeDept = oldJson.getString("placeDept");
                    String placeMemberCode = oldJson.getString("placeMemberCode");
                    str.append("修改前安置位置").append(placeDept);
                    str.append("修改前安置编号").append(placeMemberCode);
                }
            }
            String newValue = updatePlaceParentParam.getNewValue();
            if (StringUtils.isNotBlank(newValue)) {
                JSONObject oldJson = JSONObject.parseObject(newValue);
                String placeDept = oldJson.getString("placeDept");
                String placeMemberCode = oldJson.getString("placeMemberCode");
                str.append("修改后安置位置").append(placeDept);
                str.append("修改后安置编号").append(placeMemberCode);
            }
            // 拼装发送mq
            BusinessLogDTO log = BusinessLogDTO.builder()
                    .businessType(businessType)
                    .businessCode(code)
                    .businessId(null)
                    .pkMember(updatePlaceParentParam.getPkMember())
                    .content(str.toString())
                    .pkCreator(loginUser.getUserId())
                    .pkCountry(loginUser.getDataCountry())
                    .freeSignFlag(true)
                    .build();
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
        }

    }

    /**
     * 修改直推
     *
     * @param parentParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateParent(ParentParam parentParam) {
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        LoginUser loginUser = userTokenService.getLoginUser();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.UPDATE_PARENT.getValue()); //业务单号
        parentParam.setApprovalBusiness(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
        for (UpdateParentParam uc : parentParam.getUpdateParentParamList()) {
            //添加修改记录表数据

            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkMember());
            memberLog.setEditType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.CU_MEMBER_PARENT.getValue());

            memberLog.setOldValue(getMemberById(uc.getPkParent()).getMemberCode());
            memberLog.setNewValue(uc.getEditNewPlaceMemberCode());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setBusinessNo(code);
            memberLog.setPkCountry(pkCountry);
            memberLog.setProcessType(parentParam.getProcessType());
            memberLog.setApproveNumber(uc.getChangeNumber());
            //免签呈;免签呈免支付
            if (parentParam.getProcessType() == EProcessType.AVOIDSIGNING.getValue()
                    || parentParam.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
                //修改会员编号

                CuMember newParentMember = getMemberByCode(uc.getEditNewPlaceMemberCode());

                // 修改会员直推次数
                CuMember newMember = getMemberById(uc.getPkMember());
                int directPushNumber;
                if (newMember.getDirectPushNumber() == null) {
                    directPushNumber = 1;
                } else {
                    directPushNumber = newMember.getDirectPushNumber() + 1;
                }
                // 修改直推
                baseMapper.updateParentById(memberLog.getPkMember(), newParentMember.getPkId(), directPushNumber);
            } else {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.APPROVE.getValue());
                memberServiceLogService.save(memberLog);
                // 修改会员直推次数
                CuMember newParentMember = getMemberById(uc.getPkMember());
                int directPushNumber;
                if (newParentMember.getDirectPushNumber() == null) {
                    directPushNumber = 1;
                } else {
                    directPushNumber = newParentMember.getDirectPushNumber() + 1;
                }
                // 修改直推
                baseMapper.updateParentById(memberLog.getPkMember(), newParentMember.getPkId(), directPushNumber);
            }
            //扣钱
            if (parentParam.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkCountry(pkCountry);
                businessCommissionDTO.setPkAccount(uc.getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(parentParam.getMemberAmountDTOList());
                businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
                }
            }

            try {
                // 修改直推日志
                sendUpdateParentLog(parentParam, EApprovalBusiness.CU_MEMBER_PARENT.getValue(), code, loginUser);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return code;
    }

    /**
     * 推送修改直推日志
     */
    public void sendUpdateParentLog(ParentParam parentParam, Integer businessType, String code, LoginUser loginUser) {
        for (UpdateParentParam updateParentParam : parentParam.getUpdateParentParamList()) {
            StringBuilder str = new StringBuilder();
            str.append("会员编号").append(updateParentParam.getMemberCode());
            String editNewPlaceMemberCode = updateParentParam.getEditNewPlaceMemberCode();
            str.append("变更后会员编号").append(editNewPlaceMemberCode);
            // 拼装发送mq
            BusinessLogDTO log = BusinessLogDTO.builder()
                    .businessType(businessType)
                    .businessCode(code)
                    .businessId(null)
                    .pkMember(updateParentParam.getPkMember())
                    .content(str.toString())
                    .pkCreator(loginUser.getUserId())
                    .pkCountry(loginUser.getDataCountry())
                    .freeSignFlag(true)
                    .build();
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
        }

    }

    /**
     * 修改直推业务
     *
     * @param updateParentParamList
     * @param approveStatus         EApproveStatus枚举
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String editParentLog(List<UpdateParentParam> updateParentParamList, String businessNo, EApproveStatus approveStatus) {

        // 日志列表
        List<CuMemberServiceLog> MemberServiceLogList = new ArrayList<>();
        for (UpdateParentParam updateParentParam : updateParentParamList) {
            CuMember cuMember = getMember(updateParentParam.getMemberCode());
            if (cuMember != null) {
                Long pkParent = getMember(updateParentParam.getEditNewPlaceMemberCode()).getPkId();
                CuMemberServiceLog cuMemberServiceLog = new CuMemberServiceLog();
                cuMemberServiceLog.setPkMember(cuMember.getPkId());
                cuMemberServiceLog.setEditType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
                JSONObject oldJson = new JSONObject();
                oldJson.put("memberCode", cuMember.getMemberCode());
                oldJson.put("pkParent", cuMember.getPkParent());
                cuMemberServiceLog.setOldValue(oldJson.toJSONString());
                JSONObject newJson = new JSONObject();
                newJson.put("memberCode", cuMember.getMemberCode());
                newJson.put("pkParent", pkParent);
                cuMemberServiceLog.setNewValue(newJson.toJSONString());
                cuMemberServiceLog.setCreationTime(new Date());
                cuMemberServiceLog.setPkCountry(SecurityUtils.getPkCountry());
                cuMemberServiceLog.setPkCreator(SecurityUtils.getUserId());
                cuMemberServiceLog.setApproveStatus(approveStatus.getValue());
                cuMemberServiceLog.setBusinessNo(businessNo);
                Integer maxApproveNumber = memberServiceLogService.selectByMaxApproveNumber(cuMember.getPkId(),
                        EApprovalBusiness.CU_MEMBER_PARENT.getValue(), EApproveStatus.FINISH.getValue());
                cuMemberServiceLog.setApproveNumber(maxApproveNumber + 1);
                MemberServiceLogList.add(cuMemberServiceLog);
                cuMember.setPkParent(pkParent);
            }
        }
        memberServiceLogService.saveBatch(MemberServiceLogList);
        return businessNo;
    }

    /**
     * 修改直推
     *
     * @param updateParentParamList
     */
    public void editParent(List<UpdateParentParam> updateParentParamList) {
        for (UpdateParentParam updateParentParam : updateParentParamList) {
            CuMember cuMember = getMember(updateParentParam.getMemberCode());
            Long pkParent = getMember(updateParentParam.getEditNewPlaceMemberCode()).getPkId();
            cuMember.setPkParent(pkParent);
            updateById(cuMember);
        }
    }

    /**
     * 修改安置
     *
     * @param updatePlaceParentList
     * @param isApproval            是否需要审批 false 不需要 true 需要
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String editPlaceParent(List<UpdatePlaceParentParam> updatePlaceParentList, boolean isApproval) {
        //业务单号
        String businessNo = CommonUtil.createSerialNumber(EOrderPrefix.UPDATE_PLACE_PARENT.getValue());
        // 会员列表
        List<CuMember> memberList = new ArrayList<>();

        for (UpdatePlaceParentParam updatePlace : updatePlaceParentList) {
            String memberCode = updatePlace.getMemberCode();
            LambdaQueryWrapper<CuMember> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CuMember::getMemberCode, memberCode);
            CuMember cuMember = getMember(memberCode);
            if (cuMember != null) {
                Long pkPlaceParent = getMember(updatePlace.getEditNewPlaceMemberCode()).getPkId();
                cuMember.setPlaceDept(updatePlace.getEditNewPlaceDept());
                cuMember.setPkPlaceParent(pkPlaceParent);
                memberList.add(cuMember);
            }
        }
        updateBatchById(memberList);
        return businessNo;
    }

    /**
     * 生成会员编号
     *
     * @param pkCountry 国家
     */
    @Override
    public String createUserNameByPremix(Integer pkCountry, Integer digit) {
        CountryDTO country = iCountryServiceApi.getCountry(pkCountry).getData();
        String prefix = country.getCode();
        if (StringUtils.isEmpty(prefix)) {
            return null;
        }
        // 生成loginName
        String memberCode = this.createMemberCode(prefix, digit);

        CuMember cuMemberByKey = getMember(memberCode);
        if (cuMemberByKey != null && cuMemberByKey.getPkId() > 0) {
            // 用户名已经存在，则继续尝试
            return this.createUserNameByPremix(pkCountry, digit);
        } else {
            // 验证空单注册里面是否存在编号
            List<CuMemberEmptyCode> cuMemberEmptyDetails = iCuMemberEmptyCodeService.queryCuMemberEmptyCode(memberCode);
            if (CollectionUtil.isNotEmpty(cuMemberEmptyDetails)) {
                return this.createUserNameByPremix(pkCountry, digit);
            }
        }
        return memberCode;
    }

    /**
     * 创建会员编号
     *
     * @param prefix 前缀
     * @param digit  位数
     * @return
     */
    public String createMemberCode(String prefix, Integer digit) {
        // 生成loginName
        long next = (long) (Math.random() * (99999999 - 30730000 + 1) + 30730000);
        if (null != digit && digit.equals(MagicNumberConstants.DIGIT)) {
            next = (long) (Math.random() * (999999999999L - 100000000000L + 1) + 100000000000L);
        }
        String memberCode = prefix + next;

        // 2023.10.19 需求加校验，会员编号不能出现 4 和 0
        if (memberCode.contains("4") || memberCode.contains("0")) {
            return createMemberCode(prefix, digit);
        }
        return memberCode;
    }

    /**
     * 批量生成会员编号
     *
     * @param prefix
     * @param quantity
     * @return
     */
    @Override
    public List<String> createUserCodeBatch(String prefix, Integer quantity) {
        // 生成会员编号列表
        List<String> memberCodeList = new ArrayList<>();
        // 批量生成会员编号
        this.createUserCodeBatch(prefix, quantity, memberCodeList);

        return memberCodeList;
    }

    /**
     * 批量生成会员编号
     *
     * @param prefix         前缀
     * @param quantity       生成数量
     * @param memberCodeList 会员编号列表
     * @return
     */
    private List<String> createUserCodeBatch(String prefix, Integer quantity, List<String> memberCodeList) {
        // 临时会员编号，用于查库验重
        List<String> tmpCodeList = new ArrayList<>();

        for (int i = 0; i < quantity; i++) {
            // 添加到临时会员编号
            tmpCodeList.add(this.createUserCode(prefix, memberCodeList));
        }
        // 查库，验证临时会员编号是否存在
        List<String> existList = baseMapper.checkCodeExist(tmpCodeList);

        if (CollectionUtil.isEmpty(existList)) {
            // 如果都不在库中，则直接返回会员列表
            return memberCodeList;
        }
        // 库中存在的需要清除列表中的数据
        memberCodeList.removeAll(existList);

        // 存在重复的数据，需要继续调用，把重复的数据补全
        return this.createUserCodeBatch(prefix, existList.size(), memberCodeList);
    }

    /**
     * 生成单个会员编号
     *
     * @param prefix         前缀
     * @param memberCodeList 会员编号列表
     * @return
     */
    private String createUserCode(String prefix, List<String> memberCodeList) {
        // 生成会员编号
        String memberCode = this.createMemberCode(prefix, null);

        if (CollectionUtil.isNotEmpty(memberCodeList)) {
            if (memberCodeList.contains(memberCode)) {
                // 存在于会员编号列表，则继续调用生成
                return this.createUserCode(prefix, memberCodeList);
            }
        }
        // 不存在于会员编号列表，则添加会员列表中
        memberCodeList.add(memberCode);
        return memberCode;
    }

    @Override
    public List<CuMember> findMemberByMembercodesAndPkcountry(List<String> memberCodes, Integer pkCountry) {
        return baseMapper.findMemberByMembercodesAndPkcountry(memberCodes, pkCountry);
    }

    @Override
    public List<CuMemberExt> findMemberByMemberId(List<Long> pkMemberList, Integer pkCountry) {
        return baseMapper.findMemberByMemberId(pkMemberList, pkCountry);
    }

    @Override
    public Boolean batchUpdateMemberNameAndMobileByPkmember(List<BusinessMemberVO> businessMemberList, int businessType, Long updatePkMember) {
        return baseMapper.batchUpdateMemberNameAndMobileByPkmember(businessMemberList, businessType, updatePkMember);
    }

    @Override
    public Integer batchUpdateMemberByBusinessType(HandleBusinessVO handleBusinessVO) {
        return baseMapper.batchUpdateMemberByBusinessType(handleBusinessVO);
    }


    /**
     * 招商列表
     *
     * @param marketNewsParam
     * @return
     */
    @Override
    public List<UserInvestmentVo> selectBiddingList(MarketNewsParam marketNewsParam) {
        return baseMapper.selectBiddingList(marketNewsParam);
    }

    @Override
    public List<Tree<String>> systemListTree(List<CuMemberRetailSExt> memberRetailExtList, CuMemberRetailSExt memberRetailExt, String settleTableName) {
        // 汇率
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        BigDecimal inExchangeRate = currency.getData().getInExchangeRate();

        // 查询血缘伞下团队业绩和人数
        List<Long> memberIds = memberRetailExtList.stream().map(CuMemberRetailSExt::getPkMember).collect(Collectors.toList());
        List<MemberTeamInfoVo> memberTeamInfoList = baseMapper.selectBloodKinshipUnderUmbrellaByMemberIds(memberIds);
        Map<Long, MemberTeamInfoVo> memberTeamInfoMap = memberTeamInfoList.stream().collect(Collectors.toMap(MemberTeamInfoVo::getPkMember, Function.identity(), (key1, key2) -> key2));

        Map<String, GradeDTO> gradeDtoMap = queryGradeDTOMap();
        NumberFormat numberformat = NumberFormat.getNumberInstance();

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setDeep(2);
        return TreeUtil.build(memberRetailExtList, memberRetailExt.getPkParent().toString(), treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getPkMember().toString());
                    tree.setParentId(treeNode.getPkParent().toString());
                    // 代数
                    tree.putExtra("level", treeNode.getLevel());
                    // 会员名称
                    tree.setName(treeNode.getMemberName());
                    // 会员编号
                    tree.putExtra("memberCode", treeNode.getMemberCode());
                    // 推荐人编号
                    tree.putExtra("parentMemberCode", treeNode.getParentMemberCode());
                    // 直推人数
                    Integer directPushNumber = treeNode.getPushNumber() == null ? 0 : treeNode.getPushNumber();
                    tree.putExtra("directPushNumber", directPushNumber);
                    // 直推新增业绩（结算表当天直推新増）
                    String newPerformancePv = numberformat.format(pvComputeExchangeRate(treeNode.getNewConsumePv(), CountryConstants.CHINA_COUNTRY, inExchangeRate));
                    tree.putExtra("newPerformancePv", newPerformancePv);
//                    // 血缘伞下 注册 + 升级
//                    String newPerformancePv = numberformat.format(pvComputeExchangeRate(treeNode.getConsumeAchieve(), CountryConstants.CHINA_COUNTRY, inExchangeRate));
//                    tree.putExtra("newPerformancePv", newPerformancePv);

                    // 团队人数
                    Integer numberCount = 0;
                    // 团队业绩
                    BigDecimal numberAchieve = BigDecimal.ZERO;
                    MemberTeamInfoVo memberTeamInfoVo = memberTeamInfoMap.get(treeNode.getPkMember());
                    if (null != memberTeamInfoVo) {
                        numberCount = memberTeamInfoMap.get(treeNode.getPkMember()).getNumberCount();
                        numberAchieve = pvComputeExchangeRate(memberTeamInfoMap.get(treeNode.getPkMember()).getNumberAchieve(), CountryConstants.CHINA_COUNTRY, inExchangeRate);
                    }
                    // 团队人数
                    tree.putExtra("teamNumber", numberCount);
                    // 团队业绩（当前血缘伞下 注册 + 升级）
                    tree.putExtra("teamHistoryPerformancePv", numberAchieve);

                    CuMember member = this.getMember(treeNode.getPkMember());
                    if (member != null) {
                        String payDate;
                        if (member.getPayTime() != null) {
                            payDate = DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_HH_MM_SS, member.getPayTime());
                        } else {
                            payDate = "";
                        }
                        // 拼接
                        String str = "代数:" + treeNode.getLevel() + " | " + treeNode.getMemberName() + " | " + treeNode.getMemberCode()
                                + " | 直推人数：" + directPushNumber + " | 直推业绩(pv)：" + newPerformancePv
                                + " | 团队人数：" + numberCount + " | 团队业绩(pv)：" + numberAchieve
                                + " | 创建时间 " + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_HH_MM_SS, treeNode.getCreationTime())
                                + " | 支付时间 " + payDate;
                        tree.putExtra("splice", str);
                        // 支付时间
                        tree.putExtra("payDate", payDate);
                        // 头像
                        tree.putExtra("avatarUrl", settingAvatarUrl(member, gradeDtoMap));
                    }
                });
    }

    private Map<String, GradeDTO> queryGradeDTOMap() {
        Set<Integer> countrySet = new HashSet<>();
        countrySet.add(CountryConstants.CHINA_COUNTRY);
        Map<Integer, List<GradeDTO>> countryMap = iGradeServiceApi.queryCountryGradeConfigByCondition(countrySet).getData();

        Map<String, GradeDTO> gradeDtoMap = new HashMap<>();
        countryMap.forEach((pkCountry, gradeList) -> {
            gradeList.forEach(gradeDTO -> {
                gradeDtoMap.put(pkCountry.toString() + gradeDTO.getPkId().toString(), gradeDTO);
            });
        });
        return gradeDtoMap;
    }

    /**
     * 设置头像
     *
     * @param member
     * @return
     */
    private String settingAvatarUrl(CuMember member, Map<String, GradeDTO> gradeDtoMap) {
        if (member == null) {
            return EGrade.DEAD_POINT.getImageUrl();
        }
        String key = member.getPkSettleCountry().toString() + member.getPkSettleGrade().toString();
        GradeDTO gradeDTO = gradeDtoMap.get(key);
        if (member.getPayStatus() == EPayStatus.UNPAID.getValue()) {
            // 未支付订单 黑色
            return MemberFrameworkConstants.LOG_OFF;
        }
        if (member.getCategory() == ECategory.DEAD_POINT.getValue()) {
            // 待激活
            return MemberFrameworkConstants.toBeActivated;
        }
        for (EGrade grade : EGrade.values()) {
            if (-member.getCategory() == grade.getIndex()) {
                return grade.getImageUrl();
            } else if (gradeDTO != null && gradeDTO.getGradeValue() == grade.getValue()) {
                return gradeDTO.getIcon();
            }
        }

        return MemberFrameworkConstants.xuni;
    }

    /**
     * 计算汇率
     *
     * @return
     */
    public BigDecimal pvComputeExchangeRate(BigDecimal num, Integer pkCountry, BigDecimal inExchangeRate) {
        if (num == null) {
            return BigDecimal.ZERO;
        }
        if (pkCountry != null) {
            if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                return num.multiply(inExchangeRate).setScale(0, BigDecimal.ROUND_DOWN);
            }
        }

        return num;
    }

    /**
     * @description: 特殊配置 修改结算国列表
     * @author: zhang jing
     * @date: 2023/4/28 17:24
     * @param: [upseCountryVO]
     * @return: java.util.List<com.hzs.member.base.vo.UpdateSettleCountryVO>
     **/
    @Override
    public List<UpdateSettleCountryVO> upsettleCountryList(UpdateSettleCountryVO upseCountryVO) {
        return baseMapper.upsettleCountryList(upseCountryVO);
    }

    /**
     * @description: 查询修改政策币列表
     * @author: zhang jing
     * @date: 2023/5/9 14:25
     * @param: [upVO]
     * @return: java.util.List<com.hzs.member.base.vo.UpPolicyCurrencyVO>
     **/
    @Override
    public List<UpPolicyCurrencyVO> upPolicyCurrencyList(UpPolicyCurrencyVO upVO) {
        return baseMapper.upPolicyCurrencyList(upVO);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpdateSettleCountryVO updateSettleCountry(UpdateSettleCountryVO upseCountryVO) {
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 封装修改结算国业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        upseCountryVO.setApprovalBusiness(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
        for (UpdateSettleCountryVO uc : upseCountryVO.getUpstcyVOList()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setEditType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            memberLog.setOldValue(uc.getPkSettleCountry().toString());
            memberLog.setNewValue(uc.getNewPkSettleCountry().toString());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setBusinessNo(code);
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setPkCountry(pkCountry);
            memberLog.setSingleAmount(uc.getCost());
            //免签呈
            if (upseCountryVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    upseCountryVO.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
                //修改会员结算国
                //查询用户原先的结算等级注册等级真实奖衔
                CuMember member = baseMapper.selectById(uc.getPkId());
                member.setPkId(uc.getPkId());
                member.setPkSettleCountry(uc.getNewPkSettleCountry());
                member.setPkModified(userID);
                member.setModifiedTime(date);

                //查询修改前结算国等级奖衔value值

                R<GradeDTO> gd = iGradeServiceApi.getGrade(member.getPkRegisterGrade());
                Integer pkRegisterGrade = gd.getData().getGradeValue();
                gd = iGradeServiceApi.getGrade(member.getPkSettleGrade());
                Integer pkSettleGrade = gd.getData().getGradeValue();
                gd = iGradeServiceApi.getGradeByGradeValue(pkRegisterGrade, uc.getNewPkSettleCountry());
                if (null == gd.getData()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                if (null == gd.getData().getPkId()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                member.setPkRegisterGrade(gd.getData().getPkId());
                gd = iGradeServiceApi.getGradeByGradeValue(pkSettleGrade, uc.getNewPkSettleCountry());
                if (null == gd.getData()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                if (null == gd.getData().getPkId()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                member.setPkSettleGrade(gd.getData().getPkId());
                R<BdAwards> aw = iAwardsServiceApi.getAwardsOne(member.getPkAwards());
                R<List<BdAwards>> awList = iAwardsServiceApi.queryAwards(uc.getNewPkSettleCountry());
                if (CollectionUtil.isEmpty(awList.getData())) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_AWARDS_IS_NULL));
                }
                for (BdAwards baw : awList.getData()) {
                    member.setPkAwards(null);
                    if (aw.getData().getAwardsValue().equals(baw.getAwardsValue())) {
                        member.setPkAwards(baw.getPkId());
                        break;
                    }
                }
                if (null == member.getPkAwards()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_AWARDS_IS_NULL));
                }
                LambdaUpdateWrapper<CuMemberAccount> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(CuMemberAccount::getPkCountry, uc.getNewPkSettleCountry());
                updateWrapper.eq(CuMemberAccount::getPkMember, uc.getPkId());
                memberAccountService.update(updateWrapper);
                baseMapper.updateById(member);
                CuSettleCountryDetailed countryDetailed = new CuSettleCountryDetailed();
                countryDetailed.setPkServiceLog(memberLog.getPkId());
                countryDetailed.setPkMember(uc.getPkId());
                countryDetailed.setPkCreator(userID);
                countryDetailed.setPkCountry(uc.getNewPkSettleCountry());
                countryDetailed.setCreationTime(date);
                iCuSettleCountryDetailedService.save(countryDetailed);
                countryDetailed.setPkCountry(uc.getPkSettleCountry());
                iCuSettleCountryDetailedService.save(countryDetailed);

                //组装日志数据
                BusinessLogDTO businessLog = BusinessLogDTO.builder()
                        .businessType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue())
                        .businessCode(code)
                        .pkMember(uc.getPkId())
                        .content(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getLabel() + "：变更前结算国 " + uc.getShortName() + " 变更后 " + uc.getShortName2())
                        .pkCreator(userID)
                        .pkCountry(pkCountry)
                        .freeSignFlag(true).build();
                dtoList.add(businessLog);
            }

            //扣钱
            if (upseCountryVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkCountry(pkCountry);
                businessCommissionDTO.setPkAccount(upseCountryVO.getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(upseCountryVO.getMemberAmountDTOList());
                businessCommissionDTO.setTradeType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_SETTLE_PETITION));
                }
            }
        }
        //发送MQ到操作日志
        if (CollectionUtil.isNotEmpty(dtoList)) {
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                    dtoList);
        }
        return upseCountryVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpPolicyCurrencyVO upPolicyCurrency(UpPolicyCurrencyVO policyCurrencyVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        policyCurrencyVO.setApprovalBusiness(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
        for (UpPolicyCurrencyVO plc : policyCurrencyVO.getPlculist()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(plc.getPkId());
            memberLog.setEditType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
            memberLog.setNewValue(JSONObject.toJSONString(plc));
            memberLog.setPkCreator(policyCurrencyVO.getPkCreator());
            memberLog.setCreationTime(policyCurrencyVO.getCreationTime());
            memberLog.setBusinessNo(code);
            memberLog.setApproveNumber(plc.getChangeNumber());
            memberLog.setPkCountry(policyCurrencyVO.getPkCountry());
            memberLog.setSingleAmount(plc.getCost());
            memberLog.setProcessType(plc.getProcessType());
            memberLog.setBusinessScope(policyCurrencyVO.getBusinessScope());

            //免签呈
            if (policyCurrencyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    policyCurrencyVO.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);

                //组装日志数据
                BusinessLogDTO businessLog = BusinessLogDTO.builder()
                        .businessType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue())
                        .businessCode(code)
                        .pkMember(plc.getPkId())
                        .content(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getLabel() + "：政策币业务： " + plc.getEnableStatusVal() +
                                " 政策币扣款比比例(%)： " + (plc.getDeductMoney() == null ? BigDecimal.ZERO : plc.getDeductMoney()) +
                                " 政策币转账： " + (plc.getDeductMoney() == null ? "" : plc.getTransferVal()) +
                                " 业务范围： " + (plc.getDeductMoney() == null ? "" : plc.getBusinessScopeVal()))
                        .pkCreator(policyCurrencyVO.getPkCreator())
                        .pkCountry(policyCurrencyVO.getPkCountry())
                        .freeSignFlag(true).build();
                dtoList.add(businessLog);
            }
            //扣钱
            if (policyCurrencyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkCountry(policyCurrencyVO.getPkCountry());
                businessCommissionDTO.setPkAccount(policyCurrencyVO.getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(policyCurrencyVO.getMemberAmountDTOList());
                businessCommissionDTO.setTradeType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.POLICY_CURRENCY_MONEY));
                }
            }
        }
        if (CollectionUtil.isNotEmpty(dtoList)) {
            //发送MQ到操作日志
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                    dtoList);
        }
        return policyCurrencyVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpPolicyCurrencyVO delPolicyCurrency(UpPolicyCurrencyVO policyCurrencyVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        LoginUser loginUser = userTokenService.getLoginUser();
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        policyCurrencyVO.setApprovalBusiness(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
        for (UpPolicyCurrencyVO plc : policyCurrencyVO.getPlculist()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(plc.getPkMember());
            plc.setNewValue(null);
            memberLog.setEditType(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
            memberLog.setNewValue(JSONObject.toJSONString(plc));
            memberLog.setPkCreator(policyCurrencyVO.getPkCreator());
            memberLog.setCreationTime(policyCurrencyVO.getCreationTime());
            memberLog.setBusinessNo(code);
            memberLog.setApproveNumber(plc.getChangeNumber());
            memberLog.setPkCountry(policyCurrencyVO.getPkCountry());
            memberLog.setSingleAmount(plc.getCost());
            memberLog.setProcessType(plc.getProcessType());
            memberLog.setBusinessScope(policyCurrencyVO.getBusinessScope());
            if (policyCurrencyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    policyCurrencyVO.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
            } else {
                memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            }
            memberServiceLogService.save(memberLog);

            //免签呈
            if (policyCurrencyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    policyCurrencyVO.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                LambdaUpdateWrapper<CuMemberServiceLog> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(CuMemberServiceLog::getDelFlag, EDelFlag.DELETE.getValue());
                updateWrapper.set(CuMemberServiceLog::getPkModified, policyCurrencyVO.getPkCreator());
                updateWrapper.set(CuMemberServiceLog::getModifiedTime, policyCurrencyVO.getCreationTime());
                updateWrapper.eq(CuMemberServiceLog::getPkId, plc.getPkId());
                memberServiceLogService.update(updateWrapper);

                //组装日志数据
                BusinessLogDTO businessLog = BusinessLogDTO.builder()
                        .businessType(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue())
                        .businessCode(code)
                        .pkMember(plc.getPkId())
                        .content(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getLabel() + "：政策币业务： " + plc.getEnableStatusVal() +
                                " 政策币扣款比比例(%)： " + (plc.getDeductMoney() == null ? BigDecimal.ZERO : plc.getDeductMoney()) +
                                " 政策币转账： " + (plc.getDeductMoney() == null ? "" : plc.getTransferVal()) +
                                " 业务范围： " + (plc.getDeductMoney() == null ? "" : plc.getBusinessScopeVal()))
                        .pkCreator(policyCurrencyVO.getPkCreator())
                        .pkCountry(policyCurrencyVO.getPkCountry())
                        .freeSignFlag(true).build();
                dtoList.add(businessLog);
            }
            //扣钱
            if (policyCurrencyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    policyCurrencyVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkCountry(policyCurrencyVO.getPkCountry());
                businessCommissionDTO.setPkAccount(policyCurrencyVO.getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(policyCurrencyVO.getMemberAmountDTOList());
                businessCommissionDTO.setTradeType(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.POLICY_CURRENCY_MONEY));
                }
            }
        }
        if (policyCurrencyVO.getProcessType() == EProcessType.AVOIDPAY.getValue() ||
                policyCurrencyVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            //生成签呈
            ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO)
                    .businessCode(code)
                    .signType(ESignType.getEnumByValue(policyCurrencyVO.getSignType()))
                    .remark(policyCurrencyVO.getRemark())
                    .pkMemberList(policyCurrencyVO.getPkMemberList())
                    .userIdList(policyCurrencyVO.getUserIdList())
                    .sendIdList(policyCurrencyVO.getSendIdList())
                    .fileList(policyCurrencyVO.getFileList())
                    .build();
            R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
            if (!submit.isSuccess()) {
                log.error("====" + submit.getData());
                throw new RuntimeException(ConfigMsgConstants.POLICY_CURRENCY_PETITION);
            }
        }

        if (CollectionUtil.isNotEmpty(dtoList)) {
            //发送MQ到操作日志
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                    dtoList);
        }
        return policyCurrencyVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateSettleCountryAdopt(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        UpdateSettleCountryVO upseCountryVO = new UpdateSettleCountryVO();
        upseCountryVO.setBusinessNo(approvalBusinessResultDTO.getBusinessCode());
        upseCountryVO.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
        List<UpdateSettleCountryVO> upseCountryVOList = baseMapper.upseCountryList(upseCountryVO);
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        if (CollectionUtil.isNotEmpty(upseCountryVOList)) {
            for (UpdateSettleCountryVO uc : upseCountryVOList) {
                ////审核通过 修改审核状态,累加修改次数
                CuMemberServiceLog memberLog = new CuMemberServiceLog();
                memberLog.setPkId(uc.getServiceLogId());
                memberLog.setPkModified(userID);
                memberLog.setModifiedTime(date);
                memberLog.setApproveNumber(uc.getChangeNumber());
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.updateById(memberLog);
                CuSettleCountryDetailed countryDetailed = new CuSettleCountryDetailed();
                countryDetailed.setPkServiceLog(memberLog.getPkId());
                countryDetailed.setPkMember(uc.getPkId());
                countryDetailed.setPkCreator(userID);
                countryDetailed.setPkCountry(Integer.parseInt(uc.getNewSettleCountry()));
                countryDetailed.setCreationTime(date);
                iCuSettleCountryDetailedService.save(countryDetailed);
                countryDetailed.setPkCountry(uc.getPkSettleCountry());
                iCuSettleCountryDetailedService.save(countryDetailed);
                //查询用户原先的结算等级注册等级真实奖衔
                CuMember member = baseMapper.selectById(uc.getPkId());
                //修改会员结算国
                member.setPkId(uc.getPkId());
                member.setPkModified(userID);
                member.setModifiedTime(date);

                //查询修改前结算国等级奖衔value值
                R<GradeDTO> gd = iGradeServiceApi.getGrade(member.getPkRegisterGrade());
                Integer pkRegisterGrade = gd.getData().getGradeValue();
                gd = iGradeServiceApi.getGrade(member.getPkSettleGrade());
                Integer pkSettleGrade = gd.getData().getGradeValue();
                gd = iGradeServiceApi.getGradeByGradeValue(pkRegisterGrade, Integer.parseInt(uc.getNewSettleCountry()));
                if (null == gd.getData()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                if (null == gd.getData().getPkId()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                member.setPkRegisterGrade(gd.getData().getPkId());
                gd = iGradeServiceApi.getGradeByGradeValue(pkSettleGrade, Integer.parseInt(uc.getNewSettleCountry()));
                if (null == gd.getData()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                if (null == gd.getData().getPkId()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                member.setPkSettleGrade(gd.getData().getPkId());
                R<BdAwards> aw = iAwardsServiceApi.getAwardsOne(member.getPkAwards());
                R<List<BdAwards>> awList = iAwardsServiceApi.queryAwards(Integer.parseInt(uc.getNewSettleCountry()));
                if (CollectionUtil.isEmpty(awList.getData())) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_AWARDS_IS_NULL));
                }
                for (BdAwards baw : awList.getData()) {
                    member.setPkAwards(null);
                    if (aw.getData().getAwardsValue().equals(baw.getAwardsValue())) {
                        member.setPkAwards(baw.getPkId());
                        break;
                    }
                }
                if (null == member.getPkAwards()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_AWARDS_IS_NULL));
                }
                LambdaUpdateWrapper<CuMemberAccount> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(CuMemberAccount::getPkCountry, Integer.parseInt(uc.getNewSettleCountry()));
                updateWrapper.eq(CuMemberAccount::getPkMember, uc.getPkId());
                memberAccountService.update(updateWrapper);
                member.setPkSettleCountry(Integer.parseInt(uc.getNewSettleCountry()));
                baseMapper.updateById(member);
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateSettleCountryReject(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        UpdateSettleCountryVO upseCountryVO = new UpdateSettleCountryVO();
        upseCountryVO.setBusinessNo(approvalBusinessResultDTO.getBusinessCode());
        Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
        upseCountryVO.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
        upseCountryVO.setPkCountry(pkCountry);
        List<UpdateSettleCountryVO> upseCountryVOList = baseMapper.upseCountryList(upseCountryVO);
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(upseCountryVOList)) {
            //查询扣费金额，账户信息
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            serviceChargeDTO.setPkCountry(pkCountry);
            R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            if (null == serviceChargeDTOR.getData() ||
                    null == serviceChargeDTOR.getData().getPkAccount()) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
            }
            for (UpdateSettleCountryVO uc : upseCountryVOList) {
                //审核驳回
                CuMemberServiceLog memberLog = new CuMemberServiceLog();
                memberLog.setPkId(uc.getServiceLogId());
                memberLog.setPkModified(userID);
                memberLog.setModifiedTime(date);
                memberLog.setApproveNumber(uc.getChangeNumber() - 1);
                memberLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
                memberServiceLogService.updateById(memberLog);
                if (StringUtils.isNotNull(uc.getCost()) && uc.getCost().compareTo(BigDecimal.ONE) > 0) {
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(uc.getPkId());
                    memberAmountDTO.setTradeAmount(uc.getCost());
                    memberAmountDTOList.add(memberAmountDTO);
                }
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    //退款
                    BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                    businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                    businessCommissionDTO.setTradeType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
                    Boolean result = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                    if (!result) {
                        throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                    }
                }
            }
        }
        return true;
    }

    @Override
    public Integer checkCecharge(Long pkMember) {
        return baseMapper.checkCecharge(pkMember);
    }

    @Override
    public Integer checkWithdraw(Long pkMember) {
        return baseMapper.checkWithdraw(pkMember);
    }

    @Override
    public Integer checkAccount(Long pkMember) {
        return baseMapper.checkAccount(pkMember);
    }

    @Override
    public Integer checkmsLogCount(Long pkMember, Integer editType) {
        return baseMapper.checkmsLogCount(pkMember, editType);
    }

    @Override
    public Integer checkMemberAchieveCount(Long pkMember) {
        return baseMapper.checkMemberAchieveCount(pkMember);
    }

    @Override
    public Integer getGradeTranslateValue(Integer pkId) {
        R<GradeDTO> grade = iGradeServiceApi.getGrade(pkId);
        return grade.getData().getPkTransaction();
    }

    @Override
    public Integer getAwardsTranslateValue(Integer pkCountry, Integer pkId) {
        R<BdAwards> awards = iAwardsServiceApi.getAwardsOne(pkId);
        return awards.getData().getPkTransaction();
    }

    @Override
    public boolean cancelMember(Long pkMember) {
        CuMember cuMember = baseMapper.selectById(pkMember);
        if (null == cuMember) {
            return false;
        }

        LambdaUpdateWrapper<CuMember> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CuMember::getPkId, pkMember);
        // 取消点位时，会员编号处理，防止唯一索引
        updateWrapper.set(CuMember::getMemberCode, CommonUtil.deleteMemberCode(cuMember.getMemberCode()));
        updateWrapper.set(CuMember::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(CuMember::getPkModified, pkMember);
        updateWrapper.set(CuMember::getModifiedTime, new Date());
        return this.update(updateWrapper);
    }

    @Override
    public List<CuMemberExt> queryMemberSelect(MemberSelectParam param, Integer pkCountry) {
        return baseMapper.queryMemberSelect(param, pkCountry);
    }

    @Override
    public CuMember shareRegisterMember(ShareRegisterParam registerParam) {
        // 处理等级
        GradeDTO gradeDTO = iGradeServiceApi.getGradeByGradeValue(EGrade.START_UP.getValue(), CountryConstants.CHINA_COUNTRY).getData();
        if (null == gradeDTO) {
            return null;
        }

        // 新会员信息
        CuMember cuMember = packageCuMember(registerParam, registerParam.getParentMember());
        cuMember.setPkRegisterGrade(gradeDTO.getPkId());
        cuMember.setPkSettleGrade(gradeDTO.getPkId());
        cuMember.setPkAwards(gradeDTO.getPkAwards());
        cuMemberBusinessService.saveShareMember(cuMember);
        return cuMember;
    }

    /**
     * 封装分享注册会员
     *
     * @param registerParam 分享注册入参
     * @param parentMember  推荐人
     * @return
     */
    CuMember packageCuMember(ShareRegisterParam registerParam, CuMember parentMember) {
        String email = null;
        if (Validator.isEmail(registerParam.getPhone())) {
            // 邮箱
            email = registerParam.getPhone();
        }

        // 获取新的订单编号
        CuMember cuMember = CuMember.builder()
                .memberName(registerParam.getMemberName())
                .nickName(registerParam.getMemberName())
                .phone(registerParam.getPhone())
                .pkSettleCountry(CountryConstants.CHINA_COUNTRY)
                .loginPwd(SecurityUtils.encryptPassword(registerParam.getLoginPwd()))
                .loginPassword(registerParam.getLoginPwd())
                .payPwd(SecurityUtils.encryptPassword(registerParam.getPayPwd()))
                .payPassword(registerParam.getPayPwd())
                .source(registerParam.getSource() == null ? EDataSource.H5.getValue() : registerParam.getSource())
                .pkParent(parentMember.getPkId())
                .accountStatus(EAccountStatus.NORMAL.getValue())
                .pkCenterCode(parentMember.getPkId())
                // 这个时候是待支付，等支付的时候变为支付，可以跟待支付公用
                .payStatus(EPayStatus.UNPAID.getValue())
                .category(ECategory.NORMAL.getValue())
                .orderSource(EOrderSource.SOLID.getValue())
                .consumeMoney(BigDecimal.ZERO)
                .consumeAchieve(BigDecimal.ZERO)
                .registerAuthority(ERegistrationAuthority.ORDINARY.getValue())
                .customerType(ECustomerType.FANS.getValue())
                .pkVertex(parentMember.getPkVertex())
                .systemType(parentMember.getSystemType())
                .email(email)
                .build();
        cuMember.setPkCountry(parentMember.getPkSettleCountry());
        cuMember.setCreationTime(new Date());
        // 有效期按20年来处理，休止期按21年
        cuMember.setExpireDate(DateUtils.beforeMonthLastDate(DateUtils.addYears(cuMember.getCreationTime(), 20)));
        cuMember.setStopDate(DateUtils.addMonths(cuMember.getExpireDate(), 12));

        // 获取会员编号、会员主键
        cuMember = this.createRetailMemberIdAndCode(cuMember);
        cuMember.setPkCreator(cuMember.getPkId());
        return cuMember;
    }

    @Override
    public void deleteCuMemberByPkMember(Long pkMember, Long pkApprove, Date currentDateTime) {
        LambdaUpdateWrapper<CuMember> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CuMember::getDelFlag, EYesNo.NO.getIntValue());
        updateWrapper.set(CuMember::getPkModified, pkApprove);
        updateWrapper.set(CuMember::getModifiedTime, currentDateTime);
        updateWrapper.eq(CuMember::getPkId, pkMember);
        update(updateWrapper);
    }


    @Override
    public boolean updateMemberNameAndPhone(Long pkMember, String memberName, String phone, Long pkModified) {
        LambdaUpdateWrapper<CuMember> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CuMember::getMemberName, memberName);
        updateWrapper.set(CuMember::getPhone, phone);
        updateWrapper.set(CuMember::getPkModified, pkModified);
        updateWrapper.set(CuMember::getModifiedTime, new Date());
        updateWrapper.eq(CuMember::getPkId, pkMember);
        return update(updateWrapper);
    }

    @Override
    public List<MemberRealInfoVO> selectByMemberRealInfo(MemberRealInfoParam memberRealInfoParam) {
        return baseMapper.selectByMemberRealInfo(memberRealInfoParam);
    }

    @Override
    public List<ParentMemberVo> parentList(Long pkParent, String memberCode, String memberName, Date startCreateTime, Date endCreateTime, String memberInfo) {
        return baseMapper.parentList(pkParent, memberCode, memberName, startCreateTime, endCreateTime, memberInfo);
    }

    @Override
    public List<UserInvestmentVo> selectRegList(MarketNewsParam marketNewsParam) {
        return baseMapper.selectRegList(marketNewsParam);
    }

    @Override
    public Map<String, Integer> checkMemberCodeExist(Collection<String> codeList, Boolean checkEmpty, Long excludeMemberEmpty) {
        Map<String, Integer> resultMap = new HashMap<>();

        List<MemberCountDTO> list = baseMapper.checkMemberCodeExist(codeList, checkEmpty, excludeMemberEmpty);
        if (CollectionUtil.isNotEmpty(list)) {
            for (MemberCountDTO memberCountDTO : list) {
                resultMap.put(memberCountDTO.getMemberCode(), memberCountDTO.getMemberCount());
            }
        }
        return resultMap;
    }

    @Override
    public List<CuMemberExt> findAll() {
        return baseMapper.findAll();
    }

    @Override
    public Long selectByDeptNumberCount(Long pkMember, Integer placeDept) {
        return baseMapper.selectByDeptNumberCount(pkMember, placeDept);
    }

    @Override
    public List<CuMemberExt> selectMemberByMemberCode(String memberCode, String memberName, Integer pkCountry) {
        return baseMapper.selectMemberByMemberCode(memberCode, memberName, pkCountry);
    }

    @Override
    public Integer selectExistTable(String tableName) {
        return baseMapper.selectExistTable(tableName);
    }

    @Override
    public Map<Integer, Boolean> checkIsShowWares(List<ShowWaresDTO> showWaresDTOS) {
        Map<Integer, Boolean> resultMap = new HashMap<>();

        // 血缘查询
        Set<WaresAuthorityParentParam> waresAuthorityParentParamList = new HashSet<>();
        // 安置查询
        Set<WaresAuthorityParentParam> waresAuthorityPlaceParamList = new HashSet<>();
        // 指定会员
        Set<Long> pkMemberList = new HashSet<>();

        for (ShowWaresDTO showWaresDTO : showWaresDTOS) {
            for (BdWaresAuthority bw : showWaresDTO.getWaresAuthorityList()) {
                if (bw.getAuthorityType() == EWaresPermissionType.BLOOD_ALLOW.getValue() || bw.getAuthorityType() == EWaresPermissionType.BLOOD_STOP.getValue()) {
                    // 血缘关系
                    WaresAuthorityParentParam waresAuthorityParentParam = WaresAuthorityParentParam.builder()
                            .pkMember(bw.getPkMember())
                            .loginMember(showWaresDTO.getLoginMember())
                            .build();
                    waresAuthorityParentParamList.add(waresAuthorityParentParam);
                }
                if (bw.getAuthorityType() == EWaresPermissionType.PLACE_ALLWO.getValue() || bw.getAuthorityType() == EWaresPermissionType.PLACE_STOP.getValue()) {
                    // 安置关系
                    WaresAuthorityParentParam waresAuthorityParentParam = WaresAuthorityParentParam.builder()
                            .pkMember(bw.getPkMember())
                            .loginMember(showWaresDTO.getLoginMember())
                            .build();
                    waresAuthorityPlaceParamList.add(waresAuthorityParentParam);
                }
                if (bw.getAuthorityType() == EWaresPermissionType.MEMBER.getValue()) {
                    // 指定会员可见
                    pkMemberList.add(bw.getPkMember());
                }
            }
        }

        // 查询血缘
        List<Long> waresAuthorityParentList = new ArrayList<>();
        if (waresAuthorityParentParamList.size() > 0) {
            waresAuthorityParentList = queryBloodKinshipUnderUmbrella(waresAuthorityParentParamList);
        }

        // 查询安置
        List<Long> waresAuthorityPlaceList = new ArrayList<>();
        if (waresAuthorityPlaceParamList.size() > 0) {
            waresAuthorityPlaceList = queryPlaceSponsorUnderUmbrella(waresAuthorityPlaceParamList);
        }

        for (ShowWaresDTO showWaresDTO : showWaresDTOS) {
            boolean isShowWares = true;
            for (BdWaresAuthority bdWaresAuthority : showWaresDTO.getWaresAuthorityList()) {
                if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.BLOOD_ALLOW.getValue()) {
                    // 血缘可见
                    isShowWares = waresAuthorityParentList.contains(bdWaresAuthority.getPkMember());
                } else if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.BLOOD_STOP.getValue()) {
                    // 血缘禁止
                    isShowWares = !waresAuthorityParentList.contains(bdWaresAuthority.getPkMember());
                } else if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.PLACE_ALLWO.getValue()) {
                    // 安置可见
                    isShowWares = waresAuthorityPlaceList.contains(bdWaresAuthority.getPkMember());
                } else if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.PLACE_STOP.getValue()) {
                    // 安置禁止
                    isShowWares = !waresAuthorityPlaceList.contains(bdWaresAuthority.getPkMember());
                } else if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.MEMBER.getValue()) {
                    // 指定会员可见
                    isShowWares = pkMemberList.contains(showWaresDTO.getLoginMember());
                }
                if (isShowWares) {
                    break;
                }
            }
            resultMap.put(showWaresDTO.getPkWares(), isShowWares);
        }
        return resultMap;
    }

    /**
     * 批量查询会员是否在血缘伞下
     *
     * @param waresAuthorityParentParamList
     * @return
     */
    public List<Long> queryBloodKinshipUnderUmbrella(Set<WaresAuthorityParentParam> waresAuthorityParentParamList) {
        return baseMapper.queryBloodKinshipUnderUmbrella(waresAuthorityParentParamList);
    }

    /**
     * 批量查询会员是否在安置伞下
     *
     * @param waresAuthorityParentParamList
     * @return
     */
    public List<Long> queryPlaceSponsorUnderUmbrella(Set<WaresAuthorityParentParam> waresAuthorityParentParamList) {
        return baseMapper.queryPlaceSponsorUnderUmbrella(waresAuthorityParentParamList);
    }

    @Override
    public CuMemberExt queryLastPlaceByMemberCode(String memberCode, Integer placeDept) {
        return baseMapper.queryLastPlaceByMemberCode(memberCode, placeDept);
    }

    @Override
    public List<Long> querySeqList(Integer param) {
        return baseMapper.querySeqList(param);
    }

    @Override
    public List<CuMember> queryMemberListByCode(Collection<String> memberCodeList) {
        return baseMapper.queryMemberListByCode(memberCodeList);
    }

    @Override
    public int insertBatchCuMember(List<CuMember> memberList) {
        return baseMapper.insertBatchCuMember(memberList);
    }

    @Override
    public UpdateParentPetitionParam petitionUpdateParent(UpdateParentPetitionParam updateParentPetitionParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.UPDATE_PARENT.getValue());
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (UpdateParentParam uc : updateParentPetitionParam.getUpdateParentParamList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkMember());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setPkCountry(pkCountry);
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            CuMember thisMember = this.getMember(uc.getMemberCode());
            // 用于详情展示
            CuMember oldParentMember = this.getMemberById(thisMember.getPkParent());
            memberLog.setOldValue(oldParentMember.getMemberCode());
            memberLog.setNewValue(uc.getEditNewPlaceMemberCode());
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setSingleAmount(uc.getCost());
            memberLog.setProcessType(uc.getProcessType());
            memberServiceLogService.save(memberLog);

            // 拼装发送mq
            StringBuilder str = new StringBuilder();
            str.append("会员编号").append(uc.getMemberCode());
            String editNewPlaceMemberCode = uc.getEditNewPlaceMemberCode();
            str.append("变更后会员编号").append(editNewPlaceMemberCode);
            BusinessLogDTO log = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.CU_MEMBER_PARENT.getValue())
                    .businessCode(code)
                    .businessId(null)
                    .pkMember(uc.getPkMember())
                    .content(str.toString())
                    .pkCreator(loginUser.getUserId())
                    .pkCountry(loginUser.getDataCountry())
                    .freeSignFlag(false)
                    .build();
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.CU_MEMBER_PARENT)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(updateParentPetitionParam.getSignType()))
                .remark(updateParentPetitionParam.getRemark())
                .pkMemberList(updateParentPetitionParam.getPkMemberList())
                .userIdList(updateParentPetitionParam.getUserIdList())
                .sendIdList(updateParentPetitionParam.getSendIdList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.MEMBER_UPDATE_PETITION);
        }
        //扣钱
        if (updateParentPetitionParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setPkAccount(updateParentPetitionParam.getUpdateParentParamList().get(0).getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(updateParentPetitionParam.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }

        return updateParentPetitionParam;
    }

    @Override
    public UpdatePlaceParentPetitionParam petitionUpdatePlaceParent(UpdatePlaceParentPetitionParam updatePlaceParentPetitionParam) {

        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.UPDATE_PLACE_PARENT.getValue());
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (UpdatePlaceParentParam uc : updatePlaceParentPetitionParam.getUpdateParentParamList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkMember());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setPkCountry(pkCountry);
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            memberLog.setOldValue(uc.getOldValue());
            memberLog.setNewValue(uc.getNewValue());
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setSingleAmount(uc.getCost());
            memberLog.setProcessType(updatePlaceParentPetitionParam.getProcessType());
            memberServiceLogService.save(memberLog);

            // 拼装发送mq
            StringBuilder str = new StringBuilder();
            String oldValue = uc.getOldValue();
            if (StringUtils.isNotBlank(oldValue)) {
                if (JSONUtil.isTypeJSON(oldValue)) {
                    JSONObject oldJson = JSONObject.parseObject(oldValue);
                    String placeDept = oldJson.getString("placeDept");
                    String placeMemberCode = oldJson.getString("placeMemberCode");
                    str.append("修改前安置位置").append(placeDept);
                    str.append("修改前安置编号").append(placeMemberCode);
                }
            }
            String newValue = uc.getNewValue();
            if (StringUtils.isNotBlank(newValue)) {
                JSONObject oldJson = JSONObject.parseObject(newValue);
                String placeDept = oldJson.getString("placeDept");
                String placeMemberCode = oldJson.getString("placeMemberCode");
                str.append("修改后安置位置").append(placeDept);
                str.append("修改后安置编号").append(placeMemberCode);
            }
            BusinessLogDTO log = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue())
                    .businessCode(code)
                    .businessId(null)
                    .pkMember(uc.getPkMember())
                    .content(str.toString())
                    .pkCreator(loginUser.getUserId())
                    .pkCountry(loginUser.getDataCountry())
                    .freeSignFlag(false)
                    .build();
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.CU_MEMBER_PLACE_PARENT)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(updatePlaceParentPetitionParam.getSignType()))
                .remark(updatePlaceParentPetitionParam.getRemark())
                .pkMemberList(updatePlaceParentPetitionParam.getPkMemberList())
                .userIdList(updatePlaceParentPetitionParam.getUserIdList())
                .sendIdList(updatePlaceParentPetitionParam.getSendIdList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.MEMBER_UPDATE_PETITION);
        }
        //扣钱
        if (updatePlaceParentPetitionParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkAccount(updatePlaceParentPetitionParam.getUpdateParentParamList().get(0).getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(updatePlaceParentPetitionParam.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }
        return updatePlaceParentPetitionParam;
    }

    @Override
    public void updateParentByBusinessNo(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        //修改直推
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, businessCode);
        CuMemberServiceLog memberServiceLog = memberServiceLogService.getOne(queryWrapper);
        if (memberServiceLog != null) {
            CuMember newParentMember = getMemberByCode(memberServiceLog.getNewValue());
            int directPushNumber;
            if (newParentMember.getDirectPushNumber() == null) {
                directPushNumber = 1;
            } else {
                directPushNumber = newParentMember.getDirectPushNumber() + 1;
            }
            // 修改直推
            baseMapper.updateParentById(memberServiceLog.getPkMember(), newParentMember.getPkId(), directPushNumber);
            memberServiceLog.setApproveStatus(EApproveStatus.FINISH.getValue());
            //     memberServiceLog.setApproveNumber(memberServiceLog.getApproveNumber() + 1);
            memberServiceLogService.updateById(memberServiceLog);
        }
    }

    @Override
    public void updateParentByBusinessNoReject(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        //修改直推
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, businessCode);
        CuMemberServiceLog memberServiceLog = memberServiceLogService.getOne(queryWrapper);
        if (memberServiceLog != null) {
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            //查询扣费金额，账户信息
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            serviceChargeDTO.setPkCountry(memberServiceLog.getPkCountry());
            R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            if (null == serviceChargeDTOR.getData() ||
                    null == serviceChargeDTOR.getData().getPkAccount()) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
            }
            ServiceChargeDTO serviceCharge = serviceChargeDTOR.getData();
            memberServiceLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
            memberServiceLogService.updateById(memberServiceLog);

            if (StringUtils.isNotNull(serviceCharge.getCost()) && serviceCharge.getCost().compareTo(BigDecimal.ONE) > 0) {
                MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                memberAmountDTO.setPkMember(memberServiceLog.getPkMember());
                memberAmountDTO.setTradeAmount(serviceCharge.getCost());
                memberAmountDTOList.add(memberAmountDTO);
            }
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //退款
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                businessCommissionDTO.setPkCountry(memberServiceLog.getPkCountry());
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setPkCreator(memberServiceLog.getPkCreator());
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
                Boolean b = cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                }
            }
        }
    }

    @Override
    public void updatePlaceParentByBusinessNo(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        //修改安置
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, businessCode);
        List<CuMemberServiceLog> memberServiceLogList = memberServiceLogService.list(queryWrapper);
        for (CuMemberServiceLog memberServiceLog : memberServiceLogList) {
            boolean typeJSON = JSONUtil.isTypeJSON(memberServiceLog.getNewValue());
            if (typeJSON) {
                cn.hutool.json.JSONObject jo = JSONUtil.parseObj(memberServiceLog.getNewValue());
                Integer placeDept = jo.getInt("placeDept");
                CuMember newParentMember = getMemberByCode(jo.getStr("placeMemberCode"));
                // 修改安置
                baseMapper.updatePlaceParentAndPlaceDeptById(memberServiceLog.getPkMember(), newParentMember.getPkId(), placeDept);
                memberServiceLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.updateById(memberServiceLog);
            }
        }

    }

    @Override
    public void updatePlaceParentByBusinessNoReject(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, businessCode);
        CuMemberServiceLog memberServiceLog = memberServiceLogService.getOne(queryWrapper);
        if (memberServiceLog != null) {
            memberServiceLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
            memberServiceLogService.updateById(memberServiceLog);

            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            //查询扣费金额，账户信息
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            serviceChargeDTO.setPkCountry(memberServiceLog.getPkCountry());
            R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            if (null == serviceChargeDTOR.getData() ||
                    null == serviceChargeDTOR.getData().getPkAccount()) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
            }
            ServiceChargeDTO serviceCharge = serviceChargeDTOR.getData();
            if (StringUtils.isNotNull(serviceCharge.getCost()) && serviceCharge.getCost().compareTo(BigDecimal.ONE) > 0) {
                MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                memberAmountDTO.setPkMember(memberServiceLog.getPkMember());
                memberAmountDTO.setTradeAmount(serviceCharge.getCost());
                memberAmountDTOList.add(memberAmountDTO);
            }
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //退款
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                businessCommissionDTO.setPkCountry(memberServiceLog.getPkCountry());
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
                Boolean b = cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                }
            }
        }
    }

    @Override
    public List<CuMember> queryMemberLeftRightCount(Long pkMember) {
        return baseMapper.queryMemberLeftRightCount(pkMember);
    }

    @Override
    public CuMemberExt queryRegisterOrder(String orderCode, Long pkMember) {
        return baseMapper.queryRegisterOrder(orderCode, pkMember);
    }

    @Override
    public Boolean updateMemberStatusByPkIds(List<Long> pkMembers, Long updatePkMember, Integer type) {
        LambdaUpdateWrapper<CuMember> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(CuMember::getPkId, pkMembers);
        updateWrapper.set(CuMember::getPkModified, updatePkMember);
        updateWrapper.set(CuMember::getModifiedTime, new Date());
        if (type.equals(EAuthType.REAL_NAME.getValue())) {
            updateWrapper.set(CuMember::getIsRealName, EYesNo.NO.getIntValue());
            updateWrapper.set(CuMember::getServiceAgreement, EServiceStatus.UNSIGNED.getValue());
        } else {
            updateWrapper.set(CuMember::getIsBusLicense, EYesNo.NO.getIntValue());
        }
        return this.update(updateWrapper);
    }

    @Override
    public Long checkPlaceDeptAndMemberCode(String placeDeptMemberCode, Integer placeDept) {
        return baseMapper.checkPlaceDeptAndMemberCode(placeDeptMemberCode, placeDept);
    }

    @Override
    public Long checkMemberParent(Long pkMember, String memberCode) {
        return baseMapper.checkMemberParent(pkMember, memberCode);
    }

    @Override
    public Integer updateMemberEditNumber(List<Long> pkMemberList, Long updatePkMember) {
        return baseMapper.updateMemberEditNumber(pkMemberList, updatePkMember);
    }

    @Override
    public Long checkPlaceMemberList(Long pkMember, String editNewPlaceMemberCode) {
        return baseMapper.checkPlaceMemberList(pkMember, editNewPlaceMemberCode);
    }

    @Override
    public List<CuMemberExt> queryPlaceMemberList(String memberCode, Integer pkCountry) {
        return baseMapper.queryPlaceMemberList(memberCode, pkCountry);
    }

    @Override
    public CuMemberExt queryParentVertex(Long pkMember) {
        return baseMapper.queryParentVertex(pkMember);
    }

    @Override
    public List<MemberConsumptionStatVo> getMemberConsumptionStat(MemberConsumptionStatParam memberConsumptionStatParam) {
        return baseMapper.getMemberConsumptionStat(memberConsumptionStatParam);
    }

    @Override
    public CuMemberExt getMenuMember(Long pkMember) {
        return baseMapper.getMenuMember(pkMember);
    }

    @Override
    public List<MemberServiceCodeVo> queryMemberServiceCodeList(MemberServiceCodeParam memberServiceCodeParam) {
        return baseMapper.queryMemberServiceCodeList(memberServiceCodeParam);
    }

    @Override
    public void updateMemberCodeByServiceCodeBlack(String memberCode) {
        baseMapper.updateMemberCodeByServiceCodeBlack(memberCode);
    }

    @Override
    public String getMaxServiceCode(Integer pkCountry) {
        return baseMapper.getMaxServiceCode(pkCountry);
    }

    @Override
    public CuMember getParentMember(String memberCode) {
        return baseMapper.getParentMember(memberCode);
    }

    @Override
    public List<MemberAwardsQueryVO> listMemberAwards(MemberAwardsQueryParam param, Integer pkCountry) {
        return baseMapper.listMemberAwards(param, pkCountry);
    }

    @Override
    public int countGradeMemberPoint(String memberName, String phone, Integer pkGrade, Integer pkCountry) {
        return baseMapper.countGradeMemberPoint(memberName, phone, pkGrade, pkCountry);
    }

    @Override
    public CuMemberExt getRetailMemberByCode(String memberCode) {
        return baseMapper.queryRetailLoginMember(memberCode, null);
    }

    @Override
    public List<CuMemberExt> listRetailMemberByCode(List<String> memberCodeList) {
        return baseMapper.listRetailLoginMember(memberCodeList, null);
    }

    @Override
    public CuMemberExt getRetailMemberById(Long memberId) {
        return baseMapper.queryRetailLoginMember(null, memberId);
    }

    @Override
    public CuMember createRetailMemberIdAndCode(CuMember cuMember) {
        cuMember.setPkId(baseMapper.createMemberId());
        cuMember.setMemberCode(this.createRetailMemberCode(SysConstants.RETAIL_PREFIX));
        return cuMember;
    }

    @Override
    public CuMember getRetailTopMember(Long pkMember, String memberCode, Long topPkMember, String topMemberCode) {
        return baseMapper.getRetailTopMember(pkMember, memberCode, topPkMember, topMemberCode);
    }

    /**
     * 生成会员编号
     *
     * @param prefix 会员编号前缀
     * @return
     */
    public String createRetailMemberCode(String prefix) {
        if (StringUtils.isEmpty(prefix)) {
            prefix = SysConstants.RETAIL_PREFIX;
        }
        String memberCode = this.createRetailCode(prefix);

        // 校验会员编号是否存在
        if (this.count(Wrappers.<CuMember>lambdaQuery().eq(CuMember::getMemberCode, memberCode)) > 0
                || CollectionUtil.isNotEmpty(iCuMemberEmptyCodeService.queryCuMemberEmptyCode(memberCode))
        ) {
            // 会员编号已经存在 或者 空单注册里面有，则需要重新生成
            return this.createRetailMemberCode(prefix);
        }
        return memberCode;
    }

    @Override
    public String checkRegisterRelation(String phone, String parentCode) {
        if (StringUtils.isNotEmpty(parentCode)) {
            // 验证推荐人
            CuMember parentMember = this.getMemberByCode(parentCode);
            if (null == parentMember) {
                return "推荐编号不存在";
            }
            return this.checkRegisterRelation(phone, parentMember.getSystemType());
        }
        return "推荐编号不存在";
    }

    @Override
    public String checkRegisterRelation(String phone, Long pkParent) {
        if (null != pkParent) {
            // 验证推荐人
            CuMember parentMember = this.getMemberById(pkParent);
            if (null == parentMember) {
                return "推荐人不存在";
            }
            // 2025年6月9日 - 手机号不唯一,在此不做唯一校验 - start
//            return this.checkRegisterRelation(phone, parentMember.getSystemType());
            return null;
            // 2025年6月9日 - 手机号不唯一,在此不做唯一校验 - end
        } else {
            return "推荐人不存在";
        }
    }

    /**
     * 校验系统类型手机号是否可以注册
     *
     * @param phone      联系方式
     * @param systemType 系统类型
     * @return
     */
    private String checkRegisterRelation(String phone, Integer systemType) {
        // new 手机号可以重复，不需要进行是否重复校验
        return null;
//        if (this.count(Wrappers.<CuMember>lambdaQuery()
//                .eq(CuMember::getPhone, phone)
//                .eq(CuMember::getCategory, ECategory.NORMAL.getValue())
//                .eq(CuMember::getSystemType, systemType)
//        ) == 0) {
//            // 手机号不存在，可以进行注册
//            return null;
//        }
//        return "注册信息已存在，请重新输入注册信息";
    }

    @Override
    public void saveMemberGrade(CuMemberGrade cuMemberGrade) {
        baseMapper.saveMemberGrade(cuMemberGrade);
    }

    /**
     * 生成编号
     *
     * @param prefix 编号前端
     * @return
     */
    private String createRetailCode(String prefix) {
        String memberCode = prefix + String.format("%08d", RandomUtil.randomInt(999999, 99999999));
        if (memberCode.contains("4") || memberCode.contains("0")) {
            // 编号中不能出现 4 和 0
            return createRetailCode(prefix);
        }
        return memberCode;
    }

    @Override
    public List<CuMemberExt> listMemberByPhone(String phone) {
        return baseMapper.listMemberByPhone(phone);
    }

    @Override
    public List<CuMemberExt> listRecommend(Long pkMember) {
        return baseMapper.listRecommend(pkMember);
    }

    @Override
    public List<CuMemberExt> listRetailMemberNotOrder(ShareRetailMemberParam param) {
        return baseMapper.listRetailMemberNotOrder(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void shareDelete(Long pkMember, Long userId) {
        // 当前时间
        Date nowDate = new Date();

        // 删除会员
        this.update(Wrappers.<CuMember>lambdaUpdate()
                .eq(CuMember::getPkId, pkMember)
                .set(CuMember::getDelFlag, EDelFlag.DELETE.getValue())
                .set(CuMember::getPkModified, userId)
                .set(CuMember::getModifiedTime, nowDate)
        );

        // 删除会员账户
        memberAccountService.update(Wrappers.<CuMemberAccount>lambdaUpdate()
                .eq(CuMemberAccount::getPkMember, pkMember)
                .set(CuMemberAccount::getDelFlag, EDelFlag.DELETE.getValue())
                .set(CuMemberAccount::getPkModified, userId)
                .set(CuMemberAccount::getModifiedTime, nowDate)
        );

        // 删除会员注册信息
        memberRegisterService.update(Wrappers.<CuMemberRegister>lambdaUpdate()
                .eq(CuMemberRegister::getPkMember, pkMember)
                .set(CuMemberRegister::getDelFlag, EDelFlag.DELETE.getValue())
                .set(CuMemberRegister::getPkModified, userId)
                .set(CuMemberRegister::getModifiedTime, nowDate)
        );
    }

    @Override
    public void shareParentDelete(List<CuMember> memberList, Long userId) {
        if (CollectionUtil.isNotEmpty(memberList)) {
            List<Long> pkMemberList = memberList.stream().map(CuMember::getPkId).collect(Collectors.toList());
            // 当前时间
            Date nowDate = new Date();

            // 删除会员
            this.update(Wrappers.<CuMember>lambdaUpdate()
                    .in(CuMember::getPkId, pkMemberList)
                    .set(CuMember::getDelFlag, EDelFlag.DELETE.getValue())
                    .set(CuMember::getPkModified, userId)
                    .set(CuMember::getModifiedTime, nowDate)
            );

            // 删除会员账户
            memberAccountService.update(Wrappers.<CuMemberAccount>lambdaUpdate()
                    .in(CuMemberAccount::getPkMember, pkMemberList)
                    .set(CuMemberAccount::getDelFlag, EDelFlag.DELETE.getValue())
                    .set(CuMemberAccount::getPkModified, userId)
                    .set(CuMemberAccount::getModifiedTime, nowDate)
            );

            // 删除会员注册信息
            memberRegisterService.update(Wrappers.<CuMemberRegister>lambdaUpdate()
                    .in(CuMemberRegister::getPkMember, pkMemberList)
                    .set(CuMemberRegister::getDelFlag, EDelFlag.DELETE.getValue())
                    .set(CuMemberRegister::getPkModified, userId)
                    .set(CuMemberRegister::getModifiedTime, nowDate)
            );
        }
    }

    @Override
    public List<Long> checkMemberOrder(List<Long> pkMemberList) {
        return baseMapper.checkMemberOrder(pkMemberList);
    }

    @Override
    public BdTradeWhiteConfig selectMemberByUnderBlood(Long pkMember, Integer memberType) {
        return baseMapper.selectMemberByUnderBlood(pkMember, memberType);
    }

    @Override
    public int validateCompanyCount() {
        return baseMapper.validateCompanyCount(EGrade.COMPANY.getValue());
    }

    @Override
    public int validateBranchOfficeCount(Integer areaId, Long userId) {
        return baseMapper.validateBranchOfficeCount(areaId, userId);
    }

    @Override
    public CuMember getShopkeeperMember(Long pkMember) {
        return baseMapper.getShopkeeperMember(pkMember);
    }

    @Override
    public CuMember getGradeSvipMember(Long pkMember) {
        return baseMapper.getGradeSvipMember(pkMember);
    }

    @Override
    public SaOrder listRecommendVipOrder(Long pkMember, String orderCode) {
        return baseMapper.listRecommendVipOrder(pkMember, orderCode);
    }

}
