package com.ruoyi.framework.web.service;


import com.alibaba.fastjson2.JSONObject;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.Pictures;
import com.itextpdf.text.DocumentException;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.FjType;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.jPush.JPushToolUtil;
import com.ruoyi.common.utils.poi.ExcelFillUtils;
import com.ruoyi.common.utils.poi.WordUtil;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.conference.SysUserConference;
import com.ruoyi.system.domain.enterprise.SysUserEnterprise;
import com.ruoyi.system.domain.guarantee.GuaranteeInfo;
import com.ruoyi.system.domain.guarantee.GuaranteeInfoFj;
import com.ruoyi.system.domain.loan.LoanApplication;
import com.ruoyi.system.domain.loan.LoanApplicationFj;
import com.ruoyi.system.domain.loan.LoanSchedule;
import com.ruoyi.system.domain.loan.ShareholderFj;
import com.ruoyi.system.domain.remind.WaitRemind;
import com.ruoyi.system.domain.review.ReviewComments;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.loan.ILoanApplicationService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.*;
import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;



import static com.ruoyi.common.constant.CommonConstants.*;

import javax.annotation.Resource;

/**
 * 贷款申请主Service业务层处理
 *
 * @author boman
 * @date 2024-04-24
 */
@Service
public class LoanApplicationServiceImpl implements ILoanApplicationService {
    @Autowired
    private LoanApplicationMapper loanApplicationMapper;
    @Autowired
    private LoanApplicationFjMapper loanApplicationFjMapper;
    @Autowired
    private ShareholderFjMapper shareholderFjMapper;
    @Autowired
    private LoanScheduleMapper loanScheduleMapper;
    @Autowired
    private SysUserEnterpriseMapper sysUserEnterpriseMapper;
    @Autowired
    private SysUserConferenceMapper sysUserConferenceMapper;
    @Autowired
    private ReviewCommentsMapper reviewCommentsMapper;
    @Resource
    private WaitRemindMapper waitRemindMapper;
    @Resource
    private SysDictDataMapper dictDataMapper;
    @Resource
    private GuaranteeInfoMapper guaranteeInfoMapper;
    @Resource
    private GuaranteeInfoFjMapper guaranteeInfoFjMapper;

    @Autowired
    private RedisCache redisCache;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询贷款申请主
     *
     * @param loanApplicationId 贷款申请主主键
     * @return 贷款申请主
     */
    @Override
    public AjaxResult selectLoanApplicationByLoanApplicationId(Long loanApplicationId) {

        LoanApplication loanApplication = loanApplicationMapper.selectLoanApplicationByLoanApplicationId(loanApplicationId);
        if (loanApplication != null) {
            String loanApplicationNumber = loanApplication.getLoanApplicationNumber();
            //判断自定义锁，必须全部释放，才能修改
            String keyA = "lock:A:" + loanApplicationNumber;
            String keyB = "lock:B:" + loanApplicationNumber;
            String keyC = "lock:C:" + loanApplicationNumber;
            Object cacheObjectA = redisCache.getCacheObject(keyA);
            Object cacheObjectB = redisCache.getCacheObject(keyB);
            Object cacheObjectC = redisCache.getCacheObject(keyC);
            if (ObjectUtils.isNotEmpty(cacheObjectA) || ObjectUtils.isNotEmpty(cacheObjectB) || ObjectUtils.isNotEmpty(cacheObjectC)) {
                return AjaxResult.error("稍后重试，文件正在生成");
            }
        }

        //查询企业信息
        if (ObjectUtils.isNotEmpty(loanApplication.getEnterpriseId())) {
            SysUserEnterprise sysUserEnterprise = sysUserEnterpriseMapper.selectSysUserEnterpriseByEnterpriseId(loanApplication.getEnterpriseId());
            loanApplication.setSysUserEnterprise(sysUserEnterprise);
        }

        //查询相关附件
        List<LoanApplicationFj> loanApplicationFjs = loanApplicationFjMapper.selectLoanApplicationFjByLoanApplicationId(loanApplicationId);
        if (loanApplicationFjs != null && loanApplicationFjs.size() > 0) {
            //所有附件不分类
            loanApplication.setLoanApplicationFjList(loanApplicationFjs);
            //进行大类区分
            Map<String, List<LoanApplicationFj>> bigTypeFj = loanApplicationFjs.stream().collect(Collectors.groupingBy(LoanApplicationFj::getBigType));
            List<LoanApplicationFj> loanApplicationFjsA = bigTypeFj.get(A);
            if (loanApplicationFjsA != null && loanApplicationFjsA.size() > 0) {
                loanApplication.setBasicFj(loanApplicationFjsA.stream().collect(Collectors.groupingBy(LoanApplicationFj::getType)));
            }
            List<LoanApplicationFj> loanApplicationFjsB = bigTypeFj.get(B);
            if (loanApplicationFjsB != null && loanApplicationFjsB.size() > 0) {
                loanApplication.setDeclareFj(loanApplicationFjsB.stream().collect(Collectors.groupingBy(LoanApplicationFj::getType)));
            }
            List<LoanApplicationFj> loanApplicationFjsC = bigTypeFj.get(C);
            if (loanApplicationFjsC != null && loanApplicationFjsC.size() > 0) {
                loanApplication.setFileFj(loanApplicationFjsC.stream().collect(Collectors.groupingBy(LoanApplicationFj::getType)));
            }
            List<LoanApplicationFj> loanApplicationFjsD = bigTypeFj.get(D);
            if (loanApplicationFjsD != null && loanApplicationFjsD.size() > 0) {
                loanApplication.setOtherFj(loanApplicationFjsD.stream().collect(Collectors.groupingBy(LoanApplicationFj::getType)));
            }
            List<LoanApplicationFj> loanApplicationFjsF = bigTypeFj.get(F);
            if (loanApplicationFjsF != null && loanApplicationFjsF.size() > 0) {
                loanApplication.setBackFj(loanApplicationFjsF.stream().collect(Collectors.groupingBy(LoanApplicationFj::getType)));
            }
        }
        List<ShareholderFj> shareholderFjs = shareholderFjMapper.selectShareholderFjLoanApplicationId(loanApplicationId);
        if (shareholderFjs != null && shareholderFjs.size() > 0) {
            loanApplication.setShareholderFjList(shareholderFjs);
        }
        //会议状态
        loanApplication.setVotingResult(FOR);
        if (redisCache.getCacheObject(loanApplication.getLoanApplicationNumber() + "tp") != null) {
            loanApplication.setVotingResult(redisCache.getCacheObject(loanApplication.getLoanApplicationNumber() + "tp"));
        }
        //查询反担保人信息
        List<GuaranteeInfo> guaranteeInfos = guaranteeInfoMapper.selectGuaranteeInfoListByLoanApplicationId(loanApplicationId);
        //查询对应的附件
        if (guaranteeInfos != null && guaranteeInfos.size() > 0) {
            for (GuaranteeInfo guaranteeInfo : guaranteeInfos) {
                GuaranteeInfoFj guaranteeInfoFj = new GuaranteeInfoFj();
                guaranteeInfoFj.setLoanApplicationId(loanApplicationId);
                guaranteeInfoFj.setGuaranteeInfoId(guaranteeInfo.getGuaranteeInfoId());
                List<GuaranteeInfoFj> guaranteeInfoFjs = guaranteeInfoFjMapper.selectGuaranteeInfoFjList(guaranteeInfoFj);
                guaranteeInfo.setGuaranteeInfoFjList(guaranteeInfoFjs);
            }
        }
        loanApplication.setGuaranteeInfoList(guaranteeInfos);
        return AjaxResult.success(loanApplication);
    }

    /**
     * 查询贷款申请主列表
     *
     * @param loanApplication 贷款申请主
     * @return 贷款申请主
     */
    @Override
    public List<LoanApplication> selectLoanApplicationList(LoanApplication loanApplication) {
/*        //判断是否是admin或者管理员manager
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        String roleKey = "admin,manager,auditing_risk";*/
        List<LoanApplication> loanApplications = new ArrayList<>();
/*        for (SysRole role : roles) {
            if (roleKey.contains(role.getRoleKey())) {
                loanApplications = loanApplicationMapper.selectLoanApplicationList(loanApplication);
                return loanApplications;
            }
        }
        loanApplication.setUserId(SecurityUtils.getUserId());*/
        loanApplications = loanApplicationMapper.selectLoanApplicationList(loanApplication);
        return loanApplications;
    }

    /**
     * 查询需要保后的数据
     *
     * @param loanApplication
     * @return
     */
    @Override
    public List<LoanApplication> selectLoanAfterList(LoanApplication loanApplication) {
        loanApplication.setActuallyTime(DateUtils.getNowDate());
        List<LoanApplication> loanApplications = loanApplicationMapper.selectLoanAfterList(loanApplication);
        return loanApplications;
    }

    @Override
    public List<LoanApplication> conferenceList(LoanApplication loanApplication) {
        //查询人员id
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //判断当前角色是否是管理员和admin,董事长
        List<SysRole> roles = user.getRoles();
        Boolean bl = false;
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin") || role.getRoleKey().equals("manager") || role.getRoleKey().equals("sensible")) {
                bl = true;
                break;
            }
        }
        if (!bl) {
            loanApplication.setUserId(user.getUserId());
        }
        List<LoanApplication> loanApplications = new ArrayList<>();
        if ("druid".equals(RuoYiConfig.getIsYml())) {
            loanApplications = loanApplicationMapper.conferenceList(loanApplication);
        } else {
            loanApplications = loanApplicationMapper.conferenceProdList(loanApplication);
        }


        for (LoanApplication application : loanApplications) {
            application.setVotingResult(FOR);
            if (redisCache.getCacheObject(application.getLoanApplicationNumber() + "tp") != null) {
                application.setVotingResult(redisCache.getCacheObject(application.getLoanApplicationNumber() + "tp"));
            }
        }
        return loanApplications;
    }

    /**
     * 文件管理
     *
     * @param loanApplication
     * @return
     */
    @Override
    public List<LoanApplication> listOss(LoanApplication loanApplication) {
        loanApplication.setLoanSchedule(TEN);
        loanApplication.setLoanApplicationType(FOR);
        List<LoanApplication> loanApplications = loanApplicationMapper.selectLoanApplicationList(loanApplication);
        if (loanApplications != null && loanApplications.size() > 0) {
            for (LoanApplication application : loanApplications) {
                //去查询压缩包
                LoanApplicationFj loanApplicationFj = new LoanApplicationFj();
                loanApplicationFj.setLoanApplicationId(application.getLoanApplicationId());
                loanApplicationFj.setBigType("e");
                List<LoanApplicationFj> loanApplicationFjList = loanApplicationFjMapper.selectLoanApplicationFjList(loanApplicationFj);
                application.setLoanApplicationFjList(loanApplicationFjList);
            }
        }
        return loanApplications;
    }

    /**
     * 新增贷款申请主
     *
     * @param loanApplication 贷款申请主
     * @return 结果
     */
    @Override
    @Transactional
    public int insertLoanApplication(LoanApplication loanApplication) {
        if (loanApplicationMapper.selectLoanApplicationList(loanApplication).size() > 0) {
            return 0;
        }
        //先去查询贷款编码是否已经存在
        //设置为audit_schedule=1 audit_type=1
        loanApplication.setAuditSchedule(ONE);
        loanApplication.setAuditType(ONE);
        //设置申请人用户ID
        loanApplication.setUserId(SecurityUtils.getUserId());
        loanApplication.setApplicationTime(DateUtils.getNowDate());
        //贷款申请进度进入业务审核/分配
        loanApplication.setLoanSchedule(TWO);
        loanApplication.setLoanApplicationType(TWO);
        loanApplication.setUserId(SecurityUtils.getUserId());
        int i = loanApplicationMapper.insertLoanApplication(loanApplication);
        List<LoanApplicationFj> loanApplicationFjList = loanApplication.getLoanApplicationFjList();
        if (loanApplicationFjList != null && loanApplicationFjList.size() > 0) {
            for (LoanApplicationFj loanApplicationFj : loanApplicationFjList) {
                loanApplicationFj.setLoanApplicationId(loanApplication.getLoanApplicationId());
                loanApplicationFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            }
            AsyncManager.me().execute(AsyncFactory.createPdfFromImages(loanApplicationFjList, loanApplication.getLoanApplicationNumber()));
            loanApplicationFjMapper.batchLoanApplicationFj(loanApplicationFjList);
        }
        List<ShareholderFj> shareholderFjList = loanApplication.getShareholderFjList();
        if (shareholderFjList != null && shareholderFjList.size() > 0) {
            for (ShareholderFj shareholderFj : shareholderFjList) {
                shareholderFj.setLoanApplicationId(loanApplication.getLoanApplicationId());
                shareholderFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            }
            AsyncManager.me().execute(AsyncFactory.createPdfFromImagesShareholder(shareholderFjList, loanApplication.getLoanApplicationNumber(), loanApplication.getLoanApplicationId()));
        }
        //反担保基础信息和附件新增
        List<GuaranteeInfo> guaranteeInfoList = loanApplication.getGuaranteeInfoList();
        if (guaranteeInfoList != null && guaranteeInfoList.size() > 0) {
            for (GuaranteeInfo guaranteeInfo : guaranteeInfoList) {
                guaranteeInfo.setLoanApplicationId(loanApplication.getLoanApplicationId());
                guaranteeInfo.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            }
            //先新增反担保基础信息,再去异步插入附件
            guaranteeInfoMapper.batchGuaranteeInfo(guaranteeInfoList);
            //异步插入附件
            AsyncManager.me().execute(AsyncFactory.createPdfFromImagesGuaranteeInfo(guaranteeInfoList, loanApplication.getLoanApplicationNumber()));
        }
        //往业务进度表 loan_schedule 插入数据
        LoanSchedule loanSchedule = new LoanSchedule();
        loanSchedule.setLoanApplicationId(loanApplication.getLoanApplicationId());
        loanSchedule.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        loanSchedule.setLoanScheduleName(loanApplication.getLoanScheduleName());
        loanSchedule.setLoanScheduleValue(loanApplication.getLoanSchedule());
        loanSchedule.setLoanScheduleScore(0L);
        loanSchedule.setLoanScheduleTime(DateUtils.getNowDate());
        loanScheduleMapper.insertLoanSchedule(loanSchedule);
        return i;
    }


    /**
     * 修改贷款申请主
     *
     * @param loanApplication 贷款申请主
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult updateLoanApplication(LoanApplication loanApplication) {

        loanApplication.setUpdateTime(DateUtils.getNowDate());
        loanApplication.setLoanApplicationType(TWO);
        loanApplication.setApplicationTime(DateUtils.getNowDate());
        Long loanApplicationId = loanApplication.getLoanApplicationId();
        //判断如果是审核进度 =1 贷款申请进度 =2业务审核/分配 审核状态 = 3(未通过的时候)把审核状态改为1 待审核
        if (loanApplication.getLoanSchedule().equals(TWO) && loanApplication.getAuditSchedule().equals(ONE) && loanApplication.getAuditType().equals(THR)) {
            loanApplication.setAuditType(ONE);
        }

        //需要删除的id集合
        Long[] loanApplicationFjIdList = loanApplication.getLoanApplicationFjIdList();
        Long[] shareholderFjIdList = loanApplication.getShareholderFjIdList();
        Long[] guaranteeInfoIdList = loanApplication.getGuaranteeInfoIdList();
        //反担保附件删除id集合
        Long[] guaranteeInfoFjIdList = loanApplication.getGuaranteeInfoFjIdList();
        List<LoanApplicationFj> loanApplicationFjList = loanApplication.getLoanApplicationFjList();
        if (loanApplicationFjList != null && loanApplicationFjList.size() > 0) {
            //判断有附件id的附件进行修改，没有的进行新增
            List<LoanApplicationFj> loanApplicationFjsInsert = loanApplicationFjList.stream().filter(e -> ObjectUtils.isEmpty(e.getFjId())).collect(Collectors.toList());
            if (loanApplicationFjsInsert.size() > 0) {
                for (LoanApplicationFj loanApplicationFj : loanApplicationFjsInsert) {
                    loanApplicationFj.setLoanApplicationId(loanApplicationId);
                    loanApplicationFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                }
                //新增新增的附件
                loanApplicationFjMapper.batchLoanApplicationFj(loanApplicationFjsInsert);
            }
            if (loanApplicationFjsInsert.size() > 0 || (loanApplicationFjIdList != null && loanApplicationFjIdList.length > 0)) {
                AsyncManager.me().execute(AsyncFactory.createPdfFromImages(loanApplicationFjList, loanApplication.getLoanApplicationNumber()));
            }
        }
        //需要删除附件表数据
        if (loanApplicationFjIdList != null && loanApplicationFjIdList.length > 0) {
            loanApplicationFjMapper.deleteLoanApplicationFjByFjIds(loanApplicationFjIdList);
        }

        //shareholderFjMapper.deleteShareholderFjByLoanApplicationId(loanApplicationId);
        List<ShareholderFj> shareholderFjList = loanApplication.getShareholderFjList();
        if (shareholderFjList != null && shareholderFjList.size() > 0) {
            AsyncManager.me().execute(AsyncFactory.createPdfFromImagesShareholder(shareholderFjList, loanApplication.getLoanApplicationNumber(), loanApplication.getLoanApplicationId()));
            // shareholderFjMapper.batchShareholderFj(shareholderFjList);
        }
        //需要删除股东附件表数据
        if (shareholderFjIdList != null && shareholderFjIdList.length > 0) {
            shareholderFjMapper.deleteShareholderFjByShareholderFjIds(shareholderFjIdList);
        }

        //反担保基础信息和附件新增
        List<GuaranteeInfo> guaranteeInfoList = loanApplication.getGuaranteeInfoList();
        if (guaranteeInfoList != null && guaranteeInfoList.size() > 0) {
            for (GuaranteeInfo guaranteeInfo : guaranteeInfoList) {
                guaranteeInfo.setLoanApplicationId(loanApplication.getLoanApplicationId());
                guaranteeInfo.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            }
            //判断有反担保信息表id的进行修改，没有的进行新增
            List<GuaranteeInfo> guaranteeInfosInsert = guaranteeInfoList.stream().filter(e -> ObjectUtils.isEmpty(e.getGuaranteeInfoId())).collect(Collectors.toList());
            List<GuaranteeInfo> guaranteeInfosUpdate = guaranteeInfoList.stream().filter(e -> ObjectUtils.isNotEmpty(e.getGuaranteeInfoId())).collect(Collectors.toList());
            if (guaranteeInfosInsert.size() > 0) {
                guaranteeInfoMapper.batchGuaranteeInfo(guaranteeInfosInsert);
            }
            if (guaranteeInfosUpdate.size() > 0) {
                for (GuaranteeInfo guaranteeInfo : guaranteeInfosUpdate) {
                    guaranteeInfoMapper.updateGuaranteeInfo(guaranteeInfo);
                }
            }
            //先新增反担保基础信息,再去异步插入附件
            //异步插入附件
            AsyncManager.me().execute(AsyncFactory.createPdfFromImagesGuaranteeInfo(guaranteeInfoList, loanApplication.getLoanApplicationNumber()));
        }

        if (guaranteeInfoFjIdList != null && guaranteeInfoFjIdList.length > 0) {
            guaranteeInfoFjMapper.deleteGuaranteeInfoFjByGuaranteeInfoFjIds(guaranteeInfoFjIdList);
        }
        if (guaranteeInfoIdList != null && guaranteeInfoIdList.length > 0) {
            guaranteeInfoMapper.deleteGuaranteeInfoByGuaranteeInfoIds(guaranteeInfoIdList);
            guaranteeInfoFjMapper.deleteGuaranteeInfoFjByGuaranteeInfoIds(guaranteeInfoIdList);
        }
        int rows = loanApplicationMapper.updateLoanApplication(loanApplication);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改贷款申请主新只新增实际放款金额(万元)实际放款时间
     */
    @Override
    public AjaxResult updateLoanApplicationActually(LoanApplication loanApplication) {
        int rows = loanApplicationMapper.updateLoanApplication(loanApplication);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 暂存
     *
     * @param loanApplication 贷款申请主
     * @return
     */
    @Override
    @Transactional
    public AjaxResult temporary(LoanApplication loanApplication) {
        loanApplication.setLoanApplicationType(ONE);
        Long loanApplicationId = loanApplication.getLoanApplicationId();
        //走修改
        if (loanApplicationId != null) {
            //需要删除的id集合
            Long[] loanApplicationFjIdList = loanApplication.getLoanApplicationFjIdList();
            Long[] shareholderFjIdList = loanApplication.getShareholderFjIdList();
            Long[] guaranteeInfoIdList = loanApplication.getGuaranteeInfoIdList();
            //反担保附件删除id集合
            Long[] guaranteeInfoFjIdList = loanApplication.getGuaranteeInfoFjIdList();
            List<LoanApplicationFj> loanApplicationFjList = loanApplication.getLoanApplicationFjList();
            if (loanApplicationFjList != null && loanApplicationFjList.size() > 0) {
                //判断有附件id的附件进行修改，没有的进行新增
                List<LoanApplicationFj> loanApplicationFjsInsert = loanApplicationFjList.stream().filter(e -> ObjectUtils.isEmpty(e.getFjId())).collect(Collectors.toList());
                if (loanApplicationFjsInsert.size() > 0) {
                    for (LoanApplicationFj loanApplicationFj : loanApplicationFjsInsert) {
                        loanApplicationFj.setLoanApplicationId(loanApplicationId);
                        loanApplicationFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                    }
                    //新增新增的附件
                    loanApplicationFjMapper.batchLoanApplicationFj(loanApplicationFjsInsert);
                }
                if (loanApplicationFjsInsert.size() > 0 || (loanApplicationFjIdList != null && loanApplicationFjIdList.length > 0)) {
                    AsyncManager.me().execute(AsyncFactory.createPdfFromImages(loanApplicationFjList, loanApplication.getLoanApplicationNumber()));
                }
            }
            //需要删除附件表数据
            if (loanApplicationFjIdList != null && loanApplicationFjIdList.length > 0) {
                loanApplicationFjMapper.deleteLoanApplicationFjByFjIds(loanApplicationFjIdList);
            }

            List<ShareholderFj> shareholderFjList = loanApplication.getShareholderFjList();
            if (shareholderFjList != null && shareholderFjList.size() > 0) {
                for (ShareholderFj shareholderFj : shareholderFjList) {
                    shareholderFj.setLoanApplicationId(loanApplicationId);
                    shareholderFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                }
                AsyncManager.me().execute(AsyncFactory.createPdfFromImagesShareholder(shareholderFjList, loanApplication.getLoanApplicationNumber(), loanApplication.getLoanApplicationId()));
            }
            //需要删除股东附件表数据
            if (shareholderFjIdList != null && shareholderFjIdList.length > 0) {
                shareholderFjMapper.deleteShareholderFjByShareholderFjIds(shareholderFjIdList);
            }

            //反担保基础信息和附件新增
            List<GuaranteeInfo> guaranteeInfoList = loanApplication.getGuaranteeInfoList();
            if (guaranteeInfoList != null && guaranteeInfoList.size() > 0) {
                for (GuaranteeInfo guaranteeInfo : guaranteeInfoList) {
                    guaranteeInfo.setLoanApplicationId(loanApplication.getLoanApplicationId());
                    guaranteeInfo.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                }
                //判断有反担保信息表id的进行修改，没有的进行新增
                List<GuaranteeInfo> guaranteeInfosInsert = guaranteeInfoList.stream().filter(e -> ObjectUtils.isEmpty(e.getGuaranteeInfoId())).collect(Collectors.toList());
                List<GuaranteeInfo> guaranteeInfosUpdate = guaranteeInfoList.stream().filter(e -> ObjectUtils.isNotEmpty(e.getGuaranteeInfoId())).collect(Collectors.toList());
                if (guaranteeInfosInsert.size() > 0) {
                    guaranteeInfoMapper.batchGuaranteeInfo(guaranteeInfosInsert);
                }
                if (guaranteeInfosUpdate.size() > 0) {
                    for (GuaranteeInfo guaranteeInfo : guaranteeInfosUpdate) {
                        guaranteeInfoMapper.updateGuaranteeInfo(guaranteeInfo);
                    }
                }
                //先新增反担保基础信息,再去异步插入附件
                //异步插入附件
                AsyncManager.me().execute(AsyncFactory.createPdfFromImagesGuaranteeInfo(guaranteeInfoList, loanApplication.getLoanApplicationNumber()));
            }
            if (guaranteeInfoFjIdList != null && guaranteeInfoFjIdList.length > 0) {
                guaranteeInfoFjMapper.deleteGuaranteeInfoFjByGuaranteeInfoFjIds(guaranteeInfoFjIdList);
            }
            if (guaranteeInfoIdList != null && guaranteeInfoIdList.length > 0) {
                guaranteeInfoMapper.deleteGuaranteeInfoByGuaranteeInfoIds(guaranteeInfoIdList);
                guaranteeInfoFjMapper.deleteGuaranteeInfoFjByGuaranteeInfoIds(guaranteeInfoIdList);
            }

            int rows = loanApplicationMapper.updateLoanApplication(loanApplication);
            return rows > 0 ? AjaxResult.success() : AjaxResult.error();
        }
        LoanApplication loanApplicationNew = new LoanApplication();
        loanApplicationNew.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        //暂存先去判断项目编号是否重复
        List<LoanApplication> loanApplications = loanApplicationMapper.selectLoanApplicationList(loanApplicationNew);
        if (loanApplications != null && loanApplications.size() > 0) {
            return AjaxResult.error("请勿重复暂存");
        }
        //设置为audit_schedule=1 audit_type=1
        loanApplication.setAuditSchedule(ONE);
        loanApplication.setAuditType(ONE);
        //设置申请人用户ID
        loanApplication.setUserId(SecurityUtils.getUserId());
        //贷款申请进度进入业务审核/分配
        loanApplication.setLoanSchedule(TWO);
        int rows = loanApplicationMapper.insertLoanApplication(loanApplication);
        loanApplicationId = loanApplication.getLoanApplicationId();
        List<LoanApplicationFj> loanApplicationFjList = loanApplication.getLoanApplicationFjList();
        if (loanApplicationFjList != null && loanApplicationFjList.size() > 0) {
            for (LoanApplicationFj loanApplicationFj : loanApplicationFjList) {
                loanApplicationFj.setLoanApplicationId(loanApplicationId);
                loanApplicationFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            }
            AsyncManager.me().execute(AsyncFactory.createPdfFromImages(loanApplicationFjList, loanApplication.getLoanApplicationNumber()));
            loanApplicationFjMapper.batchLoanApplicationFj(loanApplicationFjList);
        }
        List<ShareholderFj> shareholderFjList = loanApplication.getShareholderFjList();
        if (shareholderFjList != null && shareholderFjList.size() > 0) {
            for (ShareholderFj shareholderFj : shareholderFjList) {
                shareholderFj.setLoanApplicationId(loanApplicationId);
                shareholderFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            }
            AsyncManager.me().execute(AsyncFactory.createPdfFromImagesShareholder(shareholderFjList, loanApplication.getLoanApplicationNumber(), loanApplication.getLoanApplicationId()));
            //shareholderFjMapper.batchShareholderFj(shareholderFjList);
        }

        //反担保基础信息和附件新增
        List<GuaranteeInfo> guaranteeInfoList = loanApplication.getGuaranteeInfoList();
        if (guaranteeInfoList != null && guaranteeInfoList.size() > 0) {
            for (GuaranteeInfo guaranteeInfo : guaranteeInfoList) {
                guaranteeInfo.setLoanApplicationId(loanApplication.getLoanApplicationId());
                guaranteeInfo.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            }
            //判断有反担保信息表id的进行修改，没有的进行新增
            List<GuaranteeInfo> guaranteeInfosInsert = guaranteeInfoList.stream().filter(e -> ObjectUtils.isEmpty(e.getGuaranteeInfoId())).collect(Collectors.toList());
            List<GuaranteeInfo> guaranteeInfosUpdate = guaranteeInfoList.stream().filter(e -> ObjectUtils.isNotEmpty(e.getGuaranteeInfoId())).collect(Collectors.toList());
            if (guaranteeInfosInsert.size() > 0) {
                guaranteeInfoMapper.batchGuaranteeInfo(guaranteeInfosInsert);
            }
            if (guaranteeInfosUpdate.size() > 0) {
                for (GuaranteeInfo guaranteeInfo : guaranteeInfosUpdate) {
                    guaranteeInfoMapper.updateGuaranteeInfo(guaranteeInfo);
                }
            }
            //先新增反担保基础信息,再去异步插入附件
            //异步插入附件
            AsyncManager.me().execute(AsyncFactory.createPdfFromImagesGuaranteeInfo(guaranteeInfoList, loanApplication.getLoanApplicationNumber()));
        }
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除贷款申请主
     *
     * @param loanApplicationIds 需要删除的贷款申请主主键
     * @return 结果
     */
    @Override
    public int deleteLoanApplicationByLoanApplicationIds(Long[] loanApplicationIds) {
        return loanApplicationMapper.deleteLoanApplicationByLoanApplicationIds(loanApplicationIds);
    }

    /**
     * 删除贷款申请主信息
     *
     * @param loanApplicationId 贷款申请主主键
     * @return 结果
     */
    @Override
    public int deleteLoanApplicationByLoanApplicationId(Long loanApplicationId) {
        return loanApplicationMapper.deleteLoanApplicationByLoanApplicationId(loanApplicationId);
    }

    /**
     * 审核
     *
     * @param reviewComments
     * @return
     */
    @Override
    @Transactional
    public AjaxResult sh(ReviewComments reviewComments) {
        reviewComments.setAuditTime(DateUtils.getNowDate());
        //List<SysUserConference> sysUserConferenceList = reviewComments.getSysUserConferenceList();
        //审核进度1：业务审核/分配 2：A角色审核 3：B角色审核 4：风险审核 5：初审风险合规 6：尽职调查7：上会评审
        String auditSchedule = reviewComments.getAuditSchedule();
        //审核状态 1：待审核 2：已通过 3：未通过 4:申诉
        String auditType = reviewComments.getAuditType();
        //校验当前项目进度
        Long loanApplicationId = reviewComments.getLoanApplicationId();
        //获取数据库中项目详情
        LoanApplication loanApplication = loanApplicationMapper.selectLoanApplicationByLoanApplicationId(loanApplicationId);
        String loanScheduleOld = loanApplication.getLoanSchedule();
        String auditScheduleOld = loanApplication.getAuditSchedule();
        String auditTypeOld = loanApplication.getAuditType();
        String loanApplicationType = loanApplication.getLoanApplicationType();
        String enterpriseName = loanApplication.getEnterpriseName();
        //判断是否已归档
        if (loanApplication.getLoanApplicationType().equals(FOR)) {
            return AjaxResult.error("当前项目已归档");
        }
        //判断是否无需审核
        if (Integer.parseInt(loanScheduleOld) > 6) {
            return AjaxResult.error("当前项目无需审核");
        }
        if (!Objects.equals(loanApplicationType, TWO)) {
            return AjaxResult.error("当前贷款申请状态非正常，请检查后重新操作");
        }
        if (ObjectUtils.isEmpty(loanApplication)) {
            return AjaxResult.error("当前贷款申请不存在，请重新刷新");
        }

        //判断数据库中进度是否小于当前申请进度
        if (Integer.parseInt(auditSchedule) <= Integer.parseInt(auditScheduleOld) && !Objects.equals(auditTypeOld, ONE)) {
            return AjaxResult.error("当前进度已审核，请勿重复审核");
        }
        List<LoanApplicationFj> fjUrl = reviewComments.getFjUrl();
        if (fjUrl != null && fjUrl.size() > 0) {
            StringBuilder type = new StringBuilder();
            for (LoanApplicationFj loanApplicationFj : fjUrl) {
                type.append(loanApplicationFj.getType()).append(",");
            }
            type.deleteCharAt(type.lastIndexOf(","));
            loanApplicationFjMapper.deleteLoanApplicationFjByLoanApplicationIdAndType(loanApplicationId, type.toString().split(","));
            //需要删除当前状态下已存在的附件
            loanApplicationFjMapper.batchLoanApplicationFj(fjUrl);
        }
        //业务审核意见
        reviewComments.setCreateBy(SecurityUtils.getUsername());
        reviewCommentsMapper.insertReviewComments(reviewComments);
        //待办信息集合
        List<WaitRemind> waitRemindList = new ArrayList<>();
        //查询审核管理员用户id
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectRoleListNoDataScope();
        //A角色进度之前审核不通过，给客户回馈不通过问题,之后的进入到申诉状态
        if (THR.equals(auditType) && ONE.equals(auditSchedule)) {
            loanApplication.setAuditType(auditType);
            loanApplication.setAuditSchedule(auditSchedule);
            loanApplication.setLoanSchedule(TWO);
            loanApplication.setLoanApplicationType(TWO);
            //插入不通过原因
            loanApplication.setRejectionReason(reviewComments.getAuditView());
            loanApplicationMapper.updateLoanApplication(loanApplication);
          /*  //给A角色，审核管理员发送待办
            WaitRemind waitRemind = new WaitRemind();
            waitRemind.setLoanApplicationId(loanApplicationId);
            waitRemind.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            waitRemind.setRemindTitle("您有一条【" + enterpriseName + "】的审核信息进入回收站");
            waitRemind.setRemindTime(DateUtils.getNowDate());
            waitRemind.setRemindType(TWO);
            waitRemind.setReadUserId(loanApplication.getaUserId().toString());
            waitRemind.setRemindContent(enterpriseName + "有一条贷款申请进入回收站需及时处理");
            waitRemindList.add(waitRemind);
            if (sysUserRoles != null && sysUserRoles.size() > 0) {
                for (SysUserRole sysUserRole : sysUserRoles) {
                    WaitRemind waitRemindManager = new WaitRemind();
                    waitRemindManager.setLoanApplicationId(loanApplicationId);
                    waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                    waitRemindManager.setRemindTitle("有一条【" + enterpriseName + "】的审核信息进入回收站");
                    waitRemindManager.setRemindTime(DateUtils.getNowDate());
                    waitRemindManager.setRemindType(TWO);
                    waitRemindManager.setReadUserId(loanApplication.getaUserId().toString());
                    waitRemindManager.setRemindContent(enterpriseName + "有一条贷款申请进入回收站需及时查看");
                    //给管理员发送待办提醒
                    waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                    waitRemindList.add(waitRemindManager);
                }
            }
            waitRemindMapper.batchWaitRemind(waitRemindList);*/
            return AjaxResult.success();
            //A角色审核不通过 audit_schedule = 2的时候贷款申请进度处于担保初审状态
        } else if (THR.equals(auditType) && auditSchedule.equals(TWO)) {
            loanApplication.setLoanSchedule(THR);
            loanApplication.setAuditType(FOR);
            loanApplication.setLoanApplicationType(TWO);
            loanApplicationMapper.updateLoanApplication(loanApplication);
            //删除已处理的待办信息
            WaitRemind waitRemindDelete = new WaitRemind();
            waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
            waitRemindDelete.setReadUserId(loanApplication.getaUserId().toString());
            waitRemindDelete.setRemindType(TWO);
            waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
            //给A角色，审核管理员发送待办
            WaitRemind waitRemind = new WaitRemind();
            waitRemind.setLoanApplicationId(loanApplicationId);
            waitRemind.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            waitRemind.setRemindTitle("您有一条【" + enterpriseName + "】的审核信息未通过");
            waitRemind.setRemindTime(DateUtils.getNowDate());
            waitRemind.setRemindType(TWO);
            waitRemind.setReadUserId(loanApplication.getaUserId().toString());
            waitRemind.setRemindContent(enterpriseName + "有一条贷款申请进入未通过需及时处理");
            waitRemindList.add(waitRemind);
            List<Long> userIdList = new ArrayList<>();
            if (sysUserRoles != null && sysUserRoles.size() > 0) {
                userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
                for (SysUserRole sysUserRole : sysUserRoles) {
                    //删除已处理的待办信息
                    waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                    waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                    waitRemindDelete.setRemindType(TWO);
                    waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);

                    WaitRemind waitRemindManager = new WaitRemind();
                    waitRemindManager.setLoanApplicationId(loanApplicationId);
                    waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                    waitRemindManager.setRemindTitle("有一条【" + enterpriseName + "】的审核信息未通过");
                    waitRemindManager.setRemindTime(DateUtils.getNowDate());
                    waitRemindManager.setRemindType(TWO);
                    waitRemindManager.setRemindContent(enterpriseName + "有一条贷款申请进入未通过需及时查看");
                    //给管理员发送待办提醒
                    waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                    waitRemindList.add(waitRemindManager);
                }
            }
            waitRemindMapper.batchWaitRemind(waitRemindList);

            //发极光推送id
            //获取所有的userid
            userIdList.add(loanApplication.getaUserId());
            List<SysUser> sysUsers = sysUserService.selectUserListByIdList(userIdList);
            if(sysUsers!=null && sysUsers.size()>0){
                String notificationTitle = "消息通知";
                String msgTitle = "审核信息";
                String msgContent = enterpriseName + "有一条贷款申请进入未通过需及时处理";
                String jPushVO = "";
                List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
                listS.removeAll(Collections.singleton(null));
                if(listS!=null && listS.size()>0){
                    String[]  registrationId = listS.toArray(new String[listS.size()]);
                    JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
                }
            }

            return AjaxResult.success();
            //审核流程结束
        } else if (THR.equals(auditType) && Integer.parseInt(auditSchedule) > 2) {
            //进入到A角色申诉状态保留当前项目状态，只把audit_type改为申诉
            loanApplication.setAuditType(FOR);
            loanApplicationMapper.updateLoanApplication(loanApplication);
            //删除已处理的待办信息
            WaitRemind waitRemindDelete = new WaitRemind();
            waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
            waitRemindDelete.setReadUserId(loanApplication.getaUserId().toString());
            waitRemindDelete.setRemindType(TWO);
            waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
            //给A角色发送待办提醒
            WaitRemind waitRemind = new WaitRemind();
            waitRemind.setLoanApplicationId(loanApplicationId);
            waitRemind.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            waitRemind.setRemindTitle("您有一条【" + enterpriseName + "】的审核信息进入申诉状态");
            waitRemind.setRemindTime(DateUtils.getNowDate());
            waitRemind.setRemindType(TWO);
            waitRemind.setReadUserId(loanApplication.getaUserId().toString());
            waitRemind.setRemindContent(enterpriseName + "有一条贷款申请进入申诉状态需及时处理");
            waitRemindList.add(waitRemind);
            List<Long> userIdList = new ArrayList<>();
            if (sysUserRoles != null && sysUserRoles.size() > 0) {
                userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
                for (SysUserRole sysUserRole : sysUserRoles) {
                    //删除已处理的待办信息
                    waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                    waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                    waitRemindDelete.setRemindType(TWO);
                    waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);

                    WaitRemind waitRemindManager = new WaitRemind();
                    waitRemindManager.setLoanApplicationId(loanApplicationId);
                    waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                    waitRemindManager.setRemindTitle("有一条【" + enterpriseName + "】的审核信息进入申诉状态");
                    waitRemindManager.setRemindTime(DateUtils.getNowDate());
                    waitRemindManager.setRemindType(TWO);
                    waitRemindManager.setReadUserId(loanApplication.getaUserId().toString());
                    waitRemindManager.setRemindContent(enterpriseName + "有一条贷款申请进入申诉状态需及时处理");
                    //给管理员发送待办提醒
                    waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                    waitRemindList.add(waitRemindManager);
                }
            }
            waitRemindMapper.batchWaitRemind(waitRemindList);

            //发极光推送id
            //获取所有的userid
            userIdList.add(loanApplication.getaUserId());
            List<SysUser> sysUsers = sysUserService.selectUserListByIdList(userIdList);
            if(sysUsers!=null && sysUsers.size()>0){
                String notificationTitle = "消息通知";
                String msgTitle = "审核信息";
                String msgContent = enterpriseName + "有一条贷款申请进入申诉状态需及时处理";
                String jPushVO = "";
                List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
                listS.removeAll(Collections.singleton(null));
                if(listS!=null && listS.size()>0){
                    String[]  registrationId = listS.toArray(new String[listS.size()]);
                    JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
                }
            }
            return AjaxResult.success();
        }
        //通过,进入到下一个步骤
        if (TWO.equals(auditType)) {

            WaitRemind waitRemindDelete = new WaitRemind();
            List<Long> userIdList = new ArrayList<>();

            WaitRemind waitRemind = new WaitRemind();
            waitRemind.setLoanApplicationId(loanApplicationId);
            waitRemind.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            waitRemind.setRemindTitle("您有一条【" + enterpriseName + "】的审核信息通过");
            waitRemind.setRemindTime(DateUtils.getNowDate());
            waitRemind.setRemindType(TWO);
            if (auditSchedule.equals(ONE)) {
                //删除已处理的待办信息
                waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindDelete.setReadUserId(loanApplication.getaUserId().toString());
                waitRemindDelete.setRemindType(TWO);
                waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
                loanApplication.setLoanSchedule(String.valueOf(Integer.parseInt(loanScheduleOld) + 1));
                loanApplication.setAuditSchedule(String.valueOf(Integer.parseInt(auditSchedule) + 1));
                loanApplication.setAuditType(ONE);
                //设置AB角色id和风险ID
                loanApplication.setaUserId(reviewComments.getaUserId());
                loanApplication.setaUserName(reviewComments.getaUserName());
                loanApplication.setbUserId(reviewComments.getbUserId());
                loanApplication.setbUserName(reviewComments.getbUserName());
                loanApplication.setfUserId(reviewComments.getfUserId());
                loanApplication.setfUserName(reviewComments.getfUserName());
                //给A角色发送待办提醒
                waitRemind.setReadUserId(reviewComments.getaUserId().toString());
                waitRemind.setRemindContent(enterpriseName + "有一条申请贷款信息审核通过");
                waitRemindList.add(waitRemind);
                if (sysUserRoles != null && sysUserRoles.size() > 0) {
                    //极光推送
                    userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());

                    for (SysUserRole sysUserRole : sysUserRoles) {
                        //删除已处理的待办信息
                        waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                        waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                        waitRemindDelete.setRemindType(TWO);
                        waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);

                        WaitRemind waitRemindManager = new WaitRemind();
                        waitRemindManager.setLoanApplicationId(loanApplicationId);
                        waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                        waitRemindManager.setRemindTitle("有一条【" + enterpriseName + "】的审核信息申请通过进入到下一阶段");
                        waitRemindManager.setRemindTime(DateUtils.getNowDate());
                        waitRemindManager.setRemindType(TWO);
                        waitRemindManager.setRemindContent(enterpriseName + "有一条贷款申请审核通过进入到下一阶段");
                        //给管理员发送待办提醒
                        waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                        waitRemindList.add(waitRemindManager);
                    }
                }
                userIdList.add(reviewComments.getaUserId());
            }
/*            //保存参会人员数据 当管理同意上会后A角色选择上会日期，系统自动选择5名评委（评委排除AB角色和风险）
            if (sysUserConferenceList != null && sysUserConferenceList.size() > 0 && auditSchedule.equals(SEV)) {
                sysUserConferenceMapper.batchSysUserConference(sysUserConferenceList);
            }*/
            //audit_schedule = 2,3的时候贷款申请进度处于担保初审状态
         else    if (auditSchedule.equals(TWO) || auditSchedule.equals(THR)) {
                loanApplication.setLoanSchedule(THR);
                loanApplication.setAuditSchedule(String.valueOf(Integer.parseInt(auditSchedule) + 1));
                loanApplication.setAuditType(ONE);
                if (auditSchedule.equals(TWO)) {
                    //删除已处理的待办信息

                    waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                    waitRemindDelete.setReadUserId(loanApplication.getbUserId().toString());
                    waitRemindDelete.setRemindType(TWO);
                    waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
                    //给B角色发送待办提醒
                    waitRemind.setReadUserId(loanApplication.getbUserId().toString());
                    waitRemind.setRemindContent(enterpriseName + "有一条贷款申请需及时处理");
                    waitRemindList.add(waitRemind);
                    if (sysUserRoles != null && sysUserRoles.size() > 0) {
                        //极光推送
                        userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());

                        for (SysUserRole sysUserRole : sysUserRoles) {
                            //删除已处理的待办信息
                            waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                            waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                            waitRemindDelete.setRemindType(TWO);
                            waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);

                            WaitRemind waitRemindManager = new WaitRemind();
                            waitRemindManager.setLoanApplicationId(loanApplicationId);
                            waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                            waitRemindManager.setRemindTitle("有一条【" + enterpriseName + "】的审核信息申请通过进入到下一阶段");
                            waitRemindManager.setRemindTime(DateUtils.getNowDate());
                            waitRemindManager.setRemindType(TWO);
                            waitRemindManager.setReadUserId(loanApplication.getaUserId().toString());
                            waitRemindManager.setRemindContent(enterpriseName + "有一条贷款申请审核通过进入到下一阶段");
                            //给管理员发送待办提醒
                            waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                            waitRemindList.add(waitRemindManager);
                        }
                    }
                    userIdList.add(loanApplication.getbUserId());
                }
                if (auditSchedule.equals(THR)) {
                    //删除已处理的待办信息

                    waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                    waitRemindDelete.setReadUserId(loanApplication.getfUserId().toString());
                    waitRemindDelete.setRemindType(TWO);
                    waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
                    //给风险角色发送待办提醒
                    waitRemind.setReadUserId(loanApplication.getfUserId().toString());
                    waitRemind.setRemindContent(enterpriseName + "有一条贷款申请需及时处理");
                    waitRemindList.add(waitRemind);
                    if (sysUserRoles != null && sysUserRoles.size() > 0) {
                        //极光推送
                        userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());


                        for (SysUserRole sysUserRole : sysUserRoles) {
                            //删除已处理的待办信息
                            waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                            waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                            waitRemindDelete.setRemindType(TWO);
                            waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);

                            WaitRemind waitRemindManager = new WaitRemind();
                            waitRemindManager.setLoanApplicationId(loanApplicationId);
                            waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                            waitRemindManager.setRemindTitle("有一条【" + enterpriseName + "】的审核信息申请通过进入到下一阶段");
                            waitRemindManager.setRemindTime(DateUtils.getNowDate());
                            waitRemindManager.setRemindType(TWO);
                            waitRemindManager.setReadUserId(loanApplication.getaUserId().toString());
                            waitRemindManager.setRemindContent(enterpriseName + "有一条贷款申请审核通过进入到下一阶段");
                            //给管理员发送待办提醒
                            waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                            waitRemindList.add(waitRemindManager);
                        }
                    }
                    userIdList.add(loanApplication.getfUserId());
                }
                //审核流程结束
            } else {
                loanApplication.setLoanSchedule(String.valueOf(Integer.parseInt(loanScheduleOld) + 1));
                loanApplication.setAuditSchedule(String.valueOf(Integer.parseInt(auditSchedule) + 1));
                loanApplication.setAuditType(ONE);
                //删除已处理的待办信息

                waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindDelete.setReadUserId(loanApplication.getaUserId().toString());
                waitRemindDelete.setRemindType(loanApplication.getLoanSchedule());
                waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
                //给A角色发送待办提醒
                waitRemind.setRemindType(loanApplication.getLoanSchedule());
                waitRemind.setReadUserId(loanApplication.getaUserId().toString());
                waitRemind.setRemindContent(enterpriseName + "的审核信息申请通过进入到下一阶段");
                waitRemindList.add(waitRemind);
                if (sysUserRoles != null && sysUserRoles.size() > 0) {
                    //极光推送
                    userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());

                    for (SysUserRole sysUserRole : sysUserRoles) {
                        //删除已处理的待办信息
                        waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                        waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                        waitRemindDelete.setRemindType(TWO);
                        waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
                        WaitRemind waitRemindManager = new WaitRemind();
                        waitRemindManager.setLoanApplicationId(loanApplicationId);
                        waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                        waitRemindManager.setRemindTitle("有一条【" + enterpriseName + "】的审核信息进入到下一阶段");
                        waitRemindManager.setRemindTime(DateUtils.getNowDate());
                        waitRemindManager.setRemindType(loanApplication.getLoanSchedule());
                        waitRemindManager.setRemindContent(enterpriseName + "的审核信息申请通过进入到下一阶段");
                        //给管理员发送待办提醒
                        waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                        waitRemindList.add(waitRemindManager);
                    }
                }
                userIdList.add(loanApplication.getaUserId());
            }
            loanApplicationMapper.updateLoanApplication(loanApplication);
            //插入流程记录表
            LoanSchedule loanSchedule = new LoanSchedule();
            loanSchedule.setLoanApplicationId(loanApplicationId);
            loanSchedule.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            loanSchedule.setLoanScheduleValue(loanApplication.getLoanSchedule());
            loanSchedule.setLoanScheduleScore(Long.parseLong(loanApplication.getLoanSchedule()));
            loanSchedule.setLoanScheduleTime(DateUtils.getNowDate());
            loanScheduleMapper.insertLoanSchedule(loanSchedule);
            //插入审核通过的待办提醒
            if (waitRemindList.size() > 0) {
                waitRemindMapper.batchWaitRemind(waitRemindList);

                //发极光推送id
                List<SysUser> sysUsers = sysUserService.selectUserListByIdList(userIdList);
                if(sysUsers!=null && sysUsers.size()>0){
                    String notificationTitle = "消息通知";
                    String msgTitle = "审核信息";
                    String msgContent = enterpriseName + "的审核信息申请通过进入到下一阶段";
                    String jPushVO = "";
                    List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
                    listS.removeAll(Collections.singleton(null));
                    if(listS!=null && listS.size()>0){
                        String[]  registrationId = listS.toArray(new String[listS.size()]);
                        JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 申诉
     *
     * @param loanApplication
     * @return
     */
    @Override
    @Transactional
    public AjaxResult ss(LoanApplication loanApplication) {
        Long loanApplicationId = loanApplication.getLoanApplicationId();
        //先判断当前人是否是A角色或者B角色
        Long userId = SecurityUtils.getUserId();
        Long aLong = loanApplication.getaUserId();
        Long bLong = loanApplication.getbUserId();
        if (Objects.equals(userId, aLong) || Objects.equals(userId, bLong)) {
            //判断当前项目是否是在申诉状态
            String auditType = loanApplication.getAuditType();
            if (!FOR.equals(auditType)) {
                return AjaxResult.error("当前项目无需申诉或状态异常");
            }
            //判断是否是放弃申诉 如果AB角色都放弃申诉则项目结束 = 放到回收站
            String ssType = loanApplication.getSsType();
            if (ONE.equals(ssType)) {
                //申诉中判断评审会进度不是1等待上会，则重置为1
                loanApplication.setReviewSchedule(ONE);
                //进入待审核
                loanApplication.setAuditType(ONE);
                loanApplicationMapper.updateLoanApplication(loanApplication);
                //删除基础附件外的所有附件
                //loanApplicationFjMapper.deleteLoanApplicationFjByLoanApplicationIdAndBigType(loanApplication.getLoanApplicationId());

                //业务审核意见
                ReviewComments reviewComments = new ReviewComments();
                reviewComments.setLoanApplicationId(loanApplicationId);
                reviewComments.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                reviewComments.setAuditSchedule(TWO);
                reviewComments.setAuditType(FOR);
                reviewComments.setAuditTime(DateUtils.getNowDate());
                reviewComments.setCreateBy(SecurityUtils.getUsername());
                reviewCommentsMapper.insertReviewComments(reviewComments);
            } else if (TWO.equals(ssType)) {
                //放弃申诉需要AB角色都要放弃
                //先判断是A还是B角色
                String key = loanApplicationId + ":ss:";
                if (Objects.equals(userId, aLong)) {
                    Object cacheObjectA = redisCache.getCacheObject(key + A);
                    if (ObjectUtils.isNotEmpty(cacheObjectA)) {
                        //
                        return AjaxResult.error("请勿重复放弃");
                    } else {
                        //A是空则查询B
                        Object cacheObjectB = redisCache.getCacheObject(key + B);
                        if (ObjectUtils.isNotEmpty(cacheObjectB)) {
                            //修改项目状态到回收站
                            loanApplication.setLoanApplicationType(THR);
                            loanApplicationMapper.updateLoanApplication(loanApplication);
                        } else {
                            redisCache.setCacheObject(key + A, aLong);
                        }
                    }
                }
                if (Objects.equals(userId, bLong)) {
                    Object cacheObjectB = redisCache.getCacheObject(key + B);
                    if (ObjectUtils.isNotEmpty(cacheObjectB)) {
                        //
                        return AjaxResult.error("请勿重复放弃");
                    } else {
                        //B是空则查询A
                        Object cacheObjectA = redisCache.getCacheObject(key + A);
                        if (ObjectUtils.isNotEmpty(cacheObjectA)) {
                            //修改项目状态到回收站
                            loanApplication.setLoanApplicationType(THR);
                            loanApplicationMapper.updateLoanApplication(loanApplication);
                        } else {
                            redisCache.setCacheObject(key + B, aLong);
                        }
                    }
                }
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("当前您无权限申诉，请联系管理员");
    }

    /**
     * 管理员同意/不同意上会审核按钮
     *
     * @param loanApplication
     * @return
     */
    @Override
    @Transactional
    public AjaxResult review(LoanApplication loanApplication) {
        String loanSchedule = loanApplication.getLoanSchedule();
        String auditSchedule = loanApplication.getAuditSchedule();
        String auditType = loanApplication.getAuditType();
        String reviewSchedule = loanApplication.getReviewSchedule();
        //判断项目状态
        if (!loanSchedule.equals(SIX) || !auditSchedule.equals(SEV) || !auditType.equals(ONE)) {
            return AjaxResult.error("当前项目状态异常，不允许上会");
        }
        int rows = loanApplicationMapper.updateLoanApplication(loanApplication);
        //删除所有状态小于的待办事项
        WaitRemind waitRemindDelete = new WaitRemind();
        waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
        waitRemindDelete.setReadUserId(loanApplication.getaUserId().toString());
        waitRemindDelete.setRemindType(SIX);
        waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
        //给A角色发送上会审核信息
        WaitRemind waitRemindManager = new WaitRemind();
        waitRemindManager.setLoanApplicationId(loanApplication.getLoanApplicationId());
        waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        waitRemindManager.setRemindTitle("有一条【" + loanApplication.getEnterpriseName() + "】的上会审核信息");
        waitRemindManager.setRemindTime(DateUtils.getNowDate());
        waitRemindManager.setRemindType(SIX);
        waitRemindManager.setReadUserId(loanApplication.getaUserId().toString());
        String result = "通过";
        if (TWO.equals(reviewSchedule)) {
            result = "不通过";
        }
        waitRemindManager.setRemindContent(loanApplication.getEnterpriseName() + "的上会审核信息申请" + result);
        //给管理员发送待办提醒
        waitRemindManager.setReadUserId(String.valueOf(loanApplication.getaUserId()));
        waitRemindMapper.insertWaitRemind(waitRemindManager);

        //发极光推送
        SysUser user = sysUserService.selectUserById(loanApplication.getaUserId());
        if(StringUtils.isNotEmpty(user.getJgId())){
            String notificationTitle = "消息通知";
            String msgTitle = "上会审核信息";
            String msgContent = loanApplication.getEnterpriseName() + "的上会审核信息申请" + result;
            String jPushVO = "";
            JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,user.getJgId());
        }

        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 7：合同签约 8：放款合规风险审核推进到下一步功能
     *
     * @param loanApplication
     * @return
     */
    @Override
    @Transactional
    public AjaxResult schedule(LoanApplication loanApplication) {
        String loanSchedule = loanApplication.getLoanSchedule();
        if (!SEV.equals(loanSchedule) && !EIG.equals(loanSchedule)) {
            return AjaxResult.error("当前项目进度错误。");
        }
        LoanApplication application = new LoanApplication();
        application.setLoanApplicationId(loanApplication.getLoanApplicationId());
        application.setAuditType(TWO);
        if (SEV.equals(loanSchedule)) {
            application.setLoanSchedule(EIG);
            application.setAuditSchedule(NIN);
        }
        if (EIG.equals(loanSchedule)) {
            application.setLoanSchedule(NIN);
            application.setAuditSchedule(TEN);
        }
        loanApplicationMapper.updateLoanApplication(application);
        //删除所有状态小于的待办事项
        WaitRemind waitRemindDelete = new WaitRemind();
        waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
        waitRemindDelete.setReadUserId(loanApplication.getaUserId().toString());
        waitRemindDelete.setRemindType(loanSchedule);
        waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
        //给A角色发送待办提醒
        //待办信息集合
        //查询审核管理员用户id
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectRoleListNoDataScope();
        List<WaitRemind> waitRemindList = new ArrayList<>();
        WaitRemind waitRemind = new WaitRemind();
        waitRemind.setLoanApplicationId(loanApplication.getLoanApplicationId());
        waitRemind.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        waitRemind.setRemindTitle("您有一条【" + loanApplication.getEnterpriseName() + "】的审核信息进入到下一阶段");
        waitRemind.setRemindTime(DateUtils.getNowDate());
        waitRemind.setRemindType(loanSchedule);
        waitRemind.setReadUserId(loanApplication.getaUserId().toString());
        waitRemind.setRemindContent(loanApplication.getEnterpriseName() + "的审核信息申请通过进入到下一阶段");
        waitRemindList.add(waitRemind);
        List<Long> userIdList = new ArrayList<>();
        if (sysUserRoles != null && sysUserRoles.size() > 0) {
            //极光推送
            userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());


            for (SysUserRole sysUserRole : sysUserRoles) {
                //删除所有状态小于的待办事项
                waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                waitRemindDelete.setRemindType(loanSchedule);
                waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);

                WaitRemind waitRemindManager = new WaitRemind();
                waitRemindManager.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                waitRemindManager.setRemindTitle("有一条【" + loanApplication.getEnterpriseName() + "】的审核信息进入到下一阶段");
                waitRemindManager.setRemindTime(DateUtils.getNowDate());
                waitRemindManager.setRemindType(loanSchedule);
                waitRemindManager.setReadUserId(loanApplication.getaUserId().toString());
                waitRemindManager.setRemindContent(loanApplication.getEnterpriseName() + "的审核信息申请通过进入到下一阶段");
                //给管理员发送待办提醒
                waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                waitRemindList.add(waitRemindManager);
            }
        }
        waitRemindMapper.batchWaitRemind(waitRemindList);

        //发极光推送id
        userIdList.add(loanApplication.getaUserId());
        List<SysUser> sysUsers = sysUserService.selectUserListByIdList(userIdList);
        if(sysUsers!=null && sysUsers.size()>0){
            String notificationTitle = "消息通知";
            String msgTitle = "审核信息";
            String msgContent = loanApplication.getEnterpriseName() + "的审核信息申请通过进入到下一阶段";
            String jPushVO = "";
            List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
            listS.removeAll(Collections.singleton(null));
            if(listS!=null && listS.size()>0){
                String[]  registrationId = listS.toArray(new String[listS.size()]);
                JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
            }
        }


        //业务审核意见
        ReviewComments reviewComments = new ReviewComments();
        reviewComments.setLoanApplicationId(loanApplication.getLoanApplicationId());
        reviewComments.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        reviewComments.setAuditSchedule(loanApplication.getAuditSchedule());
        reviewComments.setAuditType(TWO);
        reviewComments.setAuditTime(DateUtils.getNowDate());
        reviewComments.setCreateBy(SecurityUtils.getUsername());
        //业务审核意见
        reviewCommentsMapper.insertReviewComments(reviewComments);
        return AjaxResult.success();
    }

    /**
     * 撤销返回到上一步
     *
     * @param loanApplication
     * @return
     */
    @Override
    @Transactional
    public AjaxResult cx(LoanApplication loanApplication) {

        List<Long> userIdList = new ArrayList<>();

        Long loanApplicationId = loanApplication.getLoanApplicationId();
        //获取当前状态
        String loanSchedule = loanApplication.getLoanSchedule();
        String auditSchedule = loanApplication.getAuditSchedule();
        String loanApplicationType = loanApplication.getLoanApplicationType();
        String auditType = loanApplication.getAuditType();
        List<WaitRemind> waitRemindList = new ArrayList<>();

        LoanApplication loanApplicationOld = loanApplicationMapper.selectLoanApplicationByLoanApplicationId(loanApplicationId);
        //reviewCommentsMapper.deleteReviewCommentsByLoanApplicationIdAndAuditSchedule(loanApplicationId, auditSchedule);
        if (Integer.parseInt(loanSchedule) < 2 || Integer.parseInt(auditSchedule) < 1 || Integer.parseInt(loanApplicationType) != 2) {
            return AjaxResult.error("当前项目不可撤销");
        }
        if (Integer.parseInt(loanSchedule) > 7) {
            //撤销只返回贷款申请进度到上一步
            loanApplication.setLoanSchedule(String.valueOf(Integer.parseInt(loanSchedule) - 1));
            loanApplication.setAuditSchedule(String.valueOf(Integer.parseInt(auditSchedule) - 1));
        } else {
            //如果是待审核的撤销就退一步否则就是改为待审核
            if (ONE.equals(auditType)) {
                String reviewSchedule = loanApplication.getReviewSchedule();
                //等于6：评审会撤销
                if (SIX.equals(loanSchedule) && !ONE.equals(reviewSchedule)) {
                    loanApplication.setReviewSchedule(ONE);
                    if (Integer.parseInt(reviewSchedule) > 3) {
                        //撤销到确认上会
                        loanApplication.setReviewSchedule(THR);
                        loanApplication.setReviewTime("");
                        //删掉参会人员
                        sysUserConferenceMapper.deleteSysUserConferenceByTime(loanApplicationOld.getReviewTime(), loanApplicationOld.getLoanApplicationId());
                    }
                } else if (auditSchedule.equals(FOR) || auditSchedule.equals(THR)) {
                    loanApplication.setLoanSchedule(THR);
                    loanApplication.setAuditSchedule(String.valueOf(Integer.parseInt(auditSchedule) - 1));
                } else {
                    loanApplication.setAuditSchedule(String.valueOf(Integer.parseInt(auditSchedule) - 1));
                    loanApplication.setLoanSchedule(String.valueOf(Integer.parseInt(loanSchedule) - 1));
                    //撤销完成后是到上会评审=评审会进度到 3：同意上会
                    if (SIX.equals(loanApplication.getLoanSchedule())) {
                        loanApplication.setReviewSchedule(THR);
                        loanApplication.setReviewTime("");
                        //删掉参会人员
                        sysUserConferenceMapper.deleteSysUserConferenceByTime(loanApplicationOld.getReviewTime(), loanApplicationOld.getLoanApplicationId());
                    }
                    if (loanApplication.getLoanSchedule().equals(TWO) && loanApplication.getAuditSchedule().equals(ONE)) {
                        //撤回到重新分配AB风险，重置主表数据
                        loanApplication.setaUserId(null);
                        loanApplication.setaUserName("");
                        loanApplication.setbUserId(null);
                        loanApplication.setbUserName("");
                        loanApplication.setfUserId(null);
                        loanApplication.setfUserName("");
                    }
                }
            } else {
                //进入待审核
                loanApplication.setAuditType(ONE);
            }
            String enterpriseName = loanApplicationOld.getEnterpriseName();
            String loanApplicationNumber = loanApplicationOld.getLoanApplicationNumber();

            //如果退到 A角色审核 B角色审核 还需要插入待办提醒
            if (loanApplication.getAuditSchedule().equals(TWO)) {
                //删除所有状态小于的待办事项
                WaitRemind waitRemindDelete = new WaitRemind();
                waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindDelete.setReadUserId(loanApplicationOld.getaUserId().toString());
                waitRemindDelete.setRemindType(TWO);
                waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
                WaitRemind waitRemind = new WaitRemind();
                waitRemind.setLoanApplicationId(loanApplicationId);
                waitRemind.setLoanApplicationNumber(loanApplicationNumber);
                waitRemind.setRemindTitle("您有一条【" + enterpriseName + "】的审核信息待办");
                waitRemind.setRemindTime(DateUtils.getNowDate());
                waitRemind.setRemindType(TWO);
                //给A角色发送待办提醒
                waitRemind.setReadUserId(loanApplicationOld.getaUserId().toString());
                waitRemind.setRemindContent(enterpriseName + "有一条贷款申请需及时处理");
                waitRemindList.add(waitRemind);

                userIdList.add(loanApplicationOld.getaUserId());
            }
            if (loanApplication.getAuditSchedule().equals(THR)) {
                //删除所有状态小于的待办事项
                WaitRemind waitRemindDelete = new WaitRemind();
                waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindDelete.setReadUserId(loanApplicationOld.getbUserId().toString());
                waitRemindDelete.setRemindType(TWO);
                waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
                WaitRemind waitRemind = new WaitRemind();
                waitRemind.setLoanApplicationId(loanApplicationId);
                waitRemind.setLoanApplicationNumber(loanApplicationNumber);
                waitRemind.setRemindTitle("您有一条【" + enterpriseName + "】的审核信息待办");
                waitRemind.setRemindTime(DateUtils.getNowDate());
                waitRemind.setRemindType(TWO);
                //给B角色发送待办提醒
                waitRemind.setReadUserId(loanApplicationOld.getbUserId().toString());
                waitRemind.setRemindContent(enterpriseName + "有一条贷款申请需及时处理");
                waitRemindList.add(waitRemind);

                userIdList.add(loanApplicationOld.getbUserId());
            }
        }
        loanApplicationMapper.updateLoanApplication2(loanApplication);


        //给A角色发送待办提醒
        //待办信息集合
        //查询审核管理员用户id
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectRoleListNoDataScope();
        if (ObjectUtils.isNotEmpty(loanApplication.getaUserId())) {

            //删除所有状态小于的待办事项
            WaitRemind waitRemindDelete = new WaitRemind();
            waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
            waitRemindDelete.setReadUserId(loanApplication.getaUserId().toString());
            waitRemindDelete.setRemindType(loanSchedule);
            waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);

            WaitRemind waitRemind = new WaitRemind();
            waitRemind.setLoanApplicationId(loanApplication.getLoanApplicationId());
            waitRemind.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
            waitRemind.setRemindTitle("您有一条【" + loanApplication.getEnterpriseName() + "】的信息进行了撤销");
            waitRemind.setRemindTime(DateUtils.getNowDate());
            waitRemind.setRemindType(loanSchedule);
            waitRemind.setReadUserId(loanApplication.getaUserId().toString());
            waitRemind.setRemindContent(loanApplication.getEnterpriseName() + "的信息进行了撤销");
            waitRemindList.add(waitRemind);
            if (sysUserRoles != null && sysUserRoles.size() > 0) {
                //极光推送
                List<Long> userIds = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
                userIdList.addAll(userIds);

                for (SysUserRole sysUserRole : sysUserRoles) {

                    //删除所有状态小于的待办事项

                    waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                    waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                    waitRemindDelete.setRemindType(loanSchedule);
                    waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);

                    WaitRemind waitRemindManager = new WaitRemind();
                    waitRemindManager.setLoanApplicationId(loanApplication.getLoanApplicationId());
                    waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                    waitRemindManager.setRemindTitle("有一条【" + loanApplication.getEnterpriseName() + "】的信息进行了撤销");
                    waitRemindManager.setRemindTime(DateUtils.getNowDate());
                    waitRemindManager.setRemindType(loanSchedule);
                    waitRemindManager.setRemindContent(loanApplication.getEnterpriseName() + "的信息进行了撤销");
                    //给管理员发送待办提醒
                    waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                    waitRemindList.add(waitRemindManager);
                }
            }
            userIdList.add(loanApplication.getaUserId());
        }

        if (waitRemindList != null && waitRemindList.size() > 0) {
            waitRemindMapper.batchWaitRemind(waitRemindList);

            //发极光推送id
            List<SysUser> sysUsers = sysUserService.selectUserListByIdList(userIdList);
            if(sysUsers!=null && sysUsers.size()>0){
                String notificationTitle = "消息通知";
                String msgTitle = "撤销信息";
                String msgContent = loanApplication.getEnterpriseName() + "的信息进行了撤销";
                String jPushVO = "";
                List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
                listS.removeAll(Collections.singleton(null));
                if(listS!=null && listS.size()>0){
                    String[]  registrationId = listS.toArray(new String[listS.size()]);
                    JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
                }
            }
        }

        //业务审核意见插入撤销
        ReviewComments reviewComments = new ReviewComments();
        reviewComments.setLoanApplicationId(loanApplication.getLoanApplicationId());
        reviewComments.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        int auditScheduleNew = Integer.parseInt(loanApplication.getAuditSchedule());
        if (Integer.parseInt(loanApplication.getLoanSchedule()) > 6) {
            auditScheduleNew = auditScheduleNew + 1;
        }
        reviewComments.setAuditSchedule(String.valueOf(auditScheduleNew));
        reviewComments.setAuditType(FIV);
        reviewComments.setAuditTime(DateUtils.getNowDate());
        reviewComments.setCreateBy(SecurityUtils.getUsername());
        reviewCommentsMapper.insertReviewComments(reviewComments);
        return AjaxResult.success();
    }

    /**
     * 一键归档
     *
     * @param loanApplication
     * @return
     */
    @Override
    @Transactional
    public AjaxResult gd(LoanApplication loanApplication) {
        //判断项目是否能归档
        String loanSchedule = loanApplication.getLoanSchedule();
        String loanApplicationType = loanApplication.getLoanApplicationType();
        String auditType = loanApplication.getAuditType();
        if (!NIN.equals(loanSchedule) && !TWO.equals(loanApplicationType) && !TWO.equals(auditType)) {
            return AjaxResult.error("当前项目进度不能归档");
        }
        loanApplication.setLoanSchedule(TEN);
        loanApplication.setLoanApplicationType(FOR);
        loanApplication.setAuditSchedule(ELE);
        loanApplication.setFileTime(DateUtils.getNowDate());

        //插入流程记录表
        LoanSchedule loanScheduleNew = new LoanSchedule();
        loanScheduleNew.setLoanApplicationId(loanApplication.getLoanApplicationId());
        loanScheduleNew.setLoanScheduleValue(loanApplication.getLoanSchedule());
        loanScheduleNew.setLoanScheduleScore(Long.parseLong(loanApplication.getLoanSchedule()));
        loanScheduleNew.setLoanScheduleTime(DateUtils.getNowDate());
        loanScheduleNew.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        loanScheduleMapper.insertLoanSchedule(loanScheduleNew);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath() + "/";
        Long loanApplicationId = loanApplication.getLoanApplicationId();
        //附件
        List<LoanApplicationFj> loanApplicationFjList = loanApplicationFjMapper.selectLoanApplicationFjByLoanApplicationId(loanApplicationId);
        //基础附件
        LoanApplication loanApplicationOld = loanApplicationMapper.selectLoanApplicationByLoanApplicationId(loanApplicationId);
        //股东附件
        List<ShareholderFj> shareholderFjs = shareholderFjMapper.selectShareholderFjLoanApplicationId(loanApplicationId);

        //反担保人附件
        List<GuaranteeInfoFj> guaranteeInfoFjs = guaranteeInfoFjMapper.selectGuaranteeInfoFjByLoanApplicationId(loanApplicationId);
        Map<File, Integer> map = new HashMap<>();
        List<File> fileList = new ArrayList<>();
        if (loanApplicationFjList != null && loanApplicationFjList.size() > 0) {
            for (LoanApplicationFj loanApplicationFj : loanApplicationFjList) {
                File file = new File(loanApplicationFj.getUrl().replace("/profile/upload/", filePath));
                map.put(file, FjType.getDriverType(loanApplicationFj.getType()));
            }
        }
        String corporationFront = loanApplicationOld.getCorporationFront();
        String corporationBack = loanApplicationOld.getCorporationBack();
        String spouseFront = loanApplicationOld.getSpouseFront();
        String spouseBack = loanApplicationOld.getSpouseBack();

        if (StringUtils.isNotEmpty(corporationFront)) {
            map.put(new File(corporationFront.replace("/profile/upload/", filePath)), FjType.getDriverType("frsfzrmx"));
        }
        if (StringUtils.isNotEmpty(corporationBack)) {
            map.put(new File(corporationBack.replace("/profile/upload/", filePath)), FjType.getDriverType("frsfzghm"));
        }
        if (StringUtils.isNotEmpty(spouseFront)) {
            map.put(new File(spouseFront.replace("/profile/upload/", filePath)), FjType.getDriverType("frsfzpormx"));
        }
        if (StringUtils.isNotEmpty(spouseBack)) {
            map.put(new File(spouseBack.replace("/profile/upload/", filePath)), FjType.getDriverType("frsfzpoghm"));
        }
        //进行排序
        List<Map.Entry<File, Integer>> list = new ArrayList<>(map.entrySet());
        // 根据 value 进行排序，这里使用了 lambda 表达式和比较器
        list.sort(Collections.reverseOrder(Map.Entry.comparingByValue()));
        for (Map.Entry<File, Integer> fileIntegerEntry : list) {
            fileList.add(fileIntegerEntry.getKey());
        }
        //股东附件
        if (shareholderFjs != null && shareholderFjs.size() > 0) {
            for (ShareholderFj shareholderFj : shareholderFjs) {
                fileList.add(new File(shareholderFj.getShareholderZxUrl().replace("/profile/upload/", filePath)));
                String shareholderFrontUrl = shareholderFj.getShareholderFrontUrl();
                String shareholderBackUrl = shareholderFj.getShareholderBackUrl();
                String shareholderBusinessUrl = shareholderFj.getShareholderBusinessUrl();
                if (StringUtils.isNotBlank(shareholderFrontUrl)) {
                    fileList.add(new File(shareholderFj.getShareholderFrontUrl().replace("/profile/upload/", filePath)));
                }
                if (StringUtils.isNotBlank(shareholderBackUrl)) {
                    fileList.add(new File(shareholderFj.getShareholderBackUrl().replace("/profile/upload/", filePath)));
                }
                if (StringUtils.isNotBlank(shareholderBusinessUrl)) {
                    fileList.add(new File(shareholderFj.getShareholderBusinessUrl().replace("/profile/upload/", filePath)));
                }
            }
        }

        if (guaranteeInfoFjs != null && guaranteeInfoFjs.size() > 0) {
            for (GuaranteeInfoFj guaranteeInfoFj : guaranteeInfoFjs) {
                fileList.add(new File(guaranteeInfoFj.getUrl().replace("/profile/upload/", filePath)));
            }
        }

        //16位序列号
        String id = Seq.getId(Seq.uploadSeqType);
        String name = StringUtils.format("{}_{}.{}",
                loanApplicationOld.getEnterpriseName(), id + "文档", "zip");
        String zipFileName = StringUtils.format("{}/{}_{}.{}", loanApplicationOld.getLoanApplicationNumber(),
                loanApplicationOld.getEnterpriseName(), id + "文档", "zip");
        //进行压缩
        zipEncryptExample(fileList, filePath, zipFileName, "123");
        //把压缩包的url插入附件表
        LoanApplicationFj loanApplicationFj = new LoanApplicationFj();
        loanApplicationFj.setLoanApplicationId(loanApplicationId);
        loanApplicationFj.setLoanApplicationNumber(loanApplicationOld.getLoanApplicationNumber());
        loanApplicationFj.setOldName(name);
        loanApplicationFj.setName(name);
        loanApplicationFj.setUrl("/profile/upload/" + loanApplicationOld.getLoanApplicationNumber() + "/" + name);
        loanApplicationFj.setBigType("e");
        loanApplicationFj.setCreateTime(DateUtils.getNowDate());
        loanApplicationFjMapper.insertLoanApplicationFj(loanApplicationFj);
        loanApplicationMapper.updateLoanApplication(loanApplication);

/*        //给A角色发送待办提醒
        //待办信息集合
        //查询审核管理员用户id
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectRoleListNoDataScope();
        List<WaitRemind> waitRemindList = new ArrayList<>();
        WaitRemind waitRemind = new WaitRemind();
        waitRemind.setLoanApplicationId(loanApplication.getLoanApplicationId());
        waitRemind.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        waitRemind.setRemindTitle("您有一条【" + loanApplication.getEnterpriseName() + "】的信息进入归档");
        waitRemind.setRemindTime(DateUtils.getNowDate());
        waitRemind.setRemindType(loanSchedule);
        waitRemind.setReadUserId(loanApplication.getaUserId().toString());
        waitRemind.setRemindContent(loanApplication.getEnterpriseName() + "的信息进入归档");
        waitRemindList.add(waitRemind);
        List<Long> userIdList = new ArrayList<>();
        if (sysUserRoles != null && sysUserRoles.size() > 0) {
            //极光推送
            userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());

            for (SysUserRole sysUserRole : sysUserRoles) {
                WaitRemind waitRemindManager = new WaitRemind();
                waitRemindManager.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindManager.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                waitRemindManager.setRemindTitle("有一条【" + loanApplication.getEnterpriseName() + "】的信息进入归档");
                waitRemindManager.setRemindTime(DateUtils.getNowDate());
                waitRemindManager.setRemindType(loanSchedule);
                waitRemindManager.setReadUserId(loanApplication.getaUserId().toString());
                waitRemindManager.setRemindContent(loanApplication.getEnterpriseName() + "的信息进入归档");
                //给管理员发送待办提醒
                waitRemindManager.setReadUserId(sysUserRole.getUserId().toString());
                waitRemindList.add(waitRemindManager);
            }
        }
        waitRemindMapper.batchWaitRemind(waitRemindList);*/

        //发极光推送id
        /*userIdList.add(loanApplication.getaUserId());
        List<SysUser> sysUsers = sysUserService.selectUserListByIdList(userIdList);
        if(sysUsers!=null && sysUsers.size()>0){
            String notificationTitle = "消息通知";
            String msgTitle = "信息归档";
            String msgContent = loanApplication.getEnterpriseName() + "的信息进入归档";
            String jPushVO = "";
            List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
            listS.removeAll(Collections.singleton(null));
            if(listS!=null && listS.size()>0){
                String[]  registrationId = listS.toArray(new String[listS.size()]);
                JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
            }
        }*/

        //业务审核意见
        ReviewComments reviewComments = new ReviewComments();
        reviewComments.setLoanApplicationId(loanApplication.getLoanApplicationId());
        reviewComments.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        //归档
        reviewComments.setAuditSchedule(ELE);
        reviewComments.setAuditType(TWO);
        reviewComments.setAuditTime(DateUtils.getNowDate());
        reviewComments.setCreateBy(SecurityUtils.getUsername());
        reviewCommentsMapper.insertReviewComments(reviewComments);
        return AjaxResult.success();
    }

    /**
     * 暂缓出具放款合规表-风险使用
     *
     * @param loanApplication
     * @return
     */
    @Override
    public AjaxResult zanHuan(LoanApplication loanApplication) {
        //删除所有状态小于的待办事项
        WaitRemind waitRemindDelete = new WaitRemind();
        waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
        waitRemindDelete.setReadUserId(loanApplication.getaUserId().toString());
        waitRemindDelete.setRemindType(EIG);
        waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
        WaitRemind waitRemind = new WaitRemind();
        waitRemind.setLoanApplicationId(loanApplication.getLoanApplicationId());
        waitRemind.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        waitRemind.setRemindTitle("您有一条风险部暂缓出具【" + loanApplication.getEnterpriseName() + "】放款合规表的申请");
        waitRemind.setRemindTime(DateUtils.getNowDate());
        waitRemind.setRemindType(EIG);
        //给A角色发送待办提醒
        waitRemind.setReadUserId(loanApplication.getaUserId().toString());
        //getRemark()风险部暂缓出具的原因
        waitRemind.setRemindContent(loanApplication.getRemark());
        waitRemindMapper.insertWaitRemind(waitRemind);
        //给管理员发送 = 查询所有role_key等于manager的账号
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectRoleListNoDataScope();
        if (sysUserRoles != null && sysUserRoles.size() > 0) {
            for (SysUserRole sysUserRole : sysUserRoles) {
                //删除所有状态小于的待办事项
                waitRemindDelete.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindDelete.setReadUserId(sysUserRole.getUserId().toString());
                waitRemindDelete.setRemindType(EIG);
                waitRemindMapper.deleteWaitRemindByLoanApplicationId(waitRemindDelete);
                WaitRemind waitRemindRole = new WaitRemind();
                waitRemindRole.setLoanApplicationId(loanApplication.getLoanApplicationId());
                waitRemindRole.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                waitRemindRole.setRemindTitle("您有一条风险部暂缓出具【" + loanApplication.getEnterpriseName() + "】放款合规表的申请");
                waitRemindRole.setRemindTime(DateUtils.getNowDate());
                waitRemindRole.setRemindType(EIG);
                //给管理员发送待办提醒
                waitRemindRole.setReadUserId(sysUserRole.getUserId().toString());
                //getRemark()风险部暂缓出具的原因
                waitRemindRole.setRemindContent(loanApplication.getRemark());
                waitRemindMapper.insertWaitRemind(waitRemindRole);
            }
            //发极光推送id
            //获取所有的userid
            List<Long> userIdList = sysUserRoles.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
            userIdList.add(loanApplication.getaUserId());
            List<SysUser> sysUsers = sysUserService.selectUserListByIdList(userIdList);
            if(sysUsers!=null && sysUsers.size()>0){
                String notificationTitle = "消息通知";
                String msgTitle = "放款合规表的申请";
                String msgContent = "您有一条风险部暂缓出具【" + loanApplication.getEnterpriseName() + "】放款合规表的申请";
                String jPushVO = "";
                List<String> listS = sysUsers.stream().map(SysUser::getJgId).collect(Collectors.toList());
                listS.removeAll(Collections.singleton(null));
                if(listS!=null && listS.size()>0){
                    String[]  registrationId = listS.toArray(new String[listS.size()]);
                    JPushToolUtil.sendToRegistrationId(notificationTitle,msgTitle,msgContent,jPushVO,registrationId);
                }
            }

        }
        return AjaxResult.success();
    }

    /**
     * 管理员授权A角色开具放款通知书
     */
    @Override
    public AjaxResult authorize(LoanApplication loanApplication) {
        loanApplication.setLoanSchedule(NIN);
        loanApplication.setaAuthorize(Y);
        loanApplicationMapper.updateLoanApplication(loanApplication);
        return AjaxResult.success();
    }

    /**
     * 压缩文件，返回地址
     *
     * @param fileList    源文件或目录路径
     * @param zipPathDir  ZIP文件输出路径
     * @param zipFileName ZIP文件名称
     * @param password    加密密码
     * @return
     */
    public void zipEncryptExample(List<File> fileList, String zipPathDir, String zipFileName, String password) {
        String zipFilePath = zipPathDir + "/" + zipFileName;
        ZipOutputStream out = null;
        BufferedOutputStream bo = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFilePath));

            bo = new BufferedOutputStream(out);
            for (File file : fileList) {
                if (file.exists()) {
                    ZipEntry zipEntry = new ZipEntry(file.getName());

                    out.putNextEntry(zipEntry);

                    FileInputStream in = new FileInputStream(file);

                    BufferedInputStream bi = new BufferedInputStream(in);
                    int b;
                    while ((b = bi.read()) != -1) {
                        bo.write(b);
                    }
                    bo.flush();
                    bi.close();
                    in.close();
                }
            }
            bo.close();
            out.close();
            System.out.println("文件保存位置：" + zipFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出模板附件
     */
    @Override
    public AjaxResult exportMb(LoanApplication loanApplication) {
        Map<String, Object> map = new HashMap<>();
        //导出的附件
        String type = loanApplication.getType();
        //附件小类
        String fileType = loanApplication.getFileType();
        //附件大类
        String bigType = loanApplication.getBigType();
        if (loanApplication.getLoanApplicationId() != null && loanApplication.getLoanApplicationId() != 0L) {
            loanApplication = loanApplicationMapper.selectLoanApplicationByLoanApplicationId(loanApplication.getLoanApplicationId());
            loanApplication.setType(type);
            //判断附件存不存在
            LoanApplicationFj loanApplicationFj = new LoanApplicationFj();
            loanApplicationFj.setLoanApplicationId(loanApplication.getLoanApplicationId());
            loanApplicationFj.setType(fileType);
            List<LoanApplicationFj> loanApplicationFjs = loanApplicationFjMapper.selectLoanApplicationFjList(loanApplicationFj);
            if (loanApplicationFjs != null && loanApplicationFjs.size() > 0) {
                for (LoanApplicationFj applicationFj : loanApplicationFjs) {
                    redisCache.setCacheObject(applicationFj.getFjId() + "info", applicationFj, 2, TimeUnit.HOURS);
                    map.put("fileId", applicationFj.getFjId());
                    map.put("path", applicationFj.getUrl());
                    map.put("fileName", applicationFj.getName());
                    return AjaxResult.success(map);
                }
            }
        }
        String loanApplicationNumber = loanApplication.getLoanApplicationNumber();
        // 向word中添加数据
        Map<String, Object> params = new HashMap<>();
        // 向列表中添加数据
        Map<String, Object> excelMap = new HashMap<>();
        //获取当前年、月、日
        String year = DateUtils.getYear();
        String month = DateUtils.getMonth();
        String day = DateUtils.getDay();
        params.put("year", year);
        params.put("month", month);
        params.put("day", day);

        String path = "/profile/mb/temporarily/" + loanApplicationNumber;
        //查询公司信息
        SysUserEnterprise sysUserEnterprise = sysUserEnterpriseMapper.selectSysUserEnterpriseByEnterpriseId(loanApplication.getEnterpriseId());
        params.put("loanApplication", loanApplication);
        params.put("sysUserEnterprise", sysUserEnterprise);
        //查询银行名称
        String backName = dictDataMapper.selectDictLabel("shendai_bank", loanApplication.getApplicationBank());
        params.put("backName", backName);
        //将贷款金额转成中文
        String chineseNum = loanApplication.getLoanApplicationNumber();
        if (StringUtils.isNumeric(loanApplication.getLoanApplicationNumber())) {
            chineseNum = StringUtils.convert(Integer.parseInt(loanApplication.getLoanApplicationNumber()));
        }
        params.put("chineseNum", chineseNum);

        String templatePath = RuoYiConfig.getProfile();
        String fileDir = RuoYiConfig.getProfile();
        String fileName = "";
        String fileNameHz = "";
        String wordPath = "";
        String sheet = "";
        //生成二维码
        String ewmPath = RuoYiConfig.getProfile() + "/mb/ewm";
        JSONObject json = new JSONObject();
        json.put("type", "2");
        json.put("loanApplicationNumber", loanApplication.getLoanApplicationNumber());
        json.put("bigType", bigType);
        json.put("fileType", fileType);
        String imagePath = null;
        try {
            imagePath = QRCodeUtils.encodeNodate(json.toString(), null, ewmPath, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(imagePath)) {
            PictureRenderData picture = Pictures.ofLocal(imagePath).size(70, 70).create();//本地图片地址
            params.put("signPicture", picture);
        }

        SysUserConference userConference = new SysUserConference();

        LoanApplicationFj loanApplicationFjTzs = new LoanApplicationFj();

        // 创建一个列表，用来存储要填充到Excel中的数据
        List<Map<String, Object>> list = new ArrayList<>();
        switch (type) {
            case "1":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/委托担保申请书.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("委托担保申请书");
                fileName = loanApplication.getEnterpriseName() + "-委托担保申请书";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "2":
                params.put("enterpriseAddres", sysUserEnterprise.getEnterpriseAddress());
                params.put("corporationPhone", loanApplication.getCorporationPhone());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/委托保证合同.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("委托担保申请书");
                fileName = loanApplication.getEnterpriseName() + "-委托担保申请书";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "3":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = templatePath + "/mb/担保意向函.docx";
                fileDir = fileDir + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("担保意向函");
                fileName = loanApplication.getEnterpriseName() + "-担保意向函";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "4":
                //查询借据附件
                loanApplicationFjTzs.setLoanApplicationId(loanApplication.getLoanApplicationId());
                loanApplicationFjTzs.setType("jj");
                List<LoanApplicationFj> loanApplicationFjs = loanApplicationFjMapper.selectLoanApplicationFjList(loanApplicationFjTzs);
                if (loanApplicationFjs != null && loanApplicationFjs.size() > 0) {
                    loanApplicationFjTzs = loanApplicationFjs.get(0);
                }

                //查询最新的一条投票数据
                userConference = sysUserConferenceMapper.selectSysUserConferenceNew(loanApplication.getLoanApplicationId());
                //将贷款金额转成中文
                if (ObjectUtils.isNotEmpty(userConference.getLineGuarantee())) {
                    chineseNum = userConference.getLineGuarantee();
                }
                params.put("chineseNum", chineseNum);
                if (StringUtils.isNotEmpty(loanApplicationFjTzs.getUrl())) {
                    // 上传文件路径
                    String filePath = RuoYiConfig.getUploadPath();
                    //服务器路径
                    String urlOnline = filePath + loanApplicationFjTzs.getUrl().replace("/profile/upload", "");
                    //百度图片识别
                    Map<String, Object> imgMap = IdCardUtil.accurateBasicCj(urlOnline);
                    if (map != null || map.size() != 0) {
                        params.put("dkdw", imgMap.get("dkdw"));
                        params.put("jkr", imgMap.get("jkr"));
                        //params.put("jkje", imgMap.get("jkje"));
                        params.put("jkytsm", imgMap.get("jkytsm"));
                        params.put("hksj", imgMap.get("hksj"));
                    }
                }

                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/放款（出票）通知书.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("放款（出票）通知书");
                fileName = loanApplication.getEnterpriseName() + "-放款（出票）通知书";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "5":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/保证反担保合同（适用于法人).docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("保证反担保合同（适用于法人)");
                fileName = loanApplication.getEnterpriseName() + "-保证反担保合同（适用于法人)";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "6":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/保证反担保合同（适用于自然人）.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("保证反担保合同（适用于自然人）");
                fileName = loanApplication.getEnterpriseName() + "-保证反担保合同（适用于自然人）";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "7":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/抵押反担保合同（适用于法人）.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("抵押反担保合同（适用于法人）");
                fileName = loanApplication.getEnterpriseName() + "-抵押反担保合同（适用于法人）";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "8":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/抵押反担保合同（适用于自然人）.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("抵押反担保合同（适用于自然人）");
                fileName = loanApplication.getEnterpriseName() + "-抵押反担保合同（适用于自然人）";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "9":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/权利质权反担保合同（适用于法人）.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("权利质权反担保合同（适用于法人）");
                fileName = loanApplication.getEnterpriseName() + "-权利质权反担保合同（适用于法人）";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "10":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/权利质权反担保合同（适用于自然人）.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("权利质权反担保合同（适用于自然人）");
                fileName = loanApplication.getEnterpriseName() + "-权利质权反担保合同（适用于自然人）";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "11":
                //判断有多少公司  股东、反担保人

                params.put("gsName", loanApplication.getEnterpriseName());
                params.put("bgs", "本公司");
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/股东会决议.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("股东会决议");
                fileName = loanApplication.getEnterpriseName() + "-股东会决议";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";

                //生成股东公司的股东会决议
                ShareholderFj shareholderFj = new ShareholderFj();
                shareholderFj.setLoanApplicationId(loanApplication.getLoanApplicationId());
                List<ShareholderFj> shareholderFjs = shareholderFjMapper.selectShareholderFjList(shareholderFj);
                int index = 1;
                if (shareholderFjs != null && shareholderFjs.size() > 0) {
                    for (ShareholderFj fj : shareholderFjs) {
                        if (StringUtils.isNotEmpty(fj.getShareholderBusinessUrl())) {
                            params.put("gsName", fj.getShareholderName());
                            params.put("bgs", loanApplication.getEnterpriseName());

                            fileDir = RuoYiConfig.getProfile() + "/" + loanApplicationNumber;
                            //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("股东会决议");
                            fileName = fj.getShareholderName() + "-股东会决议" + index;
                            //fileNameHz = fileName + ".docx";
                            wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                            //将文件存入loan_application_fj表
                            LoanApplicationFj loanApplicationFj = new LoanApplicationFj();
                            loanApplicationFj.setLoanApplicationId(loanApplication.getLoanApplicationId());
                            loanApplicationFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                            loanApplicationFj.setOldName(fileName + ".docx");
                            loanApplicationFj.setName(fileName + ".docx");
                            loanApplicationFj.setUrl(RuoYiConfig.getUploadPath() + "/" + loanApplicationNumber + "/" + fileName + ".docx");
                            loanApplicationFj.setBigType(bigType);
                            loanApplicationFj.setType(fileType);
                            loanApplicationFj.setCreateTime(DateUtils.getNowDate());
                            loanApplicationFjMapper.insertLoanApplicationFj(loanApplicationFj);
                            index++;
                        }
                    }

                }
                //生成反担保公司的股东会决议
                GuaranteeInfo guaranteeInfo = new GuaranteeInfo();
                guaranteeInfo.setLoanApplicationId(loanApplication.getLoanApplicationId());
                guaranteeInfo.setType("2");
                List<GuaranteeInfo> guaranteeInfos = guaranteeInfoMapper.selectGuaranteeInfoList(guaranteeInfo);
                if (guaranteeInfos != null && guaranteeInfos.size() > 0) {
                    for (GuaranteeInfo info : guaranteeInfos) {
                        params.put("gsName", info.getGuaranteeName());
                        params.put("bgs", loanApplication.getEnterpriseName());

                        fileDir = RuoYiConfig.getProfile() + "/" + loanApplicationNumber;
                        //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("股东会决议");
                        fileName = info.getGuaranteeName() + "-股东会决议" + index;
                        //fileNameHz = fileName + ".docx";
                        wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                        //将文件存入loan_application_fj表
                        LoanApplicationFj loanApplicationFj = new LoanApplicationFj();
                        loanApplicationFj.setLoanApplicationId(loanApplication.getLoanApplicationId());
                        loanApplicationFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
                        loanApplicationFj.setOldName(fileName + ".docx");
                        loanApplicationFj.setName(fileName + ".docx");
                        loanApplicationFj.setUrl(RuoYiConfig.getUploadPath() + "/" + loanApplicationNumber + "/" + fileName + ".docx");
                        loanApplicationFj.setBigType(bigType);
                        loanApplicationFj.setType(fileType);
                        loanApplicationFj.setCreateTime(DateUtils.getNowDate());
                        loanApplicationFjMapper.insertLoanApplicationFj(loanApplicationFj);
                        index++;
                    }

                }

                break;
            case "12":

                //申请人名称
                excelMap.put("sqr", loanApplication.getEnterpriseName() + "   " + loanApplication.getCorporationName());
                //公司住址
                excelMap.put("address", sysUserEnterprise.getEnterpriseAddress());
                //家庭住址
                excelMap.put("fraddress", loanApplication.getCorporationAddress());
                //申请金额
                excelMap.put("sqje", loanApplication.getApplicationAmount());
                //申请期限
                excelMap.put("sqqx", loanApplication.getUsagePeriod());
                //申请银行
                excelMap.put("bank", loanApplication.getApplicationBank());
                //还款方式
                excelMap.put("hkfs", loanApplication.getRepaymentSource());
                //参会日期
                String timeData = loanApplication.getReviewTime().split(" ")[0];
                String[] split = timeData.split("-");
                excelMap.put("year", split[0]);
                excelMap.put("month", split[1]);
                excelMap.put("day", split[2]);
                //查询投票信息
                excelMap.put("ty", "");
                excelMap.put("fj", "");
                excelMap.put("qx", "");
                int ty = 0;
                int fj = 0;
                int qx = 0;

                userConference.setConferenceTime(loanApplication.getReviewTime());
                userConference.setLoanApplicationId(loanApplication.getLoanApplicationId());
                List<SysUserConference> userConferences = sysUserConferenceMapper.selectSysUserConferenceList(userConference);
                if (userConferences != null && userConferences.size() > 0) {
                    for (SysUserConference conference : userConferences) {
                        if ("Y".equals(conference.getVotingResult())) {
                            ty++;
                        } else if ("N".equals(conference.getVotingResult())) {
                            fj++;
                        } else {
                            qx++;
                        }
                    }
                    excelMap.put("ty", ty);
                    excelMap.put("fj", fj);
                    excelMap.put("qx", qx);
                }
                //贷款金额
                excelMap.put("je", loanApplication.getActuallyAmount());
                //贷款期限
                list.add(excelMap);
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("项目评审意见签批表");
                fileName = loanApplication.getEnterpriseName() + "-项目评审意见签批表";
                fileNameHz = fileName + ".xlsx";
                templatePath = RuoYiConfig.getProfile() + "/mb/项目评审意见签批表.xlsx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber + "/" + fileNameHz;
                sheet = ExcelFillUtils.fillOneSheet(templatePath, fileDir, "Sheet1", list);

                path = path + "/" + fileNameHz;
                break;
            case "13":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/担保项目合法合规表企业.xlsx";
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("担保项目合法合规表企业");
                fileName = loanApplication.getEnterpriseName() + "-担保项目合法合规表企业";
                if ("2".equals(loanApplication.getApplicationType())) {
                    templatePath = RuoYiConfig.getProfile() + "/mb/担保项目合法合规表个人个体户.xlsx";
                    //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("担保项目合法合规表个人个体户");
                    fileName = loanApplication.getEnterpriseName() + "-担保项目合法合规表个人个体户";
                }
                fileNameHz = fileName + ".xlsx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber + "/" + fileNameHz;
                sheet = ExcelFillUtils.fillOneSheet(templatePath, fileDir, "Sheet1", list);
                path = path + "/" + fileNameHz;
                break;
            case "14":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/放款审批合规表企业.xlsx";
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("放款审批合规表企业");
                fileName = loanApplication.getEnterpriseName() + "-放款审批合规表企业";
                if ("2".equals(loanApplication.getApplicationType())) {
                    templatePath = RuoYiConfig.getProfile() + "/mb/放款审批合规表个人个体户.xlsx";
                    //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("放款审批合规表个人个体户");
                    fileName = loanApplication.getEnterpriseName() + "-放款审批合规表个人个体户";
                }
                fileNameHz = fileName + ".xlsx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber + "/" + fileNameHz;
                sheet = ExcelFillUtils.fillOneSheet(templatePath, fileDir, "Sheet1", list);
                path = path + "/" + fileNameHz;
                break;
            case "15":
                //查询评审人员信息
                //查询所有人员的投票结果
                SysUserConference sysUserConference = new SysUserConference();
                sysUserConference.setLoanApplicationId(loanApplication.getLoanApplicationId());
                sysUserConference.setConferenceTime(loanApplication.getReviewTime());
                List<SysUserConference> sysUserConferences = sysUserConferenceMapper.selectSysUserConferenceList(sysUserConference);
                //拼接姓名
                StringBuilder sb = new StringBuilder();
                for (SysUserConference userConference1 : sysUserConferences) {
                    if (sb.length() > 0) {
                        sb.append("  ").append(userConference1.getRealName());
                    } else {
                        sb.append(userConference1.getRealName());
                    }

                }
                //评审会时间
                params.put("time", loanApplication.getReviewTime());
                //评审会公司
                params.put("enterpriseName", loanApplication.getEnterpriseName());
                //评审会人员
                params.put("user", sb.toString());
                //path = path + "/委托担保申请书.doc";
                templatePath = templatePath + "/mb/评审会通知.docx";
                fileDir = fileDir + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("担保意向函");
                fileName = loanApplication.getEnterpriseName() + "-评审会通知";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "16":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/不可撤销个人连带责任信用反担保合同.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("委托担保申请书");
                fileName = loanApplication.getEnterpriseName() + "-不可撤销个人连带责任信用反担保合同";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "17":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/委托保证合同（工程履约）.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("委托担保申请书");
                fileName = loanApplication.getEnterpriseName() + "-委托保证合同（工程履约）";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "18":
                //params.put("enterpriseName", loanApplication.getEnterpriseName());
                //path = path + "/委托担保申请书.doc";
                templatePath = RuoYiConfig.getProfile() + "/mb/企业信用反担保合同.docx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber;
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("委托担保申请书");
                fileName = loanApplication.getEnterpriseName() + "-企业信用反担保合同";
                fileNameHz = fileName + ".docx";
                wordPath = WordUtil.createWord(templatePath, fileDir, fileName, params);
                path = path + "/" + fileName + ".docx";
                break;
            case "19":
                //申请人名称
                excelMap.put("sqr", loanApplication.getEnterpriseName());
                //申请金额
                excelMap.put("sqje", loanApplication.getActuallyAmount());
                //申请期限
                excelMap.put("sqqx", loanApplication.getUsagePeriod());
                //申请银行
                excelMap.put("bank", loanApplication.getApplicationBank());
                list.add(excelMap);
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("项目评审意见签批表");
                fileName = loanApplication.getEnterpriseName() + "-t+1保后首次检查报告";
                fileNameHz = fileName + ".xlsx";
                templatePath = RuoYiConfig.getProfile() + "/mb/t+1保后首次检查报告.xlsx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber + "/" + fileNameHz;
                sheet = ExcelFillUtils.fillOneSheet(templatePath, fileDir, "Sheet1", list);

                path = path + "/" + fileNameHz;
                break;
            case "20":
                //申请人名称
                excelMap.put("sqr", loanApplication.getEnterpriseName());
                //申请金额
                excelMap.put("sqje", loanApplication.getActuallyAmount());
                //申请期限
                excelMap.put("sqqx", loanApplication.getUsagePeriod());
                //申请银行
                excelMap.put("bank", loanApplication.getApplicationBank());
                list.add(excelMap);
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("项目评审意见签批表");
                fileName = loanApplication.getEnterpriseName() + "-T+N保后检查报告";
                fileNameHz = fileName + ".xlsx";
                templatePath = RuoYiConfig.getProfile() + "/mb/T+N保后检查报告.xlsx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber + "/" + fileNameHz;
                sheet = ExcelFillUtils.fillOneSheet(templatePath, fileDir, "Sheet1", list);

                path = path + "/" + fileNameHz;
                break;
                //todo  担保业务备案表
            case "21":

                //分支行
                excelMap.put("fzh", "");
                //总行
                excelMap.put("zh", "");
                //起始日期
                excelMap.put("qsrq", "");
                //到期日期
                excelMap.put("dqrq", "");
                //贷款利率
                excelMap.put("dklv", "");
                //所属行业
                excelMap.put("sshy", "");
                excelMap.put("zzqje", "");

                //查询借据附件
                loanApplicationFjTzs.setLoanApplicationId(loanApplication.getLoanApplicationId());
                loanApplicationFjTzs.setType("jj");
                List<LoanApplicationFj> loanApplicationFjList = loanApplicationFjMapper.selectLoanApplicationFjList(loanApplicationFjTzs);
                if(loanApplicationFjList!=null && loanApplicationFjList.size()>0){
                    loanApplicationFjTzs = loanApplicationFjList.get(0);
                }

                if(StringUtils.isNotEmpty(loanApplicationFjTzs.getUrl())){
                    // 上传文件路径
                    String filePath = RuoYiConfig.getUploadPath();
                    //服务器路径
                    String urlOnline = filePath + loanApplicationFjTzs.getUrl().replace("/profile/upload", "");
                    //百度图片识别
                    Map<String, Object> imgMap = IdCardUtil.accurateBasicCj(urlOnline);
                    if (map != null || map.size() != 0) {

                        //分支行
                        excelMap.put("fzh", imgMap.get("dkdw"));
                        //总行
                        excelMap.put("zh", imgMap.get("zh"));
                        //起始日期
                        excelMap.put("qsrq", imgMap.get("qxr"));
                        //到期日期
                        excelMap.put("dqrq", imgMap.get("dqr"));
                        //贷款利率
                        excelMap.put("dklv", imgMap.get("dklv"));
                    }
                }

                //所属行业
                excelMap.put("sshy", loanApplication.getCategoryType());
                //主债权金额
                //查询最新的一条投票数据
                userConference = sysUserConferenceMapper.selectSysUserConferenceNew(loanApplication.getLoanApplicationId());

                excelMap.put("zzqje", userConference.getLineGuarantee());
                //债务人名称
                excelMap.put("zwrmc", loanApplication.getEnterpriseName());
                //法定代表人姓名
                excelMap.put("fddbrxm", loanApplication.getCorporationName());
                //法定代表人证件号码
                excelMap.put("fddbrzjhm", loanApplication.getCorporationIdCard());


                list.add(excelMap);
                //fileName = FileUploadUtils.extractFilenameLoanApplicationNumberNoHzm("项目评审意见签批表");
                fileName = loanApplication.getEnterpriseName() + "-担保业务备案表";
                fileNameHz = fileName + ".xlsx";
                templatePath = RuoYiConfig.getProfile() + "/mb/担保业务备案表.xlsx";
                fileDir = RuoYiConfig.getProfile() + "/mb/temporarily/" + loanApplicationNumber + "/" + fileNameHz;
                sheet = ExcelFillUtils.fillOneSheet(templatePath, fileDir, "Sheet1", list);

                path = path + "/" + fileNameHz;
                break;
            default:
                break;
        }
        //删除二维码
        File file = new File(imagePath);
        file.delete();

        LoanApplicationFj applicationFj = new LoanApplicationFj();
        applicationFj.setLoanApplicationId(loanApplication.getLoanApplicationId());
        applicationFj.setType(fileType);
        applicationFj.setBigType(bigType);
        applicationFj.setLoanApplicationNumber(loanApplication.getLoanApplicationNumber());
        applicationFj.setName(fileNameHz);
        applicationFj.setUrl(path);
        String fileId = IdUtils.fastSimpleUUID();
        redisCache.setCacheObject(fileId + "info", applicationFj, 2, TimeUnit.HOURS);
        LoanApplicationFj application = redisCache.getCacheObject(fileId + "info");

        map.put("fileId", fileId);
        map.put("path", path);
        map.put("fileName", fileNameHz);
        return AjaxResult.success(map);
    }

    private String contrastType(String type) {
        String fileType = "";
        switch (type) {
            case "1":
                fileType = "wtdbsqs";
                break;
            case "2":
                fileType = "wtdbht";
                break;
            case "3":
                fileType = "dbyxh";
                break;
            case "4":
                fileType = "fktzhsh";
                break;
            case "5":
                fileType = "bzfdbhtfr";
                break;
            case "6":
                fileType = "bzfdbhtzrr";
                break;
            case "7":
                fileType = "dyfdbhtfr";
                break;
            case "8":
                fileType = "dyfdbhtzrr";
                break;
            case "9":
                fileType = "27";
                break;
            case "10":
                fileType = "27";
                break;
            case "11":
                fileType = "gdhyjy";
                break;
            case "12":
                fileType = "psyjqpb";
                break;
            case "13":
                fileType = "clhgb";
                break;
            default:
                fileType = "fkhgb";
                break;
        }
        return fileType;
    }

   /* public static void main(String[] args) {

        *//*File file = new File("D:\\尽职调查报告4.doc");
        FileInputStream fis = null;
        XWPFDocument document = null;
        XWPFWordExtractor extractor = null;
        try {
            fis = new FileInputStream(file);
            document = new XWPFDocument(fis);
            extractor = new XWPFWordExtractor(document);
            System.out.println(extractor.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }*//*

        try {
            FileInputStream fis = new FileInputStream(new File("D:\\尽职调查报告4.doc"));
            HWPFDocument document = new HWPFDocument(fis);
            Range range = document.getRange();
            String text = range.text();
            System.out.println("11111");
            System.out.println(range.text());
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }*/

    /*public static void main(String[] args) {
        String pdfPath = "D:\\240809182122A151.pdf";
        System.out.println(Text2PdfUtil.readPDF(pdfPath));
        *//*Map<String, Object> imgMap = IdCardUtil.accurateBasicCj("D:\\240809182122A151.pdf");
        System.out.println(imgMap.toString());*//*
    }*/


}
