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

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.constants.MeterDictCode;
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.order.OrderListResponse;
import com.casic.missiles.dto.finance.AgreementApprovalListRequest;
import com.casic.missiles.dto.finance.AgreementApprovalListResponse;
import com.casic.missiles.dto.finance.AgreementInfoSaveResponse;
import com.casic.missiles.dto.finance.AgreementListRequest;
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.business.AgreementStatusEnum;
import com.casic.missiles.enums.business.OrderStatusEnum;
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.BusinessOrderListResponseMapper;
import com.casic.missiles.mapper.business.BusinessOrderMapper;
import com.casic.missiles.mapper.business.BusinessOrderSampleRelationMapper;
import com.casic.missiles.mapper.finance.FinanceAgreementInfoMapper;
import com.casic.missiles.model.business.BusinessOrderSampleRelation;
import com.casic.missiles.model.finance.FinanceAgreementInfo;
import com.casic.missiles.model.finance.FinanceAgreementOrderRelation;
import com.casic.missiles.model.finance.FinanceAgreementPaymentInfo;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.service.IBaseApprovalService;
import com.casic.missiles.service.finance.IFinanceAgreementInfoService;
import com.casic.missiles.service.finance.IFinanceAgreementOrderRelationService;
import com.casic.missiles.service.finance.IFinanceAgreementPaymentInfoService;
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 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-31
 */
@Service
public class FinanceAgreementInfoServiceImpl extends ServiceImpl<FinanceAgreementInfoMapper, FinanceAgreementInfo> implements IFinanceAgreementInfoService {
    @Autowired
    private FinanceAgreementInfoMapper agreementInfoMapper;
    @Autowired
    private BusinessOrderMapper orderMapper;
    @Autowired
    private IFinanceAgreementOrderRelationService orderRelationService;
    @Autowired
    private IFinanceAgreementPaymentInfoService paymentInfoService;
    @Resource
    private AbstractDictService dictService;
    @Autowired
    private IBaseApprovalService baseApprovalService;
    @Resource
    private RuntimeService runtimeService;
    @Autowired
    private BusinessOrderListResponseMapper orderListResponseMapper;
    @Autowired
    private BusinessOrderSampleRelationMapper sampleRelationMapper;
    @Autowired
    private ApprovalOperateService approvalOperateService;

    @Override
    @Transactional
    public Page<FinanceAgreementInfo> listPage(Page<FinanceAgreementInfo> page, AgreementListRequest request) throws Exception {
        QueryWrapper<FinanceAgreementInfo> wrapper = getWrapper(request);
        Page<FinanceAgreementInfo> infoPage = agreementInfoMapper.selectPage(page, wrapper);
        if(Objects.isNull(infoPage) || CollectionUtils.isEmpty(infoPage.getRecords())){
            return new Page<>();
        }
        //查询所有完成的委托书，用于更新未完成合同为已完成
        List<Long> orderIds = orderMapper.selectIdsByStatus(OrderStatusEnum.COMPLETE);
        for (FinanceAgreementInfo record : infoPage.getRecords()) {
            updateAgreementStatus(orderIds, record);
            DictCodeUtils.convertDictCodeToName(record);
        }
        return infoPage;
    }

    @Override
    public List<FinanceAgreementInfo> list(AgreementListRequest request) throws Exception {
        QueryWrapper<FinanceAgreementInfo> wrapper = getWrapper(request);
        List<FinanceAgreementInfo> infoList = agreementInfoMapper.selectList(wrapper);
        if(CollectionUtils.isEmpty(infoList)){
            return new ArrayList<>();
        }
        //查询所有完成的委托书，用于更新未完成合同为已完成
        List<Long> orderIds = orderMapper.selectIdsByStatus(OrderStatusEnum.COMPLETE);
        for (FinanceAgreementInfo record : infoList) {
            updateAgreementStatus(orderIds, record);
            DictCodeUtils.convertDictCodeToName(record);
        }
        return infoList;
    }

    @Override
    public List<AgreementApprovalListResponse> agreementApprovalListPage(AgreementApprovalListRequest request, Page<AgreementApprovalListResponse> 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<AgreementApprovalListResponse> responseList = handleApprovalStatus(page, request);
        if(CollectionUtils.isEmpty(responseList)){
            return new ArrayList<>();
        }
        //查询所有完成的委托书，用于更新未完成合同为已完成
        List<Long> orderIds = orderMapper.selectIdsByStatus(OrderStatusEnum.COMPLETE);
        for (AgreementApprovalListResponse response : responseList) {
            //根据委托书完成情况更新审批通过的合同为已完成
            if(ApprovalStatusEnum.PASSED.equals(request.getApprovalStatus())){
                FinanceAgreementInfo record = new FinanceAgreementInfo();
                record.setId(response.getId());
                record.setStatus(response.getStatus());
                updateAgreementStatus(orderIds, record);
            }
            DictCodeUtils.convertDictCodeToName(response);
        }
        return responseList;
    }

    @Override
    @Transactional
    public ReturnDTO<AgreementInfoSaveResponse> saveAgreementInfo(FinanceAgreementInfo agreementInfo) {
        //生成编号
        Long maxNo = agreementInfoMapper.selectMaxAgreementNo();
        String agreementNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.AGREEMENT_PREFIX, maxNo);
        agreementInfo.setAgreementNo(agreementNo);
        agreementInfo.setApprovalStatus(ApprovalStatusEnum.DRAFT); //草稿箱状态
        Assert.isFalse(Objects.isNull(ShiroKit.getUser()), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        if(Objects.isNull(agreementInfo.getCreateUser())){
            agreementInfo.setCreateUser(ShiroKit.getUser().getId()); //登录者用户id
            agreementInfo.setCreateUserName(ShiroKit.getUser().getName());
        }
        int insertFlag = agreementInfoMapper.insert(agreementInfo);
        Assert.isFalse(insertFlag <= 0, () -> {
            throw new BusinessException(BusinessExceptionEnum.AGREEMENT_SAVE_FAILED);
        });
        //保存关联委托单信息、关联收款信息
        saveBatchRelation(agreementInfo);
        AgreementInfoSaveResponse saveResponse = new AgreementInfoSaveResponse();
        saveResponse.setId(agreementInfo.getId());
        saveResponse.setAgreementNo(agreementNo);
        return ReturnUtil.success(saveResponse);
    }

    @Override
    @Transactional
    public ReturnDTO agreementDraftUpdate(FinanceAgreementInfo agreementInfo) {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        if (agreementInfoMapper.updateById(agreementInfo) > 0) {
            //关联委托单信息、关联收款信息编辑
            QueryWrapper<FinanceAgreementOrderRelation> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("agreement_id", agreementInfo.getId());
            orderRelationService.remove(orderWrapper);
            QueryWrapper<FinanceAgreementPaymentInfo> paymentWrapper = new QueryWrapper<>();
            paymentWrapper.eq("agreement_id", agreementInfo.getId());
            paymentInfoService.remove(paymentWrapper);
            saveBatchRelation(agreementInfo);
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO submitAgreement(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();

        FinanceAgreementInfo agreementInfo = new FinanceAgreementInfo();
        agreementInfo.setId(request.getId());
        agreementInfo.setApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态
        agreementInfo.setProcessId(processInstance.getId());
        int row = agreementInfoMapper.updateById(agreementInfo);
        if (row <= 0) {
            throw new BusinessException(BusinessExceptionEnum.AGREEMENT_APPLY_SUBMIT_FAILED);
        }
        return ReturnUtil.success();
    }

    @Override
    @Transactional
    public ReturnDTO agreementDelete(Long id) {
        if (agreementInfoMapper.deleteById(id) > 0) {
            //关联委托单信息、关联收款信息删除
            QueryWrapper<FinanceAgreementOrderRelation> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("agreement_id", id);
            orderRelationService.remove(orderWrapper);
            QueryWrapper<FinanceAgreementPaymentInfo> paymentWrapper = new QueryWrapper<>();
            paymentWrapper.eq("agreement_id", id);
            paymentInfoService.remove(paymentWrapper);
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO<FinanceAgreementInfo> agreementDetail(Long id) throws Exception {
        FinanceAgreementInfo agreementInfo = agreementInfoMapper.selectById(id);
        DictCodeUtils.convertDictCodeToName(agreementInfo);
        //关联委托单信息查询
        QueryWrapper<FinanceAgreementOrderRelation> orderRelationWrapper = new QueryWrapper<>();
        orderRelationWrapper.eq("agreement_id", id);
        List<FinanceAgreementOrderRelation> orderRelationList = orderRelationService.list(orderRelationWrapper);
        List<Long> orderIds = orderRelationList.stream().map(FinanceAgreementOrderRelation::getOrderId).collect(Collectors.toList());
        QueryWrapper<OrderListResponse> orderListWrapper = new QueryWrapper<>();
        orderListWrapper.in("id", orderIds);
        List<OrderListResponse> orderList = orderListResponseMapper.selectList(orderListWrapper);
        //委托书样品数量
        List<BusinessOrderSampleRelation> orderSampleList = sampleRelationMapper.selectList(null);
        Map<Long, List<BusinessOrderSampleRelation>> orderSampleMap = orderSampleList.stream().collect(
                Collectors.groupingBy(BusinessOrderSampleRelation::getOrderId)
        );
        orderList.forEach(orderSample -> {
            orderSample.setSampleCount(orderSampleMap.containsKey(orderSample.getId()) ? orderSampleMap.get(orderSample.getId()).size() : 0);
            orderSample.setStatusName(dictService.getDictNameByCode(MeterDictCode.ORDER_STATUS, String.valueOf(orderSample.getStatus())));
        });
        //关联收款信息查询
        QueryWrapper<FinanceAgreementPaymentInfo> paymentWrapper = new QueryWrapper<>();
        paymentWrapper.eq("agreement_id", id);
        List<FinanceAgreementPaymentInfo> paymentList = paymentInfoService.list(paymentWrapper);

        agreementInfo.setOrderList(orderList);
        agreementInfo.setPaymentList(paymentList);
        return ReturnUtil.success(agreementInfo);
    }

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

    @Override
    @Transactional
    public ReturnDTO agreementFailUpdate(FinanceAgreementInfo agreementInfo) {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        if (agreementInfoMapper.updateById(agreementInfo) > 0) {
            //关联委托单信息、关联收款信息编辑
            QueryWrapper<FinanceAgreementOrderRelation> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("agreement_id", agreementInfo.getId());
            orderRelationService.remove(orderWrapper);
            QueryWrapper<FinanceAgreementPaymentInfo> paymentWrapper = new QueryWrapper<>();
            paymentWrapper.eq("agreement_id", agreementInfo.getId());
            paymentInfoService.remove(paymentWrapper);
            saveBatchRelation(agreementInfo);

            baseApprovalService.failUpdate(agreementInfo.getProcessId());
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    private void updateAgreementStatus(List<Long> orderIds, FinanceAgreementInfo record) {
        //合同完成状态，根据合同对应的所有委托书状态更新未完成为已完成，表中默认为未完成
        if(AgreementStatusEnum.NOT_COMPLETE.equals(record.getStatus())){
            QueryWrapper<FinanceAgreementOrderRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("agreement_id", record.getId());
            List<FinanceAgreementOrderRelation> list = orderRelationService.list(queryWrapper);
            for (FinanceAgreementOrderRelation relation : list) {
                //合同的委托书不在完成委托书中
                if(!orderIds.contains(relation)){
                    break;
                }
            }
            //合同的委托书都在完成委托书中
            record.setStatus(AgreementStatusEnum.ALREADY_COMPLETE);
            FinanceAgreementInfo updateInfo = new FinanceAgreementInfo();
            updateInfo.setId(record.getId());
            updateInfo.setStatus(AgreementStatusEnum.ALREADY_COMPLETE);
            agreementInfoMapper.updateById(updateInfo);
        }
    }

    private QueryWrapper<FinanceAgreementInfo> getWrapper(AgreementListRequest request) {
        //flowable中已通过状态的业务id列表
        List<String> passedList = baseApprovalService.getPassedList(request.getFormId());

        QueryWrapper<FinanceAgreementInfo> wrapper = new QueryWrapper<>();
        //无审批通过则返回空数据
        if (CollectionUtils.isEmpty(passedList)) {
            wrapper.eq("id", 12344321);
            return wrapper;
        }
        wrapper.like(StringUtils.isNotBlank(request.getAgreementNo()), "agreement_no", request.getAgreementNo());
        wrapper.like(StringUtils.isNotBlank(request.getAgreementName()), "agreement_name", request.getAgreementName());
        wrapper.eq(StringUtils.isNotBlank(request.getAgreementKind()), "agreement_kind", request.getAgreementKind());
        wrapper.eq(StringUtils.isNotBlank(request.getAgreementType()), "agreement_type", request.getAgreementType());
        wrapper.eq(Objects.nonNull(request.getCustomerId()), "customer_id", request.getCustomerId());
        wrapper.like(StringUtils.isNotBlank(request.getFirstParty()), "first_party", request.getFirstParty());
        wrapper.apply(StringUtils.isNotBlank(request.getEstimateSignStartDate()),//apply方法传入参数名不能为空
                "{0} <= DATE_FORMAT(estimate_sign_date,'%Y-%m-%d')", request.getEstimateSignStartDate().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getEstimateSignEndDate()),
                "{0} >= DATE_FORMAT(estimate_sign_date,'%Y-%m-%d')", request.getEstimateSignEndDate().split(" ")[0]);
        wrapper.eq(StringUtils.isNotBlank(request.getStatus()), "status", request.getStatus());
        wrapper.in("id", passedList);
        wrapper.eq("is_del", 0);
        wrapper.orderByDesc("create_time");
        return wrapper;
    }

    private boolean saveBatchRelation(FinanceAgreementInfo agreementInfo) {
        List<FinanceAgreementOrderRelation> orderRelationList = new ArrayList<>();
        agreementInfo.getOrderIdList().forEach(orderId -> {
            FinanceAgreementOrderRelation orderRelation = new FinanceAgreementOrderRelation();
            orderRelation.setAgreementId(agreementInfo.getId());
            orderRelation.setOrderId(orderId);
            orderRelationList.add(orderRelation);
        });
        boolean saveOrderBatch = orderRelationService.saveBatch(orderRelationList);
        agreementInfo.getPaymentList().forEach(payment -> {
            payment.setAgreementId(agreementInfo.getId());
        });
        boolean savePaymentBatch = paymentInfoService.saveBatch(agreementInfo.getPaymentList());
        if(saveOrderBatch && savePaymentBatch){
            return true;
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    private List<AgreementApprovalListResponse> handleApprovalStatus(Page<AgreementApprovalListResponse> page, AgreementApprovalListRequest request) {
        List<AgreementApprovalListResponse> approvalList = new ArrayList<>();
        List<String> businessKeys = new ArrayList<>();
        List<FinanceAgreementInfo> list;
        switch (request.getApprovalStatus()) {
            //草稿
            case ApprovalStatusEnum.DRAFT:
                list = agreementInfoMapper.selectDraftListForApproval(page, request);
                approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.DRAFT);
                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 = agreementInfoMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.TO_BE_APPROVED);
                    //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 = agreementInfoMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.IN_APPROVED);
                }
                break;
            //已通过，该状态维护在flowable
            case ApprovalStatusEnum.PASSED:
                businessKeys = baseApprovalService.getPassedList(request.getFormId());
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = agreementInfoMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.PASSED);
                }
                break;
            //未通过（包括拒绝、驳回，拒绝为直接删除实例，驳回为驳回到起点），该状态维护在flowable
            case ApprovalStatusEnum.FAILED:
                businessKeys = baseApprovalService.getFailedList(request.getFormId()); //未通过-拒绝
                List<String> rejectBusinessKey = baseApprovalService.getFailedRejectList(request.getFormId()); //未通过-驳回
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = agreementInfoMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.FAILED);
                }
                List<AgreementApprovalListResponse> rejectApprovalList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(rejectBusinessKey)) {
                    List<FinanceAgreementInfo> rejectList = agreementInfoMapper.selectBatchForApproval(page, request, rejectBusinessKey);
                    rejectApprovalList = handleApprovalListResponse(approvalList, rejectList, ApprovalStatusEnum.FAILED_REJECT);
                }
                //合并未通过-拒绝和未通过-驳回
                approvalList.addAll(rejectApprovalList);
                break;
            //已取消，该状态维护在flowable
            case ApprovalStatusEnum.CANCELED:
                businessKeys = baseApprovalService.getCanceledList(request.getFormId());
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = agreementInfoMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.CANCELED);
                }
                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 = agreementInfoMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleAllApprovalListResponse(approvalList, list, AllApproveList);
                }
                break;
        }
        return approvalList;
    }

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

    private List<AgreementApprovalListResponse> handleAllApprovalListResponse(List<AgreementApprovalListResponse> approvalList, List<FinanceAgreementInfo> list, List<AllApproveDTO> allApproveList) {
        Map<String, String> taskMap = new HashMap<>();
        approvalList = ConvertUtils.sourceToTarget(list, AgreementApprovalListResponse.class);
        allApproveList.forEach(allApprove -> {
            taskMap.put(allApprove.getBusinessKey(), allApprove.getStatus());
        });
        //状态补全
        approvalList.forEach(approval -> {
            approval.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, taskMap.get(String.valueOf(approval.getId()))));
            approval.setApprovalStatus(taskMap.get(String.valueOf(approval.getId())));
        });
        //排序
        return approvalList.stream().sorted(Comparator.comparing(AgreementApprovalListResponse::getCreateTime).reversed()).collect(Collectors.toList());
    }
}
