package com.casic.missiles.service.Impl.business;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.application.service.AbstractDictService;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.dto.BaseApprovalSubmitRequest;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.business.outsource.*;
import com.casic.missiles.dto.flowable.AllApproveDTO;
import com.casic.missiles.dto.flowable.ApprovalDeleteRequest;
import com.casic.missiles.dto.flowable.ToBeApprovedDTO;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.enums.meter.MeterDictEnum;
import com.casic.missiles.enums.system.ApprovalStatusEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.business.BusinessOutsourceProjectMapper;
import com.casic.missiles.model.business.BusinessOutsourceProject;
import com.casic.missiles.model.business.BusinessOutsourceProjectSampleRelation;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.service.IBaseApprovalService;
import com.casic.missiles.service.business.IBusinessOutsourceProjectSampleRelationService;
import com.casic.missiles.service.business.IBusinessOutsourceProjectService;
import com.casic.missiles.service.flowable.ApprovalOperateService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import com.casic.missiles.utils.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 分包项目表 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2023-03-23
 */
@Service
public class BusinessOutsourceProjectServiceImpl extends ServiceImpl<BusinessOutsourceProjectMapper, BusinessOutsourceProject> implements IBusinessOutsourceProjectService {
    @Autowired
    private IBaseApprovalService baseApprovalService;
    @Autowired
    private BusinessOutsourceProjectMapper projectMapper;
    @Autowired
    private IBusinessOutsourceProjectSampleRelationService projectSampleRelationService;
    @Resource
    private AbstractDictService dictService;
    @Resource
    private RuntimeService runtimeService;
    @Autowired
    private ApprovalOperateService approvalOperateService;

    @Override
    public List<OutsourceProjectApprovalListResponse> projectApplyApprovalListPage(OutsourceProjectApprovalListRequest request, Page<OutsourceProjectApprovalListResponse> page) throws Exception {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        request.setCreateUserId(user.getId());
        List<OutsourceProjectApprovalListResponse> responseList = handleApprovalStatus(page, request);
        if(CollectionUtils.isEmpty(responseList)){
            return new ArrayList<>();
        }
        for (OutsourceProjectApprovalListResponse response : responseList) {
            DictCodeUtils.convertDictCodeToName(response);
        }
        return responseList;
    }

    @Override
    @Transactional
    public ReturnDTO<OutsourceProjectSaveResponse> saveProjectApply(BusinessOutsourceProject outsourceProject) {
        //生成编号
        Long maxNo = projectMapper.selectMaxOutsourcerNo();
        String projectNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.OUTSOURCE_PROJECT_PREFIX, maxNo);
        outsourceProject.setProjectNo(projectNo);
        outsourceProject.setApplyApprovalStatus(ApprovalStatusEnum.DRAFT); //草稿箱状态
        Assert.isFalse(Objects.isNull(ShiroKit.getUser()), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        outsourceProject.setCreateUser(ShiroKit.getUser().getId()); //登录者用户id
        outsourceProject.setApplicantId(ShiroKit.getUser().getId()); //登录者用户id
        outsourceProject.setApplicantName(ShiroKit.getUser().getName()); //登录者用户名
        int insertFlag = projectMapper.insert(outsourceProject);
        Assert.isFalse(insertFlag <= 0, () -> {
            throw new BusinessException(BusinessExceptionEnum.OUTSOURCE_PROJECT_APPLY_SAVE_FAILED);
        });
        //保存关联样品
        saveBatchRelation(outsourceProject);
        OutsourceProjectSaveResponse saveResponse = new OutsourceProjectSaveResponse();
        saveResponse.setId(outsourceProject.getId());
        saveResponse.setProjectNo(projectNo);
        return ReturnUtil.success(saveResponse);
    }

    @Override
    @Transactional
    public ReturnDTO projectApplyDraftUpdate(BusinessOutsourceProject outsourceProject) {
        int updateFlag = projectMapper.updateById(outsourceProject);
        if (updateFlag > 0) {
            //关联样品编辑
            QueryWrapper<BusinessOutsourceProjectSampleRelation> wrapper = new QueryWrapper<>();
            wrapper.eq("project_id", outsourceProject.getId());
            projectSampleRelationService.remove(wrapper);
            saveBatchRelation(outsourceProject);
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO submitProjectApply(BaseApprovalSubmitRequest request) {
        //已取消后的提交需先删除原有实例
        if (StringUtils.isNotEmpty(request.getProcessId())){
            runtimeService.updateBusinessStatus(request.getProcessId(), ApprovalStatusEnum.DELETED);
            runtimeService.deleteProcessInstance(request.getProcessId(), "删除");
        }
        //1.根据表单id获取流程定义id
        //2.根据流程定义id启动流程实例
        String formId = request.getFormId();
        ReturnDTO returnDTO = baseApprovalService.processSubmit(formId, request.getId());
        if (ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()) {
            return returnDTO;
        }
        ProcessInstance processInstance = (ProcessInstance) returnDTO.getData();

        BusinessOutsourceProject outsourceProject = new BusinessOutsourceProject();
        outsourceProject.setId(request.getId());
        outsourceProject.setApplyApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态
        outsourceProject.setApplyProcessId(processInstance.getId());
        int row = projectMapper.updateById(outsourceProject);
        if (row <= 0) {
            throw new BusinessException(BusinessExceptionEnum.OUTSOURCE_PROJECT_APPLY_SUBMIT_FAILED);
        }
        return ReturnUtil.success();
    }

    @Override
    @Transactional
    public ReturnDTO projectApplyDelete(Long id) {
        if (projectMapper.deleteById(id) > 0) {
            //关联样品删除
            QueryWrapper<BusinessOutsourceProjectSampleRelation> wrapper = new QueryWrapper<>();
            wrapper.eq("project_id", id);
            projectSampleRelationService.remove(wrapper);
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO<BusinessOutsourceProject> projectDetail(Long id) throws Exception {
        BusinessOutsourceProject detailResponse = projectMapper.selectProjectById(id);
        DictCodeUtils.convertDictCodeToName(detailResponse);
        //关联样品查询
        List<OrderSampleResponseDTO> sampleList = projectSampleRelationService.selectSampleList(id);
        detailResponse.setSampleList(sampleList);
        return ReturnUtil.success(detailResponse);
    }

    @Override
    public ReturnDTO<BusinessOutsourceProject> projectApplyDetail(OutsourceProjectDetailRequest request) throws Exception {
        BusinessOutsourceProject detailResponse = projectMapper.selectProjectById(request.getId());
        DictCodeUtils.convertDictCodeToName(detailResponse);
        //关联样品查询
        List<OrderSampleResponseDTO> sampleList = projectSampleRelationService.selectSampleList2(request.getId(), request.getSampleNo(), request.getSampleName());
        detailResponse.setSampleList(sampleList);
        return ReturnUtil.success(detailResponse);
    }

    @Override
    public ReturnDTO projectApplyApprovalDelete(ApprovalDeleteRequest request) {
        ReturnDTO returnDTO = approvalOperateService.delete(request);
        if (ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()) {
            //本地删除
            if (projectMapper.deleteById(request.getId()) > 0) {
                return ReturnUtil.success();
            }
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO projectApplyFailUpdate(BusinessOutsourceProject outsourceProject) {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        if (projectMapper.updateById(outsourceProject) > 0) {
            //关联样品编辑
            QueryWrapper<BusinessOutsourceProjectSampleRelation> wrapper = new QueryWrapper<>();
            wrapper.eq("project_id", outsourceProject.getId());
            projectSampleRelationService.remove(wrapper);
            saveBatchRelation(outsourceProject);

            baseApprovalService.failUpdate(outsourceProject.getApplyProcessId());
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public Page<BusinessOutsourceProject> projectApplyListPage(OutsourceProjectApplyListRequest request, Page<BusinessOutsourceProject> page) {
        QueryWrapper<BusinessOutsourceProject> wrapper = getWrapper(request);
        Page<BusinessOutsourceProject> projectPage = projectMapper.selectPage(page, wrapper);
        return projectPage;
    }

    private QueryWrapper<BusinessOutsourceProject> getWrapper(OutsourceProjectApplyListRequest request) {
        //flowable中已通过状态的业务id列表
        List<String> passedList = baseApprovalService.getPassedList(request.getFormId());
        QueryWrapper<BusinessOutsourceProject> wrapper = new QueryWrapper<>();
        //无审批通过则返回空数据
        if (CollectionUtils.isEmpty(passedList)) {
            wrapper.eq("id", 12344321);
            return wrapper;
        }
        wrapper.eq(Objects.nonNull(request.getOutsourcerId()), "outsourcer_id", request.getOutsourcerId());
        wrapper.like(StringUtils.isNotBlank(request.getProjectNo()), "project_no", request.getProjectNo());
        wrapper.like(StringUtils.isNotBlank(request.getProjectName()), "project_name", request.getProjectName());
        //验收状态若是草稿或空则可以被选择进行验收
        // TODO: 2023/4/24 验收不通过也不能被再验收，根据后续需求调整
        wrapper.and(wr -> wr.or().eq("check_approval_status", ApprovalStatusEnum.DRAFT).or().isNull("check_approval_status"));
        wrapper.in("id", passedList);
        wrapper.orderByDesc("create_time");
        return wrapper;
    }

    @Override
    public ReturnDTO<OutsourceProjectSaveResponse> saveOrUpdateProjectCheck(OutsourceProjectCheckSaveOrUpdateRequest request) {
        BusinessOutsourceProject outsourceProject = projectMapper.selectById(request.getId());
        outsourceProject.setCheckApprovalStatus(ApprovalStatusEnum.DRAFT); //草稿箱状态
        Assert.isFalse(Objects.isNull(ShiroKit.getUser()), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        //验收的数据是已通过申请的数据，只做更新即可
        outsourceProject.setCheckerId(ShiroKit.getUser().getId()); //登录者用户id
        outsourceProject.setCheckerName(ShiroKit.getUser().getName()); //登录者用户名
        outsourceProject.setCheckConclusion(request.getCheckConclusion());
        outsourceProject.setCheckTime(request.getCheckTime());
        outsourceProject.setCheckMinioFileName(request.getCheckMinioFileName());
        outsourceProject.setCheckRemark(request.getCheckRemark());
        int updateFlag = projectMapper.updateById(outsourceProject);
        Assert.isFalse(updateFlag <= 0, () -> {
            throw new BusinessException(BusinessExceptionEnum.OUTSOURCE_PROJECT_CHECK_SAVE_FAILED);
        });
        OutsourceProjectSaveResponse saveResponse = new OutsourceProjectSaveResponse();
        saveResponse.setId(outsourceProject.getId());
        saveResponse.setProjectNo(outsourceProject.getProjectNo());
        return ReturnUtil.success(saveResponse);
    }

    @Override
    @Transactional
    public ReturnDTO submitProjectCheck(BaseApprovalSubmitRequest request) {
        //已取消后的提交需先删除原有实例
        if (StringUtils.isNotEmpty(request.getProcessId())){
            runtimeService.updateBusinessStatus(request.getProcessId(), ApprovalStatusEnum.DELETED);
            runtimeService.deleteProcessInstance(request.getProcessId(), "删除");
        }
        //1.根据表单id获取流程定义id
        //2.根据流程定义id启动流程实例
        String formId = request.getFormId();
        ReturnDTO returnDTO = baseApprovalService.processSubmit(formId, request.getId());
        if (ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()) {
            return returnDTO;
        }
        ProcessInstance processInstance = (ProcessInstance) returnDTO.getData();

        BusinessOutsourceProject outsourceProject = new BusinessOutsourceProject();
        outsourceProject.setId(request.getId());
        outsourceProject.setCheckApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态
        outsourceProject.setCheckProcessId(processInstance.getId());
        int row = projectMapper.updateById(outsourceProject);
        if (row <= 0) {
            throw new BusinessException(BusinessExceptionEnum.OUTSOURCE_PROJECT_CHECK_SUBMIT_FAILED);
        }
        return ReturnUtil.success();
    }

    @Override
    public ReturnDTO projectCheckDelete(Long id) {
        int updateFlag = projectMapper.updateForProjectCheck(id);
        if(updateFlag > 0){
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO projectCheckApprovalDelete(ApprovalDeleteRequest request) {
        ReturnDTO returnDTO = approvalOperateService.delete(request);
        if (ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()) {
            //清空验收所填字段及验收审批状态
            int updateFlag = projectMapper.updateForProjectCheck(request.getId());
            if(updateFlag > 0){
                return ReturnUtil.success();
            }
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO projectCheckFailUpdate(OutsourceProjectCheckSaveOrUpdateRequest request) {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        BusinessOutsourceProject outsourceProject = ConvertUtils.sourceToTarget(request, BusinessOutsourceProject.class);
        if (projectMapper.updateById(outsourceProject) > 0) {
            baseApprovalService.failUpdate(request.getCheckProcessId());
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public Page<BusinessOutsourceProject> projectCheckListPage(OutsourceProjectCheckListRequest request, Page<BusinessOutsourceProject> page) {
        QueryWrapper<BusinessOutsourceProject> wrapper = getWrapper(request);
        Page<BusinessOutsourceProject> projectPage = projectMapper.selectPage(page, wrapper);
        return projectPage;
    }

    private QueryWrapper<BusinessOutsourceProject> getWrapper(OutsourceProjectCheckListRequest request) {
        //flowable中已通过状态的业务id列表
        List<String> passedList = baseApprovalService.getPassedList(request.getFormId());
        QueryWrapper<BusinessOutsourceProject> wrapper = new QueryWrapper<>();
        //无审批通过则返回空数据
        if (CollectionUtils.isEmpty(passedList)) {
            wrapper.eq("id", 12344321);
            return wrapper;
        }
        wrapper.eq(Objects.nonNull(request.getOutsourcerId()), "outsourcer_id", request.getOutsourcerId());
        wrapper.like(StringUtils.isNotBlank(request.getProjectNo()), "project_no", request.getProjectNo());
        wrapper.like(StringUtils.isNotBlank(request.getProjectName()), "project_name", request.getProjectName());
        wrapper.in("id", passedList);
        wrapper.orderByDesc("create_time");
        return wrapper;
    }

    private boolean saveBatchRelation(BusinessOutsourceProject outsourceProject) {
        List<BusinessOutsourceProjectSampleRelation> relationList = new ArrayList<>();
        outsourceProject.getOrderSampleList().forEach(dto -> {
            BusinessOutsourceProjectSampleRelation relation = new BusinessOutsourceProjectSampleRelation();
            relation.setProjectId(outsourceProject.getId());
            relation.setSampleId(dto.getSampleId());
            relation.setOrderId(dto.getOrderId());
            relationList.add(relation);
        });
        if(projectSampleRelationService.saveBatch(relationList)){
            return true;
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    private List<OutsourceProjectApprovalListResponse> handleApprovalStatus(Page<OutsourceProjectApprovalListResponse> page, OutsourceProjectApprovalListRequest request) {
        List<OutsourceProjectApprovalListResponse> approvalList = new ArrayList<>();
        List<String> businessKeys = new ArrayList<>();
        List<BusinessOutsourceProject> list;
        switch (request.getApprovalStatus()) {
            //草稿
            case ApprovalStatusEnum.DRAFT:
                list = projectMapper.selectDraftListForApproval(page, request);
                approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.DRAFT, request.getTypeFlag());
                break;
            //待审批，该状态维护在flowable中
            case ApprovalStatusEnum.TO_BE_APPROVED:
                List<ToBeApprovedDTO> toBeApprovedList = baseApprovalService.getToBeApprovedList(request.getFormId());
                if (!CollectionUtils.isEmpty(toBeApprovedList)) {
                    businessKeys = toBeApprovedList.stream().map(ToBeApprovedDTO::getBusinessKey).distinct().collect(Collectors.toList());
                }
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = projectMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.TO_BE_APPROVED, request.getTypeFlag());
                    //DTO根据业务主键补全taskId
                    approvalList.forEach(approval -> {
                        toBeApprovedList.forEach(toBeApprovedDTO -> {
                            if (String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())) {
                                approval.setTaskId(toBeApprovedDTO.getTaskId());
                                //补全可选决策项
                                approval.setDecisionItem(toBeApprovedDTO.getDecisionItem());
                            }
                        });
                    });
                }
                break;
            //审批中，该状态维护在flowable中
            case ApprovalStatusEnum.IN_APPROVED:
                businessKeys = baseApprovalService.getInApprovedList(request.getFormId());
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = projectMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.IN_APPROVED, request.getTypeFlag());
                }
                break;
            //已通过，该状态维护在flowable
            case ApprovalStatusEnum.PASSED:
                businessKeys = baseApprovalService.getPassedList(request.getFormId());
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = projectMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.PASSED, request.getTypeFlag());
                }
                break;
            //未通过（包括拒绝、驳回，拒绝为直接删除实例，驳回为驳回到起点），该状态维护在flowable
            case ApprovalStatusEnum.FAILED:
                businessKeys = baseApprovalService.getFailedList(request.getFormId()); //未通过-拒绝
                List<String> rejectBusinessKey = baseApprovalService.getFailedRejectList(request.getFormId()); //未通过-驳回
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = projectMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.FAILED, request.getTypeFlag());
                }
                List<OutsourceProjectApprovalListResponse> rejectApprovalList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(rejectBusinessKey)) {
                    List<BusinessOutsourceProject> rejectList = projectMapper.selectBatchForApproval(page, request, rejectBusinessKey);
                    rejectApprovalList = handleApprovalListResponse(approvalList, rejectList, ApprovalStatusEnum.FAILED_REJECT, request.getTypeFlag());
                }
                //合并未通过-拒绝和未通过-驳回
                approvalList.addAll(rejectApprovalList);
                //分页处理
                if(!CollectionUtils.isEmpty(approvalList)) {
                    Page pages = PageUtil.getPages((int) page.getCurrent(), (int) page.getSize(), approvalList);
                    page.setTotal(approvalList.size());
                    approvalList = pages.getRecords();
                }
                break;
            //已取消，该状态维护在flowable
            case ApprovalStatusEnum.CANCELED:
                businessKeys = baseApprovalService.getCanceledList(request.getFormId());
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = projectMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.CANCELED, request.getTypeFlag());
                }
                break;
            //全部
            //区分管理员和普通用户
            //普通用户获取自己发起的(审批中、已通过、未通过、已取消)，管理员获取全部(审批中、已通过、未通过、已取消)
            case ApprovalStatusEnum.ALL:
                List<AllApproveDTO> allApproveList = baseApprovalService.getAllList(request.getFormId());
                if (!CollectionUtils.isEmpty(allApproveList)) {
                    businessKeys = allApproveList.stream().map(AllApproveDTO::getBusinessKey).collect(Collectors.toList());
                }
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = projectMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleAllApprovalListResponse(approvalList, list, allApproveList, request.getTypeFlag());
                }
                break;
        }
        return approvalList;
    }

    private List<OutsourceProjectApprovalListResponse> handleApprovalListResponse(List<OutsourceProjectApprovalListResponse> approvalList, List<BusinessOutsourceProject> list, String status, Integer typeFlag) {
        approvalList = ConvertUtils.sourceToTarget(list, OutsourceProjectApprovalListResponse.class);
        approvalList.stream().forEach(result -> {
            //审批状态两种获取方式：1、在此处设置，2、在flowable中设置业务状态，暂采取1
            if(1 == typeFlag) {
                result.setApplyApprovalStatus(status);
                result.setApplyApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, status));
            } else if(2 == typeFlag) {
                result.setCheckApprovalStatus(status);
                result.setCheckApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, status));
            }
        });
        return approvalList;
    }

    private List<OutsourceProjectApprovalListResponse> handleAllApprovalListResponse(List<OutsourceProjectApprovalListResponse> approvalList, List<BusinessOutsourceProject> list, List<AllApproveDTO> allApproveList, Integer typeFlag) {
        Map<String, String> taskMap = new HashMap<>();
        approvalList = ConvertUtils.sourceToTarget(list, OutsourceProjectApprovalListResponse.class);
        allApproveList.forEach(allApprove -> {
            taskMap.put(allApprove.getBusinessKey(), allApprove.getStatus());
        });
        //状态补全
        approvalList.forEach(approval -> {
            if(1 == typeFlag) {
                approval.setApplyApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, taskMap.get(String.valueOf(approval.getId()))));
                approval.setApplyApprovalStatus(taskMap.get(String.valueOf(approval.getId())));
            } else if(2 == typeFlag) {
                approval.setCheckApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, taskMap.get(String.valueOf(approval.getId()))));
                approval.setCheckApprovalStatus(taskMap.get(String.valueOf(approval.getId())));
            }
        });
        //排序
        return approvalList.stream().sorted(Comparator.comparing(OutsourceProjectApprovalListResponse::getCreateTime).reversed()).collect(Collectors.toList());
    }
}
