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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
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.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.service.RedisService;
import com.hzs.common.core.utils.*;
import com.hzs.common.domain.member.account.CuMemberAccount;
import com.hzs.common.domain.member.account.CuMemberTrade;
import com.hzs.common.domain.member.achieve.CuMemberTree;
import com.hzs.common.domain.member.annuity.CuMemberAnnuity;
import com.hzs.common.domain.member.base.*;
import com.hzs.common.domain.member.detail.CuMemberAwards;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.member.empty.CuMemberEmptyCode;
import com.hzs.common.domain.member.ext.*;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.wares.BdWaresAuthority;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.domain.system.config.BdAccount;
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.core.utils.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.achieve.mapper.CuMemberTreeMapper;
import com.hzs.member.annuity.service.ICuMemberAnnuityService;
import com.hzs.member.base.controller.manager.UpdatePlaceParentPetitionParam;
import com.hzs.member.base.dto.MemberCountDTO;
import com.hzs.member.base.dto.NotActivePointDTO;
import com.hzs.member.base.dto.ShowWaresDTO;
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.member.param.MemberParam;
import com.hzs.member.pub.tool.MemberToolsHandler;
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.IAccountServiceApi;
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.LoginUser;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
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.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

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

    @Autowired
    private CuMemberTreeMapper memberTreeMapper;
    @Autowired
    private MemberToolsHandler memberToolsHandler;
    @Autowired
    private ICuMemberAnnuityService memberAnnuityService;
    @Autowired
    private ICuMemberRegisterService memberRegisterService;
    @Autowired
    private ICuMemberAccountService memberAccountService;
    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ICuMemberEmptyCodeService iCuMemberEmptyCodeService;
    @Autowired
    private ICuAwardsControlService controlService;
    @Autowired
    private ICuMemberAccountService iCuMemberAccountService;
    @Autowired
    private ICuSettleCountryDetailedService iCuSettleCountryDetailedService;
    @Autowired
    private ICuMemberTeamService memberTeamService;
    @Autowired
    private ICuMemberBusinessService cuMemberBusinessService;
    @Autowired
    private RedisService redisService;

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

    @Override
    public Boolean saveMember(CuMember cuMember) {
        boolean save;
        try {
            Integer saveRow = baseMapper.insertCuMember(cuMember);
            save = saveRow > 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return save;
    }

    @Override
    public Integer queryCuMemberByPkMember(Long pkReference) {
        QueryWrapper<CuMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(MemberFieldConstants.PK_PARENT, pkReference);
        log.info("推荐人主键:{}", pkReference);
        queryWrapper.eq("CATEGORY", ECategory.NORMAL.getValue());
        queryWrapper.eq("PAY_STATUS", EPayStatus.PAID.getValue());
        List<Integer> customerList = new ArrayList<>();
        customerList.add(ECustomerType.NORMAL.getValue());
        customerList.add(ECustomerType.EMPTY_ORDER.getValue());
        queryWrapper.in("CUSTOMER_TYPE", customerList);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count == null ? 0 : count;
    }

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

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

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

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

    @Override
    public List<Integer> queryMemberDept(Long pkMember) {
        QueryWrapper<CuMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(MemberFieldConstants.PK_PLACE_PARENT, pkMember);
        List<CuMember> cuMemberList = baseMapper.selectList(queryWrapper);
        return cuMemberList.stream().map(CuMember::getPlaceDept).collect(Collectors.toList());
    }

    @Override
    public CuMember getMember(String memberCode) {
        if (StringUtils.isEmpty(memberCode)) {
            return null;
        }
        return initializeMember(memberCode);
    }

    private CuMember initializeMember(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(Long pkMember) {
        return baseMapper.queryLoginMember(null, pkMember);
    }

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

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

    @Override
    public List<CuMember> queryCuMemberByPkId(Long pkMember) {
        QueryWrapper<CuMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(MemberFieldConstants.PK_PARENT, pkMember)
                .or()
                .eq(MemberFieldConstants.PK_PLACE_PARENT, pkMember);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public boolean checkLowerMember(Long pkMember) {
        QueryWrapper<CuMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(MemberFieldConstants.PK_PARENT, pkMember)
                .or()
                .eq(MemberFieldConstants.PK_PLACE_PARENT, 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> selectPlaceSponsorUnderUmbrellaByCondition(Long memberId, List<CuMemberExt> cuMemberExtList) {
        return baseMapper.selectPlaceSponsorUnderUmbrellaByCondition(memberId, cuMemberExtList);
    }

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

    @Override
    public CuMemberExt queryPlaceSponsorLastLeft(Long memberId, Integer placeDept) {
        CuMemberExt cuMemberExt = baseMapper.selectPlaceSponsorLastLeft(memberId, placeDept);
        if (placeDept == EPlaceDept.LEFT_DEPT.getValue()) {
            return cuMemberExt;
        } else {
            // 1判断是否存在极右极左 至少2层推荐
            // 2不存在查询code是否存在第二部门安置人 1层推荐
            // 3不存在 code就是右区的极左极下 没有推荐
            if (cuMemberExt == null) {
                List<CuMemberExt> cuMemberExtList = baseMapper.queryMemberInfoByCondition(
                        CuMember.builder().pkPlaceParent(memberId).placeDept(placeDept).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());
        generateNumber(cuMember, cuMember.getPkSettleCountry());
        // 生成主键
        return cuMember;
    }

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

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

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

    @Override
    public List<CuMemberVO> realCuMemberByCondition(CuMemberVO memberParam) {
        if (memberParam.getEndDate() != null) {
            memberParam.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, memberParam.getEndDate()));
        }
        if (memberParam.getEndDatePay() != null) {
            memberParam.setEndDatePay(DateUtils.afterDate(1, ChronoUnit.DAYS, memberParam.getEndDatePay()));
        }
        if (memberParam.getEndAttestationTime() != null) {
            memberParam.setEndAttestationTime(DateUtils.afterDate(1, ChronoUnit.DAYS, memberParam.getEndAttestationTime()));
        }
        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 = memberAccountService.updateMemberAccount(cuMemberAccount, member.getPkCreator());
                if (!b) {
                    return null;
                }
            }
            //   会员注册信息
            saveMemberRegister(cuMember);
            return cuMember;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }

    }

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

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

    @Override
    public 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());

        for (UpdateCodeVO uc : updateCode.getUpdateCodeVOList()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setEditType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            memberLog.setOldValue(uc.getMemberCode());
            memberLog.setNewValue(uc.getMemberCodeNew());
            memberLog.setPkCreator(updateCode.getPkCreator());
            memberLog.setCreationTime(updateCode.getCreationTime());
            memberLog.setBusinessNo(code);
            memberLog.setPkCountry(updateCode.getPkCountry());
            memberLog.setProcessType(updateCode.getProcessType());
            memberLog.setApproveNumber(uc.getChangeNumber());
            //免签呈;免签呈免支付
            if (updateCode.getProcessType() == EProcessType.AVOIDSIGNING.getValue()
                    || updateCode.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
                //修改会员编号
                CuMember member = new CuMember();
                member.setPkId(uc.getPkId());
                member.setMemberCode(uc.getMemberCodeNew());
                member.setPkModified(updateCode.getPkCreator());
                member.setModifiedTime(updateCode.getCreationTime());
                baseMapper.updateById(member);
            }
        }
        //扣钱
        if (updateCode.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(updateCode.getPkCountry());
            businessCommissionDTO.setMemberAmountDTOList(updateCode.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }
        return updateCode;
    }

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

        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());

        LoginUser loginUser = userTokenService.getLoginUser();
        for (UpdateCodeVO uc : updateCodeVO.getUpdateParentParamList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setPkCreator(updateCodeVO.getPkCreator());
            memberLog.setCreationTime(updateCodeVO.getCreationTime());
            memberLog.setPkCountry(updateCodeVO.getPkCountry());
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            memberLog.setOldValue(uc.getMemberCode());
            memberLog.setNewValue(uc.getMemberCodeNew());
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setSingleAmount(uc.getCost());
            memberLog.setProcessType(updateCodeVO.getProcessType());
            memberServiceLogService.save(memberLog);
        }
        //生成签呈
        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(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_PETITION));
        }
        //扣钱
        if (updateCodeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkCountry(updateCodeVO.getPkCountry());
            businessCommissionDTO.setPkAccount(updateCodeVO.getUpdateParentParamList().get(0).getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(updateCodeVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }
        return updateCodeVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpdateSettleCountryVO petition(UpdateSettleCountryVO upseCountryVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (UpdateSettleCountryVO uc : upseCountryVO.getUpstcyVOList()) {
            // 修改审核状态
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setPkCountry(pkCountry);
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            memberLog.setOldValue(uc.getPkSettleCountry().toString());
            memberLog.setNewValue(uc.getNewPkSettleCountry().toString());
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setSingleAmount(uc.getCost());
            memberLog.setProcessType(upseCountryVO.getProcessType());
            memberServiceLogService.save(memberLog);
        }
        //生成签呈
        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(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_SETTLE_PETITION));
        }
        //扣钱
        if (upseCountryVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkAccount(upseCountryVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(upseCountryVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_SETTLE_MONEY));
            }
        }
        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();
        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());
            memberServiceLogService.save(memberLog);
        }
        //生成签呈
        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())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(TransactionUtils.getContent(ConfigMsgConstants.POLICY_CURRENCY_PETITION));
        }
        //扣钱
        if (policyCurrencyVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkCountry(policyCurrencyVO.getPkCountry());
            businessCommissionDTO.setPkAccount(policyCurrencyVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(policyCurrencyVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.POLICY_CURRENCY_MONEY));
            }
        }
        return policyCurrencyVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCodeByBusinessNo(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        UpdateCodeVO updateCodeVO = new UpdateCodeVO();
        updateCodeVO.setBusinessNo(approvalBusinessResultDTO.getBusinessCode());
        updateCodeVO.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
        QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
        queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
        List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        if (CollectionUtil.isNotEmpty(list)) {
            for (CuMemberServiceLog memberLog : list) {
                ////审核通过 修改审核状态,累加修改次数
                memberLog.setPkModified(userID);
                memberLog.setModifiedTime(date);
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.updateById(memberLog);
                //修改会员编号
                CuMember member = new CuMember();
                member.setPkId(memberLog.getPkMember());
                member.setMemberCode(memberLog.getNewValue());
                member.setPkModified(userID);
                member.setModifiedTime(date);
                baseMapper.updateById(member);
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean upPolicyCurrencyProcess(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();

        UpdateWrapper<CuMemberServiceLog> updateWrapper = new UpdateWrapper<>();
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
            updateWrapper.set("APPROVE_STATUS", EApproveStatus.FINISH.getValue());
        }
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.REJECTED.getValue()) {
            Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
            updateWrapper.set("APPROVE_STATUS", EApproveStatus.REJECTED.getValue());
            QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
            List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                //查询扣费金额，账户信息
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                if (null == serviceChargeDTOR.getData() ||
                        null == serviceChargeDTOR.getData().getPkAccount()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                }
                for (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 b = cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
                    if (!b) {
                        throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                    }
                }
            }

        }
        updateWrapper.set("PK_MODIFIED", userID);
        updateWrapper.set("MODIFIED_TIME", date);
        updateWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
        memberServiceLogService.update(updateWrapper);
        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(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
            }
            for (UpdateCodeVO uc : updateCodeVOList) {
                //审核驳回
                CuMemberServiceLog memberLog = new CuMemberServiceLog();
                memberLog.setPkId(uc.getServiceLogId());
                memberLog.setPkModified(userID);
                memberLog.setModifiedTime(date);
                memberLog.setApproveNumber(uc.getChangeNumber() - 1);
                memberLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
                memberServiceLogService.updateById(memberLog);
                if (StringUtils.isNotNull(uc.getCost())) {
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(uc.getPkId());
                    memberAmountDTO.setTradeAmount(uc.getCost());
                    if (uc.getCost().compareTo(BigDecimal.ZERO) > 0) {
                        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 b = cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
                if (!b) {
                    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();
        QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
        queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
        List<CuMemberServiceLog> memberServiceLogList = memberServiceLogService.list(queryWrapper);
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        if (CollectionUtil.isNotEmpty(memberServiceLogList)) {
            for (CuMemberServiceLog cs : memberServiceLogList) {
                //审核通过 修改审核状态,累加修改次数
                cs.setPkModified(userID);
                cs.setModifiedTime(date);
                cs.setApproveStatus(approvalBusinessResultDTO.getEApproveStatus().getValue());
                memberServiceLogService.updateById(cs);
            }
            if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
                for (CuMemberServiceLog cs : memberServiceLogList) {
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue()) {
                        //新增真实奖衔控制
                        CuAwardsControl control = JSONObject.parseObject(cs.getNewValue(), CuAwardsControl.class);
                        control.setPkMember(cs.getPkMember());
                        control.setPkCountry(pkCountry);
                        control.setPkCreator(userID);
                        control.setCreationTime(date);
                        controlService.save(control);
                    }
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue()) {
                        //修改真实奖衔控制
                        CuAwardsControl control = JSONObject.parseObject(cs.getNewValue(), CuAwardsControl.class);
                        control.setPkMember(cs.getPkMember());
                        control.setPkCountry(pkCountry);
                        control.setPkCreator(userID);
                        control.setCreationTime(date);
                        controlService.updateById(control);
                    }
                    if (approvalBusinessResultDTO.getEApprovalBusiness().getValue() == EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue()) {
                        //删除真实奖衔控制
                        CuAwardsControl control = JSONObject.parseObject(cs.getNewValue(), CuAwardsControl.class);
                        UpdateWrapper<CuAwardsControl> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                        updateWrapper.set("CREATION_TIME", userID);
                        updateWrapper.set("PK_CREATOR", date);
                        updateWrapper.eq("PK_ID", control.getPkId());
                        controlService.update(updateWrapper);
                    }

                }
            }
        }
        return true;
    }

    @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());
            // 安置编号
            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));
            log.info("变更前信息:{}", JSONUtil.toJsonStr(oldUpdatePlaceVo));
            log.info("变更后信息:{}", JSONUtil.toJsonStr(newUpdatePlaceVo));
            memberLog.setPkCreator(loginUser.getUserId());
            memberLog.setCreationTime(DateUtils.currentDateTime());
            memberLog.setBusinessNo(code);
            memberLog.setPkCountry(pkCountry);
            memberLog.setProcessType(placeParentParam.getProcessType());
            memberLog.setApproveNumber(updatePlaceParentParam.getChangeNumber());

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

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

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

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

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

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

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

        }
        return code;
    }

    /**
     * 修改安置
     *
     * @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();
            QueryWrapper<CuMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("MEMBER_CODE", 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);
        //  memberServiceLogService.saveBatch(MemberServiceLogList);
        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
        long next = (long) (Math.random() * (99999999 - 30730000 + 1) + 30730000);
        if (digit.equals(MagicNumberConstants.DIGIT)) {
            next = (long) (Math.random() * (999999999999L - 100000000000L + 1) + 100000000000L);
        }
        String memberCode = prefix + next;
        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;
    }

    @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 code = prefix + (long) (Math.random() * (99999999 - 30730000 + 1) + 30730000);

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

    @Override
    public List<CuMember> findMemberByMembercodesAndPkcountry(List<String> memeberCodes, Integer pkCountry) {
        return baseMapper.findMemberByMembercodesAndPkcountry(memeberCodes, 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);
    }

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

    @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, settleTableName);
        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(30);
        //GradeDTO gradeDTO = gradeDtoMap.get(memberSettleExtList);
        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("memberName", treeNode.getMemberName());

                    // 等级
                    for (Map.Entry<String, GradeDTO> str : gradeDtoMap.entrySet()) {
                        Integer pkSettleGrade = str.getValue().getPkId();
                        if (pkSettleGrade.equals(treeNode.getPkSettleGrade())) {
                            GradeDTO grade = str.getValue();
                            String gradeName = grade.getGradeName();
                            tree.putExtra("gradeName", gradeName);
                        }
                    }

                    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 registerPv = treeNode.getRegisterPv() == null ? BigDecimal.ZERO : treeNode.getRegisterPv();
//                    BigDecimal ztyj = registerPv.add(pvComputeExchangeRate(treeNode.getANewPv(), treeNode.getPkCountry(), inExchangeRate)).add(pvComputeExchangeRate(treeNode.getBNewPv(), treeNode.getPkCountry(), inExchangeRate));
//                    tree.memberSettleExtList = {ArrayList@18690}  size = 2putExtra("newPerformancePv", numberformat.format(pvComputeExchangeRate(ztyj, treeNode.getPkCountry(), inExchangeRate)));
                    String historyPerformancePv = numberformat.format(pvComputeExchangeRate(treeNode.getHistoryPerformancePv(), treeNode.getPkCountry(), inExchangeRate));
                    tree.putExtra("historyPerformancePv", historyPerformancePv);
                    // 团队人数
                    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 content = TransactionUtils.getContent(ConfigMsgConstants.TJ_CONTENT);
                        String str = String.format(content, treeNode.getLevel(), treeNode.getMemberName(), treeNode.getMemberCode(), directPushNumber, historyPerformancePv, numberCount, numberAchieve, DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_HH_MM_SS, member.getCreationTime()), 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;
        }
        for (EGrade grade : EGrade.values()) {
            if (-member.getCategory() == grade.getIndex()) {
                return grade.getImageUrl();
            } else if (gradeDTO != null && gradeDTO.getGradeValue() == grade.getValue()) {
                //  return grade.getImageUrl();
                return gradeDTO.getIcon();
            }
        }

        return MemberFrameworkConstants.xuni;
    }

    @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<MemberMeritsSummaryVo> memberMeritsSummaryVoList = baseMapper.queryDateBySummary(censusSummaryParam);
        // Map<Integer, MemberMeritsSummaryVo> memberMeritsSummaryMap = memberMeritsSummaryVoList.stream().collect(Collectors.toMap(MemberMeritsSummaryVo::getOrderType, Function.identity()));
        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);
            //注册
            if (memberMeritsSummaryMap.get(EOrderType.REGISTER_ORDER.getValue()) != null) {
                BigDecimal amount = memberMeritsSummaryMap.get(EOrderType.REGISTER_ORDER.getValue()).getAmount();
                BigDecimal achieve = memberMeritsSummaryMap.get(EOrderType.REGISTER_ORDER.getValue()).getAchieve();
                censusSummaryVo.setRegisterAmount(computeChinaExchangeRate(loginUserCountry, amount, inExchangeRate, chinaInExchangeRate));
                censusSummaryVo.setRegisterPv(computeUSDToRMBRate(achieve, chinaInExchangeRate));
                censusSummaryVo.setRegisterAmountDollar(computeUSDExchangeRate(amount, inExchangeRate));
                censusSummaryVo.setRegisterPvDollar(checkIsDecimalNull(achieve));
                // 本地币
                censusSummaryVo.setRegisterAmountLocality(checkIsDecimalNull(amount));
                censusSummaryVo.setRegisterPvLocality(USDToRMB(loginUserCountry, achieve, inExchangeRate));
            } else {
                censusSummaryVo.setRegisterAmount(BigDecimal.ZERO);
                censusSummaryVo.setRegisterPv(BigDecimal.ZERO);
                censusSummaryVo.setRegisterAmountDollar(BigDecimal.ZERO);
                censusSummaryVo.setRegisterPvDollar(BigDecimal.ZERO);
                // 本地币
                censusSummaryVo.setRegisterAmountLocality(BigDecimal.ZERO);
                censusSummaryVo.setRegisterPvLocality(BigDecimal.ZERO);
            }
            // 升级
            if (memberMeritsSummaryMap.get(EOrderType.UPGRADE_ORDER.getValue()) != null) {
                BigDecimal amount = memberMeritsSummaryMap.get(EOrderType.UPGRADE_ORDER.getValue()).getAmount();
                BigDecimal achieve = memberMeritsSummaryMap.get(EOrderType.UPGRADE_ORDER.getValue()).getAchieve();
                censusSummaryVo.setUpgradeAmount(computeChinaExchangeRate(loginUserCountry, amount, inExchangeRate, chinaInExchangeRate));
                censusSummaryVo.setUpgradePv(computeUSDToRMBRate(achieve, chinaInExchangeRate));
                censusSummaryVo.setUpgradeAmountDollar(computeUSDExchangeRate(amount, inExchangeRate));
                censusSummaryVo.setUpgradePvDollar(checkIsDecimalNull(achieve));
                //本地币
                censusSummaryVo.setUpgradeAmountLocality(checkIsDecimalNull(amount));
                censusSummaryVo.setUpgradePvLocality(USDToRMB(loginUserCountry, achieve, inExchangeRate));
            } else {
                censusSummaryVo.setUpgradeAmount(BigDecimal.ZERO);
                censusSummaryVo.setUpgradePv(BigDecimal.ZERO);
                censusSummaryVo.setUpgradeAmountDollar(BigDecimal.ZERO);
                censusSummaryVo.setUpgradePvDollar(BigDecimal.ZERO);
                //本地币
                censusSummaryVo.setUpgradeAmountLocality(BigDecimal.ZERO);
                censusSummaryVo.setUpgradePvLocality(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.setDirectSupplyAmount(BigDecimal.ZERO);
            censusSummaryVo.setDirectSupplyPv(BigDecimal.ZERO);
            censusSummaryVo.setDirectSupplyAmountDollar(BigDecimal.ZERO);
            censusSummaryVo.setDirectSupplyPvDollar(BigDecimal.ZERO);

            // 本地币
            censusSummaryVo.setDirectSupplyAmountLocality(BigDecimal.ZERO);
            censusSummaryVo.setDirectSupplyPvLocality(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;
            if (memberMeritsSummaryMap.get(EOrderType.REPURCHASE_ORDER.getValue()) != null) {
                repurchaseAmount = memberMeritsSummaryMap.get(EOrderType.REPURCHASE_ORDER.getValue()).getAmount();
                repurchaseAchieve = memberMeritsSummaryMap.get(EOrderType.REPURCHASE_ORDER.getValue()).getAchieve();
            }

            censusSummaryVo.setRepurchaseAmount(computeChinaExchangeRate(loginUserCountry, censusSummaryVo.getDirectSupplyAmount(), inExchangeRate, chinaInExchangeRate)
                    .add(computeChinaExchangeRate(loginUserCountry, censusSummaryVo.getFansAmount(), inExchangeRate, chinaInExchangeRate))
                    .add(computeChinaExchangeRate(loginUserCountry, censusSummaryVo.getTripartiteAmount(), inExchangeRate, chinaInExchangeRate))
                    .add(computeChinaExchangeRate(loginUserCountry, repurchaseAmount, inExchangeRate, chinaInExchangeRate)));
            censusSummaryVo.setRepurchaseAmountDollar(computeUSDExchangeRate(censusSummaryVo.getRepurchaseAmount(), inExchangeRate));

            censusSummaryVo.setRepurchasePv(censusSummaryVo.getDirectSupplyPv().add(censusSummaryVo.getHiFunPv()).add(censusSummaryVo.getTripartitePv()).add(computeChinaExchangeRate(loginUserCountry, repurchaseAchieve, inExchangeRate, chinaInExchangeRate)));
            censusSummaryVo.setRepurchasePvDollar(computeUSDExchangeRate(censusSummaryVo.getRepurchasePv(), inExchangeRate));
            // 本地币
            censusSummaryVo.setRepurchaseAmountLocality(checkIsDecimalNull(censusSummaryVo.getDirectSupplyAmountLocality()).add(checkIsDecimalNull(censusSummaryVo.getFansAmountLocality())).add(checkIsDecimalNull(censusSummaryVo.getTripartiteAmountLocality())).add(checkIsDecimalNull(repurchaseAmount)));
            censusSummaryVo.setRepurchasePvLocality(censusSummaryVo.getDirectSupplyPvLocality().add(censusSummaryVo.getHiFunPvLocality()).add(censusSummaryVo.getTripartitePvLocality()).add(checkIsDecimalNull(repurchaseAchieve)));
            //  金额总计
            censusSummaryVo.setAmountTotal(checkIsDecimalNull(censusSummaryVo.getFirstPurchaseAmount())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchaseAmount())));
            //  金额总计($)
            censusSummaryVo.setAmountTotalDollar(checkIsDecimalNull(censusSummaryVo.getFirstPurchaseAmountDollar())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchaseAmountDollar())));
            // 本地币 金额汇总
            censusSummaryVo.setAmountTotalLocality(checkIsDecimalNull(censusSummaryVo.getFirstPurchaseAmountLocality())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchaseAmountLocality())));
            //  业绩汇总
            censusSummaryVo.setPvTotal(checkIsDecimalNull(censusSummaryVo.getFirstPurchasePv())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchasePv())));
            //  业绩汇总($)
            censusSummaryVo.setPvTotalDollar(checkIsDecimalNull(censusSummaryVo.getFirstPurchasePvDollar())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchasePvDollar())));

            //  业绩汇总（本地币）
            censusSummaryVo.setPvTotalLocality(checkIsDecimalNull(censusSummaryVo.getFirstPurchasePvLocality())
                    .add(checkIsDecimalNull(censusSummaryVo.getRepurchasePvLocality())));
            censusSummaryList.add(censusSummaryVo);
        }


        return censusSummaryList;
    }

    /**
     * 计算中国汇率(人民币)
     *
     * @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.divide(inExchangeRate, 2, BigDecimal.ROUND_HALF_UP).multiply(chinaInExchangeRate);
    }

    /**
     * 计算中国汇率(美金转当地币)
     *
     * @param loginUserCountry 登录用户国
     * @param amount           金额/pv
     * @param inExchangeRate   本国汇率
     * @return
     */
    private BigDecimal USDToRMB(Integer loginUserCountry, BigDecimal amount, BigDecimal inExchangeRate) {
        if (amount == null) {
            return BigDecimal.ZERO;
        }
        // 业绩汇总删除 只有中国进行美元转当地币种
//        if (loginUserCountry.equals(CountryConstants.CHINA_COUNTRY)) {
//            return amount.multiply(inExchangeRate);
//        }

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

    /**
     * 后台安置列表
     *
     * @param list
     * @param memberSettleExt
     * @return
     */
    @Override
    public List<Tree<String>> systemAzSetListTree(List<CuMemberSettleExt> list, CuMemberSettleExt memberSettleExt) {
        R<Map<Integer, BdCountry>> allCountryMap = iCountryServiceApi.getAllCountryMap();

        R<List<BdAwards>> awardsDto = iAwardsServiceApi.queryAwards(memberSettleExt.getPkCountry());
        for (BdAwards date : awardsDto.getData()) {
            if (date.getPkId().equals(memberSettleExt.getPkAwards())) {
                memberSettleExt.setColor(date.getColor());
            }
        }
        // TODO 关联网体查询等级颜色值
        Map<String, GradeDTO> gradeDtoMap = queryGradeDTOMap(list);
        Map<Integer, BdCountry> allCountryData = allCountryMap.getData();
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setDeep(30);
        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.setWeight(treeNode.getPlaceDept());
                    tree.putExtra("memberCode", treeNode.getMemberCode());
                    tree.putExtra("placeDept", treeNode.getPlaceDept());
                    tree.putExtra("level", treeNode.getLevel());
                    tree.putExtra("parentMemberCode", treeNode.getParentMemberCode());
                    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("newPv", treeNode.getNewPv());
                    tree.putExtra("avatarUrl", settingAvatarUrl(member, gradeDtoMap));
                    treeNode.getLevelMemberSettleList().sort((a, b) -> a.getPlaceDept().compareTo(b.getPlaceDept()));
                    tree.putExtra("levelMemberSettleList", treeNode.getLevelMemberSettleList());


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

        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();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        upseCountryVO.setApprovalBusiness(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
        for (UpdateSettleCountryVO uc : upseCountryVO.getUpstcyVOList()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(uc.getPkId());
            memberLog.setEditType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            memberLog.setOldValue(uc.getPkSettleCountry().toString());
            memberLog.setNewValue(uc.getNewPkSettleCountry().toString());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setBusinessNo(code);
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setPkCountry(pkCountry);
            memberLog.setSingleAmount(uc.getCost());
            //免签呈
            if (upseCountryVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    upseCountryVO.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
                //修改会员结算国
                //查询用户原先的结算等级注册等级真实奖衔
                CuMember member = baseMapper.selectById(uc.getPkId());
                member.setPkId(uc.getPkId());
                member.setPkSettleCountry(uc.getNewPkSettleCountry());
                member.setPkModified(userID);
                member.setModifiedTime(date);

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

                R<GradeDTO> gd = iGradeServiceApi.getGrade(member.getPkRegisterGrade());
                Integer pkRegisterGrade = gd.getData().getGradeValue();
                gd = iGradeServiceApi.getGrade(member.getPkSettleGrade());
                Integer pkSettleGrade = gd.getData().getGradeValue();
                gd = iGradeServiceApi.getGradeByGradeValue(pkRegisterGrade, uc.getNewPkSettleCountry());
                if (null == gd.getData()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                if (null == gd.getData().getPkId()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                member.setPkRegisterGrade(gd.getData().getPkId());
                gd = iGradeServiceApi.getGradeByGradeValue(pkSettleGrade, uc.getNewPkSettleCountry());
                if (null == gd.getData()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                if (null == gd.getData().getPkId()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                member.setPkSettleGrade(gd.getData().getPkId());
                R<BdAwards> aw = iAwardsServiceApi.getAwardsOne(member.getPkAwards());
                R<List<BdAwards>> awList = iAwardsServiceApi.queryAwards(uc.getNewPkSettleCountry());
                if (CollectionUtil.isEmpty(awList.getData())) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_AWARDS_IS_NULL));
                }
                for (BdAwards baw : awList.getData()) {
                    member.setPkAwards(null);
                    if (aw.getData().getAwardsValue().equals(baw.getAwardsValue())) {
                        member.setPkAwards(baw.getPkId());
                        break;
                    }
                }
                if (null == member.getPkAwards()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_AWARDS_IS_NULL));
                }
                UpdateWrapper<CuMemberAccount> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("PK_COUNTRY", uc.getNewPkSettleCountry());
                updateWrapper.eq("PK_MEMBER", uc.getPkId());
                iCuMemberAccountService.update(updateWrapper);
                //修改国家编号
                CuMember cm = baseMapper.queryRecentlyMember(uc.getNewPkSettleCountry());
                if (StringUtils.isNotNull(cm) && StringUtils.isNotEmpty(cm.getCountryCode())) {
                    String countryCode = this.createCountryCode(cm.getCountryCode());
                    member.setCountryCode(countryCode);
                }
                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);
            }

            //扣钱
            if (upseCountryVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkCountry(pkCountry);
                businessCommissionDTO.setPkAccount(upseCountryVO.getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(upseCountryVO.getMemberAmountDTOList());
                businessCommissionDTO.setTradeType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_SETTLE_PETITION));
                }
            }
        }
        return upseCountryVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UpPolicyCurrencyVO upPolicyCurrency(UpPolicyCurrencyVO policyCurrencyVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SPECIAL_UPDATE_CODE.getValue());
        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());

            //免签呈
            if (policyCurrencyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    policyCurrencyVO.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
            }
            //扣钱
            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.POLICY_CURRENCY_YES_NO.getValue());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.POLICY_CURRENCY_MONEY));
                }
            }
        }
        return policyCurrencyVO;
    }

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

                //查询修改前结算国等级奖衔value值
                R<GradeDTO> gd = iGradeServiceApi.getGrade(member.getPkRegisterGrade());
                Integer pkRegisterGrade = gd.getData().getGradeValue();
                gd = iGradeServiceApi.getGrade(member.getPkSettleGrade());
                Integer pkSettleGrade = gd.getData().getGradeValue();
                gd = iGradeServiceApi.getGradeByGradeValue(pkRegisterGrade, Integer.parseInt(uc.getNewSettleCountry()));
                if (null == gd.getData()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                if (null == gd.getData().getPkId()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                member.setPkRegisterGrade(gd.getData().getPkId());
                gd = iGradeServiceApi.getGradeByGradeValue(pkSettleGrade, Integer.parseInt(uc.getNewSettleCountry()));
                if (null == gd.getData()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                if (null == gd.getData().getPkId()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_GRADE_IS_NULL));
                }
                member.setPkSettleGrade(gd.getData().getPkId());
                R<BdAwards> aw = iAwardsServiceApi.getAwardsOne(member.getPkAwards());
                R<List<BdAwards>> awList = iAwardsServiceApi.queryAwards(Integer.parseInt(uc.getNewSettleCountry()));
                if (CollectionUtil.isEmpty(awList.getData())) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_AWARDS_IS_NULL));
                }
                for (BdAwards baw : awList.getData()) {
                    member.setPkAwards(null);
                    if (aw.getData().getAwardsValue().equals(baw.getAwardsValue())) {
                        member.setPkAwards(baw.getPkId());
                        break;
                    }
                }
                if (null == member.getPkAwards()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_COUNTRY_AFTER_AWARDS_IS_NULL));
                }
                UpdateWrapper<CuMemberAccount> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("PK_COUNTRY", Integer.parseInt(uc.getNewSettleCountry()));
                updateWrapper.eq("PK_MEMBER", uc.getPkId());
                iCuMemberAccountService.update(updateWrapper);
                member.setPkSettleCountry(Integer.parseInt(uc.getNewSettleCountry()));
                //修改国家编号
                CuMember cm = baseMapper.queryRecentlyMember(Integer.parseInt(uc.getNewSettleCountry()));
                if (StringUtils.isNotNull(cm) && StringUtils.isNotEmpty(cm.getCountryCode())) {
                    String countryCode = this.createCountryCode(cm.getCountryCode());
                    member.setCountryCode(countryCode);
                }
                baseMapper.updateById(member);
            }
        }
        return true;
    }

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

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

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

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

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

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

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

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

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

        UpdateWrapper<CuMember> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(SystemFieldConstants.PK_ID, pkMember);
        // 取消点位时，会员编号处理，防止唯一索引
        updateWrapper.set("MEMBER_CODE", CommonUtil.deleteMemberCode(cuMember.getMemberCode()));
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, pkMember);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, new Date());
        return this.update(updateWrapper);
    }

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

    @Override
    public CuMember confirmShareMemberByMemberParam(MemberParam memberParam) {
        CuMember parentMember = getMember(memberParam.getPkParent());
        CuMember cuMember = packageSaveUser(memberParam, parentMember);
        String memberCode = memberParam.getMemberCode();
        if (StringUtils.isEmpty(memberCode)) {
            memberCode = createUserNameByPremix(parentMember.getPkSettleCountry(), Boolean.TRUE, MagicNumberConstants.DIGIT);
        }
        cuMember.setPkId(baseMapper.createMemberId());
        generateNumber(cuMember, cuMember.getPkSettleCountry());
        memberParam.setMemberCode(memberCode);
        // 处理等级
        GradeDTO gradeDTO = iGradeServiceApi.getGradeByGradeValue(EGrade.YOU_KE.getValue(), parentMember.getPkSettleCountry()).getData();
        if (gradeDTO == null) {
            return null;
        }
        cuMember.setPkRegisterGrade(gradeDTO.getPkId());
        cuMember.setPkSettleGrade(gradeDTO.getPkId());
        cuMember.setPkAwards(gradeDTO.getPkAwards());
        // 等级对应的结算值
        cuMember.setConsumeMoney(BigDecimal.ZERO);
        cuMember.setConsumeAchieve(BigDecimal.ZERO);
        cuMember.setRegisterAuthority(gradeDTO.getRegisterAuthority());
        cuMemberBusinessService.saveShareMember(cuMember);
//        // 生成订单编号
//        CuMemberShare cuMemberShare = CuMemberShare.builder()
//                .memberCode(memberCode)
//                .memberName(memberParam.getMemberName())
//                .phone(memberParam.getPhone())
//                .pkParent(parentMember.getPkId())
//                .loginPwd(SecurityUtils.encryptPassword(memberParam.getLoginPassword()))
//                .loginPassword(memberParam.getLoginPassword())
//                .payPwd(SecurityUtils.encryptPassword(memberParam.getPayPassword()))
//                .payPassword(memberParam.getPayPassword())
//                .build();
//        cuMemberShare.setPkCreator(parentMember.getPkId());
//        cuMemberShare.setPkCountry(parentMember.getPkSettleCountry());
//        if (cuMemberShareService.saveCuMemberShare(cuMemberShare)) {
//            return cuMemberShare;
//        }
        return cuMember;
    }

    /**
     * 生成用户
     *
     * @param memberParam 参数
     */
    CuMember packageSaveUser(MemberParam memberParam, CuMember parentMember) {
        // 获取新的订单编号
        CuMember cuMember = CuMember.builder()
                .memberCode(memberParam.getMemberCode())
                .memberName(memberParam.getMemberName())
                .pkSettleCountry(parentMember.getPkSettleCountry())
                .phone(memberParam.getPhone())
                .loginPwd(SecurityUtils.encryptPassword(memberParam.getLoginPassword()))
                .loginPassword(memberParam.getLoginPassword())
                .payPwd(SecurityUtils.encryptPassword(memberParam.getPayPassword()))
                .payPassword(memberParam.getPayPassword())
                .source(EDataSource.APP.getValue())
                .pkParent(parentMember.getPkId())
                .accountStatus(EAccountStatus.NORMAL.getValue())
                // 这个时候是待支付，等支付的时候变为支付，可以跟待支付公用
                .payStatus(EPayStatus.PAID.getValue())
                .category(ECategory.NORMAL.getValue())
                .orderSource(EOrderSource.SOLID.getValue())
                .consumeMoney(BigDecimal.ZERO)
                .consumeAchieve(BigDecimal.ZERO)
                .customerType(ECustomerType.HAI_FANS.getValue())
                .registerAuthority(ERegistrationAuthority.ORDINARY.getValue())
                .build();
        // 自动上树，验证推荐人等级，推荐人是海粉，验证左右区人数，否则验证业绩
        CuMember placeCuMember = repeatTryTree(cuMember);
        cuMember.setPkPlaceParent(placeCuMember.getPkPlaceParent());
        cuMember.setPlaceDept(placeCuMember.getPlaceDept());
        cuMember.setPkCountry(parentMember.getPkCountry());
        Date currentTime = DateUtils.currentDateTime();
        cuMember.setCreationTime(currentTime);
        cuMember.setPayStatus(EPayStatus.PAID.getValue());
        cuMember.setPayTime(currentTime);
        cuMember.setPkCreator(parentMember.getPkId());
        if (parentMember.getPkTeamCode() == null) {
            // 验证父级是不是团队
            CuMemberTeamExt memberTeamExt = memberTeamService.getCuMemberTeamById(parentMember.getPkId());
            if (memberTeamExt != null) {
                cuMember.setPkTeamCode(memberTeamExt.getPkId());
            }
        } else {
            cuMember.setPkTeamCode(parentMember.getPkTeamCode());
        }
        cuMember.setPkVertex(parentMember.getPkVertex());
        return cuMember;
    }

    private CuMember repeatTryTree(CuMember cuMember) {
        CuMember placeCuMember = cuMemberBusinessService.queryCuMemberPlaceDept(cuMember, false, false);
        if (!redisService.lockKeyOnce(CacheConstants.POSITION + placeCuMember.getPkPlaceParent() + placeCuMember.getPlaceDept())) {
            try {
                Thread.sleep(100);
                repeatTryTree(cuMember);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return placeCuMember;
    }

    @Override
    public void deleteCuMemberByPkMember(Long pkMember, Long pkApprove, Date currentDateTime, String memberCode, Integer orderStatus) {
        UpdateWrapper<CuMember> updateWrapper = new UpdateWrapper<>();
        if (orderStatus == 0) {
            updateWrapper.set("MEMBER_CODE", CommonUtil.deleteMemberCode(memberCode));
        }
        updateWrapper.set(SystemFieldConstants.DEL_FLAG, EYesNo.NO.getIntValue());
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, pkApprove);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, currentDateTime);
        updateWrapper.eq(SystemFieldConstants.PK_ID, pkMember);
        update(updateWrapper);
    }

    @Override
    public List<CuMemberExt> queryCuMemberLastPlaceParent(List<Integer> placeDetpList, Long pkMember) {
        return baseMapper.queryCuMemberLastPlaceParent(placeDetpList, pkMember);
    }

    @Override
    public boolean getMemberPlaceParent(Integer pkPlaceParent, String memberCode) {
        QueryWrapper<CuMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_PLACE_PARENT", pkPlaceParent);
        List<CuMember> cuMembers = baseMapper.selectList(queryWrapper);
        List<String> list = cuMembers.stream().map(CuMember::getMemberCode).collect(Collectors.toList());
        return list.contains(memberCode);
    }

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

    @Override
    public void generateNumber(CuMember cuMember, Integer pkCountry) {
        CuMember cm = baseMapper.queryRecentlyMember(pkCountry);
        CuMember cm1 = baseMapper.queryInternationalMember();
        //全球编号
        String globalCode = "";
        //国家编号
        String countryCode = "";
        if (StringUtils.isNotNull(cm1) && StringUtils.isNotEmpty(cm1.getGlobalCode())) {
            globalCode = RandomNumberGenerator.getNextNumber(Integer.parseInt(cm1.getGlobalCode()));
        }
        if (StringUtils.isNotNull(cm) && StringUtils.isNotEmpty(cm.getCountryCode())) {
            countryCode = this.createCountryCode(cm.getCountryCode());
        }
        cuMember.setGlobalCode(globalCode);
        cuMember.setCountryCode(countryCode);
    }

    @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 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 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 Map<Integer, Boolean> checkIsShowWares(List<ShowWaresDTO> showWaresDTOS) {
        Map<Integer, Boolean> resultMap = new HashMap<>();
        for (ShowWaresDTO showWaresDTO : showWaresDTOS) {
            boolean isShowWares = true;
            for (BdWaresAuthority bdWaresAuthority : showWaresDTO.getWaresAuthorityList()) {
                if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.BLOOD_ALLOW.getValue()) {
                    // 血缘可见
                    //   List<CuMemberExt> cuMemberExts = queryBloodKinshipUnderUmbrella(bdWaresAuthority.getPkMember());
                    Long count = queryBloodKinshipUnderUmbrellaCount(bdWaresAuthority.getPkMember(), showWaresDTO.getLoginMember());
                    isShowWares = (count != null && count > 0) || bdWaresAuthority.getPkMember().equals(showWaresDTO.getLoginMember());
                    //  isShowWares = cuMemberExts.stream().anyMatch(a -> a.getPkId().equals(showWaresDTO.getLoginMember()));
                } else if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.BLOOD_STOP.getValue()) {
                    // 血缘禁止
//                    List<CuMemberExt> cuMemberExts = queryBloodKinshipUnderUmbrella(bdWaresAuthority.getPkMember());
//                    boolean b = cuMemberExts.stream().anyMatch(a -> a.getPkId().equals(showWaresDTO.getLoginMember()));
//                    if (b) {
//                        isShowWares = false;
//                    }
                    Long count = queryBloodKinshipUnderUmbrellaCount(bdWaresAuthority.getPkMember(), showWaresDTO.getLoginMember());
                    if ((count != null && count > 0) || bdWaresAuthority.getPkMember().equals(showWaresDTO.getLoginMember())) {
                        isShowWares = false;
                    }
                } else if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.PLACE_ALLWO.getValue()) {
                    // 安置可见

                    List<CuMemberExt> cuMemberExts = queryPlaceSponsorUnderUmbrella(bdWaresAuthority.getPkMember(), showWaresDTO.getLoginMemberCode());
                    boolean b = cuMemberExts.stream().anyMatch(a -> a.getPkId().equals(showWaresDTO.getLoginMember()));
                    isShowWares = b || bdWaresAuthority.getPkMember().equals(showWaresDTO.getLoginMember());

                } else if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.PLACE_STOP.getValue()) {
                    // 安置禁止
                    List<CuMemberExt> cuMemberExts = queryPlaceSponsorUnderUmbrella(bdWaresAuthority.getPkMember(), showWaresDTO.getLoginMemberCode());
                    boolean b = cuMemberExts.stream().anyMatch(a -> a.getPkId().equals(showWaresDTO.getLoginMember()));
                    if (b || bdWaresAuthority.getPkMember().equals(showWaresDTO.getLoginMember())) {
                        isShowWares = false;
                    }
                } else if (bdWaresAuthority.getAuthorityType() == EWaresPermissionType.AUTH_ORITY_TYPE.getValue()) {
                    isShowWares = true;
                }
            }
            resultMap.put(showWaresDTO.getPkWares(), isShowWares);
        }
        return resultMap;
    }

    /**
     * 查询pkMember伞下是否存在memberId
     *
     * @param pkMember
     * @param memberId
     * @return
     */
    public Long queryBloodKinshipUnderUmbrellaCount(Long pkMember, Long memberId) {
        return baseMapper.queryBloodKinshipUnderUmbrellaCount(pkMember, memberId);
    }

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

    @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.getMemberByCode(uc.getMemberCode());
            // 用于详情展示
            CuMember oldParentMember = this.getMemberById(thisMember.getPkParent());
            memberLog.setOldValue(oldParentMember.getMemberCode());
            memberLog.setNewValue(uc.getEditNewPlaceMemberCode());
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setSingleAmount(uc.getCost());
            memberLog.setProcessType(uc.getProcessType());
            memberServiceLogService.save(memberLog);
        }
        //生成签呈
        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(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_PETITION));
        }
        //扣钱
        if (updateParentPetitionParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setPkAccount(updateParentPetitionParam.getUpdateParentParamList().get(0).getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(updateParentPetitionParam.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }
        return updateParentPetitionParam;
    }

    @Override
    public UpdatePlaceParentPetitionParam petitionUpdatePlaceParent(UpdatePlaceParentPetitionParam updatePlaceParentPetitionParam) {

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

            memberLog.setOldValue(uc.getOldValue());
            memberLog.setNewValue(uc.getNewValue());
            memberLog.setApproveNumber(uc.getChangeNumber());
            memberLog.setSingleAmount(uc.getCost());
            memberLog.setProcessType(updatePlaceParentPetitionParam.getProcessType());
            memberServiceLogService.save(memberLog);
        }
        //生成签呈
        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(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_PETITION));
        }
        //扣钱
        if (updatePlaceParentPetitionParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkAccount(updatePlaceParentPetitionParam.getUpdateParentParamList().get(0).getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(updatePlaceParentPetitionParam.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
            }
        }
        return updatePlaceParentPetitionParam;
    }

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

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

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

    @Override
    public void updatePlaceParentByBusinessNo(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        //修改安置
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BUSINESS_NO", businessCode);
        List<CuMemberServiceLog> memberServiceLogList = memberServiceLogService.list(queryWrapper);
        //   CuMemberServiceLog memberServiceLog = memberServiceLogService.getOne(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 = getMember(jo.getStr("placeMemberCode"));
                log.info("修改安置最终数据{}", jo);
                // 修改安置
                baseMapper.updatePlaceParentAndPlaceDeptById(memberServiceLog.getPkMember(), newParentMember.getPkId(), placeDept);
                memberServiceLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                //    memberServiceLog.setApproveNumber(memberServiceLog.getApproveNumber() + 1);
                memberServiceLogService.updateById(memberServiceLog);
            }
        }

    }

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

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

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exchangeAnnuity(BigDecimal renewAmount, Integer number, Long pkMember, Integer pkRate, Date expireDate, CuMemberAccount cemberAccount, String memberCode, Integer pkAwards, Integer pkSettleGrade, Date payTime) {
        Integer pkCountry = SecurityUtils.getPkCountry();

        Date nowDate = DateUtils.currentDate();
        // 如果奖金年包【到期日期】比购买时间小或为空，则从当前天开始加奖金年包时间覆盖【到期日期】
        // 如果奖金年包【到期日期】比购买时间大，则直接在【到期日期】上累积
        if (expireDate == null || expireDate.compareTo(payTime) < 0) {
            expireDate = nowDate;
        } else {
            if (expireDate.compareTo(DateUtils.currentDate()) < 0) {
                expireDate = nowDate;
            }
        }
        // 修改前剩余天数
        Long beforeResidue = DateUtil.between(expireDate, nowDate, DateUnit.DAY);
        // 更新年金到期时间
        DateTime dateTime = DateUtil.offset(expireDate, DateField.YEAR, number);
        // 计算购买之后的年金时间
        R<Map<Integer, BdAccount>> accountDto = iAccountServiceApi.getAccountListByCountry(SecurityUtils.getPkCountry());
        Map<Integer, BdAccount> accountMap = accountDto.getData();

        // 修改后剩余天数
        Long afterResidue = DateUtil.between(dateTime, nowDate, DateUnit.DAY);
        // 需要锁会员
        final String redisLock = CacheConstants.BONUS_ANNUITY + pkMember;
        if (redisService.lockKeyOnce(redisLock)) {
            try {
                // 单价 * 数量
                BigDecimal relaseIncomeBonus = new BigDecimal(number).multiply(renewAmount);
                /**
                 * #消费 + 奖金扣款
                 * #优先扣除消费  奖金账户要扣除 奖金账户 和 可提现账户
                 * 生成 trade 记录
                 */
                BigDecimal account1 = cemberAccount.getAccount1();
                if (cemberAccount.getAccount1().compareTo(relaseIncomeBonus) < 0) {
                    // 消费 不充足 扣除奖金
                    // 交易前奖金账户
                    BigDecimal tradeBeforeAccount4 = cemberAccount.getAccount4();
                    BigDecimal account4 = relaseIncomeBonus.subtract(account1);
                    CuMemberAccount cuMemberAccount = new CuMemberAccount();
                    cuMemberAccount.setAccount1(account1.negate());
                    cuMemberAccount.setAccount4(account4.negate());
                    cuMemberAccount.setWithdrawAccount4(account4.negate());
                    cuMemberAccount.setPkMember(pkMember);
                    cuMemberAccount.setPkCountry(pkCountry);
                    cuMemberAccount.setPkModified(pkMember);

                    if (memberAccountService.updateMemberAccount(cuMemberAccount, pkMember)) {
                        CuMemberAccount updateMemberAccount = memberAccountService.getOne(new QueryWrapper<CuMemberAccount>().eq("PK_MEMBER", pkMember));
                        // 会员年金明细
                        CuMemberAnnuity cuMemberAnnuity = this.packageMemberAnnuity(pkMember, renewAmount, number, pkCountry, beforeResidue, afterResidue, pkSettleGrade, pkAwards, dateTime);
                        String code = cuMemberAnnuity.getCode();
                        memberAnnuityService.save(cuMemberAnnuity);
                        // 消费账户
                        Integer pkAccount1 = null;
                        // 奖金账户
                        Integer pkAccount4 = null;
                        for (Map.Entry<Integer, BdAccount> integer : accountMap.entrySet()) {
                            if (integer.getValue().getFieldValue().equals(EAccount.CONSUME.getValue())) {
                                pkAccount1 = integer.getKey();
                            }
                            if (integer.getValue().getFieldValue().equals(EAccount.BONUS.getValue())) {
                                pkAccount4 = integer.getKey();
                            }
                        }
                        CuMemberTrade cuMemberTrade1 = this.packageMemberTrade(pkMember, pkAccount1,
                                pkRate, account1.negate(), updateMemberAccount.getAccount1(),
                                account1, code, pkCountry);
                        CuMemberTrade cuMemberTrade4 = this.packageMemberTrade(pkMember, pkAccount4,
                                pkRate, account4.negate(), updateMemberAccount.getAccount4(),
                                tradeBeforeAccount4, code, pkCountry);
                        cuMemberTradeService.save(cuMemberTrade1);
                        cuMemberTradeService.save(cuMemberTrade4);
                    }
                } else {
                    // 消费 充足 扣除消费
                    CuMemberAccount cuMemberAccount = new CuMemberAccount();
                    cuMemberAccount.setAccount1(relaseIncomeBonus.negate());
                    cuMemberAccount.setPkMember(pkMember);
                    cuMemberAccount.setPkCountry(pkCountry);
                    cuMemberAccount.setPkModified(pkMember);
                    if (memberAccountService.updateMemberAccount(cuMemberAccount, pkMember)) {
                        // 会员年金明细
                        CuMemberAnnuity cuMemberAnnuity = this.packageMemberAnnuity(pkMember, renewAmount, number, pkCountry, beforeResidue, afterResidue, pkSettleGrade, pkAwards, dateTime);
                        String code = cuMemberAnnuity.getCode();
                        memberAnnuityService.save(cuMemberAnnuity);

                        CuMemberAccount updateMemberAccount = memberAccountService.getOne(new QueryWrapper<CuMemberAccount>().eq("PK_MEMBER", pkMember));
                        // 消费账户
                        Integer pkAccount1 = null;
                        for (Map.Entry<Integer, BdAccount> integer : accountMap.entrySet()) {
                            if (integer.getValue().getFieldValue().equals(EAccount.CONSUME.getValue())) {
                                pkAccount1 = integer.getKey();
                            }
                        }
                        CuMemberTrade cuMemberTrade1 = this.packageMemberTrade(pkMember, pkAccount1,
                                pkRate, relaseIncomeBonus.negate(), updateMemberAccount.getAccount1(),
                                account1, code, pkCountry);
                        cuMemberTradeService.save(cuMemberTrade1);
                    }
                }

                baseMapper.updateExpireDate(pkMember, dateTime);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                redisService.unlock(redisLock);
            }
        }
    }

    /**
     * 封装奖金年金明细
     *
     * @param pkMember
     * @param price
     * @param quantity
     * @param pkCountry
     * @return
     */
    private CuMemberAnnuity packageMemberAnnuity(Long pkMember, BigDecimal price, Integer quantity, Integer pkCountry,
                                                 Long beforeResidue, Long afterResidue, Integer pkSettleGrade, Integer pkAwards, Date expireDate) {
        CuMemberAnnuity memberAnnuity = new CuMemberAnnuity();
        memberAnnuity.setPkMember(pkMember);
        memberAnnuity.setCode(memberToolsHandler.createTradeCode(EOrderPrefix.MEMBER_ANNUITY.getValue()));
        memberAnnuity.setUnitPrice(price);
        memberAnnuity.setQuantity(quantity);
        memberAnnuity.setTotalPrice(price.multiply(new BigDecimal(quantity)));
        memberAnnuity.setPkCountry(pkCountry);
        memberAnnuity.setPkCreator(pkMember);
        memberAnnuity.setBeforeResidue(beforeResidue);
        memberAnnuity.setAfterResidue(afterResidue);
        memberAnnuity.setPkSettleGrade(pkSettleGrade);
        memberAnnuity.setPkAwards(pkAwards);
        // 到期日期
        memberAnnuity.setExpireDate(expireDate);
        return memberAnnuity;
    }

    /**
     * 会员交易流水
     *
     * @param pkMember           会员
     * @param pkAccount          账户类型(来源于参照：币种配置)
     * @param pkRate             汇率
     * @param tradeAmount        交易金额
     * @param tradeBalance       交易余额
     * @param tradeBeforeBalance 交易前余额
     * @param sourceCode         来源
     * @param pkCountry          所属国家
     * @return
     */
    private CuMemberTrade packageMemberTrade(Long pkMember, Integer pkAccount, Integer pkRate,
                                             BigDecimal tradeAmount, BigDecimal tradeBalance, BigDecimal tradeBeforeBalance, String sourceCode, Integer pkCountry) {
        CuMemberTrade cuMemberTrade = new CuMemberTrade();
        cuMemberTrade.setPkMember(pkMember);
        cuMemberTrade.setTradeCode(memberToolsHandler.createTradeCode(EOrderPrefix.TRADE_CODE.getValue()));
        cuMemberTrade.setPkAccount(pkAccount);
        cuMemberTrade.setTradeType(ETradeType.EXCHANGE_ANNUITY.getValue());
        cuMemberTrade.setTradeClassify(ETradeClassify.CONSUME.getValue());
        cuMemberTrade.setPkRate(pkRate);
        cuMemberTrade.setTradeAmount(tradeAmount);
        cuMemberTrade.setTradeBalance(tradeBalance);
        cuMemberTrade.setTradeBeforeBalance(tradeBeforeBalance);
        cuMemberTrade.setSourceCode(sourceCode);
        cuMemberTrade.setTradeStatue(ETradeStatus.TAKE_EFFECT.getValue());
        cuMemberTrade.setPkCountry(pkCountry);
        cuMemberTrade.setPkCreator(pkMember);
        // TODO 记录买前剩余  和买后剩余
        return cuMemberTrade;
    }

    @Override
    public List<CuMemberVO> selectMemberPlaceDeptByPkMember(Long pkMember, Integer placeDept) {
        return baseMapper.selectMemberPlaceDeptByPkMember(pkMember, placeDept);
    }

    @Override
    public List<MemberSettleTreeExt> queryMemberSettle(String settleTableName, List<Long> pkMembers, Integer level) {
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        BigDecimal inExchangeRate = currency.getData().getInExchangeRate();

        List<CuMemberSettleDExt> memberSettleExtList = memberTreeMapper.queryMemberSettle(settleTableName, pkMembers, level);
        List<MemberSettleTreeExt> resultList = new ArrayList<>();
        for (CuMemberSettleDExt cuMemberSettleExt : memberSettleExtList) {
            Integer pkSettleCountry = cuMemberSettleExt.getPkSettleCountry();
            MemberSettleTreeExt memberSettleTree = new MemberSettleTreeExt();
            memberSettleTree.setPkMember(cuMemberSettleExt.getPkMember());
            memberSettleTree.setPlaceDept(cuMemberSettleExt.getPlaceDept());
            memberSettleTree.setNewPv(pvComputeExchangeRate(cuMemberSettleExt.getNewPv(), pkSettleCountry, inExchangeRate));
            // 首购累计业绩
            memberSettleTree.setSumPv(pvComputeExchangeRate(cuMemberSettleExt.getSumPv(), pkSettleCountry, inExchangeRate));

            // 首购累计金额
            memberSettleTree.setSumAmount(pvComputeExchangeRate(cuMemberSettleExt.getSumAmount(), pkSettleCountry, inExchangeRate));
            // 首购新增金额
            memberSettleTree.setNewAmount(pvComputeExchangeRate(cuMemberSettleExt.getNewAmount(), pkSettleCountry, inExchangeRate));
            // 星期一新增pv
            memberSettleTree.setMonNewPv(pvComputeExchangeRate(cuMemberSettleExt.getMonNewPv(), pkSettleCountry, inExchangeRate));
            // 左区真实累计
            memberSettleTree.setABalance(pvComputeExchangeRate(cuMemberSettleExt.getABalance(), pkSettleCountry, inExchangeRate));
            // 右区真实累计
            memberSettleTree.setBBalance(pvComputeExchangeRate(cuMemberSettleExt.getBBalance(), pkSettleCountry, inExchangeRate));

            resultList.add(memberSettleTree);
        }
        return resultList;
    }

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

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

    @Override
    public Boolean updateMemberReSaleNumber(Long pkMember, Integer reSaleNumber) {
        return baseMapper.updateMemberReSaleNumber(pkMember, reSaleNumber) > 0;
    }

    @Override
    public List<NotActivePointVO> notActiveList(NotActivePointVO notActivePointVO) {
        return baseMapper.notActiveList(notActivePointVO);
    }

    @Override
    public Long notActiveOrderId(NotActivePointVO notActivePointVO) {
        return baseMapper.notActiveOrderId(notActivePointVO);
    }

    @Override
    public boolean delNotActiveOrder(NotActivePointVO notActivePointVO) {
        return baseMapper.delNotActiveOrder(notActivePointVO);
    }

    @Override
    public boolean delNotActiveOrderItems(NotActivePointVO notActivePointVO) {
        return baseMapper.delNotActiveOrderItems(notActivePointVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public NotActivePointVO notActiveRevokeBusiness(NotActivePointVO notActive) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());
        notActive.setApprovalBusiness(EApprovalBusiness.NOT_ACTIVE_POINT.getValue());

        for (NotActivePointVO zo : notActive.getNotActiveVOList()) {
            //添加修改记录表数据
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(zo.getPkId());
            memberLog.setEditType(EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
            memberLog.setOldValue(JSONObject.toJSONString(zo));
            memberLog.setNewValue(JSONObject.toJSONString(zo));
            memberLog.setPkCreator(notActive.getPkCreator());
            memberLog.setCreationTime(notActive.getCreationTime());
            memberLog.setBusinessNo(code);
            memberLog.setPkCountry(notActive.getPkCountry());
            memberLog.setProcessType(notActive.getProcessType());
            memberLog.setApproveNumber(zo.getChangeNumber());
            //免签呈;免签呈免支付
            if (notActive.getProcessType() == EProcessType.AVOIDSIGNING.getValue()
                    || notActive.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                //添加修改记录表数据
                memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLogService.save(memberLog);
                //校验会员是否存在推荐或安置
                CuMember member = new CuMember();
                member.setPkId(zo.getPkId());
                member.setPkModified(notActive.getPkCreator());
                member.setModifiedTime(notActive.getCreationTime());
                if (!checkLowerMember(zo.getPkId())) {
                    //删除
                    UpdateWrapper<CuMember> updateWrapper = new UpdateWrapper();
                    updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                    updateWrapper.set("PK_MODIFIED", notActive.getPkCreator());
                    updateWrapper.set("MODIFIED_TIME", notActive.getCreationTime());
                    updateWrapper.eq("PK_ID", zo.getPkId());
                    baseMapper.update(null, updateWrapper);
                    //删除订单和订单明细
                    Long pkOrder = notActiveOrderId(zo);
                    if (pkOrder != null) {
                        zo.setPkOrder(pkOrder);
                        zo.setPkModified(notActive.getPkCreator());
                        delNotActiveOrder(zo);
                        delNotActiveOrderItems(zo);
                    }
                }

            }
        }
        return notActive;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public NotActivePointVO notActivePetition(NotActivePointVO notActivePointVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());

        LoginUser loginUser = userTokenService.getLoginUser();
        for (NotActivePointVO nap : notActivePointVO.getNotActiveVOList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(nap.getPkId());
            memberLog.setPkCreator(notActivePointVO.getPkCreator());
            memberLog.setCreationTime(notActivePointVO.getCreationTime());
            memberLog.setPkCountry(notActivePointVO.getPkCountry());
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
            memberLog.setOldValue(JSONObject.toJSONString(nap));
            memberLog.setNewValue(JSONObject.toJSONString(nap));
            memberLog.setApproveNumber(1);
            memberLog.setSingleAmount(nap.getCost());
            memberLog.setProcessType(nap.getProcessType());
            memberServiceLogService.save(memberLog);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.NOT_ACTIVE_POINT)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(notActivePointVO.getSignType()))
                .remark(notActivePointVO.getRemark())
                .pkMemberList(notActivePointVO.getPkMemberList())
                .userIdList(notActivePointVO.getUserIdList())
                .sendIdList(notActivePointVO.getSendIdList())
                .fileList(notActivePointVO.getFileList())
                .build();
        R<String> submit = iApprovalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(TransactionUtils.getContent(ConfigMsgConstants.NOT_ACTIVE_POINT_PETITION));
        }
        return notActivePointVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean notActiveByBusinessNo(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        UpdateWrapper<CuMemberServiceLog> updateWrapper = new UpdateWrapper();
        //审核通过
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
            updateWrapper.set("APPROVE_STATUS", EApproveStatus.FINISH.getValue());
            //查询日志
            QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper();
            queryWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
            queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
            List<CuMemberServiceLog> memberServiceLogList = memberServiceLogService.list(queryWrapper);
            for (CuMemberServiceLog cs : memberServiceLogList) {
                NotActivePointVO nap = JSONObject.parseObject(cs.getNewValue(), NotActivePointVO.class);
                nap.setPkModified(userID);
                //校验会员是否存在推荐或安置
                CuMember member = new CuMember();
                member.setPkId(nap.getPkId());
                member.setPkModified(userID);
                member.setModifiedTime(date);
                if (!checkLowerMember(nap.getPkId())) {
                    //删除
                    UpdateWrapper<CuMember> updateWrapper1 = new UpdateWrapper();
                    updateWrapper1.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                    updateWrapper1.set("PK_MODIFIED", userID);
                    updateWrapper1.set("MODIFIED_TIME", date);
                    updateWrapper1.eq("PK_ID", nap.getPkId());
                    baseMapper.update(null, updateWrapper1);
                    //删除订单和订单明细
                    Long pkOrder = notActiveOrderId(nap);
                    if (pkOrder != null) {
                        nap.setPkOrder(pkOrder);
                        delNotActiveOrder(nap);
                        delNotActiveOrderItems(nap);
                    }
                }
            }
        }
        //驳回
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.REJECTED.getValue()) {
            Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
            updateWrapper.set("APPROVE_STATUS", EApproveStatus.REJECTED.getValue());
            QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper();
            queryWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
            List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                //查询扣费金额，账户信息
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                if (null == serviceChargeDTOR.getData() ||
                        null == serviceChargeDTOR.getData().getPkAccount()) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                }
                for (CuMemberServiceLog msl : list) {
                    if (StringUtils.isNotNull(msl.getSingleAmount()) && msl.getSingleAmount().compareTo(BigDecimal.ONE) > 0) {
                        MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                        memberAmountDTO.setPkMember(msl.getPkMember());
                        memberAmountDTO.setTradeAmount(msl.getSingleAmount());
                        memberAmountDTOList.add(memberAmountDTO);
                    }
                }
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    //退款
                    BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                    businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                    businessCommissionDTO.setTradeType(EApprovalBusiness.NOT_ACTIVE_POINT.getValue());
                    Boolean b = cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
                    if (!b) {
                        throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_REFUND));
                    }
                }
            }
        }
        updateWrapper.set("PK_MODIFIED", userID);
        updateWrapper.set("MODIFIED_TIME", date);
        updateWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
        memberServiceLogService.update(updateWrapper);

        return true;
    }

    @Override
    public List<NotActivePointDTO> notActiveByBusinessList(AnalysisBusinessAppealParam analysisBusinessAppealParam) {
        //查询日志
        List<NotActivePointDTO> zeoList = new ArrayList<>();
        QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper();
        queryWrapper.eq("BUSINESS_NO", analysisBusinessAppealParam.getBusinessNo());
        queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
        List<CuMemberServiceLog> memberServiceLogList = memberServiceLogService.list(queryWrapper);
        for (CuMemberServiceLog cs : memberServiceLogList) {
            NotActivePointDTO zero = JSONObject.parseObject(cs.getNewValue(), NotActivePointDTO.class);
            zeoList.add(zero);
        }
        return zeoList;
    }

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

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

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

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

    @Override
    public CuMemberExt getMemberByCodeNotDel(String memberCode) {
        return baseMapper.getMemberByCodeNotDel(memberCode);
    }

    @Override
    public List<CuMemberExt> getMemberAll(List<Integer> gradeId, Integer pkCountry, Date startTime, Date endTime) {
        return baseMapper.getMemberAll(gradeId, pkCountry, startTime, endTime);
    }

    @Override
    public List<Tree<String>> systemAzSetFirstListTree(List<CuMemberSettleExt> list, CuMemberSettleExt memberSettleExt) {
        List<Integer> countryList = list.stream().map(a -> a.getPkSettleCountry()).collect(Collectors.toList());
        R<List<BdAwards>> awardsDto = iAwardsServiceApi.queryAwardsByIdList(countryList);
        for (BdAwards date : awardsDto.getData()) {
            if (date.getPkId().equals(memberSettleExt.getPkAwards())) {
                memberSettleExt.setColor(date.getColor());
                memberSettleExt.setAwardsName(date.getAwardsName());
            }
        }
        Map<String, GradeDTO> gradeDtoMap = queryGradeDTOMap(list);
        for (Map.Entry<String, GradeDTO> str : gradeDtoMap.entrySet()) {
            GradeDTO grade = str.getValue();
            if (grade.getPkId().equals(memberSettleExt.getPkSettleGrade())) {
                String gradeName = grade.getGradeName();
                memberSettleExt.setGradeName(gradeName);
            }
        }
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setDeep(30);
        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());
                    for (BdAwards date : awardsDto.getData()) {
                        if (date.getPkId().equals(treeNode.getPkAwards())) {
                            tree.putExtra("awardsName", date.getAwardsName());
                        }
                    }
                    //    GradeDTO gradeDTO = gradeDtoMap.get(treeNode.getPkGrade());
                    for (Map.Entry<String, GradeDTO> str : gradeDtoMap.entrySet()) {
                        GradeDTO grade = str.getValue();
                        if (grade.getPkId().equals(treeNode.getPkSettleGrade())) {
                            String gradeName = grade.getGradeName();
                            tree.putExtra("gradeName", gradeName);
                        }
                    }
                    // 设置权重
                    tree.setWeight(treeNode.getPlaceDept());
                    tree.putExtra("sParentCount", treeNode.getSParentCount());
                    tree.putExtra("memberCode", treeNode.getMemberCode());
                    tree.putExtra("placeDept", treeNode.getPlaceDept());
                    tree.putExtra("level", treeNode.getLevel());
                    tree.putExtra("parentMemberCode", treeNode.getParentMemberCode());
                    for (BdAwards date : awardsDto.getData()) {
                        if (date.getPkId().equals(treeNode.getPkAwards())) {
                            tree.putExtra("color", date.getColor());
                        }
                    }
                    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("newPv", treeNode.getNewPv());
                    tree.putExtra("avatarUrl", settingAvatarUrl(member, gradeDtoMap));
                    treeNode.getLevelMemberSettleList().sort((a, b) -> a.getPlaceDept().compareTo(b.getPlaceDept()));
                    tree.putExtra("levelMemberSettleList", treeNode.getLevelMemberSettleList());
                });
        return build;
    }

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

    /**
     * 创建国家最新唯一编号
     *
     * @param countryCode
     * @return
     */
    private String createCountryCode(String countryCode) {
        countryCode = RandomNumberGenerator.getNextNumber(countryCode, 3);

        LambdaQueryWrapper<CuMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMember::getCountryCode, countryCode);
        // 校验是否已经存在，不存在则返回
        return baseMapper.selectCount(queryWrapper) == 0 ? countryCode : this.createCountryCode(countryCode);
    }

    @Override
    public void updateExpireDate(SaOrderExt saOrder) {
        CuMember member = this.getMember(saOrder.getPkMember());

        Date expireDate = member.getExpireDate();
        // 当前时间
        Date nowDate = DateUtils.currentDate();
        // 如果奖金年包【到期日期】比购买时间小或为空，则从当前天开始加奖金年包时间覆盖【到期日期】
        if (null == member.getExpireDate() || expireDate.compareTo(saOrder.getPayTime()) < 0) {
            expireDate = nowDate;
        } else {
            // 如果奖金年包【到期日期】比购买时间大，则直接在【到期日期】上累积
            if (expireDate.compareTo(nowDate) < 0) {
                // 过期时间比当前时间小，也按当前时间
                expireDate = nowDate;
            }
        }
        // 修改前剩余天数
        Long beforeResidue = DateUtil.between(expireDate, nowDate, DateUnit.DAY);
        // 更新年金到期时间
        DateTime dateTime = DateUtil.offset(expireDate, DateField.YEAR, 1);
        // 修改后剩余天数
        Long afterResidue = DateUtil.between(dateTime, nowDate, DateUnit.DAY);

        CuMemberAnnuity memberAnnuity = new CuMemberAnnuity();
        memberAnnuity.setPkMember(member.getPkId());
        memberAnnuity.setCode(memberToolsHandler.createTradeCode(EOrderPrefix.MEMBER_ANNUITY.getValue()));
        memberAnnuity.setUnitPrice(saOrder.getOrderAmount());
        memberAnnuity.setQuantity(1);
        memberAnnuity.setTotalPrice(saOrder.getOrderAmount());
        memberAnnuity.setPkCountry(member.getPkSettleCountry());
        memberAnnuity.setPkCreator(member.getPkId());
        memberAnnuity.setBeforeResidue(beforeResidue);
        memberAnnuity.setAfterResidue(afterResidue);
        memberAnnuity.setPkSettleGrade(member.getPkSettleGrade());
        memberAnnuity.setPkAwards(member.getPkAwards());
        memberAnnuity.setExpireDate(expireDate);
        memberAnnuityService.save(memberAnnuity);

        // 更新年包时间
        baseMapper.updateExpireDate(member.getPkId(), dateTime);
    }

}
