package com.hzs.system.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzs.activity.base.IActivityApprovalServiceApi;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.DocumentMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.ThreadUtils;
import com.hzs.common.domain.system.sys.*;
import com.hzs.common.domain.system.sys.ext.SysApprovalBusinessExt;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.IBusinessCommission;
import com.hzs.member.account.IMemberAccountAuditServiceApi;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.handlebusiness.ICuHandleBusinessServiceApi;
import com.hzs.report.stat.IStatisticalLogServiceApi;
import com.hzs.sale.order.dto.OrderUseBarCodeDTO;
import com.hzs.sale.pub.ISaleApprovalServiceApi;
import com.hzs.system.base.IApprovalPushInfo;
import com.hzs.system.base.IBarCodeServiceApi;
import com.hzs.system.base.INoticeAuditServiceApi;
import com.hzs.system.base.dto.ApprovalPushInfoDTO;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.LoginUser;
import com.hzs.system.sys.param.ApprovalCustomParam;
import com.hzs.system.sys.service.*;
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.util.*;
import java.util.stream.Collectors;

/**
 * 审批业务处理
 */
@Slf4j
@Service
public class ApprovalServiceImpl implements IApprovalService {

    @Autowired
    private ISysApprovalBusinessService iSysApprovalBusinessService;
    @Autowired
    private ISysApprovalBusinessDetailService iSysApprovalBusinessDetailService;
    @Autowired
    private ISysApprovalBusinessDataService iSysApprovalBusinessDataService;
    @Autowired
    private ISysApprovalBusinessFileService iSysApprovalBusinessFileService;
    @Autowired
    private ISysApprovalBusinessMemberService iSysApprovalBusinessMemberService;
    @Autowired
    private ISysApprovalBusinessSendService iSysApprovalBusinessSendService;
    @Autowired
    private ISysApprovalBusinessReceiveService iSysApprovalBusinessReceiveService;
    @Autowired
    private ISysBusinessLogService iSysBusinessLogService;
    @Autowired
    private ISysUserService iSysUserService;

    @DubboReference
    IBusinessCommission iBusinessCommission;
    @DubboReference
    IBarCodeServiceApi iBarCodeServiceApi;
    @DubboReference
    ICuHandleBusinessServiceApi iCuHandleBusinessServiceApi;
    @DubboReference
    ISaleApprovalServiceApi iSaleApprovalServiceApi;
    @DubboReference
    IMemberAccountAuditServiceApi iMemberAccountAuditServiceApi;
    @DubboReference
    INoticeAuditServiceApi iNoticeAuditServiceApi;
    @DubboReference
    IActivityApprovalServiceApi iActivityApprovalServiceApi;
    @DubboReference
    IApprovalPushInfo iApprovalPushInfo;
    @DubboReference
    IStatisticalLogServiceApi statisticalLogServiceApi;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String submit(ApprovalSubmitDTO param, LoginUser loginUser, Object obj, List<ApprovalPushInfoDTO> pushInfoList) {
        Integer approvalBusinessVal = param.getEApprovalBusiness().getValue();

        // 审批用户列表
        List<Long> userIdList = param.getUserIdList();
        if (CollectionUtil.isNotEmpty(userIdList)) {
            userIdList = userIdList.stream().filter(Objects::nonNull).collect(Collectors.toList());
        }
        if (CollectionUtil.isEmpty(userIdList)) {
            // 审批流程不能为空
            return TransactionUtils.getContent(DocumentMsgConstants.APPROVAL_FLOW_EMPTY);
        }
        // 去重会员ID列表
        List<Long> distinctUserIdList = userIdList.stream().distinct().collect(Collectors.toList());
        if (userIdList.size() != distinctUserIdList.size()) {
            // 审批流程不能重复
            return TransactionUtils.getContent(DocumentMsgConstants.APPROVAL_FLOW_REPEAT_USER);
        }

        // 所属国家
        Integer pkCountry = loginUser.getDataCountry();
        // 登录用户
        Long userId = loginUser.getUserId();

        // 校验该业务单是否已经存在审批中数据
        if (iSysApprovalBusinessService.checkBusinessExist(Collections.singletonList(approvalBusinessVal), Collections.singletonList(param.getBusinessCode()), pkCountry) > 0) {
            // 正在审批中,不能重复提交
            return TransactionUtils.getContent(DocumentMsgConstants.APPROVAL_FLOW_PROGRESS);
        }

        // 审批大类
        EApprovalType eApprovalType = EApprovalType.getEnumByApprovalBusinessValue(approvalBusinessVal);
        // 当前时间
        Date nowDate = new Date();
        // 当前用户
        SysUser createUser = iSysUserService.queryUserAndDeptName(userId, null);
        // 审批用户（提交审批，第一级审批就是当前审批用户）
        SysUser sysUser = iSysUserService.queryUserAndDeptName(userIdList.get(0), ELoginType.USER.getValueInt());

        // 封装审批业务
        SysApprovalBusiness sysApprovalBusiness = new SysApprovalBusiness();
        sysApprovalBusiness.setApprovalCode(iSysApprovalBusinessService.queryLastCode());
        sysApprovalBusiness.setApprovalType(eApprovalType.getValue());
        sysApprovalBusiness.setApprovalBusiness(approvalBusinessVal);
        sysApprovalBusiness.setBusinessCode(param.getBusinessCode());
        sysApprovalBusiness.setApprovalStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
        sysApprovalBusiness.setPkUser(sysUser.getUserId());
        sysApprovalBusiness.setSignType(param.getSignType().getValue());
        sysApprovalBusiness.setRemark(param.getRemark());
        sysApprovalBusiness.setUserName(createUser.getNickName());
        sysApprovalBusiness.setPkCreator(userId);
        sysApprovalBusiness.setDeptName(createUser.getDeptName());
        sysApprovalBusiness.setPkDept(createUser.getPkDept());
        sysApprovalBusiness.setCreationTime(nowDate);
        sysApprovalBusiness.setPkModified(userId);
        sysApprovalBusiness.setModifiedTime(nowDate);
        sysApprovalBusiness.setPkCountry(pkCountry);
        sysApprovalBusiness.setSignSource(null == param.getSignSource() ? ESignSource.MANAGE.getValue() : param.getSignSource().getValue());

        if (iSysApprovalBusinessService.save(sysApprovalBusiness)) {
            // 审批入库成功，封装入库审批业务明细表
            List<SysApprovalBusinessDetail> detailList = new ArrayList<>();
            for (int i = 0; i < userIdList.size(); i++) {
                SysApprovalBusinessDetail sysApprovalBusinessDetail = new SysApprovalBusinessDetail();
                sysApprovalBusinessDetail.setPkApprovalBusiness(sysApprovalBusiness.getPkId());
                sysApprovalBusinessDetail.setApprovalLevel(i + 1);
                sysApprovalBusinessDetail.setPkUser(userIdList.get(i));
                detailList.add(sysApprovalBusinessDetail);
            }
            // 审批业务明细入库
            iSysApprovalBusinessDetailService.insertBatch(detailList);

            if (StringUtils.isNotEmpty(param.getBusinessData())) {
                // 审批业务数据入库
                SysApprovalBusinessData sysApprovalBusinessData = new SysApprovalBusinessData();
                sysApprovalBusinessData.setPkApprovalBusiness(sysApprovalBusiness.getPkId());
                sysApprovalBusinessData.setBusinessData(param.getBusinessData());
                iSysApprovalBusinessDataService.save(sysApprovalBusinessData);
            }

            // 审批业务附件数据
            List<String> fileList = param.getFileList();
            if (CollectionUtil.isNotEmpty(fileList)) {
                for (String str : fileList) {
                    if (StringUtils.isNotEmpty(str)) {
                        SysApprovalBusinessFile sysApprovalBusinessFile = new SysApprovalBusinessFile();
                        sysApprovalBusinessFile.setPkApprovalBusiness(sysApprovalBusiness.getPkId());
                        sysApprovalBusinessFile.setFilePath(str);
                        iSysApprovalBusinessFileService.save(sysApprovalBusinessFile);
                    }
                }
            }

            // 审批业务涉及会员数据
            Set<Long> pkMemberList = param.getPkMemberList();
            if (CollectionUtil.isNotEmpty(pkMemberList)) {
                iSysApprovalBusinessMemberService.insertBatch(sysApprovalBusiness.getPkId(), pkMemberList);
            }

            // 审批抄送人数据（去重）
            if (CollectionUtil.isNotEmpty(param.getSendIdList())) {
                List<Long> sendIdList = param.getSendIdList().stream().distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(sendIdList)) {
                    iSysApprovalBusinessSendService.insertBatch(sysApprovalBusiness.getPkId(), sendIdList);
                }
            }

            // 判断是否需要后续调用处理
            if (null != obj) {
                if (obj instanceof BusinessCommissionDTO) {
                    // 扣款业务处理
                    BusinessCommissionDTO dto = (BusinessCommissionDTO) obj;
                    if (CollectionUtil.isNotEmpty(dto.getMemberAmountDTOList())) {
                        R<?> tmpR = iBusinessCommission.businessCommissionSubmit(dto);
                        if (!tmpR.isSuccess()) {
                            log.error("订单业务处理扣款失败: {}", tmpR.getMsg());
                            throw new ServiceException(tmpR.getMsg());
                        }
                    }
                } else if (obj instanceof OrderUseBarCodeDTO) {
                    // 订单自提使用条码业务处理
                    OrderUseBarCodeDTO dto = (OrderUseBarCodeDTO) obj;
                    if (CollectionUtil.isNotEmpty(dto.getBarCodeUseList())) {
                        R<?> tmpR = iBarCodeServiceApi.useBarCode(dto.getBarCodeUseList(), dto.getPkCountry(), dto.getUserId());
                        if (!tmpR.isSuccess()) {
                            log.error("订单自提使用条码处理失败: {}", tmpR.getMsg());
                            throw new ServiceException(tmpR.getMsg());
                        }
                    }
                }
            }

            // 推送消息DTO
            ApprovalPushInfoDTO approvalPushInfoDTO = ApprovalPushInfoDTO.builder()
                    .submitTime(nowDate)
                    .pkSubmit(userId)
                    .submitDept(createUser.getDeptName())
                    .approvalBusiness(param.getEApprovalBusiness())
                    .approvalCode(sysApprovalBusiness.getApprovalCode())
                    .pkCountry(pkCountry)
                    .pkCreator(userId)
                    .pkDept(createUser.getDeptName())
                    .noticeBusinessType(ENoticeBusinessType.PETITION)
                    .approveRechargeStatus(EApproveRechargeStatus.WAIT)
                    .pkMembers(Collections.singletonList(sysUser.getUserId()))
                    .build();

            if (null == pushInfoList) {
                // 推送站内信消息
                this.pushInfo(Collections.singletonList(approvalPushInfoDTO));
            } else {
                // 批量操作时，把消息返回全部处理完成后统一推送
                pushInfoList.add(approvalPushInfoDTO);
            }

            return null;
        }
        log.error("签呈处理失败：更新数据失败");
        return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String submitBatch(List<ApprovalSubmitDTO> paramList, LoginUser loginUser) {
        List<ApprovalPushInfoDTO> pushInfoList = new ArrayList<>(paramList.size());

        for (ApprovalSubmitDTO param : paramList) {
            String str = this.submit(param, loginUser, null, pushInfoList);
            if (null != str) {
                throw new ServiceException(str);
            }
        }

        // 当站内信列表不为空时，则进行批量推送
        if (CollectionUtil.isNotEmpty(pushInfoList)) {
            this.pushInfo(pushInfoList);
        }

        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String approval(SysApprovalBusinessExt approvalBusinessExt, Integer approveOperation, String remark, LoginUser loginUser) {
        // 审批业务明细列表
        List<SysApprovalBusinessDetail> detailList = approvalBusinessExt.getDetailList();
        // 当前时间
        Date nowDate = new Date();
        // 当前审批状态
        EApproveStatus eApproveStatus;
        // 当前审批明细信息
        SysApprovalBusinessDetail nowApprovalBusinessDetail = null;
        // 下级审批明细信息
        SysApprovalBusinessDetail nextApprovalBusinessDetail = null;
        // 审批业务类型
        EApprovalBusiness eApprovalBusiness = EApprovalBusiness.getEnumByValue(approvalBusinessExt.getApprovalBusiness());

        for (int i = 0; i < detailList.size(); i++) {
            SysApprovalBusinessDetail tmpApprovalBusinessDetail = detailList.get(i);
            if (null == tmpApprovalBusinessDetail.getStatus()) {
                // 如果审批人为空，则为当前层级审批信息
                nowApprovalBusinessDetail = tmpApprovalBusinessDetail;
                if (i < detailList.size() - 1) {
                    // 当前不为最后一级
                    nextApprovalBusinessDetail = detailList.get(i + 1);
                }
                break;
            }
        }

        if (null == nowApprovalBusinessDetail) {
            // 签呈审批已完成
            return TransactionUtils.getContent(DocumentMsgConstants.SIGN_APPROVAL_AGREE);
        }

        // 审批用户（当前用户就是审批操作用户）
        SysUser sysUser = iSysUserService.queryUserAndDeptName(loginUser.getUserId(), ELoginType.USER.getValueInt());

        // 校验用户权限，封装数据
        if (sysUser.getUserId().equals(nowApprovalBusinessDetail.getPkUser())) {
            // 当前用户ID与审批用户ID相同，可以进行审批

            // 业务数据
            String businessData = null;
            // 推送消息状态
            EApproveRechargeStatus eApproveRechargeStatus = EApproveRechargeStatus.WAIT;

            // 更新 审批业务表
            SysApprovalBusiness approvalBusiness = new SysApprovalBusiness();
            approvalBusiness.setPkId(approvalBusinessExt.getPkId());
            approvalBusiness.setPkModified(sysUser.getUserId());
            approvalBusiness.setModifiedTime(nowDate);
            if (EApproveOperation.AGREE.getValue() == approveOperation) {
                // 通过操作
                if (null == nextApprovalBusinessDetail) {
                    // 没有下一级审批了，更新为已完成状态
                    eApproveStatus = EApproveStatus.FINISH;
                    approvalBusiness.setPkUser(null);
                    approvalBusiness.setEndTime(nowDate);

                    // 审批最终结束时，根据审核ID查询业务缓存数据
                    QueryWrapper<SysApprovalBusinessData> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("PK_APPROVAL_BUSINESS", approvalBusinessExt.getPkId());
                    SysApprovalBusinessData approvalBusinessData = iSysApprovalBusinessDataService.getOne(queryWrapper);
                    if (null != approvalBusinessData) {
                        businessData = approvalBusinessData.getBusinessData();
                    }

                    eApproveRechargeStatus = EApproveRechargeStatus.AGREE;
                } else {
                    // 中间审批层级，更新下级审批角色
                    eApproveStatus = EApproveStatus.APPROVE;
                    approvalBusiness.setPkUser(nextApprovalBusinessDetail.getPkUser());
                }
            } else {
                // 驳回操作
                eApproveStatus = EApproveStatus.REJECTED;
                approvalBusiness.setPkUser(null);
                approvalBusiness.setEndTime(nowDate);

                eApproveRechargeStatus = EApproveRechargeStatus.REJECT;
            }
            approvalBusiness.setApprovalStatus(eApproveStatus.getValue());


            // 更新审批业务表
            if (iSysApprovalBusinessService.updateById(approvalBusiness)) {
                // 更新审批业务明细表
                UpdateWrapper<SysApprovalBusinessDetail> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("PK_APPROVAL_BUSINESS", approvalBusinessExt.getPkId());
                updateWrapper.eq("APPROVAL_LEVEL", nowApprovalBusinessDetail.getApprovalLevel());
                updateWrapper.set("APPROVER", sysUser.getNickName());
                updateWrapper.set("APPROVER_TIME", nowDate);
                updateWrapper.set("PK_DEPT", sysUser.getPkDept());
                updateWrapper.set("APPROVER_DEPT", sysUser.getDeptName());
                updateWrapper.set("STATUS", approveOperation);
                updateWrapper.set("REMARK", remark);
                iSysApprovalBusinessDetailService.update(updateWrapper);

                // 审批站内信实体
                ApprovalPushInfoDTO approvalPushInfoDTO = ApprovalPushInfoDTO.builder()
                        .submitTime(approvalBusinessExt.getCreationTime())
                        .pkSubmit(approvalBusinessExt.getPkCreator())
                        .submitDept(approvalBusinessExt.getDeptName())
                        .approvalBusiness(EApprovalBusiness.getEnumByValue(approvalBusinessExt.getApprovalBusiness()))
                        .approvalCode(approvalBusinessExt.getApprovalCode())
                        .pkCountry(approvalBusinessExt.getPkCountry())
                        .pkCreator(sysUser.getUserId())
                        .pkDept(sysUser.getDeptName())
                        .pkReject(sysUser.getPkDept())
                        .rejectDept(sysUser.getDeptName())
                        .noticeBusinessType(ENoticeBusinessType.PETITION)
                        .approveRechargeStatus(eApproveRechargeStatus)
                        .build();

                if (EApproveStatus.APPROVE.equals(eApproveStatus)) {
                    // 待审批，推送消息给下级审批人，不调用各业务dubbo服务
                    approvalPushInfoDTO.setPkMembers(Collections.singletonList(approvalBusiness.getPkUser()));
                    // 推送站内信消息
                    this.pushInfo(Collections.singletonList(approvalPushInfoDTO));
                    return null;
                }

                // 审批结束，推送消息用户
                List<Long> sendIdList = new ArrayList<>();
                // 发起人
                sendIdList.add(approvalBusinessExt.getPkCreator());
                // 审批流程用户
                sendIdList.addAll(detailList.stream().map(SysApprovalBusinessDetail::getPkUser).collect(Collectors.toList()));
                // 抄送用户
                QueryWrapper<SysApprovalBusinessSend> sendQueryWrapper = new QueryWrapper<>();
                sendQueryWrapper.eq("PK_APPROVAL_BUSINESS", approvalBusinessExt.getPkId());
                List<SysApprovalBusinessSend> sendList = iSysApprovalBusinessSendService.list(sendQueryWrapper);
                if (CollectionUtil.isNotEmpty(sendList)) {
                    sendIdList.addAll(sendList.stream().map(SysApprovalBusinessSend::getPkUser).collect(Collectors.toList()));
                }
                approvalPushInfoDTO.setPkMembers(sendIdList);

                if (EApproveStatus.FINISH.equals(eApproveStatus) && CollectionUtil.isNotEmpty(sendList)) {
                    // 如果是审批完成，需要给抄送人发送未读明细
                    List<SysApprovalBusinessReceive> receiveList = new ArrayList<>(sendList.size());

                    for (SysApprovalBusinessSend sysApprovalBusinessSend : sendList) {
                        SysApprovalBusinessReceive approvalBusinessReceive = new SysApprovalBusinessReceive();
                        approvalBusinessReceive.setPkApprovalBusiness(approvalBusinessExt.getPkId());
                        approvalBusinessReceive.setSendTime(nowDate);
                        approvalBusinessReceive.setPkReceive(sysApprovalBusinessSend.getPkUser());
                        receiveList.add(approvalBusinessReceive);
                    }
                    iSysApprovalBusinessReceiveService.insertBatch(receiveList);
                }

                // 更新业务操作日志
                UpdateWrapper<SysBusinessLog> businessLogUpdateWrapper = new UpdateWrapper<>();
                businessLogUpdateWrapper.eq("BUSINESS_TYPE", approvalBusinessExt.getApprovalBusiness());
                businessLogUpdateWrapper.eq("BUSINESS_CODE", approvalBusinessExt.getBusinessCode());
                businessLogUpdateWrapper.set("BUSINESS_STATUS", eApproveStatus.getValue());
                businessLogUpdateWrapper.set(SystemFieldConstants.PK_MODIFIED, loginUser.getUserId());
                businessLogUpdateWrapper.set(SystemFieldConstants.MODIFIED_TIME, nowDate);
                iSysBusinessLogService.update(businessLogUpdateWrapper);

                // 调用各业务dubbo服务
                return this.callBusiness(ApprovalBusinessResultDTO.builder()
                                .approvalCode(approvalBusinessExt.getApprovalCode())
                                .eApprovalBusiness(eApprovalBusiness)
                                .businessCode(approvalBusinessExt.getBusinessCode())
                                .businessData(businessData)
                                .eApproveStatus(eApproveStatus)
                                .sysUser(sysUser)
                                .loginUser(loginUser)
                                .operationTime(nowDate)
                                .approveOperation(approveOperation)
                                .approveRemark(remark)
                                .signSource(approvalBusinessExt.getSignSource())
                                .build(),
                        approvalPushInfoDTO);
            }
        }
        return "当前用户无权限审批该业务";
    }

    /**
     * 调用业务处理
     *
     * @param approvalBusinessResultDTO 审批数据DTO
     * @param approvalPushInfoDTO       推送消息DTO
     * @return
     */
    private String callBusiness(ApprovalBusinessResultDTO approvalBusinessResultDTO,
                                ApprovalPushInfoDTO approvalPushInfoDTO) {
        log.info("审批调用业务服务参数：{}", approvalBusinessResultDTO);

        R resultR = null;

        switch (EApprovalType.getEnumByApprovalBusinessValue(approvalBusinessResultDTO.getEApprovalBusiness().getValue())) {
            case MEMBER_BUSINESS:
                // 会员相关
                resultR = getMemberBusiness(approvalBusinessResultDTO);
                break;
            case ORDER_BUSINESS:
                // 商品、订单相关
                resultR = iSaleApprovalServiceApi.approvalCallback(approvalBusinessResultDTO);
                break;
            case FINANCE_BUSINESS:
                // 财务相关
                resultR = iMemberAccountAuditServiceApi.auditProcess(approvalBusinessResultDTO);
                break;
            case NOTICE_BUSINESS:
                // 公告、站内信相关
                resultR = iNoticeAuditServiceApi.noticeAuditProcess(approvalBusinessResultDTO);
                break;
            case ACTIVITY_BUSINESS:
                // 活动相关处理
                resultR = iActivityApprovalServiceApi.approvalCallback(approvalBusinessResultDTO);
                break;
            case CUSTOM_BUSINESS:
                // 自定义签呈不需要进行后续业务操作
                return null;
        }

        if (null == resultR) {
            throw new ServiceException("没有可匹配的业务处理");
        }

        if (resultR.isSuccess()) {
            if (null != approvalPushInfoDTO) {
                // 推送站内信消息
                this.pushInfo(Collections.singletonList(approvalPushInfoDTO));
            }

            return null;
        } else {
            log.error("调用业务处理失败: {}", resultR.getMsg());
            throw new ServiceException("签呈业务处理失败： " + (StringUtils.isNotEmpty(resultR.getMsg()) ? resultR.getMsg() : ""));
        }
    }

    /**
     * 调用会员业务处理
     *
     * @param approvalBusinessResultDTO 审批数据DTO
     * @return R
     */
    private R<?> getMemberBusiness(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        if (approvalBusinessResultDTO.getEApprovalBusiness() == EApprovalBusiness.BUSINESS_LICENSE ||
                approvalBusinessResultDTO.getEApprovalBusiness() == EApprovalBusiness.BUSINESS_LICENSE_RESETTING) {
            //营业执照
            return iMemberAccountAuditServiceApi.auditProcess(approvalBusinessResultDTO);
        } else if (approvalBusinessResultDTO.getEApprovalBusiness() == EApprovalBusiness.DIRECT_PUSH_DATA_MAIL) {
            //直推数据发送站内信
            return statisticalLogServiceApi.sendingMessagesProcess(approvalBusinessResultDTO);
        } else {
            // 后台业务办理
            return iCuHandleBusinessServiceApi.signForApproval(approvalBusinessResultDTO);
        }
    }

    /**
     * 推送站内信消息
     *
     * @param pushInfoDTOList 站内信信息列表
     */
    public void pushInfo(final List<ApprovalPushInfoDTO> pushInfoDTOList) {
        ThreadUtils.threadPoolExecutor.submit(() -> iApprovalPushInfo.approvalPushInfo(pushInfoDTOList));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String submitCustom(ApprovalCustomParam param, Long userId, Integer pkCountry) {
        // 审批用户列表
        List<Long> userIdList = param.getUserIdList();
        // 校验自定义签呈参数
        String checkStr = this.checkSelfParam(userIdList);
        if (null != checkStr) {
            return checkStr;
        }

        // 当前时间
        Date nowDate = new Date();
        // 当前用户
        SysUser createUser = iSysUserService.queryUserAndDeptName(userId, null);
        // 审批用户（提交审批，第一级审批就是当前审批用户）
        SysUser sysUser = iSysUserService.queryUserAndDeptName(userIdList.get(0), ELoginType.USER.getValueInt());

        if (null == param.getPkId()) {
            // 没有数据ID，直接新増
            SysApprovalBusiness sysApprovalBusiness = new SysApprovalBusiness();
            sysApprovalBusiness.setApprovalCode(iSysApprovalBusinessService.queryLastCode());
            sysApprovalBusiness.setApprovalType(EApprovalType.CUSTOM_BUSINESS.getValue());
            sysApprovalBusiness.setApprovalBusiness(EApprovalBusiness.CUSTOM.getValue());
            sysApprovalBusiness.setApprovalBusinessVal(param.getApprovalBusinessVal());
            sysApprovalBusiness.setBusinessCode(sysApprovalBusiness.getApprovalCode());
            sysApprovalBusiness.setApprovalStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            sysApprovalBusiness.setPkUser(sysUser.getUserId());
            sysApprovalBusiness.setSignType(param.getSignType());
            sysApprovalBusiness.setRemark(param.getRemark());
            sysApprovalBusiness.setPkCreator(userId);
            sysApprovalBusiness.setUserName(createUser.getNickName());
            sysApprovalBusiness.setPkDept(createUser.getPkDept());
            sysApprovalBusiness.setDeptName(createUser.getDeptName());
            sysApprovalBusiness.setPkModified(userId);
            sysApprovalBusiness.setModifiedTime(nowDate);
            sysApprovalBusiness.setPkCountry(pkCountry);

            if (iSysApprovalBusinessService.save(sysApprovalBusiness)) {
                // 保存签呈数据
                this.saveApprovalDetailData(param, userIdList, sysApprovalBusiness);
            }
        } else {
            // 存在数据ID，直接先查询再修改
            SysApprovalBusiness sysApprovalBusiness = iSysApprovalBusinessService.getById(param.getPkId());
            sysApprovalBusiness.setApprovalBusinessVal(param.getApprovalBusinessVal());
            sysApprovalBusiness.setApprovalStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            sysApprovalBusiness.setPkUser(sysUser.getUserId());
            sysApprovalBusiness.setSignType(param.getSignType());
            sysApprovalBusiness.setRemark(param.getRemark());
            sysApprovalBusiness.setPkModified(userId);
            sysApprovalBusiness.setModifiedTime(nowDate);

            if (iSysApprovalBusinessService.updateById(sysApprovalBusiness)) {
                // 清空签呈关联数据
                this.clearApprovalDetailData(param.getPkId());
                // 保存签呈关联数据
                this.saveApprovalDetailData(param, userIdList, sysApprovalBusiness);
            }
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String stagingCustom(ApprovalCustomParam param, Long userId, Integer pkCountry) {
        // 审批用户列表
        List<Long> userIdList = param.getUserIdList();
        // 校验自定义签呈参数
        String checkStr = this.checkSelfParam(userIdList);
        if (null != checkStr) {
            return checkStr;
        }

        // 当前时间
        Date nowDate = new Date();
        // 当前用户
        SysUser createUser = iSysUserService.queryUserAndDeptName(userId, null);
        // 审批用户（提交审批，第一级审批就是当前审批用户）
        SysUser sysUser = iSysUserService.queryUserAndDeptName(userIdList.get(0), ELoginType.USER.getValueInt());

        if (null == param.getPkId()) {
            // 没有数据ID，直接新増
            SysApprovalBusiness sysApprovalBusiness = new SysApprovalBusiness();
            sysApprovalBusiness.setApprovalCode(iSysApprovalBusinessService.queryLastCode());
            sysApprovalBusiness.setApprovalType(EApprovalType.CUSTOM_BUSINESS.getValue());
            sysApprovalBusiness.setApprovalBusiness(EApprovalBusiness.CUSTOM.getValue());
            sysApprovalBusiness.setApprovalBusinessVal(param.getApprovalBusinessVal());
            sysApprovalBusiness.setBusinessCode(sysApprovalBusiness.getApprovalCode());
            sysApprovalBusiness.setApprovalStatus(EApproveStatus.DRAFT.getValue());
            sysApprovalBusiness.setPkUser(sysUser.getUserId());
            sysApprovalBusiness.setSignType(param.getSignType());
            sysApprovalBusiness.setRemark(param.getRemark());
            sysApprovalBusiness.setPkCreator(userId);
            sysApprovalBusiness.setUserName(createUser.getNickName());
            sysApprovalBusiness.setPkDept(createUser.getPkDept());
            sysApprovalBusiness.setDeptName(createUser.getDeptName());
            sysApprovalBusiness.setPkModified(userId);
            sysApprovalBusiness.setModifiedTime(nowDate);
            sysApprovalBusiness.setPkCountry(pkCountry);

            if (iSysApprovalBusinessService.save(sysApprovalBusiness)) {
                // 保存签呈数据
                this.saveApprovalDetailData(param, userIdList, sysApprovalBusiness);
            }
        } else {
            // 存在数据ID，直接先查询再修改
            SysApprovalBusiness sysApprovalBusiness = iSysApprovalBusinessService.getById(param.getPkId());
            sysApprovalBusiness.setApprovalBusinessVal(param.getApprovalBusinessVal());
            sysApprovalBusiness.setApprovalStatus(EApproveStatus.DRAFT.getValue());
            sysApprovalBusiness.setPkUser(sysUser.getUserId());
            sysApprovalBusiness.setSignType(param.getSignType());
            sysApprovalBusiness.setRemark(param.getRemark());
            sysApprovalBusiness.setPkModified(userId);
            sysApprovalBusiness.setModifiedTime(nowDate);

            if (iSysApprovalBusinessService.updateById(sysApprovalBusiness)) {
                // 清空签呈关联数据
                this.clearApprovalDetailData(param.getPkId());
                // 保存签呈关联数据
                this.saveApprovalDetailData(param, userIdList, sysApprovalBusiness);
            }
        }
        return null;
    }

    /**
     * 校验自定义签呈参数
     *
     * @param userIdList 审批用户列表
     * @return
     */
    private String checkSelfParam(List<Long> userIdList) {
        if (CollectionUtil.isNotEmpty(userIdList)) {
            userIdList = userIdList.stream().filter(Objects::nonNull).collect(Collectors.toList());
        }
        if (CollectionUtil.isEmpty(userIdList)) {
            // 审批流程不能为空
            return TransactionUtils.getContent(DocumentMsgConstants.APPROVAL_FLOW_EMPTY);
        }
        // 去重用户ID列表
        List<Long> distinctUserIdList = userIdList.stream().distinct().collect(Collectors.toList());
        if (userIdList.size() != distinctUserIdList.size()) {
            // 审批流程不能重复
            return TransactionUtils.getContent(DocumentMsgConstants.APPROVAL_FLOW_REPEAT_USER);
        }
        return null;
    }

    /**
     * 清除签呈关联数据
     *
     * @param pkApprovalBusiness 审批业务ID
     */
    private void clearApprovalDetailData(Long pkApprovalBusiness) {
        // 清除审批业务明细
        LambdaQueryWrapper<SysApprovalBusinessDetail> detailQueryWrapper = new LambdaQueryWrapper<>();
        detailQueryWrapper.eq(SysApprovalBusinessDetail::getPkApprovalBusiness, pkApprovalBusiness);
        iSysApprovalBusinessDetailService.remove(detailQueryWrapper);

        // 清除审批业务附件
        LambdaQueryWrapper<SysApprovalBusinessFile> fileQueryWrapper = new LambdaQueryWrapper<>();
        fileQueryWrapper.eq(SysApprovalBusinessFile::getPkApprovalBusiness, pkApprovalBusiness);
        iSysApprovalBusinessFileService.remove(fileQueryWrapper);

        // 清除审批抄送人
        LambdaQueryWrapper<SysApprovalBusinessSend> sendQueryWrapper = new LambdaQueryWrapper<>();
        sendQueryWrapper.eq(SysApprovalBusinessSend::getPkApprovalBusiness, pkApprovalBusiness);
        iSysApprovalBusinessSendService.remove(sendQueryWrapper);
    }

    /**
     * 保存签呈关联数据
     *
     * @param param               请求参数
     * @param userIdList          审批会员列表
     * @param sysApprovalBusiness 签呈主数据
     */
    private void saveApprovalDetailData(ApprovalCustomParam param, List<Long> userIdList, SysApprovalBusiness sysApprovalBusiness) {
        // 审批入库成功，封装入库审批业务明细表
        List<SysApprovalBusinessDetail> detailList = new ArrayList<>();
        for (int i = 0; i < userIdList.size(); i++) {
            SysApprovalBusinessDetail sysApprovalBusinessDetail = new SysApprovalBusinessDetail();
            sysApprovalBusinessDetail.setPkApprovalBusiness(sysApprovalBusiness.getPkId());
            sysApprovalBusinessDetail.setApprovalLevel(i + 1);
            sysApprovalBusinessDetail.setPkUser(userIdList.get(i));
            detailList.add(sysApprovalBusinessDetail);
        }
        // 审批业务明细入库
        iSysApprovalBusinessDetailService.insertBatch(detailList);

        // 审批业务附件数据
        List<String> fileList = param.getFileList();
        if (CollectionUtil.isNotEmpty(fileList)) {
            for (String str : fileList) {
                if (StringUtils.isNotEmpty(str)) {
                    SysApprovalBusinessFile sysApprovalBusinessFile = new SysApprovalBusinessFile();
                    sysApprovalBusinessFile.setPkApprovalBusiness(sysApprovalBusiness.getPkId());
                    sysApprovalBusinessFile.setFilePath(str);
                    iSysApprovalBusinessFileService.save(sysApprovalBusinessFile);
                }
            }
        }

        // 审批抄送人数据（去重）
        if (CollectionUtil.isNotEmpty(param.getSendIdList())) {
            List<Long> sendIdList = param.getSendIdList().stream().distinct().collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(sendIdList)) {
                iSysApprovalBusinessSendService.insertBatch(sysApprovalBusiness.getPkId(), sendIdList);
            }
        }
    }

}
