package com.hzs.member.base.controller.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.EnumsPrefixConstants;
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.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
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.dto.MemberBalanceDTO;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.CuMemberVO;
import com.hzs.member.base.vo.UpdateCodeImportVO;
import com.hzs.member.base.vo.UpdateCodeVO;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import com.hzs.member.detail.vo.CuMemberServiceLogVO;
import com.hzs.system.config.IServiceChargeServiceApi;
import com.hzs.system.config.dto.ServiceChargeDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @description: 特殊配置-修改会员编号
 * @author: zhang jing
 * @date: 2022/12/29 11:39
 * @param:
 * @return:
 **/
@RequestMapping("/manager/updatecode")
@RestController
public class UpdateCodeController extends BaseController {

    @Autowired
    private ICuMemberService cuMemberService;

    @Autowired
    public void setCuMemberService(ICuMemberService cuMemberService) {
        this.cuMemberService = cuMemberService;
    }

    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @DubboReference
    private IServiceChargeServiceApi serviceChargeServiceApi;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private ICuMemberBaseService cuMemberBaseService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;


    /**
     * @description: 特殊业务-修改会员编号列表
     * @author: zhang jing
     * @date: 2022/11/17 15:39
     * @param: []
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.SELECT)
    @GetMapping("/puCodeList")
    public TableDataInfo puCodeList(UpdateCodeVO updateCodeVO) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        updateCodeVO.setPkCountry(pkCountry);
        List<UpdateCodeVO> list = cuMemberService.puCodeList(updateCodeVO);
        list.forEach(itm -> {
            //注册等级key
            Integer pkGrade = cuMemberService.getGradeTranslateValue(itm.getPkSettleGrade());
            itm.setPkSettleGrade(pkGrade);
            Integer pkAwards = cuMemberService.getAwardsTranslateValue(pkCountry, itm.getPkAwards());
            itm.setPkAwards(pkAwards);
        });
        return getDataTable(list);
    }

    /**
     * @description: 查询特殊业务会员信息
     * @author: zhang jing
     * @date: 2023/7/17 11:52
     * @param: [updateCodeVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.SELECT)
    @GetMapping("/specialBusinessQuery")
    public AjaxResult specialBusinessQuery(UpdateCodeVO updateCodeVO) {

        if (StringUtils.isEmpty(updateCodeVO.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_EMPTY));
        }
        if (StringUtils.isEmpty(updateCodeVO.getMemberCode()) && StringUtils.isEmpty(updateCodeVO.getMemberName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NAME_NOT_NULL));
        }
        if (null == updateCodeVO.getApprovalBusiness()) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.WORK_TYPE_NOT_NULL));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        UpdateCodeVO businessQuery = cuMemberService.specialBusinessQuery(updateCodeVO);
        if (null == businessQuery) {
            return AjaxResult.success(businessQuery);
        }
        Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(businessQuery.getPkId(),
                updateCodeVO.getApprovalBusiness(), EApproveStatus.FINISH.getValue());
        updateCodeVO.setChangeNumber(approveNumber + 1);
        //查询扣费金额，账户信息
        ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
        serviceChargeDTO.setType(updateCodeVO.getApprovalBusiness());
        serviceChargeDTO.setQuantity(approveNumber + 1);
        serviceChargeDTO.setPkCountry(pkCountry);
        R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
        businessQuery.setCost(serviceChargeDTOR.getData().getCost());
        businessQuery.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
        businessQuery.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
        return AjaxResult.success(businessQuery);
    }


    /**
     * 导出
     *
     * @param response
     * @param updateCodeVO
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UpdateCodeVO updateCodeVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        updateCodeVO.setPkCountry(pkCountry);
        List<UpdateCodeVO> list = cuMemberService.puCodeList(updateCodeVO);
        if (CollectionUtil.isNotEmpty(list)) {
            Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                    EnumsPrefixConstants.KEY_AWARD);
            list.forEach(itm -> {
                //注册等级key
                Integer pkGrade = cuMemberService.getGradeTranslateValue(itm.getPkSettleGrade());
                itm.setPkSettleGrade(pkGrade);
                itm.setPkSettleGradeVal(transactionMap1.get(pkGrade));
                Integer pkAwards = cuMemberService.getAwardsTranslateValue(pkCountry, itm.getPkAwards());
                itm.setPkAwards(pkAwards);
                itm.setPkAwardsVal(transactionMap1.get(pkAwards));
            });
        }

        ExcelUtil<UpdateCodeVO> util = new ExcelUtil<>(UpdateCodeVO.class);
        util.exportExcel(response, list, "导出修改会员编号");
    }

    /**
     * 下载模板
     *
     * @param response
     * @param
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.EXPORT)
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        List<UpdateCodeImportVO> list = new ArrayList<>();
        ExcelUtil<UpdateCodeImportVO> util = new ExcelUtil<>(UpdateCodeImportVO.class);
        util.exportExcel(response, list, "修改会员编号");
    }

    /**
     * @description: 导入会员信息
     * @author: zhang jing
     * @date: 2023/1/11 10:27
     * @param: [file, updateSupport]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<UpdateCodeImportVO> util = new ExcelUtil<>(UpdateCodeImportVO.class);
        List<UpdateCodeImportVO> list = util.importExcel(file.getInputStream());
        List<UpdateCodeVO> newlist = new ArrayList<>();
        List<UpdateCodeVO> errorlist = new ArrayList<>();
        List<Long> pkMemberList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (UpdateCodeImportVO ucv : list) {
                if (StringUtils.isNull(ucv.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
                if (StringUtils.isNull(ucv.getMemberCodeNew())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NEW_NOT_NULL));
                }
                String memberCode = ucv.getMemberCode().substring(0, 2);
                String memberCodeNew = ucv.getMemberCodeNew().substring(0, 2);
                if (!memberCode.equals(memberCodeNew)) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_EQUAL));
                }
                CuMember cuMember = cuMemberService.getMember(ucv.getMemberCode());
                CuMember cuMember1 = cuMemberService.getMember(ucv.getMemberCodeNew());
                if (StringUtils.isNotNull(cuMember1)) {
                    UpdateCodeVO updateCodeVO = BeanUtil.copyProperties(ucv, UpdateCodeVO.class);
                    updateCodeVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_MEMBER_CODE_REPEAT));
                    errorlist.add(updateCodeVO);
                    continue;
                }
                if (StringUtils.isNull(cuMember)) {
                    UpdateCodeVO updateCodeVO = BeanUtil.copyProperties(ucv, UpdateCodeVO.class);
                    updateCodeVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
                    errorlist.add(updateCodeVO);
                } else {
                    UpdateCodeVO updateCodeVO = BeanUtil.copyProperties(cuMember, UpdateCodeVO.class);
                    updateCodeVO.setMemberCodeNew(ucv.getMemberCodeNew());
                    updateCodeVO.setNewValue(ucv.getMemberCodeNew());
                    //当前最大次数
                    Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(updateCodeVO.getPkId(),
                            EApprovalBusiness.CHANGE_MEMBER_CODE.getValue(), EApproveStatus.FINISH.getValue());
                    updateCodeVO.setChangeNumber(approveNumber + 1);
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
                    serviceChargeDTO.setQuantity(approveNumber + 1);
                    serviceChargeDTO.setPkCountry(SecurityUtils.getPkCountry());
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    updateCodeVO.setCost(serviceChargeDTOR.getData().getCost());
                    updateCodeVO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    updateCodeVO.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
                    newlist.add(updateCodeVO);
                    pkMemberList.add(updateCodeVO.getPkId());
                }

            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }
            CuMemberServiceLogVO cuMemberServiceLogVO = new CuMemberServiceLogVO();
            cuMemberServiceLogVO.setPkMemberList(pkMemberList);
            cuMemberServiceLogVO.setEditType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
            List<CuMemberServiceLogVO> cslList = memberServiceLogService.selectServiceLogList(cuMemberServiceLogVO);
            if (CollectionUtil.isNotEmpty(cslList)) {
                cslList.forEach(itm -> {
                    UpdateCodeVO updateCodeVO = BeanUtil.copyProperties(itm, UpdateCodeVO.class);
                    updateCodeVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                });
            }
        }
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist);
        }
        return AjaxResult.success(newlist);
    }


    /**
     * @description: 选择会员进行修改会员编号
     * @author: zhang jing
     * @date: 2023/3/27 17:52
     * @param: [updateCodeVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.SELECT)
    @PostMapping("/selected")
    public AjaxResult selected(@RequestBody UpdateCodeVO updateCodeVO) {
        if (StringUtils.isEmpty(updateCodeVO.getMemberCode()) && StringUtils.isEmpty(updateCodeVO.getMemberName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        List<Long> list = updateCodeVO.getPkIdList();
        List<UpdateCodeVO> newlist = new ArrayList<>();
        List<UpdateCodeVO> errorlist = new ArrayList<>();
        Integer pkCountry = SecurityUtils.getPkCountry();
        CuMemberVO memberParam = BeanUtil.copyProperties(updateCodeVO, CuMemberVO.class);
        memberParam.setPkCountry(pkCountry);
        List<CuMemberVO> memberVOList = cuMemberService.realCuMemberByCondition(memberParam);
        if (CollectionUtil.isNotEmpty(memberVOList)) {
            memberVOList.forEach(item -> newlist.add(BeanUtil.copyProperties(item, UpdateCodeVO.class)));
        }
        if (CollectionUtil.isNotEmpty(newlist)) {
            for (UpdateCodeVO ucvo : newlist) {
                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(ucvo.getPkId(),
                        EApprovalBusiness.CHANGE_MEMBER_CODE.getValue(), EApproveStatus.FINISH.getValue());
                ucvo.setChangeNumber(approveNumber + 1);
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
                serviceChargeDTO.setQuantity(approveNumber + 1);
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                ucvo.setCost(serviceChargeDTOR.getData().getCost());
                ucvo.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                ucvo.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
            }
        }
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist);
        }
        return AjaxResult.success(newlist);
    }

    /**
     * @description: 修改会员编号
     * @author: zhang jing
     * @date: 2023/11/30 10:22
     * @param: [postageParams]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.SUBMIT)
    @PostMapping("/updateCode")
    public AjaxResult updateCode(@RequestBody UpdateCodeVO updateCodeVO) {
        UpdateCodeVO updateCodeNewVO;
        List<UpdateCodeVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(updateCodeVO.getUpdateCodeVOList())) {
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            if (StringUtils.isNull(updateCodeVO.getProcessType())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
            }
            Date date = new Date();
            Long userID = SecurityUtils.getUserId();
            Integer pkCountry = SecurityUtils.getPkCountry();
            updateCodeVO.setPkCountry(pkCountry);
            updateCodeVO.setPkCreator(userID);
            updateCodeVO.setCreationTime(date);
            List<UpdateCodeVO> updateParentParamList = new ArrayList<>();
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            for (UpdateCodeVO uc : updateCodeVO.getUpdateCodeVOList()) {
                if (StringUtils.isEmpty(uc.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getPkId())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PKID_NOT_NULL));
                }
                if (StringUtils.isEmpty(uc.getMemberCodeNew())) {
                    uc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NEW_NOT_NULL));
                    errorlist.add(uc);
                    continue;
                }
                uc.setNewValue(uc.getMemberCodeNew());
                //查库
                CuMember cuMember1 = cuMemberService.getMemberByCode(uc.getMemberCodeNew());
                if (StringUtils.isNotNull(cuMember1)) {
                    uc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_MEMBER_CODE_REPEAT));
                    errorlist.add(uc);
                    continue;
                }
                uc.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
                uc.setPkCountry(pkCountry);
                List<UpdateCodeVO> list = cuMemberService.puCodeList(uc);

                if (CollectionUtil.isNotEmpty(list)) {
                    uc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(uc);
                    continue;
                }
                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(uc.getPkId(),
                        EApprovalBusiness.CHANGE_MEMBER_CODE.getValue(), EApproveStatus.FINISH.getValue());
                uc.setChangeNumber(approveNumber + 1);
                if (updateCodeVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                        updateCodeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {

                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
                    serviceChargeDTO.setPkCountry(pkCountry);
                    serviceChargeDTO.setQuantity(approveNumber + 1);
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    if (null == serviceChargeDTOR.getData() ||
                            null == serviceChargeDTOR.getData().getPkAccount()) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                    }
                    //接口查询金额是否足够
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(uc.getPkId());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    uc.setCost(serviceChargeDTOR.getData().getCost());
                    uc.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    memberAmountDTOList.add(memberAmountDTO);
                    updateCodeVO.setMemberAmountDTOList(memberAmountDTOList);
                }
                uc.setNewValue(uc.getMemberCodeNew());
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist);
            }
            updateCodeVO.getUpdateCodeVOList().forEach(item -> updateParentParamList.add(BeanUtil.copyProperties(item, UpdateCodeVO.class)));
            updateCodeVO.setUpdateParentParamList(updateParentParamList);
            businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    return AjaxResult.error(504, ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT, memberBalanceList);
                }
            }

            updateCodeNewVO = cuMemberService.updateCode(updateCodeVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(updateCodeNewVO);
    }

    /**
     * @description: 发起签呈 免付，需要签呈需要付费
     * @author: zhang jing
     * @date: 2023/3/4 11:06
     * @param: [updateCodeVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.SUBMIT)
    @PostMapping("/petition")
    public AjaxResult petition(@RequestBody UpdateCodeVO updateCodeVO) {
        if (StringUtils.isEmpty(updateCodeVO.getUpdateParentParamList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        if (StringUtils.isNull(updateCodeVO.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(updateCodeVO.getSignType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(updateCodeVO.getUserIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXAMINE_AND_APPROVE_NOT_NULL));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        updateCodeVO.setPkCountry(pkCountry);
        updateCodeVO.setPkCreator(userID);
        updateCodeVO.setCreationTime(date);
        Set<Long> pkMemberIds = new HashSet<>();
        BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        for (UpdateCodeVO uc : updateCodeVO.getUpdateParentParamList()) {
            if (StringUtils.isEmpty(uc.getMemberCode())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
            }
            if (StringUtils.isNull(uc.getPkId())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PKID_NOT_NULL));
            }
            pkMemberIds.add(uc.getPkId());
            if (StringUtils.isEmpty(uc.getMemberCodeNew())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NEW_NOT_NULL));
            }
            uc.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            uc.setPkCountry(pkCountry);
            List<UpdateCodeVO> list = cuMemberService.puCodeList(uc);
            if (CollectionUtil.isNotEmpty(list)) {
                return AjaxResult.error(uc.getMemberCode(), ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT);
            }
            //当前最大次数
            Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(uc.getPkId(),
                    EApprovalBusiness.CHANGE_MEMBER_CODE.getValue(), EApproveStatus.FINISH.getValue());
            uc.setChangeNumber(approveNumber + 1);
            if (updateCodeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
                serviceChargeDTO.setQuantity(approveNumber + 1);
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                //接口查询金额是否足够
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setPkCountry(pkCountry);
                MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                memberAmountDTO.setPkMember(uc.getPkId());
                memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                uc.setCost(serviceChargeDTOR.getData().getCost());
                uc.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                memberAmountDTOList.add(memberAmountDTO);
            }
        }
        updateCodeVO.setPkMemberList(pkMemberIds);
        updateCodeVO.setMemberAmountDTOList(memberAmountDTOList);
        businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
        if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
            //接口查询金额是否足够
            if (updateCodeVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    return AjaxResult.error(504, ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT, memberBalanceList);
                }
            }
        }
        cuMemberService.petition(updateCodeVO);
        return AjaxResult.success(true);
    }

}
