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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
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.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.CuMemberTree;
import com.hzs.common.domain.member.base.*;
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.member.ext.CuMemberSettleExt;
import com.hzs.common.domain.sale.wares.BdWaresAuthority;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.domain.system.config.BdAwards;
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.census.param.CensusSummaryParam;
import com.hzs.member.census.vo.CensusSummaryVo;
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.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 iCuMemberRegisterService;
    @Autowired
    private ICuMemberAccountService iCuMemberAccountService;
    @Autowired
    private ICuMemberServiceLogService iCuMemberServiceLogService;
    @Autowired
    private ICuMemberTradeService iCuMemberTradeService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ICuMemberEmptyCodeService iCuMemberEmptyCodeService;
    @Autowired
    private ICuAwardsControlService iCuAwardsControlService;
    @Autowired
    private ICuSettleCountryDetailedService iCuSettleCountryDetailedService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Boolean saveMember(CuMember cuMember) {
        boolean save = false;
        try {
            if (cuMember.getIsMakerGift() == null) {
                cuMember.setIsMakerGift(EYesNo.NO.getIntValue());
            }
            Integer saveRow = baseMapper.insertCuMember(cuMember);
            if (saveRow > 0) {
                save = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        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());
        // 2023.11.02 需求调整，首单校验时，空单也算
        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) {
        CuMemberExt cuMemberExt = baseMapper.queryLoginMember(memberCode, null);
        if (null == cuMemberExt && memberCode.length() == 7) {
            return baseMapper.queryTmpLoginMember(memberCode);
        }
        return cuMemberExt;
    }

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

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

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

    @Override
    public CuMember getMember(Long pkId) {
        if (pkId == null) {
            return null;
        }
        return getCuMember(pkId);
    }

    @Override
    public CuMember queryMember(String memberCode) {
        CuMember cuMember = baseMapper.queryLoginMember(memberCode, null);
        if (null == cuMember && memberCode.length() == 7) {
            return baseMapper.queryTmpLoginMember(memberCode);
        }
        return cuMember;
    }

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

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

    private CuMember getCuMember(Long pkId) {
        return baseMapper.queryLoginMember(null, pkId);
    }

    @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) {
        return baseMapper.selectPlaceSponsorOnUmbrella(memberId, null, null);
    }

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

    @Override
    public List<CuMemberExt> querySponsorOnUmbrella(Long memberId, List<String> memberCodeList) {
        return baseMapper.querySponsorOnUmbrella(memberId, memberCodeList);
    }

    @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);
        }
    }

    /**
     * 根据会员编号，查找该会员编号极左极下的那个人
     *
     * @param memberId  会员编号
     * @param placeDept 1代表左区极左极下，2代表右区极左极下
     * @return: CuMemberExt
     */
    @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, Boolean isHaiFun) {
        cuMember.setMemberCode(createUserNameByPremix(cuMember.getPkSettleCountry(), isHaiFun, MagicNumberConstants.OLD_DIGIT));
        cuMember.setPkId(baseMapper.createMemberId());
        // 生成主键
        return cuMember;
    }

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

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

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

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

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

    @Override
    public CuMember createEmptyOrderMember(CuMemberExt member) {
        try {
            CuMember cuMember = createMemberIdAndCode(member, false);
            // 根据推荐编号查询推荐人
            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 = iCuMemberAccountService.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(cuMember.getPkCountry());
        cuMemberRegister.setPkMember(cuMember.getPkId());
        iCuMemberRegisterService.save(cuMemberRegister);
    }

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

    @Override
    public List<UpdateExpireStopVO> getMemberExpireStopList(UpdateExpireStopVO updateExpireStopVO) {
        return baseMapper.getMemberExpireStopList(updateExpireStopVO);
    }

    @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 = iCuMemberServiceLogService.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;
    }

    @Override
    public UpdateCodeVO specialBusinessQuery(UpdateCodeVO updateCodeVO) {
        return baseMapper.specialBusinessQuery(updateCodeVO);
    }

    @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());
                iCuMemberServiceLogService.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 = iCuMemberTradeService.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 UpdateExpireStopVO upExpireStop(UpdateExpireStopVO upESVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());
        upESVO.setApprovalBusiness(EApprovalBusiness.MEMBER_EXPIRE_STOP.getValue());
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        for (UpdateExpireStopVO uc : upESVO.getUesList()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setEditType(EApprovalBusiness.MEMBER_EXPIRE_STOP.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.MEMBER_EXPIRE_STOP.getValue());
            memberLog.setNewValue(JSONObject.toJSONString(uc));
            memberLog.setPkCreator(upESVO.getPkCreator());
            memberLog.setCreationTime(upESVO.getModifiedTime());
            memberLog.setModifiedTime(upESVO.getModifiedTime());
            memberLog.setBusinessNo(code);
            memberLog.setPkCountry(upESVO.getPkCountry());
            memberLog.setProcessType(upESVO.getProcessType());
            memberLog.setApproveNumber(uc.getChangeNumber());
            //免签呈;免签呈免支付
            if (upESVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
                //修改会员有效期休止期
                CuMember member = new CuMember();
                member.setPkId(uc.getPkId());
                member.setExpireDate(uc.getExpireDateNew());
                member.setStopDate(uc.getStopDateNew());
                member.setExpireStatus(uc.getExpireStatusNew());
                member.setPkModified(upESVO.getPkCreator());
                member.setModifiedTime(upESVO.getModifiedTime());
                baseMapper.updateById(member);
                //组装日志数据
                BusinessLogDTO businessLog = BusinessLogDTO.builder()
                        .businessType(EApprovalBusiness.MEMBER_EXPIRE_STOP.getValue())
                        .businessCode(code)
                        .pkMember(uc.getPkId())
                        .content(EApprovalBusiness.MEMBER_EXPIRE_STOP.getLabel() + "：变更前有效期 "
                                + uc.getExpireDateOld() + "变更后 " + uc.getExpireDateNew() + " 变更前休止期 " + uc.getStopDateOld()
                                + " 变更后 " + uc.getStopDateNew() + " 变更前状态 " + EExpireStatus.getEnumByValue(uc.getExpireStatusOld())
                                + " 变更后 " + EExpireStatus.getEnumByValue(uc.getExpireStatusNew()))
                        .pkCreator(upESVO.getPkCreator())
                        .pkCountry(upESVO.getPkCountry())
                        .freeSignFlag(true).build();
                dtoList.add(businessLog);
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
            } else if (upESVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                //组装日志数据
                BusinessLogDTO businessLog = BusinessLogDTO.builder()
                        .businessType(EApprovalBusiness.MEMBER_EXPIRE_STOP.getValue())
                        .businessCode(code)
                        .pkMember(uc.getPkId())
                        .content(EApprovalBusiness.MEMBER_EXPIRE_STOP.getLabel() + "：变更前有效期 "
                                + uc.getExpireDateOld() + "变更后 " + uc.getExpireDateNew() + " 变更前休止期 " + uc.getStopDateOld()
                                + " 变更后 " + uc.getStopDateNew() + " 变更前状态 " + EExpireStatus.getEnumByValue(uc.getExpireStatusOld())
                                + " 变更后 " + EExpireStatus.getEnumByValue(uc.getExpireStatusNew()))
                        .pkCreator(upESVO.getPkCreator())
                        .pkCountry(upESVO.getPkCountry())
                        .freeSignFlag(false).build();
                dtoList.add(businessLog);
                memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            }
            //添加修改记录表数据
            iCuMemberServiceLogService.save(memberLog);
        }
        //生成签呈
        if (upESVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            LoginUser loginUser = userTokenService.getLoginUser();
            ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.MEMBER_EXPIRE_STOP)
                    .businessCode(code)
                    .signType(ESignType.getEnumByValue(upESVO.getSignType()))
                    .remark(upESVO.getRemark())
                    .userIdList(upESVO.getUserIdList())
                    .sendIdList(upESVO.getSendIdList())
                    .fileList(upESVO.getFileList())
                    .build();
            R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
            if (!submit.isSuccess()) {
                log.error("====" + submit.getData());
                throw new RuntimeException(ConfigMsgConstants.MEMBER_UPDATE_PETITION);
            }
        }
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);

        return upESVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean upExpireStopProcess(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());
            List<CuMemberServiceLog> list = iCuMemberServiceLogService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                for (CuMemberServiceLog cs : list) {
                    UpdateExpireStopVO ues = JSONObject.parseObject(cs.getNewValue(), UpdateExpireStopVO.class);
                    //修改会员有效期休止期
                    CuMember member = new CuMember();
                    member.setPkId(ues.getPkId());
                    member.setExpireDate(ues.getExpireDateNew());
                    member.setStopDate(ues.getStopDateNew());
                    member.setExpireStatus(ues.getExpireStatusNew());
                    member.setPkModified(ues.getPkCreator());
                    member.setModifiedTime(ues.getModifiedTime());
                    baseMapper.updateById(member);
                }
            }
        }
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.REJECTED.getValue()) {
            updateWrapper.set(CuMemberServiceLog::getApproveStatus, EApproveStatus.REJECTED.getValue());
        }
        //修改日志
        updateWrapper.set(CuMemberServiceLog::getPkModified, userID);
        updateWrapper.set(CuMemberServiceLog::getModifiedTime, date);
        updateWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
        iCuMemberServiceLogService.update(updateWrapper);
        return true;
    }

    /**
     * @description: 发起签呈-修改会员编号
     **/
    @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());
            iCuMemberServiceLogService.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 = iCuMemberTradeService.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());
            iCuMemberServiceLogService.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 = iCuMemberTradeService.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());
            iCuMemberServiceLogService.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 = iCuMemberTradeService.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;
    }

    @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 = iCuMemberServiceLogService.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 = iCuMemberServiceLogService.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(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 = iCuMemberTradeService.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());
        iCuMemberServiceLogService.update(updateWrapper);

        return true;
    }

    @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 = iCuMemberServiceLogService.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());
                iCuMemberServiceLogService.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;
    }

    @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 = iCuMemberServiceLogService.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(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 = iCuMemberTradeService.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());
        iCuMemberServiceLogService.update(updateWrapper);
        return true;
    }

    @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 = iCuMemberServiceLogService.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(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 = iCuMemberTradeService.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());
                    iCuMemberServiceLogService.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());
            iCuMemberServiceLogService.update(updateWrapper);
        } else {
            throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_ERROR));
        }
        return true;
    }

    @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(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());
                iCuMemberServiceLogService.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 = iCuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                if (!result) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                }
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean awardsControlPetition(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
        queryWrapper.eq(CuMemberServiceLog::getApproveStatus, EApproveStatus.ALREADY_SUBMIT.getValue());
        List<CuMemberServiceLog> memberServiceLogList = iCuMemberServiceLogService.list(queryWrapper);
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(memberServiceLogList)) {
            for (CuMemberServiceLog cs : memberServiceLogList) {
                //审核通过 修改审核状态,累加修改次数
                cs.setPkModified(userID);
                cs.setModifiedTime(date);
                cs.setApproveStatus(approvalBusinessResultDTO.getEApproveStatus().getValue());
                iCuMemberServiceLogService.updateById(cs);
                //新增真实奖衔控制
                CuAwardsControlVO controlVO = JSONObject.parseObject(cs.getNewValue(), CuAwardsControlVO.class);
                CuAwardsControl control = BeanUtil.copyProperties(controlVO, CuAwardsControl.class);
                control.setPkMember(cs.getPkMember());
                control.setPkCountry(pkCountry);
                control.setPkCreator(userID);
                control.setCreationTime(date);

                if (StringUtils.isNotNull(controlVO.getCost())) {
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(controlVO.getPkMember());
                    memberAmountDTO.setTradeAmount(controlVO.getCost());
                    memberAmountDTO.setPkAccount(controlVO.getPkAccount());
                    memberAmountDTOList.add(memberAmountDTO);
                }
                if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue()) {
                        iCuAwardsControlService.save(control);
                    }
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue()) {
                        iCuAwardsControlService.updateById(control);
                    }
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue()) {
                        //删除真实奖衔控制
                        LambdaUpdateWrapper<CuAwardsControl> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.set(CuAwardsControl::getDelFlag, EDelFlag.DELETE.getValue());
                        updateWrapper.set(CuAwardsControl::getCreationTime, date);
                        updateWrapper.set(CuAwardsControl::getPkCreator, userID);
                        updateWrapper.eq(CuAwardsControl::getPkId, control.getPkId());
                        iCuAwardsControlService.update(updateWrapper);
                    }
                }
            }
            if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.REJECTED.getValue()) {
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    //退款
                    BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                    businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    businessCommissionDTO.setPkAccount(memberAmountDTOList.get(0).getPkAccount());
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                    businessCommissionDTO.setTradeType(approvalBusinessResultDTO.getEApprovalBusiness().getValue());
                    Boolean result = iCuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                    if (!result) {
                        throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_CONTROL_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());
                iCuMemberServiceLogService.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());
                iCuMemberServiceLogService.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 = iCuMemberTradeService.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());
                iCuMemberServiceLogService.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());
                iCuMemberServiceLogService.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 = iCuMemberTradeService.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 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;
    }

    @Override
    public String createUserNameByPremix(Integer pkCountry, Boolean isHaiFun, Integer digit) {
        String prefix;
        if (isHaiFun) {
            prefix = SysConstants.HAI_FUN_PREFIX;
        } else {
            CountryDTO country = iCountryServiceApi.getCountry(pkCountry).getData();
            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, isHaiFun, digit);
        } else {
            // 验证空单注册里面是否存在编号
            List<CuMemberEmptyCode> cuMemberEmptyDetails = iCuMemberEmptyCodeService.queryCuMemberEmptyCode(memberCode);
            if (CollectionUtil.isNotEmpty(cuMemberEmptyDetails)) {
                return this.createUserNameByPremix(pkCountry, isHaiFun, 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 pkCountry
     * @param isHaiFun
     * @param quantity
     * @return
     */
    @Override
    public List<String> createUserCodeBatch(Integer pkCountry, Boolean isHaiFun, Integer quantity) {
        String prefix;
        if (isHaiFun) {
            prefix = SysConstants.HAI_FUN_PREFIX;
        } else {
            CountryDTO country = iCountryServiceApi.getCountry(pkCountry).getData();
            prefix = country.getCode();
        }
        if (StringUtils.isEmpty(prefix)) {
            return null;
        }

        // 生成会员编号列表
        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<CuMember> findMemberByMemberCodeList(List<String> memberCodeList, Integer pkCountry) {
        return baseMapper.findMemberByMemberCodeList(memberCodeList, pkCountry);
    }

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

    @Override
    public MemberDataVO queryMemberData(Long memberId) {
        return baseMapper.queryMemberData(memberId);
    }

    @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);
    }

    /**
     * 后台设置推荐上下级
     *
     * @param memberSettleExtList 列表
     * @param memberSettleExt     顶点
     * @return
     */
    @Override
    public List<Tree<String>> systemTjSetListTree(List<CuMemberSettleExt> memberSettleExtList, CuMemberSettleExt memberSettleExt, String settleTableName, Boolean isMemberSecord) {
        R<Map<Integer, BdCountry>> allCountryMap = iCountryServiceApi.getAllCountryMap();
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
        // 查询血缘伞下团队业绩和人数
        List<Long> memberIds = memberSettleExtList.stream().map(CuMemberTree::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(memberSettleExtList);
        Map<Integer, BdCountry> allCountryData = allCountryMap.getData();
        NumberFormat numberformat = NumberFormat.getNumberInstance();
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setDeep(6);
        List<Tree<String>> build = TreeUtil.build(memberSettleExtList, memberSettleExt.getPkParent().toString(), treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getPkMember().toString());
                    tree.setParentId(treeNode.getPkParent().toString());
                    // 名称
                    tree.setName(treeNode.getMemberName());
                    // 编号
                    tree.putExtra("memberCode", treeNode.getMemberCode());
                    tree.putExtra("placeDept", treeNode.getPlaceDept());
                    tree.putExtra("parentMemberCode", treeNode.getParentMemberCode());
                    // 代数
                    tree.putExtra("level", treeNode.getLevel());
                    if (treeNode.getPkSettleCountry() != null) {
                        // 结算国
                        tree.putExtra("pkSettleCountry", allCountryData.get(treeNode.getPkSettleCountry()).getPkId());
                        tree.putExtra("settleCountryName", allCountryData.get(treeNode.getPkSettleCountry()).getName());
                        tree.putExtra("settleCountryUrl", allCountryData.get(treeNode.getPkSettleCountry()).getNationalFlag1());
                        tree.putExtra("settleCountryUrl2", allCountryData.get(treeNode.getPkSettleCountry()).getNationalFlag2());
                    }
                    if (treeNode.getPkCountry() != null) {
                        // 会员国
                        tree.putExtra("pkCountry", allCountryData.get(treeNode.getPkCountry()).getPkId());
                        tree.putExtra("countryName", allCountryData.get(treeNode.getPkCountry()).getName());
                        tree.putExtra("countryUrl", allCountryData.get(treeNode.getPkCountry()).getNationalFlag2());
                        tree.putExtra("countryUrl2", allCountryData.get(treeNode.getPkCountry()).getNationalFlag2());
                    }
                    // 直推人数
                    Long directPushNumber = treeNode.getDirectPushNumber() == null ? 0 : treeNode.getDirectPushNumber();
                    tree.putExtra("directPushNumber", directPushNumber);
                    // 直推新增业绩  注册新增 + 升级新增
                    BigDecimal registerNewPv = treeNode.getRegisterNewPv() == null ? BigDecimal.ZERO : treeNode.getRegisterNewPv();
                    BigDecimal upgradeNewPv = treeNode.getUpgradeNewPv() == null ? BigDecimal.ZERO : treeNode.getUpgradeNewPv();
                    BigDecimal ztyj = registerNewPv.add(upgradeNewPv);
                    tree.putExtra("newPerformancePv", numberformat.format(pvComputeExchangeRate(ztyj, treeNode.getPkCountry(), inExchangeRate)));

                    // 团队人数
                    Integer numberCount = 0;
                    // 团队业绩
                    BigDecimal numberAchieve = BigDecimal.ZERO;
                    MemberTeamInfoVo memberTeamInfoVo = memberTeamInfoMap.get(treeNode.getPkMember());
                    if (memberTeamInfoVo != null) {
                        numberCount = memberTeamInfoMap.get(treeNode.getPkMember()).getNumberCount();
                        numberAchieve = pvComputeExchangeRate(memberTeamInfoMap.get(treeNode.getPkMember()).getNumberAchieve(), treeNode.getPkCountry(), 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)" + ztyj + "| 团队人数" + numberCount + "|团队业绩(pv) |"
                                + numberAchieve + " 创建时间 " + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_HH_MM_SS, member.getCreationTime())
                                + "| 支付时间 " + payDate;
                        tree.putExtra("splice", str);

                        if (member.getPayTime() != null) {
                            // 支付时间
                            tree.putExtra("payDate", payDate);
                        }
                        // 头像
                        tree.putExtra("avatarUrl", settingAvatarUrl(member, gradeDtoMap));
                    }
                });
        return build;
    }

    private Map<String, GradeDTO> queryGradeDTOMap(List<CuMemberSettleExt> memberSettleExtList) {
        Set<Integer> countrySet = memberSettleExtList.stream().distinct().map(CuMemberSettleExt::getPkSettleCountry).collect(Collectors.toSet());
        Map<String, GradeDTO> gradeDtoMap = new HashMap<>();
        Map<Integer, List<GradeDTO>> countryMap = iGradeServiceApi.queryCountryGradeConfigByCondition(countrySet).getData();
        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;
    }

    /**
     * 计算中国汇率(人民币)
     *
     * @param loginUserCountry    登录用户国
     * @param amount              金额/pv
     * @param inExchangeRate      本国汇率
     * @param chinaInExchangeRate 中国汇率
     * @return
     */
    private BigDecimal computeChinaExchangeRate(Integer loginUserCountry, BigDecimal amount, BigDecimal inExchangeRate, BigDecimal chinaInExchangeRate) {
        if (loginUserCountry.equals(CountryConstants.CHINA_COUNTRY)) {
            return amount;
        }
        if (amount == null) {
            return BigDecimal.ZERO;
        }
        return amount.multiply(chinaInExchangeRate).divide(inExchangeRate, 2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 计算中国汇率(美金转人民币)
     *
     * @param loginUserCountry 登录用户国
     * @param amount           金额/pv
     * @param inExchangeRate   本国汇率
     * @return
     */
    private BigDecimal USDToRMB(Integer loginUserCountry, BigDecimal amount, BigDecimal inExchangeRate) {
        if (amount == null) {
            return BigDecimal.ZERO;
        }
        return amount.multiply(inExchangeRate);
    }

    /**
     * 计算美金汇率
     *
     * @param number         金额/pv
     * @param inExchangeRate 美金汇率
     * @return
     */
    private BigDecimal computeUSDExchangeRate(BigDecimal number, BigDecimal inExchangeRate) {
        if (number == null) {
            return BigDecimal.ZERO;
        }
        return number.divide(inExchangeRate, 2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 计算美金汇率转人民币汇率
     *
     * @param number
     * @return
     */
    private BigDecimal computeUSDToRMBRate(BigDecimal number, BigDecimal inExchangeRate) {
        if (number == null) {
            return BigDecimal.ZERO;
        }
        return number.multiply(inExchangeRate);
    }

    private BigDecimal checkIsDecimalNull(BigDecimal num) {
        if (num == null) {
            return BigDecimal.ZERO;
        }
        return num;
    }

    @Override
    public List<Tree<String>> systemAzSetListTree(List<CuMemberSettleExt> list, CuMemberSettleExt memberSettleExt) {
        R<Map<Integer, BdCountry>> allCountryMap = iCountryServiceApi.getAllCountryMap();
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        BigDecimal inExchangeRate = currency.getData().getInExchangeRate();

        R<List<BdAwards>> awardsDto = iAwardsServiceApi.queryAwards(memberSettleExt.getPkCountry());
        for (BdAwards date : awardsDto.getData()) {
            if (date.getPkId().equals(memberSettleExt.getPkAwards())) {
                memberSettleExt.setColor(date.getColor());
            }
        }
        Map<String, GradeDTO> gradeDtoMap = queryGradeDTOMap(list);
        Map<Integer, BdCountry> allCountryData = allCountryMap.getData();
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // java 千分符展示
        NumberFormat numberformat = NumberFormat.getNumberInstance();
        treeNodeConfig.setDeep(10);
        List<Tree<String>> build = TreeUtil.build(list, memberSettleExt.getPkPlaceParent().toString(), treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getPkMember().toString());
                    tree.setParentId(treeNode.getPkPlaceParent().toString());
                    tree.setName(treeNode.getMemberName());
                    tree.putExtra("memberCode", treeNode.getMemberCode());
                    tree.putExtra("placeDept", treeNode.getPlaceDept());
                    tree.putExtra("level", treeNode.getLevel());
                    tree.putExtra("parentMemberCode", treeNode.getParentMemberCode());
                    Integer pkSettleCountry = treeNode.getPkSettleCountry();
                    if (treeNode.getPkSettleCountry() != null) {
                        // 结算国
                        tree.putExtra("pkSettleCountry", allCountryData.get(treeNode.getPkSettleCountry()).getPkId());
                        tree.putExtra("settleCountryName", allCountryData.get(treeNode.getPkSettleCountry()).getName());
                        tree.putExtra("settleCountryUrl", allCountryData.get(treeNode.getPkSettleCountry()).getNationalFlag1());
                        tree.putExtra("settleCountryUrl2", allCountryData.get(treeNode.getPkSettleCountry()).getNationalFlag2());

                    }
                    for (BdAwards date : awardsDto.getData()) {
                        if (date.getPkId().equals(treeNode.getPkAwards())) {
                            tree.putExtra("color", date.getColor());
                        }
                    }
                    if (treeNode.getPkCountry() != null) {
                        // 国家
                        tree.putExtra("pkCountry", allCountryData.get(treeNode.getPkCountry()).getPkId());
                        tree.putExtra("countryName", allCountryData.get(treeNode.getPkCountry()).getName());
                        tree.putExtra("countryUrl", allCountryData.get(treeNode.getPkCountry()).getNationalFlag1());
                        tree.putExtra("countryUrl2", allCountryData.get(treeNode.getPkCountry()).getNationalFlag2());

                    }
                    CuMember member = this.getMember(treeNode.getPkMember());
                    if (member != null) {
                        if (member.getPayTime() != null) {
                            String payDate = DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_HH_MM_SS, member.getPayTime());
                            tree.putExtra("payDate", payDate);
                        }
                    }
                    tree.putExtra("avatarUrl", settingAvatarUrl(member, gradeDtoMap));

                    // TODO 数据统计
                    // 左区真实新增pv
                    tree.putExtra("leftRealNewPv", numberformat.format(pvComputeExchangeRate(treeNode.getANewPv(), pkSettleCountry, inExchangeRate).add(pvComputeExchangeRate(treeNode.getRepANewPv(), pkSettleCountry, inExchangeRate))));
                    // 右区真实新增pv
                    tree.putExtra("rightRealNewPv", numberformat.format(pvComputeExchangeRate(treeNode.getBNewPv(), pkSettleCountry, inExchangeRate).add(pvComputeExchangeRate(treeNode.getRepBNewPv(), pkSettleCountry, inExchangeRate))));
                    // 左区首购新增
                    tree.putExtra("leftFirstPurchaseAdd", numberformat.format(pvComputeExchangeRate(treeNode.getANewPv(), pkSettleCountry, inExchangeRate)));
                    // 右区首购新增
                    tree.putExtra("rightFirstPurchaseAdd", numberformat.format(pvComputeExchangeRate(treeNode.getBNewPv(), pkSettleCountry, inExchangeRate)));
                    // 左区复购新增
                    tree.putExtra("leftRepeatPurchaseAdd", numberformat.format(pvComputeExchangeRate(treeNode.getRepANewPv(), pkSettleCountry, inExchangeRate)));
                    // 右区复购新增
                    tree.putExtra("rightRepeatPurchaseAdd", numberformat.format(pvComputeExchangeRate(treeNode.getRepBNewPv(), pkSettleCountry, inExchangeRate)));
                    // 左区真实累计
                    tree.putExtra("leftRealTotal", numberformat.format(pvComputeExchangeRate(treeNode.getASumRealPv(), pkSettleCountry, inExchangeRate)));
                    // 右区真实累计
                    tree.putExtra("rightRealTotal", numberformat.format(pvComputeExchangeRate(treeNode.getBSumRealPv(), pkSettleCountry, inExchangeRate)));
                    // 左区首购累计
                    tree.putExtra("leftFirstTotal", numberformat.format(pvComputeExchangeRate(treeNode.getASumPv(), pkSettleCountry, inExchangeRate)));
                    // 右区首购累计
                    tree.putExtra("rightFirstTotal", numberformat.format(pvComputeExchangeRate(treeNode.getBSumPv(), pkSettleCountry, inExchangeRate)));
                    // 左区复购累计
                    tree.putExtra("leftRepeatPurchaseTotal", numberformat.format(pvComputeExchangeRate(treeNode.getRepASumPv(), pkSettleCountry, inExchangeRate)));
                    // 右区复购累计
                    tree.putExtra("rightRepeatPurchaseTotal", numberformat.format(pvComputeExchangeRate(treeNode.getRepBSumPv(), pkSettleCountry, inExchangeRate)));
                    // 左区首购结余
                    tree.putExtra("leftFirstSurplus", numberformat.format(pvComputeExchangeRate(treeNode.getABalance(), pkSettleCountry, inExchangeRate)));
                    // 右区首购结余
                    tree.putExtra("rightFirstSurplus", numberformat.format(pvComputeExchangeRate(treeNode.getBBalance(), pkSettleCountry, inExchangeRate)));
                    // 左区复购结余
                    tree.putExtra("leftRepeatPurchaseSurplus", numberformat.format(pvComputeExchangeRate(treeNode.getRepABalance(), pkSettleCountry, inExchangeRate)));
                    // 右区复购结余
                    tree.putExtra("rightRepeatPurchaseSurplus", numberformat.format(pvComputeExchangeRate(treeNode.getRepBBalance(), pkSettleCountry, inExchangeRate)));
                });
        return build;
    }

    @Override
    public List<Tree<String>> systemAzSetListTreeFive(List<CuMemberSettleExt> list, CuMemberSettleExt memberSettleExt) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setDeep(10);
        List<Tree<String>> build = TreeUtil.build(list, memberSettleExt.getPkPlaceParent().toString(), treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getPkMember().toString());
                    tree.setParentId(treeNode.getPkPlaceParent().toString());
                    tree.setName(treeNode.getMemberName());
                    tree.putExtra("memberCode", treeNode.getMemberCode());
                    tree.putExtra("placeDept", treeNode.getPlaceDept());
                    tree.putExtra("level", treeNode.getLevel());
                    tree.putExtra("gradeName", treeNode.getGradeName());
                    tree.putExtra("awardsName", treeNode.getAwardsName());
                    tree.putExtra("parentMemberCode", treeNode.getParentMemberCode());

                });
        return build;
    }

    /**
     * 计算汇率
     *
     * @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(2, BigDecimal.ROUND_DOWN);
            }
        }
        return num;
    }

    @Override
    public List<UpdateSettleCountryVO> upsettleCountryList(UpdateSettleCountryVO upseCountryVO) {
        return baseMapper.upsettleCountryList(upseCountryVO);
    }

    @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());
                iCuMemberServiceLogService.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());
                iCuMemberAccountService.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 = iCuMemberTradeService.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());
                iCuMemberServiceLogService.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 = iCuMemberTradeService.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());
            }
            iCuMemberServiceLogService.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());
                iCuMemberServiceLogService.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 = iCuMemberTradeService.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());
                iCuMemberServiceLogService.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());
                iCuMemberAccountService.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(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());
                iCuMemberServiceLogService.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 = iCuMemberTradeService.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 List<CensusSummaryVo> selectCensusSummary(CensusSummaryParam censusSummaryParam, List<String> days) {
        Integer loginUserCountry = SecurityUtils.getPkCountry();
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(loginUserCountry);
        // 本国汇率
        BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
        // 中国汇率
        R<CurrencyDTO> chinaCurrency = iCurrencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY);
        BigDecimal chinaInExchangeRate = chinaCurrency.getData().getInExchangeRate();
        // 根据类型查询所有人各类型的订单业绩汇总##
        List<CensusSummaryVo> censusSummaryList = new ArrayList<>();
        for (String day : days) {
            censusSummaryParam.setTime(day);
            censusSummaryParam.setPkCountry(SecurityUtils.getPkCountry());
            List<MemberMeritsSummaryVo> memberMeritsSummaryVoList = baseMapper.queryDateBySummary(censusSummaryParam);
            Map<Integer, MemberMeritsSummaryVo> memberMeritsSummaryMap = memberMeritsSummaryVoList.stream().collect(Collectors.toMap(MemberMeritsSummaryVo::getOrderType, Function.identity()));

            CensusSummaryVo censusSummaryVo = new CensusSummaryVo();
            censusSummaryVo.setSettleDate(day);
            // 特殊注册订单
            BigDecimal lxReamount = BigDecimal.ZERO;
            BigDecimal lxReachieve = BigDecimal.ZERO;
            if (memberMeritsSummaryMap.get(EOrderType.SPECIAL_REGISTER_ORDER.getValue()) != null) {
                lxReamount = memberMeritsSummaryMap.get(EOrderType.SPECIAL_REGISTER_ORDER.getValue()).getAmount();
                if (lxReamount == null) {
                    lxReamount = BigDecimal.ZERO;
                }
                lxReachieve = memberMeritsSummaryMap.get(EOrderType.SPECIAL_REGISTER_ORDER.getValue()).getAchieve();
                if (lxReachieve == null) {
                    lxReachieve = BigDecimal.ZERO;
                }
            }
            //注册 订单当中 pv是美金 金额是当地币
            BigDecimal reAmount = BigDecimal.ZERO;
            BigDecimal reAchieve = BigDecimal.ZERO;
            if (memberMeritsSummaryMap.get(EOrderType.REGISTER_ORDER.getValue()) != null) {
                reAmount = memberMeritsSummaryMap.get(EOrderType.REGISTER_ORDER.getValue()).getAmount();
                reAchieve = memberMeritsSummaryMap.get(EOrderType.REGISTER_ORDER.getValue()).getAchieve();
            }
            censusSummaryVo.setRegisterAmount(computeChinaExchangeRate(loginUserCountry, reAmount.add(lxReamount), inExchangeRate, chinaInExchangeRate));
            censusSummaryVo.setRegisterPv(computeUSDToRMBRate(reAchieve.add(lxReachieve), chinaInExchangeRate));
            censusSummaryVo.setRegisterAmountDollar(computeUSDExchangeRate(reAmount.add(lxReamount), inExchangeRate));
            censusSummaryVo.setRegisterPvDollar(checkIsDecimalNull(reAchieve.add(lxReachieve)));
            censusSummaryVo.setRegisterAmountLocality(checkIsDecimalNull(reAmount.add(lxReamount)));
            censusSummaryVo.setRegisterPvLocality(USDToRMB(loginUserCountry, reAchieve.add(lxReachieve), inExchangeRate));

            // 特殊升级
            BigDecimal lxamount = BigDecimal.ZERO;
            BigDecimal lxachieve = BigDecimal.ZERO;
            if (memberMeritsSummaryMap.get(EOrderType.SPECIAL_UPGRADE_ORDER.getValue()) != null) {
                lxamount = memberMeritsSummaryMap.get(EOrderType.SPECIAL_UPGRADE_ORDER.getValue()).getAmount();
                if (lxamount == null) {
                    lxamount = BigDecimal.ZERO;
                }
                lxachieve = memberMeritsSummaryMap.get(EOrderType.SPECIAL_UPGRADE_ORDER.getValue()).getAchieve();
                if (lxachieve == null) {
                    lxachieve = BigDecimal.ZERO;
                }
            }
            // 升级
            BigDecimal upAmount = BigDecimal.ZERO;
            BigDecimal upAchieve = BigDecimal.ZERO;
            if (memberMeritsSummaryMap.get(EOrderType.UPGRADE_ORDER.getValue()) != null) {
                upAmount = memberMeritsSummaryMap.get(EOrderType.UPGRADE_ORDER.getValue()).getAmount();
                upAchieve = memberMeritsSummaryMap.get(EOrderType.UPGRADE_ORDER.getValue()).getAchieve();
            }
            censusSummaryVo.setUpgradeAmount(computeChinaExchangeRate(loginUserCountry, upAmount.add(lxamount), inExchangeRate, chinaInExchangeRate));
            censusSummaryVo.setUpgradePv(computeUSDToRMBRate(upAchieve.add(lxachieve), chinaInExchangeRate));
            censusSummaryVo.setUpgradeAmountDollar(computeUSDExchangeRate(upAmount.add(lxamount), inExchangeRate));
            censusSummaryVo.setUpgradePvDollar(checkIsDecimalNull(upAchieve.add(lxachieve)));
            censusSummaryVo.setUpgradeAmountLocality(checkIsDecimalNull(upAmount.add(lxamount)));
            censusSummaryVo.setUpgradePvLocality(USDToRMB(loginUserCountry, upAchieve.add(lxachieve), inExchangeRate));
            //特殊升级
            if (memberMeritsSummaryMap.get(EOrderType.SPECIAL_UPGRADE_ORDER.getValue()) != null) {
                BigDecimal amount = memberMeritsSummaryMap.get(EOrderType.SPECIAL_UPGRADE_ORDER.getValue()).getAmount();
                BigDecimal achieve = memberMeritsSummaryMap.get(EOrderType.SPECIAL_UPGRADE_ORDER.getValue()).getAchieve();
                censusSummaryVo.setSpecialUpgradeAmount(computeChinaExchangeRate(loginUserCountry, amount, inExchangeRate, chinaInExchangeRate));
                censusSummaryVo.setSpecialUpgradePv(computeUSDToRMBRate(achieve, chinaInExchangeRate));
                censusSummaryVo.setSpecialUpgradeAmountDollar(computeUSDExchangeRate(amount, inExchangeRate));
                censusSummaryVo.setSpecialUpgradePvDollar(checkIsDecimalNull(achieve));
                censusSummaryVo.setSpecialUpgradeAmountLocality(checkIsDecimalNull(amount));
                censusSummaryVo.setSpecialUpgradePvLocality(USDToRMB(loginUserCountry, achieve, inExchangeRate));
            } else {
                censusSummaryVo.setSpecialUpgradeAmount(BigDecimal.ZERO);
                censusSummaryVo.setSpecialUpgradePv(BigDecimal.ZERO);
                censusSummaryVo.setSpecialUpgradeAmountDollar(BigDecimal.ZERO);
                censusSummaryVo.setSpecialUpgradePvDollar(BigDecimal.ZERO);
                censusSummaryVo.setSpecialUpgradeAmountLocality(BigDecimal.ZERO);
                censusSummaryVo.setSpecialUpgradePvLocality(BigDecimal.ZERO);
            }
            // 首购
            censusSummaryVo.setFirstPurchaseAmount(censusSummaryVo.getRegisterAmount().add(censusSummaryVo.getUpgradeAmount()));
            censusSummaryVo.setFirstPurchaseAmountDollar(censusSummaryVo.getRegisterAmountDollar().add(censusSummaryVo.getUpgradeAmountDollar()));
            censusSummaryVo.setFirstPurchasePv(censusSummaryVo.getRegisterPv().add(censusSummaryVo.getUpgradePv()));
            censusSummaryVo.setFirstPurchasePvDollar(censusSummaryVo.getRegisterPvDollar().add(censusSummaryVo.getUpgradePvDollar()));
            censusSummaryVo.setFirstPurchaseAmountLocality(censusSummaryVo.getRegisterAmountLocality().add(censusSummaryVo.getUpgradeAmountLocality()));
            censusSummaryVo.setFirstPurchasePvLocality(censusSummaryVo.getRegisterPvLocality().add(censusSummaryVo.getUpgradePvLocality()));
            // 三方
            int otherNumber = 99;
            if (memberMeritsSummaryMap.get(otherNumber) != null) {
                // 99 虚拟 用于方便统计
                BigDecimal amount = memberMeritsSummaryMap.get(otherNumber).getAmount();
                BigDecimal achieve = memberMeritsSummaryMap.get(otherNumber).getAchieve();
                censusSummaryVo.setTripartiteAmount(computeChinaExchangeRate(loginUserCountry, amount, inExchangeRate, chinaInExchangeRate));
                censusSummaryVo.setTripartitePv(computeUSDToRMBRate(achieve, chinaInExchangeRate));
                censusSummaryVo.setTripartiteAmountDollar(computeUSDExchangeRate(amount, inExchangeRate));
                censusSummaryVo.setTripartitePvDollar(checkIsDecimalNull(achieve));
                censusSummaryVo.setTripartiteAmountLocality(checkIsDecimalNull(amount));
                censusSummaryVo.setTripartitePvLocality(USDToRMB(loginUserCountry, achieve, inExchangeRate));
            } else {
                censusSummaryVo.setTripartiteAmount(BigDecimal.ZERO);
                censusSummaryVo.setTripartitePv(BigDecimal.ZERO);
                censusSummaryVo.setTripartiteAmountDollar(BigDecimal.ZERO);
                censusSummaryVo.setTripartitePvDollar(BigDecimal.ZERO);
                censusSummaryVo.setTripartiteAmountLocality(BigDecimal.ZERO);
                censusSummaryVo.setTripartitePvLocality(BigDecimal.ZERO);
            }

            censusSummaryVo.setFansAmount(BigDecimal.ZERO);
            censusSummaryVo.setHiFunPv(BigDecimal.ZERO);
            censusSummaryVo.setFansAmountDollar(BigDecimal.ZERO);
            censusSummaryVo.setHiFunPvDollar(BigDecimal.ZERO);
            censusSummaryVo.setFansAmountLocality(BigDecimal.ZERO);
            censusSummaryVo.setHiFunPvLocality(BigDecimal.ZERO);

            // 复购金额
            BigDecimal repurchaseAmount = BigDecimal.ZERO;
            // 复购业绩
            BigDecimal repurchaseAchieve = BigDecimal.ZERO;
            // 海粉金额
            BigDecimal fansAmount = BigDecimal.ZERO;
            // 海粉业绩
            BigDecimal fansAchieve = BigDecimal.ZERO;
            // 海粉升级
            BigDecimal haiFunUpgradeAmount = BigDecimal.ZERO;
            // 海粉升级
            BigDecimal haiFunUpgradeAchieve = BigDecimal.ZERO;
            // 直播订单
            BigDecimal mallOrderAmount = BigDecimal.ZERO;
            BigDecimal mallOrderAchieve = BigDecimal.ZERO;
            // 合作订单
            BigDecimal cooperateAmount = BigDecimal.ZERO;
            BigDecimal cooperateAchieve = BigDecimal.ZERO;
            // 特殊复购
            BigDecimal specialRepurchaseAmount = BigDecimal.ZERO;
            BigDecimal specialRepurchaseAchieve = BigDecimal.ZERO;
            // 3  10, 7 , 27 ，12 ， 14，19 ，22 ，26
            if (memberMeritsSummaryMap.get(EOrderType.REPURCHASE_ORDER.getValue()) != null) {
                // 复购
                repurchaseAmount = memberMeritsSummaryMap.get(EOrderType.REPURCHASE_ORDER.getValue()).getAmount();
                repurchaseAchieve = memberMeritsSummaryMap.get(EOrderType.REPURCHASE_ORDER.getValue()).getAchieve();
            }
            //复消
            if (memberMeritsSummaryMap.get(EOrderType.CONSUME_ORDER.getValue()) != null) {
                // 复消
                repurchaseAmount = repurchaseAmount.add(memberMeritsSummaryMap.get(EOrderType.CONSUME_ORDER.getValue()).getAmount());
            }
            if (memberMeritsSummaryMap.get(EOrderType.SPECIAL_REPURCHASE_ORDER.getValue()) != null) {
                // 特殊复购
                specialRepurchaseAmount = memberMeritsSummaryMap.get(EOrderType.SPECIAL_REPURCHASE_ORDER.getValue()).getAmount();
                specialRepurchaseAchieve = memberMeritsSummaryMap.get(EOrderType.SPECIAL_REPURCHASE_ORDER.getValue()).getAchieve();
            }
            // 复购金额+海粉金额+海粉升级+直播订单+合作订单+特殊复购
            BigDecimal amount = repurchaseAmount.add(fansAmount).add(haiFunUpgradeAmount)
                    .add(mallOrderAmount).add(cooperateAmount).add(specialRepurchaseAmount);

            censusSummaryVo.setRepurchaseAmount(computeChinaExchangeRate(loginUserCountry, amount, inExchangeRate, chinaInExchangeRate));
            censusSummaryVo.setRepurchaseAmountDollar(computeUSDExchangeRate(amount, inExchangeRate));
            censusSummaryVo.setRepurchaseAmountLocality(checkIsDecimalNull(amount));
            BigDecimal repurchasePvSum = repurchaseAchieve.add(fansAchieve).add(haiFunUpgradeAchieve)
                    .add(mallOrderAchieve).add(cooperateAchieve).add(specialRepurchaseAchieve);

            censusSummaryVo.setRepurchasePv(computeUSDToRMBRate(repurchasePvSum, chinaInExchangeRate));
            censusSummaryVo.setRepurchasePvDollar(checkIsDecimalNull(repurchasePvSum));
            censusSummaryVo.setRepurchasePvLocality(USDToRMB(loginUserCountry, repurchasePvSum, inExchangeRate));
            // 金额总计
            censusSummaryVo.setAmountTotal(checkIsDecimalNull(censusSummaryVo.getFirstPurchaseAmount())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchaseAmount()))
                    .add(checkIsDecimalNull(censusSummaryVo.getTripartiteAmount())));
            // 金额总计($)
            censusSummaryVo.setAmountTotalDollar(checkIsDecimalNull(censusSummaryVo.getFirstPurchaseAmountDollar())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchaseAmountDollar()))
                    .add(checkIsDecimalNull(censusSummaryVo.getTripartiteAmountDollar())));
            // 本地币 金额汇总
            censusSummaryVo.setAmountTotalLocality(checkIsDecimalNull(censusSummaryVo.getFirstPurchaseAmountLocality())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchaseAmountLocality()))
                    .add(checkIsDecimalNull(censusSummaryVo.getTripartiteAmountLocality())));
            // 业绩汇总
            censusSummaryVo.setPvTotal(checkIsDecimalNull(censusSummaryVo.getFirstPurchasePv())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchasePv()))
                    .add(checkIsDecimalNull(censusSummaryVo.getTripartitePv()))
            );
            // 业绩汇总($)
            censusSummaryVo.setPvTotalDollar(checkIsDecimalNull(censusSummaryVo.getFirstPurchasePvDollar())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchasePvDollar()))
                    .add(checkIsDecimalNull(censusSummaryVo.getTripartitePvDollar())));
            // 业绩汇总（本地币）
            censusSummaryVo.setPvTotalLocality(checkIsDecimalNull(censusSummaryVo.getFirstPurchasePvLocality())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchasePvLocality()))
                    .add(checkIsDecimalNull(censusSummaryVo.getTripartitePvLocality())));
            censusSummaryList.add(censusSummaryVo);
        }
        return censusSummaryList;
    }

    @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 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<CuMemberExt> queryCuMemberLastPlaceParent(Long pkMember) {
        return baseMapper.queryCuMemberLastPlaceParent(pkMember);
    }

    @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 List<String> findNoPayMember(List<String> memberCodes, Integer pkCountry) {
        return baseMapper.findNoPayMember(memberCodes, pkCountry);
    }

    @Override
    public int checkParent(String topCode, Long pkMember) {
        return baseMapper.checkParent(topCode, pkMember);
    }

    @Override
    public CuMemberExt checkMemberByParentList(List<String> topCodeList, Long userId) {
        return baseMapper.checkMemberByParentList(topCodeList, userId);
    }

    @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) {
            if (CollectionUtil.isNotEmpty(showWaresDTO.getWaresAuthorityList())) {
                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;
            if (CollectionUtil.isNotEmpty(showWaresDTO.getWaresAuthorityList())) {
                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 Long checkPlaceSponsorUnderUmbrella(Long pkMember, String memberCode) {
        return baseMapper.checkPlaceSponsorUnderUmbrella(pkMember, memberCode);
    }

    @Override
    public int checkPlaceParent(String topCode, Long pkMember) {
        return baseMapper.checkPlaceParent(topCode, pkMember);
    }

    @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());
            iCuMemberServiceLogService.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 = iCuMemberTradeService.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());
            iCuMemberServiceLogService.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 = iCuMemberTradeService.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 = iCuMemberServiceLogService.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());
            iCuMemberServiceLogService.updateById(memberServiceLog);
        }
    }

    @Override
    public void updateParentByBusinessNoReject(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        //修改直推
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, businessCode);
        CuMemberServiceLog memberServiceLog = iCuMemberServiceLogService.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(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL);
            }
            ServiceChargeDTO serviceCharge = serviceChargeDTOR.getData();
            memberServiceLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
            iCuMemberServiceLogService.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 = iCuMemberTradeService.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 = iCuMemberServiceLogService.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());
                iCuMemberServiceLogService.updateById(memberServiceLog);
            }
        }
    }

    @Override
    public void updatePlaceParentByBusinessNoReject(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberServiceLog::getBusinessNo, businessCode);
        CuMemberServiceLog memberServiceLog = iCuMemberServiceLogService.getOne(queryWrapper);
        if (memberServiceLog != null) {
            memberServiceLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
            iCuMemberServiceLogService.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(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 = iCuMemberTradeService.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 queryFansOrder(String orderCode) {
        return baseMapper.queryFansOrder(orderCode);
    }

    @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 List<CuMemberExt> selectPlaceErrorCode() {
        return baseMapper.selectPlaceErrorCode();
    }

    @Override
    public Boolean queryCuMemberUnderUmbrella(Long pkMember) {
        List<CuMember> cuMemberList = baseMapper.queryCuMemberUnderUmbrella(pkMember);
        return cuMemberList != null && cuMemberList.size() > 0;
    }

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

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

    @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 List<CuMember> checkMemberPlaceParent(Long pkMember, String editNewPlaceMemberCode) {
        return baseMapper.checkMemberPlaceParent(pkMember, editNewPlaceMemberCode);
    }

    @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 Integer updateMemberExpireDate() {
        return baseMapper.updateMemberExpireDate();
    }

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

    @Override
    public CuMemberExt querySameMemberByAwards(String memberName, String phone, Integer pkCountry) {
        return baseMapper.querySameMemberByAwards(memberName, phone, pkCountry);
    }

    @Override
    public int resetExpireAndStopDate(String memberName, String phone, Date expireDate, Date stopDate, Integer pkCountry) {
        return baseMapper.resetExpireAndStopDate(memberName, phone, expireDate, stopDate, pkCountry);
    }

    @Override
    public int updateExpireAndStopDate(Long pkMember, String memberName, String phone, Date expireDate, Integer stopMonth, Integer pkCountry) {
        return baseMapper.updateExpireAndStopDate(pkMember, memberName, phone, expireDate, stopMonth, pkCountry);
    }

    @Override
    public int updateStopDate(Long pkMember, String memberName, String phone, Integer stopMonth, Integer pkCountry) {
        return baseMapper.updateStopDate(pkMember, memberName, phone, stopMonth, pkCountry);
    }

    @Override
    public int updateExpireAndStopDateByChange(Long pkMember, String memberName, String phone, Integer stopMonth, Integer pkCountry) {
        return baseMapper.updateExpireAndStopDateByChange(pkMember, memberName, phone, stopMonth, pkCountry);
    }

    @Override
    public int updateExpireStatus(Long pkMember, String memberName, String phone, Integer pkCountry) {
        return baseMapper.updateExpireStatus(pkMember, memberName, phone, pkCountry);
    }

    @Override
    public int flushStopDateBatch(Integer pkCountry) {
        return baseMapper.flushStopDateBatch(pkCountry);
    }

    @Override
    public int flushExpireStatusBatch(Integer pkCountry) {
        return baseMapper.flushExpireStatusBatch(pkCountry);
    }

    @Override
    public int flushStopStatusBatch(Integer pkCountry) {
        return baseMapper.flushStopStatusBatch(pkCountry);
    }

    @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 int countGradeMemberPoint(String memberName, String phone, Integer pkGrade, Integer pkCountry) {
        return baseMapper.countGradeMemberPoint(memberName, phone, pkGrade, pkCountry);
    }

}
