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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.constant.SysConstants;
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.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.account.CuMemberAuthentication;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.detail.CuMemberAwards;
import com.hzs.common.domain.member.detail.CuMemberGrade;
import com.hzs.common.domain.member.detail.CuMemberLevel;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.member.handleBusiness.CuHandleBusiness;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.service.*;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.detail.service.ICuMemberAwardsService;
import com.hzs.member.detail.service.ICuMemberLevelService;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import com.hzs.member.handlebusiness.mapper.CuHandleBusinessMapper;
import com.hzs.member.handlebusiness.service.ICuHandleBusinessService;
import com.hzs.member.handlebusiness.vo.BusinessMemberVO;
import com.hzs.member.handlebusiness.vo.BusinessTypeValueVO;
import com.hzs.member.handlebusiness.vo.HandleBusinessShowVO;
import com.hzs.member.handlebusiness.vo.HandleBusinessVO;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.BusinessLogDTO;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 业务办理表 服务实现类
 */
@Service
@Slf4j
public class CuHandleBusinessServiceImpl extends ServiceImpl<CuHandleBusinessMapper, CuHandleBusiness> implements ICuHandleBusinessService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @Autowired
    private ICuMemberService cuMemberService;
    @Autowired
    private ICuMemberBankService cuMemberBankService;
    @Autowired
    private ICuHandleBusinessService handleBusinessService;
    @Autowired
    private ICuMemberAccountService cuMemberAccountService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private ICuMemberLevelService cuMemberLevelService;
    @Autowired
    private ICuMemberAwardsService cuMemberAwardsService;
    @Autowired
    private ICuMemberAuthenticationService cuMemberAuthenticationService;
    @Autowired
    private ICuMemberBusinessLicenseService cuMemberBusinessLicenseService;
    @Autowired
    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;

    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    ICountryServiceApi iCountryServiceApi;
    @DubboReference
    IApprovalServiceApi iApprovalServiceApi;
    @DubboReference
    IAwardsServiceApi iAwardsServiceApi;

    @Override
    public List<HandleBusinessShowVO> queryHandleBusinessList(HandleBusinessShowVO handleBusinessVO) {
        return baseMapper.queryHandleBusinessList(handleBusinessVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean businessHandling(HandleBusinessVO handleBusinessVO, LoginUser loginUser) {
        boolean result = false;
        Integer processType = handleBusinessVO.getProcessType();
        //业务办理变更信息
        List<BusinessTypeValueVO> valueVOList = handleBusinessVO.getHandleBusinessList();
        //去重（现在前端传的数据是重复的）
        List<BusinessTypeValueVO> handleBusinessList = valueVOList.stream().
                collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(v -> v.getBusinessType() + "-" + StringUtils.join(v.getBusinessValueList(), ",")))), ArrayList::new));
        handleBusinessVO.setHandleBusinessList(handleBusinessList);
        //查询数据
        Object[] objects = getHandleBusiness(handleBusinessVO, loginUser, processType);
        List<CuMemberServiceLog> memberServiceLogsList = (List<CuMemberServiceLog>) objects[0];
        List<CuHandleBusiness> handleBusinessesList = (List<CuHandleBusiness>) objects[1];
        //保存业务办理信息
        memberServiceLogService.saveBatch(memberServiceLogsList);
        this.saveBatch(handleBusinessesList);
        //流程类型（1 免签呈 2免付费 3免签呈+免付费 4 需要签呈需要付费）
        //更新业务办理
        if (processType.equals(EProcessType.AVOIDSIGNING.getValue()) || processType.equals(EProcessType.DOUBLEAVOID.getValue())) {
            // 免签或全免
            result = updateBusinessMember(handleBusinessVO, loginUser);
        }
        //扣手续费
        if (processType.equals(EProcessType.AVOIDSIGNING.getValue())) {
            //业务办理的会员信息
            List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();
            businessCommissionDTO(handleBusinessesList, businessMemberList);
        }
        createPetitionConfirmLog(memberServiceLogsList, loginUser, true, processType);
        return result;
    }

    /**
     * 在线签呈审核
     *
     * @param approvalBusinessResultDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R signForApprovalExamine(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        LoginUser loginUser = approvalBusinessResultDTO.getLoginUser();
        if (approvalBusinessResultDTO.getApproveOperation() == EApproveOperation.AGREE.getValue()) {
            // 通过
            LambdaQueryWrapper<CuHandleBusiness> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CuHandleBusiness::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
            CuHandleBusiness handleBusiness = handleBusinessService.getOne(wrapper);
            // 更新主日志表
            LambdaUpdateWrapper<CuHandleBusiness> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CuHandleBusiness::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
            updateWrapper.set(CuHandleBusiness::getApproveStatus, EApproveStatus.FINISH.getValue());
            handleBusinessService.update(updateWrapper);
            LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CuMemberServiceLog::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
            List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
            List<BusinessMemberVO> businessMemberList = new ArrayList<>();
            for (CuMemberServiceLog cuMemberServiceLog : list) {
                // 更新次日志表
                Integer number = memberServiceLogService.selectByMaxApproveNumber(cuMemberServiceLog.getPkMember(), cuMemberServiceLog.getEditType(), EApproveStatus.FINISH.getValue());
                CuMemberServiceLog memberServiceLog = new CuMemberServiceLog();
                memberServiceLog.setPkId(cuMemberServiceLog.getPkId());
                memberServiceLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberServiceLog.setApproveNumber(number + 1);
                memberServiceLogService.updateById(memberServiceLog);

                BusinessMemberVO businessMemberVO = new BusinessMemberVO();
                businessMemberVO.setPkMember(cuMemberServiceLog.getPkMember());
                businessMemberVO.setBusinessType(cuMemberServiceLog.getEditType());
                businessMemberVO.setNewValue(cuMemberServiceLog.getNewValue());
                businessMemberVO.setOldValue(cuMemberServiceLog.getOldValue());
                businessMemberVO.setEndValidityDate(cuMemberServiceLog.getEndValidityDate());
                businessMemberList.add(businessMemberVO);
            }

            HandleBusinessVO handleBusinessVO = new HandleBusinessVO();
            handleBusinessVO.setPkCountry(loginUser.getDataCountry());
            handleBusinessVO.setHandleBusinessList(setHandleBusinessList(handleBusiness));
            handleBusinessVO.setBusinessMemberList(businessMemberList);
            // 更新办理业务
            updateBusinessMember(handleBusinessVO, loginUser);
        } else {
            String tradeCode = approvalBusinessResultDTO.getBusinessCode();
            // 驳回
            LambdaQueryWrapper<CuHandleBusiness> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CuHandleBusiness::getBusinessNo, approvalBusinessResultDTO.getBusinessCode());
            CuHandleBusiness handleBusiness = handleBusinessService.getOne(wrapper);
            // 更新主日志表
            LambdaUpdateWrapper<CuHandleBusiness> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(CuHandleBusiness::getBusinessNo, tradeCode);
            updateWrapper.set(CuHandleBusiness::getApproveStatus, EApproveStatus.REJECTED.getValue());
            handleBusinessService.update(updateWrapper);
            LambdaQueryWrapper<CuMemberServiceLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CuMemberServiceLog::getBusinessNo, tradeCode);
            List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            for (CuMemberServiceLog cuMemberServiceLog : list) {
                // 更新次日志表
                CuMemberServiceLog memberServiceLog = new CuMemberServiceLog();
                memberServiceLog.setPkId(cuMemberServiceLog.getPkId());
                memberServiceLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
                memberServiceLogService.updateById(memberServiceLog);
                //费用大于0元才会退费
                if (cuMemberServiceLog.getSingleAmount().compareTo(BigDecimal.ZERO) > 0) {
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(cuMemberServiceLog.getPkMember());
                    memberAmountDTO.setTradeAmount(cuMemberServiceLog.getSingleAmount());
                    memberAmountDTOList.add(memberAmountDTO);
                }
            }
            // 退款
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkAccount(handleBusiness.getPkAccount());
                businessCommissionDTO.setPkCountry(loginUser.getDataCountry());
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                businessCommissionDTO.setTradeType(handleBusiness.getEditType());
                businessCommissionDTO.setTradeCode(tradeCode);
                businessCommissionDTO.setPkCreator(approvalBusinessResultDTO.getLoginUser().getUserId());
                Boolean result = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                if (!result) {
                    return R.fail(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
                }
            }
        }
        return R.ok();
    }

    /**
     * 在线签呈
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean onlinePetitionConfirm(HandleBusinessVO handleBusinessVO, LoginUser loginUser) {
        Integer processType = handleBusinessVO.getProcessType();
        Object[] objects = getHandleBusiness(handleBusinessVO, loginUser, processType);
        List<CuMemberServiceLog> memberServiceLogsList = (List<CuMemberServiceLog>) objects[0];
        List<CuHandleBusiness> handleBusinessesList = (List<CuHandleBusiness>) objects[1];
        //扣手续费
        if (processType.equals(EProcessType.DOUBLEPAY.getValue())) {
            //业务办理的会员信息
            List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();
            businessCommissionDTO(handleBusinessesList, businessMemberList);
        } else {
            memberServiceLogsList.forEach(itm -> {
                itm.setSingleAmount(BigDecimal.ZERO);
            });
        }
        //保存业务办理信息
        memberServiceLogService.saveBatch(memberServiceLogsList);
        Boolean result = this.saveBatch(handleBusinessesList);
        submitApproval(handleBusinessVO, loginUser, handleBusinessesList);

        // 生成审批日志mq
        createPetitionConfirmLog(memberServiceLogsList, loginUser, false, processType);
        return result;

    }

    /**
     * @param memberServiceLogsList 业务相关信息
     * @param loginUser             登录用户
     * @param freeSignFlag          是否免签（true=是，其它=否）
     */
    public void createPetitionConfirmLog(List<CuMemberServiceLog> memberServiceLogsList, LoginUser loginUser, Boolean freeSignFlag, Integer processType) {
        List<Integer> typeList = memberServiceLogsList.stream().map(CuMemberServiceLog::getEditType).collect(Collectors.toList());
        Integer pkCountry = loginUser.getDataCountry();
        // 注册等级
        Map<Integer, String> gradeMap = new HashMap<>();
        if (typeList.contains(EApprovalBusiness.CHANGE_REGISTER_GRADE.getValue()) || typeList.contains(EApprovalBusiness.CHANGE_SETTLEMENT_GRADE.getValue())) {
            R<List<GradeDTO>> gradeDTOList = iGradeServiceApi.queryGradeList(pkCountry);
            gradeMap = gradeDTOList.getData().stream().collect(Collectors.toMap(GradeDTO::getPkId, GradeDTO::getGradeName));
        }
        // 修改真实奖衔
        Map<Integer, String> awardsMap = new HashMap<>();
        if (typeList.contains(EApprovalBusiness.CHANGE_AWARDS.getValue())) {
            R<List<BdAwards>> awardsDTO = iAwardsServiceApi.queryAwards(pkCountry);
            awardsMap = awardsDTO.getData().stream().collect(Collectors.toMap(BdAwards::getPkId, BdAwards::getAwardsName));
        }
        // 结算国/自然国
        Map<Integer, BdCountry> countryMap = new HashMap<>();
        if (typeList.contains(EApprovalBusiness.CHANGE_NATURAL_COUNTRY.getValue())) {
            R<Map<Integer, BdCountry>> countryDTO = iCountryServiceApi.getAllCountryMap();
            countryMap = countryDTO.getData();
        }

        try {
            StringBuilder str = new StringBuilder();
            for (CuMemberServiceLog memberServiceLog : memberServiceLogsList) {
                CuMember member = cuMemberService.getMember(memberServiceLog.getPkMember());
                str.append("会员编号：").append(member.getMemberCode());
                str.append("会员名称：").append(member.getMemberName());
                if (memberServiceLog.getEditType().equals(EApprovalBusiness.CHANGE_NAME.getValue())) {
                    // 修改姓名
                    str.append("变更前会员姓名：").append(memberServiceLog.getOldValue());
                    str.append("变更后会员姓名：").append(memberServiceLog.getNewValue());
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.CHANGE_PHONE.getValue())) {
                    // 变更联系方式
                    str.append("变更前联系方式：").append(memberServiceLog.getOldValue());
                    str.append("变更后联系方式：").append(memberServiceLog.getNewValue());
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.RESET_LOGIN_PASSWORD.getValue())) {
                    // 重置会员密码
                    str.append("重置会员：").append(member.getMemberCode()).append("会员密码");
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.CHANGE_REGISTER_GRADE.getValue())) {
                    str.append("修改注册等级：").append(gradeMap.get(Integer.parseInt(memberServiceLog.getOldValue()))).append("变更为: ").append(gradeMap.get(Integer.parseInt(memberServiceLog.getNewValue())));
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.CHANGE_AWARDS.getValue())) {
                    // 修改真实奖衔
                    str.append("修改真实奖衔：").append(awardsMap.get(Integer.parseInt(memberServiceLog.getOldValue()))).append("变更为: ").append(awardsMap.get(Integer.parseInt(memberServiceLog.getNewValue())));
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.RESET_BANK.getValue())) {
                    // 重置银行信息
                    str.append("重置会员").append(member.getMemberName()).append("银行信息");
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.CHANGE_SETTLEMENT_GRADE.getValue())) {
                    // 修改结算等级
                    str.append("修改结算等级：").append(gradeMap.get(Integer.parseInt(memberServiceLog.getOldValue()))).append("变更为: ").append(gradeMap.get(Integer.parseInt(memberServiceLog.getNewValue())));
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.CHANGE_NATURAL_COUNTRY.getValue())) {
                    // 修改自然国家
                    str.append("修改自然国家：").append(countryMap.get(Integer.parseInt(memberServiceLog.getOldValue())).getName()).append("变更为：").append(countryMap.get(Integer.parseInt(memberServiceLog.getNewValue())).getName());
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.SIGN_IN_STATE.getValue())) {
                    // 修改登录状态
                    if (EAccountStatus.getEAccountStatus(Integer.parseInt(memberServiceLog.getNewValue())) != null) {
                        String label = EAccountStatus.getEAccountStatus(Integer.parseInt(memberServiceLog.getNewValue())).getLabel();
                        str.append("修改登录状态：").append(label);
                    } else {
                        str.append("修改登录状态");
                    }
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.PROFIT_STATE.getValue())) {
                    // 修改收益状态
                    EIncomeStatus[] values = EIncomeStatus.values();
                    String name = "";
                    for (EIncomeStatus value : values) {
                        if (Integer.parseInt(memberServiceLog.getNewValue()) == value.getValue()) {
                            name = value.getLabel();
                        }
                    }
                    str.append("修改收益状态：").append(name);
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.WALLET_STATE.getValue())) {
                    // 修改钱包状态
                    String[] oldSp = memberServiceLog.getOldValue().split(",");
                    String[] newSp = memberServiceLog.getNewValue().split(",");
                    // 修改前
                    StringBuilder oldStr = new StringBuilder();
                    for (String s : oldSp) {
                        String labelByIntValue = EMemberAccount.getLabelByIntValue(Integer.parseInt(s));
                        oldStr.append(labelByIntValue).append(" ");
                    }
                    // 修改后
                    StringBuilder newStr = new StringBuilder();
                    for (String s : newSp) {
                        String labelByIntValue = EMemberAccount.getLabelByIntValue(Integer.parseInt(s));
                        newStr.append(labelByIntValue).append(" ");
                    }

                    str.append("修改钱包状态：").append(oldStr).append("变更为： ").append(newStr);
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.FREE_ASSESSMENT_STATE.getValue())) {
                    // 修改免考状态
                    String[] oldSp = memberServiceLog.getNewValue().split(",");
                    StringBuilder newStr = new StringBuilder();
                    for (String s : oldSp) {
                        newStr.append(EFreeAssessmentState.getEnumByValue(Integer.parseInt(s)).getLabel());
                    }
                    str.append("修改免考状态：").append(newStr);
                } else if (memberServiceLog.getEditType().equals(EApprovalBusiness.REGISTER_POWER_STATE.getValue())) {
                    // 修改注册权限
                    String oldLabel = "";
                    ERegistrationAuthority oldRegistrationAuthority = ERegistrationAuthority.getEnumByValue(Integer.parseInt(memberServiceLog.getOldValue()));
                    if (oldRegistrationAuthority != null) {
                        oldLabel = oldRegistrationAuthority.getLabel();
                    }
                    String newLabel = "";
                    ERegistrationAuthority newRegistrationAuthority = ERegistrationAuthority.getEnumByValue(Integer.parseInt(memberServiceLog.getNewValue()));
                    if (newRegistrationAuthority != null) {
                        newLabel = newRegistrationAuthority.getLabel();
                    }
                    str.append("修改注册权限：").append(oldLabel).append("变更为：").append(newLabel);
                }
                if (memberServiceLog.getEditType().equals(EApprovalBusiness.IS_REGION.getValue())) {
                    // 修改是否收益区域
                    str.append("变更前是否收益区域：").append(EDealerYesNo.getLabelByIntValue(Integer.parseInt(memberServiceLog.getOldValue())));
                    str.append("变更后是否收益区域：").append(EDealerYesNo.getLabelByIntValue(Integer.parseInt(memberServiceLog.getNewValue())));
                }
                if (memberServiceLog.getEditType().equals(EApprovalBusiness.IS_ACTIVATE.getValue())) {
                    // 修改是否收益区域
                    str.append("变更前是否激活：").append(EDealerYesNo.getLabelByIntValue(Integer.parseInt(memberServiceLog.getOldValue())));
                    str.append("变更后是否激活：").append(EDealerYesNo.getLabelByIntValue(Integer.parseInt(memberServiceLog.getNewValue())));
                }
                // 拼装发送mq
                BusinessLogDTO log = BusinessLogDTO.builder()
                        .businessType(memberServiceLog.getEditType())
                        .businessCode(memberServiceLog.getBusinessNo())
                        .pkMember(memberServiceLog.getPkMember())
                        .content(str.toString())
                        .pkCreator(loginUser.getUserId())
                        .pkCountry(loginUser.getDataCountry())
                        .freeSignFlag(freeSignFlag)
                        .build();
                rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
            }
        } catch (Exception e) {
            log.error("基础业务MQ发送失败");
            e.printStackTrace();
        }


    }

    /**
     * 提交审批
     *
     * @param handleBusinessVO 业务办理入参
     * @param loginUser        用户信息
     */
    public void submitApproval(HandleBusinessVO handleBusinessVO, LoginUser loginUser, List<CuHandleBusiness> handleBusinessesList) {
        //调用审批接口，修改审批状态
        List<BusinessTypeValueVO> handleBusinessList = handleBusinessVO.getHandleBusinessList();
        List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();
        List<ApprovalSubmitDTO> approvalSubmitDTOList = new ArrayList<>();
        //业务办理
        Map<Integer, CuHandleBusiness> handleBusinessMap = handleBusinessesList.stream().collect(Collectors.toMap(CuHandleBusiness::getEditType, o -> o));
        for (BusinessTypeValueVO businessTypeValueVO : handleBusinessList) {
            Integer businessType = businessTypeValueVO.getBusinessType();
            List<BusinessMemberVO> memberList = getBusinessMemberByBusinessType(businessMemberList, businessType);
            List<Long> pkMemberIds = memberList.stream().map(BusinessMemberVO::getPkMember).collect(Collectors.toList());
            List<String> fileList = businessTypeValueVO.getFileList();
            ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder()
                    .eApprovalBusiness(EApprovalBusiness.getEnumByValue(businessType))
                    .businessCode(handleBusinessMap.get(businessType).getBusinessNo())
                    .sendIdList(businessTypeValueVO.getSendIdList())
                    .signType(ESignType.getEnumByValue(businessTypeValueVO.getSignType()))
                    .remark(businessTypeValueVO.getRemark())
                    .pkMemberList(CollUtil.newHashSet(pkMemberIds)).fileList(businessTypeValueVO.getFileList())
                    .userIdList(businessTypeValueVO.getUserIdList()).build();
            if (CollUtil.isNotEmpty(fileList)) {
                approvalSubmitDTO.setFileList(fileList);
            }
            approvalSubmitDTOList.add(approvalSubmitDTO);
        }
        R<String> submit = iApprovalServiceApi.submitBatch(approvalSubmitDTOList, loginUser);
        if (!submit.isSuccess()) {
            throw new RuntimeException(submit.getMsg());
        }
    }

    /**
     * 根据业务大单号查询
     *
     * @param orderNumber
     * @return
     */
    @Override
    public List<CuHandleBusiness> selectByOrderNumber(String orderNumber) {
        return baseMapper.selectByOrderNumber(orderNumber);
    }


    private List<BusinessTypeValueVO> setHandleBusinessList(CuHandleBusiness handleBusiness) {
        List<BusinessTypeValueVO> businessTypeValueList = new ArrayList<>();
        BusinessTypeValueVO businessTypeValueVO = new BusinessTypeValueVO();
        List<Integer> businessValueList = new ArrayList<>();
        for (String s : handleBusiness.getStoredValue().split(",")) {
            businessValueList.add(Integer.parseInt(s));
        }
        businessTypeValueVO.setBusinessValueList(businessValueList);
        businessTypeValueVO.setBusinessType(handleBusiness.getEditType());
        businessTypeValueList.add(businessTypeValueVO);
        return businessTypeValueList;
    }

    /**
     * 获取业务办理信息
     *
     * @param handleBusinessVO 业务办理信息
     * @param loginUser        登录信息
     * @param processType      操作按钮类型
     * @return Integer
     */
    private Object[] getHandleBusiness(HandleBusinessVO handleBusinessVO, LoginUser loginUser, Integer processType) {
        Integer approveStatus;
        CuHandleBusiness handleBusiness;
        List<CuHandleBusiness> handleBusinessesList = new ArrayList<>();
        //业务办理日志信息
        List<CuMemberServiceLog> memberServiceLogsList = new ArrayList<>();
        //业务办理变更信息
        List<BusinessTypeValueVO> handleBusinessList = handleBusinessVO.getHandleBusinessList();
        //业务办理的会员信息
        List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();
        //业务编号
        String orderNumber = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());

        //流程类型（1 免签呈 2免付费 3免签呈+免付费 4 需要签呈需要付费）
        //审批状态（免签呈时、审核通过）
        if (processType.equals(EProcessType.AVOIDSIGNING.getValue()) || processType.equals(EProcessType.DOUBLEAVOID.getValue())) {
            approveStatus = EApproveStatus.FINISH.getValue();
        } else {
            approveStatus = EApproveStatus.WAIT_SUBMIT.getValue();
        }
        for (BusinessTypeValueVO businessTypeValueVO : handleBusinessList) {
            //业务类型对应的值
            String value = StringUtils.join(businessTypeValueVO.getBusinessValueList(), ",");
            handleBusiness = CuHandleBusiness.builder().orderNumber(orderNumber)
                    .storedValue(value).editType(businessTypeValueVO.getBusinessType())
                    .approveStatus(approveStatus)
                    .processType(handleBusinessVO.getProcessType())
                    .pkAccount(businessTypeValueVO.getPkAccount())
                    .businessNo(CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue())).build();
            handleBusiness.setPkCountry(handleBusinessVO.getPkCountry());
            handleBusiness.setPkCreator(loginUser.getUserId());
            List<CuMemberServiceLog> memberServiceLogs = getMemberServiceLog(handleBusiness, businessMemberList);
            memberServiceLogsList.addAll(memberServiceLogs);
            handleBusinessesList.add(handleBusiness);
        }
        if (!checkRepeat(handleBusinessesList)) {
            getHandleBusiness(handleBusinessVO, loginUser, processType);
        }
        return new Object[]{memberServiceLogsList, handleBusinessesList, orderNumber};
    }

    /**
     * 校验  handleBusinessesList的getBusinessNo是否存在重复
     **/
    public static boolean checkRepeat(List<CuHandleBusiness> list) {
        Map<String, Long> counts = list.stream()
                .collect(Collectors.groupingBy(CuHandleBusiness::getBusinessNo, Collectors.counting()));
        // 检查是否有任何计数大于1
        return counts.values().stream().allMatch(count -> count == 1);
    }

    /**
     * 获取办理业务日志信息
     *
     * @param handleBusiness     业务办理信息
     * @param businessMemberList 办理业务的会员信息
     * @return List<CuMemberServiceLog>
     */
    private List<CuMemberServiceLog> getMemberServiceLog(CuHandleBusiness handleBusiness, List<BusinessMemberVO> businessMemberList) {
        CuMemberServiceLog memberServiceLog;
        List<CuMemberServiceLog> memberServiceLogsList = new ArrayList<>();
        for (BusinessMemberVO businessMemberVO : businessMemberList) {
            if (businessMemberVO.getBusinessType().equals(handleBusiness.getEditType())) {
                memberServiceLog = CuMemberServiceLog.builder().pkMember(businessMemberVO.getPkMember())
                        .editType(handleBusiness.getEditType()).oldValue(businessMemberVO.getOldValue())
                        .newValue(businessMemberVO.getNewValue()).businessNo(handleBusiness.getBusinessNo())
                        .editTypePay(ETradeType.getValueByApprovalValue(handleBusiness.getEditType()))
                        .singleAmount(businessMemberVO.getSingleAmount())
                        .approveStatus(handleBusiness.getApproveStatus())
                        .approveNumber(businessMemberVO.getApproveNumber())
                        .build();
                if (handleBusiness.getEditType().equals(EApprovalBusiness.CHANGE_AWARDS.getValue())) {
                    memberServiceLog.setEndValidityDate(businessMemberVO.getEndValidityDate());
                }
                memberServiceLog.setPkCreator(handleBusiness.getPkCreator());
                memberServiceLog.setPkCountry(handleBusiness.getPkCountry());
                memberServiceLogsList.add(memberServiceLog);
                businessMemberVO.setBusinessNo(handleBusiness.getBusinessNo());
            }
        }
        return memberServiceLogsList;
    }

    /**
     * 业务办理扣费（先扣款）
     *
     * @param handleBusinessesList 业务办理信息
     * @param businessMemberList   业务办理的会员信息
     */
    public void businessCommissionDTO(List<CuHandleBusiness> handleBusinessesList, List<BusinessMemberVO> businessMemberList) {
        BusinessCommissionDTO businessCommissionDTO;
        for (CuHandleBusiness handleBusiness : handleBusinessesList) {
            Integer businessType = ETradeType.getValueByApprovalValue(handleBusiness.getEditType());
            businessCommissionDTO = BusinessCommissionDTO.builder().pkAccount(handleBusiness.getPkAccount())
                    .tradeType(businessType)
                    .tradeCode(handleBusiness.getBusinessNo())
                    .pkCountry(handleBusiness.getPkCountry())
                    .pkCreator(handleBusiness.getPkCreator()).build();
            businessCommissionDTO.setMemberAmountDTOList(getMemberAmountDTO(handleBusiness, businessMemberList));
            cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
        }
    }

    /**
     * 获取会员办理业务手续费
     *
     * @param businessMemberList 业务办理的会员信息
     * @return List<MemberAmountDTO>
     */
    public List<MemberAmountDTO> getMemberAmountDTO(CuHandleBusiness handleBusiness, List<BusinessMemberVO> businessMemberList) {
        MemberAmountDTO memberAmountDTO;
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        for (BusinessMemberVO businessMemberVO : businessMemberList) {
            if (handleBusiness.getEditType().equals(businessMemberVO.getBusinessType())) {
                memberAmountDTO = new MemberAmountDTO();
                memberAmountDTO.setPkMember(businessMemberVO.getPkMember());
                memberAmountDTO.setTradeAmount(businessMemberVO.getSingleAmount());
                memberAmountDTOList.add(memberAmountDTO);
            }
        }
        return memberAmountDTOList;
    }

    /**
     * 更新业务办理
     *
     * @param handleBusinessVO 业务办理信息
     * @param loginUser        登录信息
     * @return Boolean
     */
    public Boolean updateBusinessMember(HandleBusinessVO handleBusinessVO, LoginUser loginUser) {
        int number = 0;
        Boolean result = false;
        BusinessTypeValueVO businessTypeValueUpdate;
        List<BusinessMemberVO> businessMemberListUpdate;

        List<BusinessTypeValueVO> handleBusinessList = handleBusinessVO.getHandleBusinessList();
        List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();

        HandleBusinessVO handleBusinessUpdate = new HandleBusinessVO();
        List<BusinessTypeValueVO> handleBusinessListUpdate = new ArrayList<>();
        for (BusinessTypeValueVO businessTypeValueVO : handleBusinessList) {
            Integer businessType = businessTypeValueVO.getBusinessType();
            //变更姓名、变更联系方式
            if (businessType.equals(EApprovalBusiness.CHANGE_NAME.getValue()) || businessType.equals(EApprovalBusiness.CHANGE_PHONE.getValue())) {
                businessMemberListUpdate = getBusinessMemberByBusinessType(businessMemberList, businessType);
                result = cuMemberService.batchUpdateMemberNameAndMobileByPkmember(businessMemberListUpdate, businessType, loginUser.getUserId());
                //重置银行卡
                cuMemberBankService.batchUpdateBankBypkMembers(businessMemberListUpdate, loginUser.getUserId());
                //更新姓名修改认证状态
                if (businessType.equals(EApprovalBusiness.CHANGE_NAME.getValue())) {
                    changeBusinessByChangeName(businessMemberList, loginUser);
                }
                //修改会员的变更次数
                List<Long> pkMembers = businessMemberListUpdate.stream().map(BusinessMemberVO::getPkMember).distinct().collect(Collectors.toList());
                cuMemberService.updateMemberEditNumber(pkMembers, loginUser.getUserId());
            }
            //重置银行卡
            if (businessType.equals(EApprovalBusiness.RESET_BANK.getValue())) {
                businessMemberListUpdate = getBusinessMemberByBusinessType(businessMemberList, businessType);
                Integer rows = cuMemberBankService.batchUpdateBankBypkMembers(businessMemberListUpdate, loginUser.getUserId());
                result = rows > 0;
            }
            //修改钱包状态
            if (businessType.equals(EApprovalBusiness.WALLET_STATE.getValue())) {
                businessMemberListUpdate = getBusinessMemberByBusinessType(businessMemberList, businessType);
                Integer rows = cuMemberAccountService.batchUpdateWalletStateByPkMember(businessTypeValueVO.getBusinessValueList(), businessMemberListUpdate, loginUser.getUserId());
                result = rows > 0;
            }
            //其它业务办理
            if (!businessType.equals(EApprovalBusiness.CHANGE_NAME.getValue())
                    && !businessType.equals(EApprovalBusiness.CHANGE_PHONE.getValue())
                    && !businessType.equals(EApprovalBusiness.RESET_BANK.getValue())
                    && !businessType.equals(EApprovalBusiness.WALLET_STATE.getValue())) {
                businessTypeValueUpdate = new BusinessTypeValueVO();
                businessTypeValueUpdate.setBusinessType(businessTypeValueVO.getBusinessType());
                businessTypeValueUpdate.setBusinessValueList(businessTypeValueVO.getBusinessValueList());
                if (number == 0) {
                    businessMemberListUpdate = getBusinessMemberByBusinessType(businessMemberList, businessType);
                    handleBusinessUpdate.setBusinessMemberList(businessMemberListUpdate);
                    handleBusinessUpdate.setPkCountry(handleBusinessVO.getPkCountry());
                }
                number = number + 1;
                handleBusinessListUpdate.add(businessTypeValueUpdate);
            }
            //实名认证
            saveMemberRealName(businessType, handleBusinessUpdate, loginUser);
            //重置会员密码 （密码为初始值）
            reSetBusinessPassword(businessType, handleBusinessUpdate, businessTypeValueVO);
        }
        //更新其它业务
        if (CollUtil.isNotEmpty(handleBusinessListUpdate)) {
            //去重业务类型、业务值
            List<BusinessTypeValueVO> valueList = handleBusinessListUpdate.stream().distinct().collect(Collectors.toList());
            handleBusinessUpdate.setHandleBusinessList(valueList);
            handleBusinessUpdate.setUpdatePkMember(loginUser.getUserId());

            Integer row = cuMemberService.batchUpdateMemberByBusinessType(handleBusinessUpdate);
            //批量更新等级升级记录
            saveMemberLevel(handleBusinessVO, loginUser);
            //批量插入奖衔升级记录表
            saveMemberAwards(handleBusinessVO, loginUser);
            result = row > 0;
        }

        if (result) {
            // 修改是否激活，旧值为未激活，新值为激活的会员需要推MQ处理秒结状态
            List<Long> pkMemberList = handleBusinessVO.getBusinessMemberList().stream()
                    .filter(
                            tmpData -> EApprovalBusiness.IS_ACTIVATE.getValue() == tmpData.getBusinessType()
                                    && tmpData.getOldValue().equals(EYesNo.NO.getIntValue() + "")
                                    && tmpData.getNewValue().equals(EYesNo.YES.getIntValue() + "")
                    )
                    .map(BusinessMemberVO::getPkMember)
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(pkMemberList)) {
                // 推送会员激活处理
                rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_SECOND_ACTIVATE_COMPENSATION_EXCHANGE, RabbitMqConstants.ORDER_SECOND_ACTIVATE_COMPENSATION_KEY, pkMemberList);
            }
        }

        return result;
    }

    /**
     * 更新姓名删除相关实名操作
     *
     * @param businessMember 业务办理会员信息
     * @param loginUser      更新人信息
     * @return Boolean
     */
    private void changeBusinessByChangeName(List<BusinessMemberVO> businessMember, LoginUser loginUser) {
        List<Long> pkMembers = businessMember.stream().map(BusinessMemberVO::getPkMember).distinct().collect(Collectors.toList());
        //更新实名认证
        Boolean auth = cuMemberAuthenticationService.deleteByPkMembers(pkMembers, loginUser.getUserId());
        //更新会员是否实名
        if (auth) {
            cuMemberService.updateMemberStatusByPkIds(pkMembers, loginUser.getUserId(), EAuthType.REAL_NAME.getValue());
        }
        //更新营业执照
        Boolean license = cuMemberBusinessLicenseService.updateMemberLicenseByPkMembers(pkMembers, loginUser.getUserId());
        //更新会员是否营业执照
        if (license) {
            cuMemberService.updateMemberStatusByPkIds(pkMembers, loginUser.getUserId(), EAuthType.BUS_LICENSE.getValue());
        }
    }

    /**
     * 批量更新等级升级记录
     *
     * @param handleBusinessVO 业务办理信息
     * @param loginUser        登录用户信息
     * @return Boolean
     */
    private Boolean saveMemberLevel(HandleBusinessVO handleBusinessVO, LoginUser loginUser) {
        List<BusinessTypeValueVO> handleBusinessList = handleBusinessVO.getHandleBusinessList();
        //获取期数
        String localDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Integer period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(localDate).getPkId();
        for (BusinessTypeValueVO businessTypeValueVO : handleBusinessList) {
            Integer businessType = businessTypeValueVO.getBusinessType();
            if (businessType.equals(EApprovalBusiness.CHANGE_SETTLEMENT_GRADE.getValue())) {
                List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();
                List<BusinessMemberVO> businessMemberListUpdate = getBusinessMemberByBusinessType(businessMemberList, businessType);
                CuMemberLevel cuMemberLevel;
                List<CuMemberLevel> cuMemberLevelList = new ArrayList<>();
                if (CollUtil.isNotEmpty(businessMemberListUpdate)) {
                    for (BusinessMemberVO businessMemberVO : businessMemberListUpdate) {
                        // 记录升级历史
                        cuMemberLevel = CuMemberLevel.builder()
                                .pkMember(businessMemberVO.getPkMember())
                                .upType(EUpgradeType.MANUAL_UPGRADE.getValue())
                                .oldLevel(Integer.parseInt(businessMemberVO.getOldValue()))
                                .newLevel(Integer.parseInt(businessMemberVO.getNewValue()))
                                .upgradeTime(new Date())
                                .build();
                        cuMemberLevel.setPkCountry(handleBusinessVO.getPkCountry());
                        cuMemberLevel.setPkCreator(loginUser.getUserId());
                        cuMemberLevelList.add(cuMemberLevel);
                        //添加等级升级记录
                        CuMemberGrade cuMemberGrade = new CuMemberGrade();
                        cuMemberGrade.setPeriod(period);
                        cuMemberGrade.setPkMember(businessMemberVO.getPkMember());
                        cuMemberGrade.setUpType(EUpgradeType.MANUAL_UPGRADE.getValue());
                        cuMemberGrade.setOldLevel(Integer.parseInt(businessMemberVO.getOldValue()));
                        cuMemberGrade.setNewLevel(Integer.parseInt(businessMemberVO.getNewValue()));
                        cuMemberGrade.setPkCreator(loginUser.getUserId());
                        cuMemberGrade.setPkCountry(handleBusinessVO.getPkCountry());
                        cuMemberService.saveMemberGrade(cuMemberGrade);
                    }
                }
                return cuMemberLevelService.saveBatch(cuMemberLevelList);
            }
        }
        return Boolean.FALSE;

    }


    /**
     * 批量插入奖衔升级记录
     *
     * @param handleBusinessVO 业务办理信息
     * @param loginUser        登录用户信息
     * @return Boolean
     */
    private Boolean saveMemberAwards(HandleBusinessVO handleBusinessVO, LoginUser loginUser) {
        List<BusinessTypeValueVO> handleBusinessList = handleBusinessVO.getHandleBusinessList();
        for (BusinessTypeValueVO businessTypeValueVO : handleBusinessList) {
            Integer businessType = businessTypeValueVO.getBusinessType();
            if (businessType.equals(EApprovalBusiness.CHANGE_AWARDS.getValue())) {
                List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();
                List<BusinessMemberVO> businessMemberListUpdate = getBusinessMemberByBusinessType(businessMemberList, businessType);
                CuMemberAwards cuMemberAwards;
                List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
                if (CollUtil.isNotEmpty(businessMemberListUpdate)) {
                    //批量插入奖衔升级记录
                    //获取期数
                    String localDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    Integer period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(localDate).getPkId();
                    for (BusinessMemberVO businessMemberVO : businessMemberListUpdate) {
                        //默认为S0
                        int oldLevel = 1;
                        String oldValue = businessMemberVO.getOldValue();
                        if (StringUtils.isNotEmpty(oldValue)) {
                            oldLevel = Integer.parseInt(oldValue);
                        }
                        Long pkMember = businessMemberVO.getPkMember();
                        // 记录升级历史
                        cuMemberAwards = CuMemberAwards.builder()
                                .pkMember(pkMember)
                                .period(period)
                                .upType(EUpgradeType.MANUAL_UPGRADE.getValue())
                                .oldLevel(oldLevel)
                                .newLevel(Integer.parseInt(businessMemberVO.getNewValue()))
                                .purchaseStatus(getPurchaseStatus(pkMember, oldLevel))
                                .endValidityDate(businessMemberVO.getEndValidityDate())
                                .build();
                        cuMemberAwards.setPkCountry(handleBusinessVO.getPkCountry());
                        cuMemberAwards.setPkCreator(loginUser.getUserId());
                        cuMemberAwardsList.add(cuMemberAwards);
                    }
                }
                cuMemberAwardsService.saveBatch(cuMemberAwardsList);
            }
            // 2025年6月19日 手改注册等级为合伙人时,如奖衔为空,则改为黄宝 start
            if(businessType.equals(EApprovalBusiness.CHANGE_SETTLEMENT_GRADE.getValue())){
                // 拿本次办理业务的类型
                List<Integer> businessTypeList = handleBusinessList.stream()
                        .map(BusinessTypeValueVO::getBusinessType)
                        .collect(Collectors.toList());
                if(!businessTypeList.contains(EApprovalBusiness.CHANGE_AWARDS.getValue())){
                    List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();
                    List<BusinessMemberVO> businessMemberListUpdate = getBusinessMemberByBusinessType(businessMemberList, EApprovalBusiness.CHANGE_SETTLEMENT_GRADE.getValue());
                    String localDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    Integer period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(localDate).getPkId();
                    Integer pkCountry = loginUser.getDataCountry();
                    R<List<BdAwards>> awardsList = iAwardsServiceApi.queryAwards(pkCountry);
                    R<List<GradeDTO>> gradeList = iGradeServiceApi.queryGradeList(pkCountry);
                    Map<Integer, BdAwards> awardsMap = awardsList.getData().stream().collect(Collectors.toMap(BdAwards::getAwardsValue, o -> o));
                    Map<Integer, GradeDTO> gradesMap = gradeList.getData().stream().collect(Collectors.toMap(GradeDTO::getGradeValue, o -> o));
                    int newLevel = awardsMap.get(EAwards.HEADER.getValue()).getPkId();
                    List<CuMemberAwards> cuMemberAwardsList = new ArrayList<>();
                    HandleBusinessVO businessVO = new HandleBusinessVO();
                    businessVO.setHandleBusinessList(Arrays.asList(
                            BusinessTypeValueVO.builder()
                                    .businessValueList(Arrays.asList(newLevel))
                                    .businessType(EApprovalBusiness.CHANGE_AWARDS.getValue()).build())
                    );
                    businessVO.setUpdatePkMember(loginUser.getUserId());
                    List<BusinessMemberVO> businessMemberVOList = new ArrayList<>();
                    businessVO.setBusinessMemberList(businessMemberVOList);
                    for (BusinessMemberVO memberVO : businessMemberListUpdate) {
                        CuMemberExt memberExt = cuMemberService.getMemberById(memberVO.getPkMember());
                        if(!gradesMap.get(EGrade.S_VIP.getValue()).getPkId().equals(Integer.parseInt(memberVO.getNewValue()))){
                            continue;
                        }
                        // 没有奖衔
                        Integer memberAwardsValue = awardsList.getData().stream().filter(o -> o.getPkId().equals(memberExt.getPkAwards())).findFirst().get().getAwardsValue();
                        if(ObjectUtil.isNotEmpty(memberExt) && EAwards.HEADER.getValue() > memberAwardsValue){
                            businessMemberVOList.add(BusinessMemberVO.builder().pkMember(memberExt.getPkId()).build());
                            int oldLevel = awardsMap.get(memberAwardsValue).getPkId();
                            Long pkMember = memberExt.getPkId();
                            // 记录升级历史
                            CuMemberAwards cuMemberAwards = CuMemberAwards.builder()
                                    .pkMember(pkMember)
                                    .period(period)
                                    .upType(EUpgradeType.MANUAL_UPGRADE.getValue())
                                    .oldLevel(oldLevel)
                                    .newLevel(newLevel)
                                    .purchaseStatus(getPurchaseStatus(pkMember, oldLevel))
                                    .endValidityDate(memberVO.getEndValidityDate())
                                    .build();
                            cuMemberAwards.setPkCountry(handleBusinessVO.getPkCountry());
                            cuMemberAwards.setPkCreator(loginUser.getUserId());
                            cuMemberAwardsList.add(cuMemberAwards);
                        }
                    }
                    // 改奖衔
                    if(CollUtil.isNotEmpty(businessVO.getHandleBusinessList()) && CollUtil.isNotEmpty(businessVO.getBusinessMemberList())){
                        cuMemberService.batchUpdateMemberByBusinessType(businessVO);
                    }
                    // 插入升级记录
                    if(CollUtil.isNotEmpty(cuMemberAwardsList)){
                        cuMemberAwardsService.saveBatch(cuMemberAwardsList);
                    }
                }
            }
            // 2025年6月19日 手改注册等级为合伙人时,如奖衔为空,则改为黄宝 end
        }
        return Boolean.TRUE;
    }

    /**
     * 实名认证保存
     *
     * @param businessType         业务类型
     * @param handleBusinessUpdate 业务办理的
     * @param loginUser            登录用户信息
     * @return Boolean
     */
    private Boolean saveMemberRealName(Integer businessType, HandleBusinessVO handleBusinessUpdate, LoginUser loginUser) {
        if (businessType.equals(EApprovalBusiness.REAL_NAME_AUTHENTICATION.getValue())) {
            List<BusinessMemberVO> businessMemberList = handleBusinessUpdate.getBusinessMemberList();
            CuMemberAuthentication cuMemberAuthentication;
            List<CuMemberAuthentication> memberAuthenticationList = new ArrayList<>();
            Integer pkCountry = handleBusinessUpdate.getPkCountry();
            if (CollUtil.isNotEmpty(businessMemberList)) {
                //认证处理
                String newValue = businessMemberList.get(0).getNewValue();
                if (Integer.parseInt(newValue) == (EYesNoAttestation.NORMAL.getValue())) {
                    for (BusinessMemberVO businessMemberVO : businessMemberList) {
                        Long pkMember = businessMemberVO.getPkMember();
                        //增加实名认证
                        cuMemberAuthentication = CuMemberAuthentication.builder()
                                .pkMember(pkMember).build();
                        cuMemberAuthentication.setPkCountry(pkCountry);
                        cuMemberAuthentication.setPkCreator(loginUser.getUserId());
                        memberAuthenticationList.add(cuMemberAuthentication);
                    }
                    return cuMemberAuthenticationService.saveBatch(memberAuthenticationList);
                } else {
                    //未认证删除实名认证
                    List<Long> pkMembers = businessMemberList.stream().map(BusinessMemberVO::getPkMember).distinct().collect(Collectors.toList());
                    return cuMemberAuthenticationService.deleteByPkMembers(pkMembers, loginUser.getUserId());
                }
            }
        }
        return Boolean.FALSE;
    }

    /**
     * 查询是否复购免考
     *
     * @param pkMember 用户主键
     * @param oldLevel 原奖衔
     * @return Integer
     */
    private Integer getPurchaseStatus(Long pkMember, Integer oldLevel) {
        int purchaseStatus = 1;
        //查询用户是否存在
        LambdaQueryWrapper<CuMemberAwards> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuMemberAwards::getPkMember, pkMember);
        List<CuMemberAwards> list = cuMemberAwardsService.list(queryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            purchaseStatus = 0;
            return purchaseStatus;
        }
        //查询奖衔为会员的
        BdAwards awardsOne = iAwardsServiceApi.getAwardsOne(oldLevel).getData();
        if (awardsOne != null && awardsOne.getAwardsValue().equals(EAwards.MEMBER.getValue())) {
            purchaseStatus = 0;
        }
        return purchaseStatus;
    }

    /**
     * 重置会员密码 （密码为初始值）
     *
     * @param businessType         业务类型
     * @param handleBusinessUpdate 业务处理
     * @param businessTypeValueVO  业务办理变更信息
     * @return HandleBusinessVO
     */
    private HandleBusinessVO reSetBusinessPassword(Integer businessType, HandleBusinessVO handleBusinessUpdate, BusinessTypeValueVO businessTypeValueVO) {
        List<Integer> businessValueList = businessTypeValueVO.getBusinessValueList();
        //重置登录密码
        if (businessType.equals(EApprovalBusiness.RESET_LOGIN_PASSWORD.getValue()) && CollUtil.isNotEmpty(businessValueList)) {
            if (businessValueList.get(0).equals(EResetPassword.LOGIN_PASSWORD.getValue())) {
                handleBusinessUpdate.setLoginPwd(SecurityUtils.encryptPassword(SysConstants.LOGIN_PASSWORD));
                handleBusinessUpdate.setLoginPassword(SysConstants.LOGIN_PASSWORD);
            } else if (businessValueList.get(0).equals(EResetPassword.PAY_PASSWORD.getValue())) {
                handleBusinessUpdate.setPayPwd(SecurityUtils.encryptPassword(SysConstants.PAY_PASSWORD));
                handleBusinessUpdate.setPayPassword(SysConstants.PAY_PASSWORD);
            } else {
                handleBusinessUpdate.setLoginPwd(SecurityUtils.encryptPassword(SysConstants.LOGIN_PASSWORD));
                handleBusinessUpdate.setLoginPassword(SysConstants.LOGIN_PASSWORD);
                handleBusinessUpdate.setPayPwd(SecurityUtils.encryptPassword(SysConstants.PAY_PASSWORD));
                handleBusinessUpdate.setPayPassword(SysConstants.PAY_PASSWORD);
            }
        }
        return handleBusinessUpdate;
    }

    /**
     * 根据业务类型获取会员办理业务信息
     *
     * @param businessMemberList 业务办理的会员信息
     * @param businessType       业务类型
     * @return List<BusinessMemberVO>
     */
    private List<BusinessMemberVO> getBusinessMemberByBusinessType(List<BusinessMemberVO> businessMemberList, Integer businessType) {
        //变更姓名与联系方式
        if (businessType.equals(EApprovalBusiness.CHANGE_NAME.getValue()) || businessType.equals(EApprovalBusiness.CHANGE_PHONE.getValue())) {
            return businessMemberList.stream().filter(member -> member.getBusinessType().equals(businessType))
                    .filter(member -> StringUtils.isNotEmpty(member.getNewValue())).collect(Collectors.toList());
        }
        return businessMemberList.stream().filter(member -> member.getBusinessType().equals(businessType)).collect(Collectors.toList());
    }

}
