package com.hzs.system.sys.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzs.activity.base.IActivityApprovalServiceApi;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
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.utils.DateUtils;
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.system.sys.*;
import com.hzs.common.domain.system.sys.ext.SysApprovalBusinessExt;
import com.hzs.common.domain.system.sys.ext.SysApprovalBusinessSendExt;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.*;
import com.hzs.member.base.dto.UpPolicyCurrencyDTO;
import com.hzs.member.base.dto.ZeroElementRevokeDTO;
import com.hzs.member.handlebusiness.ICuHandleBusinessServiceApi;
import com.hzs.member.handlebusiness.dto.AnalysisBusinessAppealParam;
import com.hzs.member.self.ICuSelfServiceServiceApi;
import com.hzs.member.self.dto.SelfServiceDataDTO;
import com.hzs.sale.pub.ISaleApprovalServiceApi;
import com.hzs.system.index.vo.IndexApprovalDetailVO;
import com.hzs.system.sys.param.ApprovalBusinessParam;
import com.hzs.system.sys.param.ApprovalCustomParam;
import com.hzs.system.sys.param.ApprovalCustomQueryParam;
import com.hzs.system.sys.service.*;
import com.hzs.system.sys.vo.ApprovalBusinessDetailVO;
import com.hzs.system.sys.vo.ApprovalBusinessSendVO;
import com.hzs.system.sys.vo.ApprovalBusinessVO;
import com.hzs.system.sys.vo.ApprovalCustomVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 审批业务处理
 */
@RestController
@RequestMapping("/manage/approval-business")
public class SysApprovalBusinessController extends BaseController {

    @Autowired
    private ISysApprovalBusinessService iSysApprovalBusinessService;
    @Autowired
    private ISysApprovalBusinessDetailService iSysApprovalBusinessDetailService;
    @Autowired
    private ISysApprovalBusinessDataService iSysApprovalBusinessDataService;
    @Autowired
    private ISysApprovalBusinessSendService iSysApprovalBusinessSendService;
    @Autowired
    private ISysApprovalBusinessFileService iSysApprovalBusinessFileService;
    @Autowired
    private IApprovalService iApprovalService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    @DubboReference
    ICuHandleBusinessServiceApi iCuHandleBusinessServiceApi;
    @DubboReference
    ISaleApprovalServiceApi iSaleApprovalServiceApi;
    @DubboReference
    ICuMemberAchieveLogServiceApi achieveLogServiceApi;
    @DubboReference
    ICuSelfServiceServiceApi cuSelfServiceServiceApi;
    @DubboReference
    IActivityApprovalServiceApi iActivityApprovalServiceApi;
    @DubboReference
    IUpPolicyCurrencyServiceApi upPolicyCurrencyServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;

    /**
     * 获取审批详情
     *
     * @param approvalCode 审批单号
     * @return
     */
    @Log(module = EOperationModule.HOME_PAGE, business = EOperationBusiness.APPROVAL_DETAIL, method = EOperationMethod.SELECT)
    @GetMapping("/detail/{approvalCode}")
    public AjaxResult detail(@PathVariable("approvalCode") String approvalCode) {
        // 审批详情
        SysApprovalBusinessExt approvalBusinessExt = iSysApprovalBusinessService.queryByApprovalCode(approvalCode);
        if (null == approvalBusinessExt) {
            // 签呈信息不存在
            return AjaxResult.error(TransactionUtils.getContent(DocumentMsgConstants.SIGN_NOT_EXIST));
        }

        // 签呈抄送列表
        Map<Long, List<SysApprovalBusinessSendExt>> sendMap = iSysApprovalBusinessSendService.approvalSendMap(Collections.singletonList(approvalBusinessExt.getPkId()));

        // 多级未审批，只有第一级进行补全，后面不做处理
        for (SysApprovalBusinessDetail sysApprovalBusinessDetail : approvalBusinessExt.getDetailList()) {
            if (null == sysApprovalBusinessDetail.getStatus()) {
                if (SecurityUtils.getUserId().equals(sysApprovalBusinessDetail.getPkUser())) {
                    // 当前需要登录管理员审批时，需要处理显示为可编辑状态
                    SysUser sysUser = iSysUserService.queryUserAndDeptName(sysApprovalBusinessDetail.getPkUser());
                    sysApprovalBusinessDetail.setApproverDept(sysUser.getDeptName());
                    sysApprovalBusinessDetail.setStatus(0);
                }
                break;
            }
        }

        // 封装返回前台数据
        ApprovalBusinessVO approvalBusinessVO = BeanUtil.copyProperties(approvalBusinessExt, ApprovalBusinessVO.class);
        approvalBusinessVO.setStatus(approvalBusinessExt.getApprovalStatus());
        approvalBusinessVO.setDetailIdList(approvalBusinessExt.getDetailList().stream().map(SysApprovalBusinessDetail::getPkUser).collect(Collectors.toList()));

        List<SysApprovalBusinessSendExt> approvalSendList = sendMap.get(approvalBusinessExt.getPkId());
        if (CollectionUtil.isNotEmpty(approvalSendList)) {
            // 抄送人ID列表
            List<Long> sendIdList = new ArrayList<>();
            // 抄送人列表
            List<ApprovalBusinessSendVO> sendList = new ArrayList<>();
            // 处理抄送人
            StringBuilder sendSb = new StringBuilder();
            for (SysApprovalBusinessSendExt sysApprovalBusinessSend : approvalSendList) {
                sendSb.append(",").append(sysApprovalBusinessSend.getNickName());

                sendIdList.add(sysApprovalBusinessSend.getPkUser());
                sendList.add(ApprovalBusinessSendVO.builder()
                        .pkSend(sysApprovalBusinessSend.getPkUser())
                        .build());
            }
            approvalBusinessVO.setSendStr(sendSb.substring(1));
            approvalBusinessVO.setSendIdList(sendIdList);
            approvalBusinessVO.setSendList(sendList);
        }

        // 审批附件
        LambdaQueryWrapper<SysApprovalBusinessFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysApprovalBusinessFile::getPkApprovalBusiness, approvalBusinessExt.getPkId());
        queryWrapper.orderByAsc(SysApprovalBusinessFile::getPkId);
        List<SysApprovalBusinessFile> fileList = iSysApprovalBusinessFileService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(fileList)) {
            approvalBusinessVO.setFilePathList(fileList.stream().map(SysApprovalBusinessFile::getFilePath).collect(Collectors.toList()));
        }

        // 调用各服务，查询显示内容
        switch (EApprovalType.getEnumByApprovalBusinessValue(approvalBusinessExt.getApprovalBusiness())) {
            case MEMBER_BUSINESS:
                // 会员相关
                if (approvalBusinessExt.getApprovalBusiness() == EApprovalBusiness.MEMBER_ACHIEVE.getValue()) {
                    // 注水业绩审核列表信息
                    AnalysisBusinessAppealParam analysisBusinessAppealParam1 = new AnalysisBusinessAppealParam();
                    analysisBusinessAppealParam1.setBusinessNo(approvalBusinessExt.getBusinessCode());
                    analysisBusinessAppealParam1.setEditType(approvalBusinessExt.getApprovalBusiness());
                    analysisBusinessAppealParam1.setPkCountry(SecurityUtils.getPkCountry());
                    analysisBusinessAppealParam1.setToLanguageTag(LocaleContextHolder.getLocale().toLanguageTag());
                    R achieveLog = achieveLogServiceApi.memberAchieveLog(analysisBusinessAppealParam1);
                    if (achieveLog.isSuccess()) {
                        if (achieveLog.getData() != null) {
                            approvalBusinessVO.setBusinessData(JSONUtil.toJsonStr(achieveLog.getData()));
                        }
                    }
                } else if (approvalBusinessExt.getApprovalBusiness() == EApprovalBusiness.DOMICILE_CHANGE.getValue() ||
                        approvalBusinessExt.getApprovalBusiness() == EApprovalBusiness.SELF_MODIFY_ADDRESS.getValue()) {
                    //自助服务
                    SelfServiceDataDTO serviceDataDTO = SelfServiceDataDTO.builder().businessNo(approvalBusinessExt.getBusinessCode())
                            .editType(approvalBusinessExt.getApprovalBusiness())
                            .pkCountry(SecurityUtils.getPkCountry()).build();
                    R<?> serviceData = cuSelfServiceServiceApi.analysisSelfServiceData(serviceDataDTO);
                    if (serviceData.isSuccess()) {
                        if (serviceData.getData() != null) {
                            approvalBusinessVO.setBusinessData(JSONUtil.toJsonStr(serviceData.getData()));
                        }
                    }
                } else if (approvalBusinessExt.getApprovalBusiness() == EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue() ||
                        approvalBusinessExt.getApprovalBusiness() == EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue()) {
                    //修改政策币审核列表
                    AnalysisBusinessAppealParam analysisBusinessAppealParam1 = new AnalysisBusinessAppealParam();
                    analysisBusinessAppealParam1.setBusinessNo(approvalBusinessExt.getBusinessCode());
                    analysisBusinessAppealParam1.setToLanguageTag(LocaleContextHolder.getLocale().toLanguageTag());
                    R<List<UpPolicyCurrencyDTO>> pgpList = upPolicyCurrencyServiceApi.policyCurrencyList(analysisBusinessAppealParam1);
                    if (pgpList.isSuccess()) {
                        if (pgpList.getData() != null) {
                            approvalBusinessVO.setBusinessData(JSONUtil.toJsonStr(pgpList.getData()));
                        }
                    }

                } else if (approvalBusinessExt.getApprovalBusiness() == EApprovalBusiness.BUSINESS_LICENSE.getValue()
                        || approvalBusinessExt.getApprovalBusiness() == EApprovalBusiness.BUSINESS_LICENSE_RESETTING.getValue()) {
                    // 财务相关、公告站内信（直接取冗余在审批中的信息）
                    LambdaQueryWrapper<SysApprovalBusinessData> dataQueryWrapper = new LambdaQueryWrapper<>();
                    dataQueryWrapper.eq(SysApprovalBusinessData::getPkApprovalBusiness, approvalBusinessExt.getPkId());
                    SysApprovalBusinessData sysApprovalBusinessData = iSysApprovalBusinessDataService.getOne(dataQueryWrapper);
                    if (null != sysApprovalBusinessData) {
                        approvalBusinessVO.setBusinessData(sysApprovalBusinessData.getBusinessData());
                    }
                    //零元撤单
                } else if (approvalBusinessExt.getApprovalBusiness() == EApprovalBusiness.ZERO_ELEMENT_REVOKE.getValue()) {
                    //零元撤单审核列表
                    AnalysisBusinessAppealParam analysisBusinessAppealParam1 = new AnalysisBusinessAppealParam();
                    analysisBusinessAppealParam1.setBusinessNo(approvalBusinessExt.getBusinessCode());
                    R<List<ZeroElementRevokeDTO>> zeroList = iMemberServiceApi.zeroByBusinessList(analysisBusinessAppealParam1);
                    if (zeroList.isSuccess()) {
                        if (zeroList.getData() != null) {
                            approvalBusinessVO.setBusinessData(JSONUtil.toJsonStr(zeroList.getData()));
                        }
                    }
                } else {
                    R memberR = iCuHandleBusinessServiceApi.analysisBusinessAppeal(AnalysisBusinessAppealParam.builder()
                            .businessNo(approvalBusinessExt.getBusinessCode())
                            .editType(approvalBusinessExt.getApprovalBusiness())
                            .pkCountry(SecurityUtils.getPkCountry())
                            .signSource(approvalBusinessExt.getSignSource())
                            .toLanguageTag(LocaleContextHolder.getLocale().toLanguageTag())
                            .build());
                    if (memberR.isSuccess()) {
                        if (null != memberR.getData()) {
                            approvalBusinessVO.setBusinessData(JSONUtil.toJsonStr(memberR.getData()));
                        }
                    }
                }
                break;
            case ORDER_BUSINESS:
                // 订单相关
                R orderR = iSaleApprovalServiceApi.queryApprovalData(EApprovalBusiness.getEnumByValue(approvalBusinessExt.getApprovalBusiness()), approvalBusinessExt.getBusinessCode(), LocaleContextHolder.getLocale().toLanguageTag());
                if (orderR.isSuccess()) {
                    if (null != orderR.getData()) {
                        approvalBusinessVO.setBusinessData(JSONUtil.toJsonStr(orderR.getData()));
                    }
                }
                break;
            case FINANCE_BUSINESS:
            case NOTICE_BUSINESS:
                // 财务相关、公告站内信（直接取冗余在审批中的信息）
                LambdaQueryWrapper<SysApprovalBusinessData> dataQueryWrapper = new LambdaQueryWrapper<>();
                dataQueryWrapper.eq(SysApprovalBusinessData::getPkApprovalBusiness, approvalBusinessExt.getPkId());
                SysApprovalBusinessData sysApprovalBusinessData = iSysApprovalBusinessDataService.getOne(dataQueryWrapper);
                if (null != sysApprovalBusinessData) {
                    approvalBusinessVO.setBusinessData(sysApprovalBusinessData.getBusinessData());
                }
                break;
            case ACTIVITY_BUSINESS:
                // 活动服务信息处理
                R<?> activityR = iActivityApprovalServiceApi.queryApprovalData(EApprovalBusiness.getEnumByValue(approvalBusinessExt.getApprovalBusiness()), approvalBusinessExt.getBusinessCode(), SecurityUtils.getPkCountry());
                if (activityR.isSuccess()) {
                    if (null != activityR.getData()) {
                        JSONConfig jsonConfig = JSONConfig.create().setDateFormat("yyyy-MM-dd HH:mm:ss");
                        approvalBusinessVO.setBusinessData(JSONUtil.toJsonStr(activityR.getData(), jsonConfig));
                    }
                }
                break;
            default:
        }
        return AjaxResult.success(approvalBusinessVO);
    }

    /**
     * 审批
     *
     * @param param 审批入参
     * @return
     */
    @RepeatSubmitSimple
    @Log(module = EOperationModule.HOME_PAGE, business = EOperationBusiness.APPROVAL_DETAIL, method = EOperationMethod.APPROVAL)
    @PutMapping("/approval")
    public AjaxResult approval(@RequestBody ApprovalBusinessParam param) {
        if (StringUtils.isEmpty(param.getApprovalCode()) || null == param.getApproveOperation()) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        // 查询审批业务信息
        SysApprovalBusinessExt approvalBusinessExt = iSysApprovalBusinessService.queryByApprovalCode(param.getApprovalCode());
        if (null == approvalBusinessExt || CollectionUtils.isEmpty(approvalBusinessExt.getDetailList())) {
            // 签呈信息不存在
            return AjaxResult.error(TransactionUtils.getContent(DocumentMsgConstants.SIGN_NOT_EXIST));
        }
        if (EApproveStatus.REJECTED.getValue() == approvalBusinessExt.getApprovalStatus()) {
            // 签呈审批已经驳回p
            return AjaxResult.error(TransactionUtils.getContent(DocumentMsgConstants.SIGN_APPROVAL_REJECT));
        } else if (EApproveStatus.FINISH.getValue() == approvalBusinessExt.getApprovalStatus()) {
            // 签呈审批已完成
            return AjaxResult.error(TransactionUtils.getContent(DocumentMsgConstants.SIGN_APPROVAL_AGREE));
        } else if (EApproveStatus.DRAFT.getValue() == approvalBusinessExt.getApprovalStatus()
                || EApproveStatus.WAIT_SUBMIT.getValue() == approvalBusinessExt.getApprovalStatus()
                || EApproveStatus.CANCEL.getValue() == approvalBusinessExt.getApprovalStatus()) {
            return AjaxResult.error(TransactionUtils.getContent(DocumentMsgConstants.APPROVAL_STATUS_ERROR));
        }

        String str = iApprovalService.approval(approvalBusinessExt, param.getApproveOperation(), param.getRemark(), userTokenService.getLoginUser());

        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }

    /**
     * 提交自定义签呈
     *
     * @param param
     * @return
     */
    @RepeatSubmitSimple
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.CUSTOM_BUSINESS, method = EOperationMethod.SUBMIT)
    @PostMapping("/submit-custom")
    public AjaxResult submitCustom(@RequestBody ApprovalCustomParam param) {
        if (StringUtils.isAnyEmpty(param.getApprovalBusinessVal(), param.getRemark())
                || null == param.getSignType() || CollectionUtil.isEmpty(param.getUserIdList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        // 提交自定义签呈
        String str = iApprovalService.submitCustom(param, SecurityUtils.getUserId(), SecurityUtils.getPkCountry());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }

    /**
     * 自定义签呈列表（日常申请）
     *
     * @param param
     * @return
     */
    @GetMapping("/custom-list")
    public TableDataInfo customList(ApprovalCustomQueryParam param) {
        DateUtils.handTimeStartAndEnd(param.getCreationTime());
        DateUtils.handTimeStartAndEnd(param.getEndTime());

        startPage();
        List<SysApprovalBusiness> list = iSysApprovalBusinessService.customList(param, SecurityUtils.getUserId(), SecurityUtils.getPkCountry());

        // 返回前台数据
        List<ApprovalCustomVO> resultList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(list)) {
            // 返回数据处理
            List<Long> pkIdList = list.stream().map(SysApprovalBusiness::getPkId).collect(Collectors.toList());
            // 批量查询审批明细数据
            Map<Long, List<SysApprovalBusinessDetail>> detailMap = iSysApprovalBusinessDetailService.approvalBusinessMap(pkIdList);

            for (SysApprovalBusiness sysApprovalBusiness : list) {
                // 返回明细数据列表
                List<IndexApprovalDetailVO> detailList = new ArrayList<>();

                // 发起人信息
                IndexApprovalDetailVO tmpIndexApprovalDetailVO = new IndexApprovalDetailVO();
                tmpIndexApprovalDetailVO.setNickName(sysApprovalBusiness.getUserName());
                tmpIndexApprovalDetailVO.setDeptName(sysApprovalBusiness.getDeptName());
                tmpIndexApprovalDetailVO.setUseTime("0");
                detailList.add(tmpIndexApprovalDetailVO);

                // 审批进度下标
                Integer approvalIndex = null;
                // 遍历审批明细
                List<SysApprovalBusinessDetail> tmpDetailList = detailMap.get(sysApprovalBusiness.getPkId());
                for (int i = 0; i < tmpDetailList.size(); i++) {
                    SysApprovalBusinessDetail sysApprovalBusinessDetail = tmpDetailList.get(i);

                    IndexApprovalDetailVO indexApprovalDetailVO = new IndexApprovalDetailVO();
                    indexApprovalDetailVO.setNickName(sysApprovalBusinessDetail.getApprover());
                    indexApprovalDetailVO.setDeptName(sysApprovalBusinessDetail.getApproverDept());
                    detailList.add(indexApprovalDetailVO);

                    // 处理审批用时
                    if (null != sysApprovalBusinessDetail.getApproverTime()) {
                        indexApprovalDetailVO.setUseTime("0");
                    } else {
                        if (null == approvalIndex) {
                            // 记录审批到哪一步的下标
                            approvalIndex = i;
                        }
                    }
                }

                resultList.add(ApprovalCustomVO.builder()
                        .pkId(sysApprovalBusiness.getPkId())
                        .approvalCode(sysApprovalBusiness.getApprovalCode())
                        .approvalBusinessVal(sysApprovalBusiness.getApprovalBusinessVal())
                        .remark(sysApprovalBusiness.getRemark())
                        .approveStatus(sysApprovalBusiness.getApprovalStatus())
                        .creationTime(sysApprovalBusiness.getCreationTime())
                        .endTime(sysApprovalBusiness.getEndTime())
                        .detailList(detailList)
                        .approvalIndex(approvalIndex)
                        .build());
            }
        }

        TableDataInfo tableDataInfo = getDataTable(list);
        tableDataInfo.setRows(resultList);
        return tableDataInfo;
    }

    /**
     * 导出自定义签呈列表
     *
     * @param response
     * @param param
     */
    @PostMapping("/custom-export")
    public void customExport(HttpServletResponse response, ApprovalCustomQueryParam param) {
        DateUtils.handTimeStartAndEnd(param.getCreationTime());
        DateUtils.handTimeStartAndEnd(param.getEndTime());

        List<SysApprovalBusiness> list = iSysApprovalBusinessService.customList(param, SecurityUtils.getUserId(), SecurityUtils.getPkCountry());

        // 返回前台数据
        List<ApprovalCustomVO> resultList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(list)) {
            // 获取需要翻译的枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EApproveStatus.values());

            // 返回数据处理
            List<Long> pkIdList = list.stream().map(SysApprovalBusiness::getPkId).collect(Collectors.toList());
            // 批量查询审批明细数据
            Map<Long, List<SysApprovalBusinessDetail>> detailMap = iSysApprovalBusinessDetailService.approvalBusinessMap(pkIdList);

            for (SysApprovalBusiness sysApprovalBusiness : list) {
                // 返回签呈进度数据
                String detailStr = "";

                StringBuilder detailSb = new StringBuilder();
                // 遍历审批明细
                for (SysApprovalBusinessDetail sysApprovalBusinessDetail : detailMap.get(sysApprovalBusiness.getPkId())) {
                    detailSb.append(sysApprovalBusinessDetail.getApprover()).append("(").append(sysApprovalBusinessDetail.getApproverDept()).append(")").append("; \n");
                }
                detailStr = detailSb.toString();

                resultList.add(ApprovalCustomVO.builder()
                        .approvalBusinessVal(sysApprovalBusiness.getApprovalBusinessVal())
                        .remark(sysApprovalBusiness.getRemark())
                        .detailStr(detailStr)
                        .approveStatusVal(transactionMap.get(EnumsPrefixConstants.APPROVE_STATUS + sysApprovalBusiness.getApprovalStatus()))
                        .creationTime(sysApprovalBusiness.getCreationTime())
                        .endTime(sysApprovalBusiness.getEndTime())
                        .build());
            }
        }

        ExcelUtil<ApprovalCustomVO> util = new ExcelUtil<>(ApprovalCustomVO.class);
        util.exportExcel(response, resultList, "自定义签呈数据导出");
    }

    /**
     * 暂存自定义签呈
     *
     * @param param
     * @return
     */
    @RepeatSubmitSimple
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.CUSTOM_BUSINESS, method = EOperationMethod.INSERT)
    @PostMapping("/staging-custom")
    public AjaxResult stagingCustom(@RequestBody ApprovalCustomParam param) {
        if (StringUtils.isAnyEmpty(param.getApprovalBusinessVal(), param.getRemark())
                || null == param.getSignType() || CollectionUtil.isEmpty(param.getUserIdList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        String str = iApprovalService.stagingCustom(param, SecurityUtils.getUserId(), SecurityUtils.getPkCountry());
        if (null == str) {
            return AjaxResult.success();
        }
        return AjaxResult.error(str);
    }

    /**
     * 撤回自定义签呈
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.CUSTOM_BUSINESS, method = EOperationMethod.UPDATE, remark = "撤回签呈")
    @PostMapping("/revoke-custom")
    public AjaxResult revokeCustom(@RequestBody ApprovalCustomQueryParam param) {
        if (null == param.getPkId()) {
            return AjaxResult.error("请选择需要操作的签呈");
        }
        SysApprovalBusiness sysApprovalBusiness = iSysApprovalBusinessService.getById(param.getPkId());
        if (null == sysApprovalBusiness) {
            return AjaxResult.error("签呈不存在");
        }
        if (EApproveStatus.ALREADY_SUBMIT.getValue() != sysApprovalBusiness.getApprovalStatus()) {
            // 非 待审核 状态不能撤回
            return AjaxResult.error("签呈当前状态不能撤回");
        }

        LambdaUpdateWrapper<SysApprovalBusiness> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysApprovalBusiness::getPkId, sysApprovalBusiness.getPkId());
        updateWrapper.eq(SysApprovalBusiness::getApprovalStatus, EApproveStatus.ALREADY_SUBMIT.getValue());
        updateWrapper.set(SysApprovalBusiness::getApprovalStatus, EApproveStatus.DRAFT.getValue());
        updateWrapper.set(SysApprovalBusiness::getPkModified, SecurityUtils.getUserId());
        updateWrapper.set(SysApprovalBusiness::getModifiedTime, new Date());
        iSysApprovalBusinessService.update(updateWrapper);
        return AjaxResult.success();
    }

    /**
     * 作废自定义签呈
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.CUSTOM_BUSINESS, method = EOperationMethod.UPDATE, remark = "作废签呈")
    @PostMapping("/cancel-custom")
    public AjaxResult cancelCustom(@RequestBody ApprovalCustomQueryParam param) {
        if (null == param.getPkId()) {
            return AjaxResult.error("请选择需要操作的签呈");
        }
        SysApprovalBusiness sysApprovalBusiness = iSysApprovalBusinessService.getById(param.getPkId());
        if (null == sysApprovalBusiness) {
            return AjaxResult.error("签呈不存在");
        }
        if (EApproveStatus.REJECTED.getValue() != sysApprovalBusiness.getApprovalStatus()) {
            // 非 已驳回 状态不能作废
            return AjaxResult.error("签呈当前状态不能作废");
        }

        LambdaUpdateWrapper<SysApprovalBusiness> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysApprovalBusiness::getPkId, sysApprovalBusiness.getPkId());
        updateWrapper.eq(SysApprovalBusiness::getApprovalStatus, EApproveStatus.REJECTED.getValue());
        updateWrapper.set(SysApprovalBusiness::getApprovalStatus, EApproveStatus.CANCEL.getValue());
        updateWrapper.set(SysApprovalBusiness::getPkModified, SecurityUtils.getUserId());
        updateWrapper.set(SysApprovalBusiness::getModifiedTime, new Date());
        iSysApprovalBusinessService.update(updateWrapper);
        return AjaxResult.success();
    }

    /**
     * 重启自定义签呈
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.HANDLE_BUSINESS, business = EOperationBusiness.CUSTOM_BUSINESS, method = EOperationMethod.CREATE, remark = "重启签呈")
    @PostMapping("/restart-custom")
    public AjaxResult restartCustom(@RequestBody ApprovalCustomQueryParam param) {
        if (null == param.getPkId()) {
            return AjaxResult.error("请选择需要操作的签呈");
        }
        SysApprovalBusiness sysApprovalBusiness = iSysApprovalBusinessService.getById(param.getPkId());
        if (null == sysApprovalBusiness) {
            return AjaxResult.error("签呈不存在");
        }
        if (EApproveStatus.REJECTED.getValue() != sysApprovalBusiness.getApprovalStatus()) {
            // 非 已驳回 状态不能作废
            return AjaxResult.error("签呈当前状态不能重启");
        }

        // 封装返回前台数据
        ApprovalBusinessVO approvalBusinessVO = BeanUtil.copyProperties(sysApprovalBusiness, ApprovalBusinessVO.class);
        approvalBusinessVO.setPkId(null);
        approvalBusinessVO.setApprovalCode(null);
        approvalBusinessVO.setStatus(null);
        approvalBusinessVO.setCreationTime(null);

        // 查询审批业务详情
        LambdaQueryWrapper<SysApprovalBusinessDetail> detailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailLambdaQueryWrapper.eq(SysApprovalBusinessDetail::getPkApprovalBusiness, sysApprovalBusiness.getPkId());
        detailLambdaQueryWrapper.orderByAsc(SysApprovalBusinessDetail::getApprovalLevel);
        List<SysApprovalBusinessDetail> detailList = iSysApprovalBusinessDetailService.list(detailLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(detailList)) {
            // 返回的审核业务详情列表
            List<ApprovalBusinessDetailVO> detailVOList = new ArrayList<>(detailList.size());
            for (SysApprovalBusinessDetail sysApprovalBusinessDetail : detailList) {
                detailVOList.add(ApprovalBusinessDetailVO.builder()
                        .approvalLevel(sysApprovalBusinessDetail.getApprovalLevel())
                        .pkApprover(sysApprovalBusinessDetail.getPkUser())
                        .build());
            }
            approvalBusinessVO.setDetailList(detailVOList);
        }

        // 查询抄送人列表
        LambdaQueryWrapper<SysApprovalBusinessSend> sendLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sendLambdaQueryWrapper.eq(SysApprovalBusinessSend::getPkApprovalBusiness, sysApprovalBusiness.getPkId());
        List<SysApprovalBusinessSend> sendList = iSysApprovalBusinessSendService.list(sendLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(sendList)) {
            // 返回的审核业务详情列表
            List<ApprovalBusinessSendVO> sendVOList = new ArrayList<>(sendList.size());
            for (SysApprovalBusinessSend sysApprovalBusinessSend : sendList) {
                sendVOList.add(ApprovalBusinessSendVO.builder()
                        .pkSend(sysApprovalBusinessSend.getPkUser())
                        .build());
            }
            approvalBusinessVO.setSendList(sendVOList);
        }

        // 查询附件地址列表
        LambdaQueryWrapper<SysApprovalBusinessFile> fileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fileLambdaQueryWrapper.eq(SysApprovalBusinessFile::getPkApprovalBusiness, sysApprovalBusiness.getPkId());
        fileLambdaQueryWrapper.orderByAsc(SysApprovalBusinessFile::getPkId);
        List<SysApprovalBusinessFile> fileList = iSysApprovalBusinessFileService.list(fileLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(fileList)) {
            approvalBusinessVO.setFilePathList(fileList.stream().map(SysApprovalBusinessFile::getFilePath).collect(Collectors.toList()));
        }

        return AjaxResult.success(approvalBusinessVO);
    }

}
