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

import cn.hutool.core.collection.CollUtil;
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.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.detail.CuMemberAwards;
import com.hzs.common.domain.member.detail.CuMemberLevel;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.member.handleBusiness.CuHandleBusiness;
import com.hzs.common.domain.system.config.BdAwards;
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.*;
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.*;
import com.hzs.system.config.IAwardsServiceApi;
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 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.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 ICuMemberServiceLogService memberServiceLogService;
    @Autowired
    private ICuMemberService cuMemberService;
    @Autowired
    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;
    @Autowired
    private ICuMemberBankService cuMemberBankService;
    @Autowired
    private ICuHandleBusinessService handleBusinessService;
    @Autowired
    private ICuMemberAccountService cuMemberAccountService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private ICuMemberLevelService cuMemberLevelService;
    @Autowired
    private ICuMemberAwardsService cuMemberAwardsService;

    @DubboReference
    IApprovalServiceApi approvalServiceApi;
    @DubboReference
    IAwardsServiceApi awardsServiceApi;


    /**
     * 查询办理业务列表
     **/
    @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);
        }
        return result;
    }

    /**
     * 在线签呈审核
     *
     * @param approvalBusinessResultDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R signForApprovalExamine(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        LoginUser loginUser = approvalBusinessResultDTO.getLoginUser();
        if (approvalBusinessResultDTO.getApproveOperation() == EApproveOperation.AGREE.getValue()) {
            // 通过
            QueryWrapper<CuHandleBusiness> wrapper = new QueryWrapper<>();
            wrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
            CuHandleBusiness handleBusiness = handleBusinessService.getOne(wrapper);
            // 更新主日志表
            UpdateWrapper<CuHandleBusiness> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
            updateWrapper.set("APPROVE_STATUS", EApproveStatus.FINISH.getValue());
            handleBusinessService.update(updateWrapper);
            QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BUSINESS_NO", 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());
                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();
            // 驳回
            QueryWrapper<CuHandleBusiness> wrapper = new QueryWrapper<>();
            wrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
            CuHandleBusiness handleBusiness = handleBusinessService.getOne(wrapper);
            // 更新主日志表
            UpdateWrapper<CuHandleBusiness> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("BUSINESS_NO", tradeCode);
            updateWrapper.set("APPROVE_STATUS", EApproveStatus.REJECTED.getValue());
            handleBusinessService.update(updateWrapper);
            QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("BUSINESS_NO", 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);

                MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                memberAmountDTO.setPkMember(cuMemberServiceLog.getPkMember());
                memberAmountDTO.setTradeAmount(cuMemberServiceLog.getSingleAmount());
                memberAmountDTOList.add(memberAmountDTO);
            }
            // 退款
            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];
        //保存业务办理信息
        memberServiceLogService.saveBatch(memberServiceLogsList);
        Boolean result = this.saveBatch(handleBusinessesList);
        //扣手续费
        if (processType.equals(EProcessType.DOUBLEPAY.getValue())) {
            //业务办理的会员信息
            List<BusinessMemberVO> businessMemberList = handleBusinessVO.getBusinessMemberList();
            businessCommissionDTO(handleBusinessesList, businessMemberList);
        }
        submitApproval(handleBusinessVO, loginUser, handleBusinessesList);
        return result;

    }


    /**
     * 提交审批
     *
     * @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 = approvalServiceApi.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);
        }
        return new Object[]{memberServiceLogsList, handleBusinessesList, orderNumber};
    }

    /**
     * 获取办理业务日志信息
     *
     * @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();
                memberServiceLog.setPkCreator(handleBusiness.getPkCreator());
                memberServiceLog.setPkCountry(handleBusiness.getPkCountry());
                memberServiceLogsList.add(memberServiceLog);
            }
        }
        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());
                //修改会员的变更次数
                List<Long> pkMembers = businessMemberListUpdate.stream().map(BusinessMemberVO::getPkMember).distinct().collect(Collectors.toList());
                cuMemberService.updateMemberEditNumber(pkMembers, loginUser.getUserId());
            }
            //修改邮箱
            if (businessType.equals(EApprovalBusiness.RESET_EMAIL.getValue())) {
                businessMemberListUpdate = getBusinessMemberByBusinessType(businessMemberList, businessType);
                result = cuMemberService.batchUpdateMemberNameAndMobileByPkmember(businessMemberListUpdate, businessType, 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);
                }
                number = number + 1;
                handleBusinessListUpdate.add(businessTypeValueUpdate);
            }
            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;
        }
        return result;
    }

    /**
     * 批量更新等级升级记录
     *
     * @param handleBusinessVO 业务办理信息
     * @param loginUser        登录用户信息
     * @return Boolean
     */
    private Boolean saveMemberLevel(HandleBusinessVO handleBusinessVO, LoginUser loginUser) {
        List<BusinessTypeValueVO> handleBusinessList = handleBusinessVO.getHandleBusinessList();
        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);
                    }
                }
                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) {
                        Integer oldLevel = Integer.parseInt(businessMemberVO.getOldValue());
                        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))
                                .build();
                        cuMemberAwards.setPkCountry(handleBusinessVO.getPkCountry());
                        cuMemberAwards.setPkCreator(loginUser.getUserId());
                        cuMemberAwardsList.add(cuMemberAwards);
                    }
                }
                return cuMemberAwardsService.saveBatch(cuMemberAwardsList);
            }
        }
        return Boolean.FALSE;

    }

    /**
     * 查询是否复购免考
     *
     * @param pkMember 用户主键
     * @param oldLevel 原奖衔
     * @return Integer
     */
    private Integer getPurchaseStatus(Long pkMember, Integer oldLevel) {
        int purchaseStatus = 1;
        //查询用户是否存在
        QueryWrapper<CuMemberAwards> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_MEMBER", pkMember);
        List<CuMemberAwards> list = cuMemberAwardsService.list(queryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            purchaseStatus = 0;
            return purchaseStatus;
        }
        //查询奖衔为会员的
        BdAwards awardsOne = awardsServiceApi.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());
    }

}
