package com.jeeplus.assess.reimbursement.reimbursementInfo.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.assess.reimbursement.reimbursementInfo.service.dto.*;
import com.jeeplus.assess.workContract.mapper.WorkContractInfoMapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.*;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.assess.program.configuration.projectList.domain.ProgramProjectListInfo;
import com.jeeplus.assess.program.configuration.projectList.domain.ProgramReportNo;
import com.jeeplus.assess.program.configuration.projectList.mapper.ProgramReportNoMapper;
import com.jeeplus.assess.program.configuration.projectList.mapper.ProjectListMapper;
import com.jeeplus.assess.reimbursement.reimbursementInfo.domain.*;
import com.jeeplus.assess.reimbursement.reimbursementInfo.mapper.*;
import com.jeeplus.assess.workContract.service.WorkContractService;
import com.jeeplus.assess.workContract.service.dto.WorkContractInfoDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReimbursementInfoService {

    @Resource
    private ReimbursementInfoMapper infoMapper;

    @Resource
    private ReimbursementDetailInfoMapper detailInfoMapper;

    @Resource
    private ReimbursementAmountInfoMapper amountInfoMapper;

//    @Resource
//    private OssServiceMapper ossServiceMapper;

//    @Resource
//    private SerialnumTplService serialnumTplService;

    @Resource
    private WorkContractService workContractService;

//    @Autowired
//    private OfficeMapper officeMapper;

    @Autowired
    private ReimbursementDetailInfoContractMapper reimbursementDetailInfoContractMapper;

    @Autowired
    private ReimbursementDetailInfoOtherMapper reimbursementDetailInfoOtherMapper;

    @Autowired
    private ReimbursementDetailInfoProcuredMapper reimbursementDetailInfoProcuredMapper;

    @Resource
    private IFlowableApi flowTaskService;

    @Autowired
    private IFlowableApi taskService;

    @Resource
    private ProjectListMapper projectListMapper;

    @Resource
    private ProgramReportNoMapper programReportNoMapper;

    @Resource
    private ReimbursementInfoUpHiMapper reimbursementInfoUpHiMapper;

    @Resource
    private ReimbursementFileSupplementMapper reimbursementFileSupplementMapper;

    @Resource
    private WorkContractInfoMapper mapper;
    /**
     * 列表查询
     */
    public IPage<RetureListDto> list(Page<RetureListDto> page , QueryListDto dto,Boolean isExport) throws Exception{
        IUserApi userApi = SpringUtil.getBean(IUserApi.class);
        IOfficeApi officeApi = SpringUtil.getBean(IOfficeApi.class);
        QueryWrapper<QueryListDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, QueryListDto.class);
        /**
         * a表是reimbursementInfo
         * b表是reimbursementDetailInfo
         * c表是sysUser
         */
        queryWrapper.eq("a.del_flag", 0);
        // 报销项目
        if (StringUtils.isNotEmpty(dto.getProject())) {
            queryWrapper.apply("((b.project_id LIKE {0} OR b.project_name LIKE {1})", "%" + dto.getProject() + "%", "%" + dto.getProject() + "%");
            queryWrapper.or().apply("(b4.project_id = {0} OR b4.project_name LIKE {1})", dto.getProject(), "%" + dto.getProject() + "%");
            queryWrapper.or().apply("(b5.project_id = {0} OR b5.project_name LIKE {1}))", dto.getProject(), "%" + dto.getProject() + "%");

        }
        // 报销时间 - 根据综合管理部主任角色审核时间筛选
        if (dto.getDates() != null && dto.getDates().length > 0) {
            queryWrapper.apply("ht_role.end_time >= {0}", dto.getDates()[0] + " 00:00:00");
            queryWrapper.apply("ht_role.end_time <= {0}", dto.getDates()[1] + " 23:59:59");
        }
        // 经办人
        if (StringUtils.isNotEmpty(dto.getHandled())) {
            queryWrapper.apply("(a.create_by_id = {0} OR c.name LIKE {1})", dto.getHandled(), "%" + dto.getHandled() + "%");
        }
        // 报销人
        if (com.jeeplus.utils.StringUtils.isNotEmpty(dto.getReimBy())) {
            List<User> users = userApi.findListByLikeName(dto.getReimBy());
            if (users == null || users.isEmpty()) {
                queryWrapper.apply("1 = 0");
            } else {
                queryWrapper.and(qw -> {
                    for (User u : users) {
                        qw.or(orQw -> orQw
                                .like("b.user_id", u.getId())
                                .or().like("b2.user_id", u.getId())
                                .or().like("b4.user_id", u.getId())
                                .or().like("b5.user_id", u.getId())
                                .or().like("us.name", dto.getReimBy())
                                .or().like("us2.name", dto.getReimBy())
                                .or().like("us4.name", dto.getReimBy())
                                .or().like("us5.name", dto.getReimBy())
                        );
                    }
                });
            }
        }
        // 报销状态
        if (StringUtils.isNotEmpty(dto.getType())) {
            queryWrapper.eq("a.type", dto.getType());
        }
        // 报销项状态
        if (StringUtils.isNotEmpty(dto.getReimbursementType())) {
            queryWrapper.eq("a.reimbursement_type", dto.getReimbursementType());
        }
        // 报销部门
        if (StringUtils.isNotEmpty(dto.getDepartment())) {
            OfficeDTO officeDto = officeApi.getOfficeByName(dto.getDepartment());
            queryWrapper.apply("(( b.dept_id like {0} OR so.name LIKE {1} )", "%" + officeDto.getId()+ "%", "%" + dto.getDepartment() + "%");
            queryWrapper.or().apply("( b2.dept_id like {0} OR so2.name LIKE {1} )", "%" + officeDto.getId()+ "%", "%" + dto.getDepartment() + "%");
            queryWrapper.or().apply("( b4.dept_id like {0} OR so4.name LIKE {1} )", "%" + officeDto.getId()+ "%", "%" + dto.getDepartment() + "%");
            queryWrapper.or().apply("( b5.dept_id like {0} OR so5.name LIKE {1} ))", "%" + officeDto.getId()+ "%", "%" + dto.getDepartment() + "%");

        }
        // 报销类别
        if (StringUtils.isNotEmpty(dto.getRemiType())) {
            queryWrapper.apply(" ((b.type_id = {0} OR t.name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b2.type_id = {0} OR t2.name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b4.type_id = {0} OR t4.name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b5.type_id = {0} OR t5.name LIKE {1})) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");

        }
        // 报销金额
        if (dto.getAmounts() != null) {
            if (StringUtils.isNotEmpty(dto.getAmounts()[0])) {
                queryWrapper.and(w->
                    w.ge("b.number", Double.parseDouble(dto.getAmounts()[0]))
                        .or().ge("b2.number", Double.parseDouble(dto.getAmounts()[0]))
                        .or().ge("b4.number", Double.parseDouble(dto.getAmounts()[0]))
                        .or().ge("b5.number", Double.parseDouble(dto.getAmounts()[0]))
                );
            }
            if (StringUtils.isNotEmpty(dto.getAmounts()[1])) {
                queryWrapper.and(w->
                        w.le("b.number", Double.parseDouble(dto.getAmounts()[1]))
                                .or().le("b2.number", Double.parseDouble(dto.getAmounts()[1]))
                                .or().le("b4.number", Double.parseDouble(dto.getAmounts()[1]))
                                .or().le("b5.number", Double.parseDouble(dto.getAmounts()[1]))
                );
            }
        }
        // 报告号
        if (StringUtils.isNotEmpty(dto.getReportNumber())) {
            queryWrapper.like("(b.report_number", dto.getReportNumber());
            queryWrapper.or().like("b2.report_number", dto.getReportNumber());
            queryWrapper.or().like("b4.report_number", dto.getReportNumber());
            queryWrapper.or().like("b5.report_number)", dto.getReportNumber());
        }
        // 报销类型
        if (StringUtils.isNotBlank(dto.getSourceType())) {
            queryWrapper.eq("a.source_type", dto.getSourceType());
        }
        // 报销编号
        if (StringUtils.isNotEmpty(dto.getNo())) {
            queryWrapper.like("a.no", dto.getNo());
        }
        // 付款状态
        if (com.jeeplus.utils.StringUtils.isNotEmpty(dto.getPaymentStatus())) {
            queryWrapper.like("a.payment_status", dto.getPaymentStatus());
        }
        // 发票号
        if (com.jeeplus.utils.StringUtils.isNotEmpty(dto.getFinanceNumber())) {
            queryWrapper.inSql("a.id","SELECT info_id FROM reimbursement_amount_info WHERE number = '"+ dto.getFinanceNumber() +"' AND del_flag = 0");
        }
        //获取当前登录人信息
        /*UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        //获取当前登录人所属角色
        //若是评估部门主任，则仅展示部门主任信息
        //若是评估员工，则仅展示自己的数据信息
        List<RoleDTO> roleDTOList = userDTO.getRoleDTOList();
        for (RoleDTO roleDTO : roleDTOList) {
            //根据角色id查询角色信息
            RoleDTO roleDTOById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
            if("yg".equals(roleDTOById.getEnName()) && "评估员工".equals(roleDTOById.getName())){
                queryWrapper.eq("a.create_by_id", userDTO.getId());
                break;
            }else if("bmzr".equals(roleDTOById.getEnName()) && "评估部门主任".equals(roleDTOById.getName())){
                queryWrapper.eq("c.office_id", userDTO.getOfficeDTO().getId());
                break;
            }
        }*/



        IPage<RetureListDto> pageList = infoMapper.findList(page, queryWrapper);
        if (!isExport){
            pageList.getRecords().stream().forEach(item -> {
                // 报销申请
                if (StringUtils.isNotBlank(item.getTaskId()) && StringUtils.isNotBlank(item.getType())) {
                    if ("2".equals(item.getType())) { // “审核中”的数据要获取数据审核人
                        item.setAuditUserIds(flowTaskService.getTaskAuditUsers(item.getTaskId()));  // 获取数据审核人
                        String currentTaskName = flowTaskService.getCurrentTaskName(item.getProcInsId());
                        if (item.getType().equals("2") && com.jeeplus.utils.StringUtils.isNotBlank(currentTaskName) && !currentTaskName.contains("综合管理部主任") && !currentTaskName.contains("部门主任")){
                            item.setApplyFile(true);
                        }
                    }
                }

                if (StringUtils.isNotBlank(item.getSourceType()) && "1".equals(item.getSourceType())) { //项目报销
                    if (StringUtils.isNotBlank(item.getProjectId())) {
                        String proName = selectProjectByIds(item.getProjectId());
                        item.setProjectName(proName);
                        String reportNo = selectReportNoByIds(item.getProjectId());
                        item.setReportNumber(reportNo);
                    }
                }
                //文件补充
                ReimbursementFileSupplement reimbursementFileSupplement = reimbursementFileSupplementMapper.getByReimId(item.getId());
                if (ObjectUtils.isNotEmpty(reimbursementFileSupplement)){
                    item.setFileStatus(reimbursementFileSupplement.getStatus());
                    item.setFileSuppleId(reimbursementFileSupplement.getId());
                    item.setProcInsIdFile(reimbursementFileSupplement.getProcInsId());
                    item.setTaskIdFile(reimbursementFileSupplement.getTaskIdFile());
                }
                //文件补充
                if (StringUtils.isNotBlank(item.getTaskIdFile()) && StringUtils.isNotBlank(item.getFileStatus())) {
                    if ("2".equals(item.getFileStatus()) || "4".equals(item.getFileStatus())) { // “审核中”的数据要获取数据审核人
                        item.setAuditFileUserIds(flowTaskService.getTaskAuditUsers(item.getTaskIdFile()));  // 获取数据审核人
                    }
                }
                if (StringUtils.isBlank(item.getDeptName())){
                    //处理部门名
                    String offices = getOfficeNameByIds(item.getDeptId());
                    item.setDeptName(offices);
                }
                if (StringUtils.isBlank(item.getName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(item.getUserId());
                    item.setName(names);
                }

            });
        }
        return pageList;
    }

    /**
     * 根据项目id查询项目名称
     * @param ids 以逗号分隔的多个项目id字符串
     * @return
     */
    public String selectProjectByIds(String ids) {
        String projectName = "";
        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);
        List<ProgramProjectListInfo> list = projectListMapper.getListByidList(idList);
        if (CollectionUtil.isNotEmpty(list)) {
            projectName = list.stream().map(ProgramProjectListInfo::getName).collect(Collectors.joining(","));
        }
        return projectName;
    }

    /**
     * 根据项目id查询报告号
     * @param ids 以逗号分隔的多个项目id字符串
     * @return
     */
    public String selectReportNoByIds(String ids) {
        List<String> reportNoList = new ArrayList<>();
        String reportNo = "";
        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);
        List<ProgramProjectListInfo> list = projectListMapper.getListByidList(idList);
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(item -> {
                ProgramReportNo programReportNo = programReportNoMapper.selectByProgramId(item.getId());
                if (ObjectUtil.isNotEmpty(programReportNo) && StringUtils.isNotBlank(programReportNo.getReportNo())) {
                    reportNoList.add(programReportNo.getReportNo());
                } else {
                    reportNoList.add("无");
                }
            });
            if (CollectionUtil.isNotEmpty(reportNoList)) {
                reportNo = reportNoList.stream().collect(Collectors.joining(","));
            }
        }
        return reportNo;
    }

    public ReimbursementInfo save(SaveInfoDto dto) throws Exception{
        // 获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        if (StringUtils.isNotEmpty(dto.getId())) {
            return update(dto, userDTO);
        } else {
            return add(dto, userDTO);
        }
    }

    public ReimbursementInfo add(SaveInfoDto dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        // 判断超过 2026-01-01
        Date targetDate = DateUtil.parseDate("2026-01-01");
        boolean isAfterTargetDate = DateUtil.date().after(targetDate);
        String bizCode = isAfterTargetDate ? dto.NEW_BIZ_CODE : dto.BIZ_CODE;
        // 生成编号
        String no = SpringUtil.getBean(IWorkAttachmentApi.class)
                .genSerialNum(
                        userDTO.getCompanyDTO().getId(),
                        bizCode,
                        TokenProvider.getCurrentToken()
                );

        // 保存基础信息表信息
        ReimbursementInfo info = new ReimbursementInfo();
        BeanUtils.copyProperties(dto, info);
        info.setId(id);
        info.setNo(no);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setDelFlag(0);
        if ("2".equals(dto.getType())){
            info.setApprovalTime(new Date());
        }
        infoMapper.insert(info);
        // 保存项目详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfos())) {
            int i = 0;
            for (ReimbursementDetailInfo detailInfo : dto.getDetailInfos()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                detailInfo.setSort(String.valueOf(i));
                detailInfoMapper.insert(detailInfo);
                i++;
            }
        }
        // 保存合同详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoContracts())) {
            for (ReimbursementDetailInfoContract detailInfo : dto.getDetailInfoContracts()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                reimbursementDetailInfoContractMapper.insert(detailInfo);
            }
        }
        // 保存其他报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoOthers())) {
            int i = 0;
            for (ReimbursementDetailInfoOther detailInfo : dto.getDetailInfoOthers()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                detailInfo.setSort(String.valueOf(i));
                reimbursementDetailInfoOtherMapper.insert(detailInfo);
                i++;
            }
        }
        // 保存采购报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoProcured())) {
            for (ReimbursementDetailInfoProcured detailInfo : dto.getDetailInfoProcured()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                reimbursementDetailInfoProcuredMapper.insert(detailInfo);
            }
        }
        if(StringUtils.isNotBlank(dto.getReimbursementType())){
            if("0".equals(dto.getReimbursementType())){
                // 保存专用发票列表信息
                if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
                    for (ReimbursementAmountInfo amountInfo : dto.getAmountInfos()) {
                        //普通报销 发票信息
                        amountInfo.setReimbursementType("0");
                        // 生成id
                        String amountId = UUID.randomUUID().toString().replace("-", "");
                        amountInfo.setId(amountId);
                        amountInfo.setCreateById(userDTO.getId());
                        amountInfo.setCreateTime(new Date());
                        amountInfo.setUpdateById(userDTO.getId());
                        amountInfo.setUpdateTime(new Date());
                        amountInfo.setDelFlag(0);
                        // 保存基础表信息主键值
                        amountInfo.setInfoId(id);
                        amountInfoMapper.insert(amountInfo);
                    }
                }
                //清除电子发票信息
                // 删除合同列表
                LambdaQueryWrapper<ReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                deleteInfo.eq(ReimbursementAmountInfo::getInfoId, dto.getId());
                deleteInfo.ne(ReimbursementAmountInfo::getReimbursementType, "0");
                amountInfoMapper.delete(deleteInfo);
            }else if("1".equals(dto.getReimbursementType())){
                // 保存电子发票列表信息
                if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                    for (ReimAmountAndFileDto amountInfo : dto.getInvoiceReimbursementFiles()) {
                        if (com.jeeplus.utils.StringUtils.isNotBlank(amountInfo.getUrl())){
                            ReimbursementAmountInfo reimbursementAmountInfo = new ReimbursementAmountInfo();
                            BeanUtils.copyProperties(amountInfo,reimbursementAmountInfo);
                            //电子发票报销 发票信息
                            reimbursementAmountInfo.setReimbursementType("1");
                            // 生成id
                            String amountId = UUID.randomUUID().toString().replace("-", "");
                            reimbursementAmountInfo.setId(amountId);
                            reimbursementAmountInfo.setCreateById(userDTO.getId());
                            reimbursementAmountInfo.setCreateTime(new Date());
                            reimbursementAmountInfo.setUpdateById(userDTO.getId());
                            reimbursementAmountInfo.setUpdateTime(new Date());
                            reimbursementAmountInfo.setDelFlag(0);
                            // 保存基础表信息主键值
                            reimbursementAmountInfo.setInfoId(id);
                            reimbursementAmountInfo.setFileUrl(amountInfo.getUrl());
                            //文件类型处理
                            List<String> strings = Arrays.asList(amountInfo.getName().split("\\."));
                            if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                                reimbursementAmountInfo.setFileType(strings.get(strings.size() - 1));
                            }
                            reimbursementAmountInfo.setAttachmentName(amountInfo.getName());
                            reimbursementAmountInfo.setAttachmentFlag("invoiceReimbursement");
                            reimbursementAmountInfo.setFileSize(amountInfo.getSize());
                            amountInfoMapper.insert(reimbursementAmountInfo);
                        }

                    }
                }
                //清除专用发票信息
                LambdaQueryWrapper<ReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                deleteInfo.eq(ReimbursementAmountInfo::getInfoId, dto.getId());
                deleteInfo.ne(ReimbursementAmountInfo::getReimbursementType, "1");
                amountInfoMapper.delete(deleteInfo);

                // 保存电子发票附件列表信息
                if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                    this.saveFiles(dto.getInvoiceReimbursementFiles(), userDTO, id,"invoiceReimbursement");
                }
            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            workContractService.saveFiles(dto.getFiles(), userDTO, id);
        }
        return info;
    }


    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<ReimAmountAndFileDto> list, UserDTO userDTO, String id, String attachmentFlag) {
        int j = 1;
        for (ReimAmountAndFileDto dto : list) {
            if (com.jeeplus.utils.StringUtils.isNotBlank(dto.getUrl())){
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
                i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateTime(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(strings.size() - 1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag(attachmentFlag);
                i.setFileSize(dto.getSize());
                i.setRemarks(dto.getRemarks());
                i.setSort(j);
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
                Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);
                SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
                j++;
            }
        }
    }


    public ReimbursementInfo update(SaveInfoDto dto, UserDTO userDTO) throws Exception {
        boolean admin = userDTO.isAdmin();
        //判断当前登录人是否是管理员,管理员修改时需要生成一条历史记录
        if (admin){
            SaveInfoDto byId = this.findById(dto.getId());
            String data=JSON.toJSONString(byId);
            ReimbursementInfoUpHi cwReimbursementInfoUpHi = new ReimbursementInfoUpHi();
            cwReimbursementInfoUpHi.setCreateTime(new Date());
            cwReimbursementInfoUpHi.setInfoId(dto.getId());
            cwReimbursementInfoUpHi.setJsonData(data);
            reimbursementInfoUpHiMapper.insert(cwReimbursementInfoUpHi);
        }
        // 生成编号
        //根据报销id 查询该报销信息是否存在报销编号
        String oldNumber = infoMapper.getNumberById(dto.getId());
        if(StringUtils.isBlank(oldNumber)){
            // 生成编号
            String number = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE, TokenProvider.getCurrentToken());
            dto.setNo(number);
        }
        // 修改基础信息
        ReimbursementInfo info = new ReimbursementInfo();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());

        //根据id查询申请日期是否存在
        ReimbursementInfo reimbursementInfo = infoMapper.selectById(dto.getId());
        if ("2".equals(dto.getType())){
            if (ObjectUtil.isEmpty(reimbursementInfo.getApprovalTime())){
                info.setApprovalTime(new Date());
            }
        }
        //获取当前审核节点
        String currentTaskName = SpringUtil.getBean(IFlowableApi.class).getCurrentTaskName(dto.getProcInsId());
        //当前节点为财务审批且通过
        if ("财务审批".equals(currentTaskName) && "2".equals(dto.getType())){
            //判断付款时间存不存在,不存在则添加
            if (null == reimbursementInfo.getPaymentTime()){
                info.setPaymentStatus("1");
                info.setPaymentTime(new Date());
            }
        }

        infoMapper.updateById(info);
        // 修改报销详情列表信息
        // 删除原有数据
        LambdaQueryWrapper<ReimbursementDetailInfo> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(ReimbursementDetailInfo::getInfoId, dto.getId());
        detailInfoMapper.delete(detailWrapper);
        // 删除合同列表
        LambdaQueryWrapper<ReimbursementDetailInfoContract> detailWrapperContract = new LambdaQueryWrapper<>();
        detailWrapperContract.eq(ReimbursementDetailInfoContract::getInfoId, dto.getId());
        reimbursementDetailInfoContractMapper.delete(detailWrapperContract);
        // 删除其他报销表
        LambdaQueryWrapper<ReimbursementDetailInfoOther> detailWrapperOthers = new LambdaQueryWrapper<>();
        detailWrapperOthers.eq(ReimbursementDetailInfoOther::getInfoId, dto.getId());
        reimbursementDetailInfoOtherMapper.delete(detailWrapperOthers);
        // 删除采购报销表
        LambdaQueryWrapper<ReimbursementDetailInfoProcured> detailWrapperProcured = new LambdaQueryWrapper<>();
        detailWrapperProcured.eq(ReimbursementDetailInfoProcured::getInfoId, dto.getId());
        reimbursementDetailInfoProcuredMapper.delete(detailWrapperProcured);

        // 保存项目详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfos())) {
            int i = 0;
            for (ReimbursementDetailInfo detailInfo : dto.getDetailInfos()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                detailInfo.setSort(String.valueOf(i));
                detailInfoMapper.insert(detailInfo);
                i++;
            }
        }
        // 保存合同详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoContracts())) {
            for (ReimbursementDetailInfoContract detailInfo : dto.getDetailInfoContracts()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                reimbursementDetailInfoContractMapper.insert(detailInfo);
            }
        }
        // 保存其他报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoOthers())) {
            int i = 0;
            for (ReimbursementDetailInfoOther detailInfo : dto.getDetailInfoOthers()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                detailInfo.setSort(String.valueOf(i));
                reimbursementDetailInfoOtherMapper.insert(detailInfo);
                i++;
            }
        }
        // 保存采购报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoProcured())) {
            for (ReimbursementDetailInfoProcured detailInfo : dto.getDetailInfoProcured()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                reimbursementDetailInfoProcuredMapper.insert(detailInfo);
            }
        }
        // 修改专用发票信息列表
        // 删除原有数据
        LambdaQueryWrapper<ReimbursementAmountInfo> amountWrapper = new LambdaQueryWrapper<>();
        amountWrapper.eq(ReimbursementAmountInfo::getInfoId, dto.getId());
        amountInfoMapper.delete(amountWrapper);
        if(StringUtils.isNotBlank(dto.getReimbursementType())){
            if("0".equals(dto.getReimbursementType())){
                // 保存专用发票列表信息
                if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
                    for (ReimbursementAmountInfo amountInfo : dto.getAmountInfos()) {
                        //普通报销 发票信息
                        amountInfo.setReimbursementType("0");
                        // 生成id
                        String amountId = UUID.randomUUID().toString().replace("-", "");
                        amountInfo.setId(amountId);
                        amountInfo.setCreateById(userDTO.getId());
                        amountInfo.setCreateTime(new Date());
                        amountInfo.setUpdateById(userDTO.getId());
                        amountInfo.setUpdateTime(new Date());
                        amountInfo.setDelFlag(0);
                        // 保存基础表信息主键值
                        amountInfo.setInfoId(dto.getId());
                        amountInfoMapper.insert(amountInfo);
                    }
                }
                //清除电子发票信息
                // 删除合同列表
                LambdaQueryWrapper<ReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                deleteInfo.eq(ReimbursementAmountInfo::getInfoId, dto.getId());
                deleteInfo.ne(ReimbursementAmountInfo::getReimbursementType, "0");
                amountInfoMapper.delete(deleteInfo);
            }else if("1".equals(dto.getReimbursementType())){
                // 保存电子发票列表信息
                if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                    for (ReimAmountAndFileDto amountInfo : dto.getInvoiceReimbursementFiles()) {
                        if (com.jeeplus.utils.StringUtils.isNotBlank(amountInfo.getUrl())){
                            ReimbursementAmountInfo reimbursementAmountInfo = new ReimbursementAmountInfo();
                            BeanUtils.copyProperties(amountInfo,reimbursementAmountInfo);
                            //电子发票报销 发票信息
                            reimbursementAmountInfo.setReimbursementType("1");
                            // 生成id
                            String amountId = UUID.randomUUID().toString().replace("-", "");
                            reimbursementAmountInfo.setId(amountId);
                            reimbursementAmountInfo.setCreateById(userDTO.getId());
                            reimbursementAmountInfo.setCreateTime(new Date());
                            reimbursementAmountInfo.setUpdateById(userDTO.getId());
                            reimbursementAmountInfo.setUpdateTime(new Date());
                            reimbursementAmountInfo.setDelFlag(0);
                            // 保存基础表信息主键值
                            reimbursementAmountInfo.setInfoId(dto.getId());
                            reimbursementAmountInfo.setFileUrl(amountInfo.getUrl());
                            //文件类型处理
                            List<String> strings = Arrays.asList(amountInfo.getName().split("\\."));
                            if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                                reimbursementAmountInfo.setFileType(strings.get(strings.size() - 1));
                            }
                            reimbursementAmountInfo.setAttachmentName(amountInfo.getName());
                            reimbursementAmountInfo.setAttachmentFlag("invoiceReimbursement");
                            reimbursementAmountInfo.setFileSize(amountInfo.getSize());
                            amountInfoMapper.insert(reimbursementAmountInfo);
                        }

                    }
                }
                //清除专用发票信息
                LambdaQueryWrapper<ReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                deleteInfo.eq(ReimbursementAmountInfo::getInfoId, dto.getId());
                deleteInfo.ne(ReimbursementAmountInfo::getReimbursementType, "1");
                amountInfoMapper.delete(deleteInfo);


                // 保存电子发票附件列表信息
                if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                    this.updateFiles(dto.getInvoiceReimbursementFiles(), userDTO, dto.getId(),"invoiceReimbursement");
                }
            }
        }

        /*if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
            for (ReimbursementAmountInfo amountInfo : dto.getAmountInfos()) {
                // 生成id
                String amountId = UUID.randomUUID().toString().replace("-", "");
                amountInfo.setId(amountId);
                amountInfo.setCreateById(userDTO.getId());
                amountInfo.setCreateTime(new Date());
                amountInfo.setUpdateById(userDTO.getId());
                amountInfo.setUpdateTime(new Date());
                amountInfo.setDelFlag(0);
                // 保存基础表信息主键值
                amountInfo.setInfoId(dto.getId());
                amountInfoMapper.insert(amountInfo);
            }
        }*/
        // 修改附件信息列表
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            workContractService.updateFiles(dto.getFiles(), userDTO, dto.getId(),"workcontract");
        }
        return info;
    }


    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<ReimAmountAndFileDto> list, UserDTO userDTO, String id, String attachmentFlag) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (ReimAmountAndFileDto dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = mapper.findListByIdAndAttachmentFlag(id,attachmentFlag);
        if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
//                    ossServiceMapper.deleteById(i.getId());
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (ReimAmountAndFileDto dto : list) {
            //判断是否存在
            Integer isExit = mapper.findByUrlIsExit(id, dto.getUrl());
            if (isExit == 0) {
                if (com.jeeplus.utils.StringUtils.isNotBlank(dto.getUrl())){
                    WorkAttachmentInfo i = new WorkAttachmentInfo();
                    //包含了url、size、name
                    i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                    i.setCreateTime(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                    i.setUpdateTime(new Date());
                    i.setDelFlag(0);
                    i.setUrl(dto.getUrl());
                    //文件类型处理
                    List<String> strings = Arrays.asList(dto.getName().split("\\."));
                    if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                        i.setType(strings.get(strings.size() - 1));
                    }
                    i.setAttachmentId(id);
                    i.setAttachmentName(dto.getName());
                    i.setAttachmentFlag(attachmentFlag);
                    i.setFileSize(dto.getSize());
                    i.setRemarks(dto.getRemarks());
                    i.setSort(j);
                    Map<String,String> map = new HashMap<>();
                    String workAttachment = JSON.toJSONString((i));
                    String userDTOInfo = JSON.toJSONString((userDTO));
                    map.put("workAttachment",workAttachment);
                    map.put("userDTO",userDTOInfo);
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
//                ossServiceMapper.insertWorkAttachment(i, userDTO);
                    j++;
                }

            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public String remove(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        // 删除基础信息表
        infoMapper.deleteBatchIds(idList);
        // 删除详情列表
        detailInfoMapper.delete(new LambdaQueryWrapper<ReimbursementDetailInfo>()
                .in(ReimbursementDetailInfo::getInfoId, idList));
        // 删除合同列表
        reimbursementDetailInfoContractMapper.delete(new LambdaQueryWrapper<ReimbursementDetailInfoContract>()
                .in(ReimbursementDetailInfoContract::getInfoId, idList));
        // 删除其他报销列表
        reimbursementDetailInfoOtherMapper.delete(new LambdaQueryWrapper<ReimbursementDetailInfoOther>()
                .in(ReimbursementDetailInfoOther::getInfoId, idList));
        // 删除采购报销列表
        reimbursementDetailInfoProcuredMapper.delete(new LambdaQueryWrapper<ReimbursementDetailInfoProcured>()
                .in(ReimbursementDetailInfoProcured::getInfoId, idList));
        // 删除专用发票信息列表
        amountInfoMapper.delete(new LambdaQueryWrapper<ReimbursementAmountInfo>()
                .in(ReimbursementAmountInfo::getInfoId, idList));

        idList.forEach(id ->
                SpringUtil.getBean(IWorkAttachmentApi.class)
                        .deleteByAttachmentId(id)
        );
        return "操作成功";
    }

    public String getOfficeNameByIds(String ids){
        List<String> deptIdList = new ArrayList<>();
        if (ids != null && !ids.trim().isEmpty()) {
            deptIdList = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .collect(Collectors.toList());
            List<String> names = SpringUtil.getBean( IOfficeApi.class ).getOfficeNameByIds(deptIdList);
            return String.join(",",names);
        }
        return "";
    }
    public SaveInfoDto findById(String id) {
        SaveInfoDto dto = new SaveInfoDto();
        // 查询基础信息表
        ReimbursementInfo info = infoMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(info)){
            BeanUtils.copyProperties(info, dto);
            if(StringUtils.isNotBlank(info.getDepartment())) {
                OfficeDTO byId = SpringUtil.getBean ( IOfficeApi.class ).getOfficeById(info.getDepartment());
                if (ObjectUtil.isNotEmpty(byId)) {
                    dto.setDepartmentName(byId.getName());
                }
            }
            IUserApi userApi = SpringUtil.getBean(IUserApi.class);
            // 项目报销详情
            List<ReimbursementDetailInfo> detailList = infoMapper.getDetailList(id);
            detailList.stream().forEach(projectDetail -> {
                if (StringUtils.isNotBlank(projectDetail.getProjectId())) {
                    String proName = selectProjectByIds(projectDetail.getProjectId());
                    projectDetail.setProjectName(proName);
                    String reportNo = selectReportNoByIds(projectDetail.getProjectId());
                    projectDetail.setReportNumber(reportNo);
                } else {
                    projectDetail.setProjectName("");
                    projectDetail.setReportNumber("");
                }
                if (StringUtils.isBlank(projectDetail.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(projectDetail.getUserId());
                    projectDetail.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(projectDetail.getDeptId());
                    projectDetail.setDeptName(offices);
                }
            });
            dto.setDetailInfos(detailList);
            // 合同报销详情
            List<ReimbursementDetailInfoContract> contractDetailList = infoMapper.getContractDetailList(id);
            contractDetailList.stream().forEach(contract -> {
                if (StringUtils.isBlank(contract.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(contract.getUserId());
                    contract.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(contract.getDeptId());
                    contract.setDeptName(offices);
                }
            });
            dto.setDetailInfoContracts(contractDetailList);
            // 其他报销
            List<ReimbursementDetailInfoOther> otherDetailList = infoMapper.getOtherDetailList(id);
            otherDetailList.stream().forEach(details -> {
                if (StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            dto.setDetailInfoOthers(otherDetailList);
            // 采购报销
            List<ReimbursementDetailInfoProcured> procuredDetailList = infoMapper.getProcuredDetailList(id);
            procuredDetailList.stream().forEach(details -> {
                if (StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            dto.setDetailInfoProcured(procuredDetailList);
            // 查询专用发票信息列表
            LambdaQueryWrapper<ReimbursementAmountInfo> amountInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            amountInfoLambdaQueryWrapper.eq(ReimbursementAmountInfo::getInfoId, id);
            amountInfoLambdaQueryWrapper.eq(ReimbursementAmountInfo::getReimbursementType, "0");
            List<ReimbursementAmountInfo> amountInfos = amountInfoMapper.selectList(amountInfoLambdaQueryWrapper);
            dto.setAmountInfos(amountInfos);
            LambdaQueryWrapper<ReimbursementAmountInfo> invoiceReimbursementsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            invoiceReimbursementsLambdaQueryWrapper.eq(ReimbursementAmountInfo::getInfoId, id);
            invoiceReimbursementsLambdaQueryWrapper.eq(ReimbursementAmountInfo::getReimbursementType, "1");
            List<ReimbursementAmountInfo> invoiceReimbursements = amountInfoMapper.selectList(invoiceReimbursementsLambdaQueryWrapper);
//            dto.setInvoiceReimbursements(invoiceReimbursements);
            // 查询附件信息
            List<WorkAttachmentInfo> fileList = infoMapper.findFiles(id);
            List<WorkAttachmentInfo> files = Lists.newArrayList();
            Set<ReimAmountAndFileDto> invoiceReimbursementFiles = new HashSet<>(); // 使用 Set 去重

            if (CollectionUtils.isNotEmpty(fileList)) {
                // 提前为 invoiceReimbursements 构建 URL 到 invoiceReimbursement 的映射，减少嵌套循环
                Map<String, ReimbursementAmountInfo> reimbursementMap = new HashMap<>();
                for (ReimbursementAmountInfo invoiceReimbursement : invoiceReimbursements) {
                    if (com.jeeplus.utils.StringUtils.isNotBlank(invoiceReimbursement.getFileUrl())) {
                        reimbursementMap.put(invoiceReimbursement.getFileUrl(), invoiceReimbursement);
                    }
                }
                //查询数电发票解析后的数据
//                ArrayList<String> strings = new ArrayList<>();
//                strings.add(id);
//                Map<String, String> map = SpringUtil.getBean(IWorkAttachmentApi.class).disposeElectronicEngineeringInvoiceNumber(strings, "3");


                for (WorkAttachmentInfo i : fileList) {
                    if ("invoiceReimbursement".equals(i.getAttachmentFlag())) {
                        ReimbursementAmountInfo invoiceReimbursement = reimbursementMap.get(i.getUrl());

                        if (invoiceReimbursement != null) {
                            // 处理有 URL 匹配的文件
                            processMatchingFiles(i, invoiceReimbursement, invoiceReimbursementFiles);
                        }
//                        else {
//                            if (map !=null){
//                                for (Map.Entry<String, String> entry : map.entrySet()) {
//                                    for (ReimbursementAmountInfo reimbursement : invoiceReimbursements) {
//                                        String key = entry.getKey();
//                                        String value = entry.getValue();
//                                        if (reimbursement.getNumber().equals(key) && i.getUrl().equals(value)){
//                                            ReimAmountAndFileDto ccpmReimAmountAndFileDto = new ReimAmountAndFileDto();
//                                            BeanUtils.copyProperties(i, ccpmReimAmountAndFileDto);
//                                            BeanUtils.copyProperties(reimbursement, ccpmReimAmountAndFileDto);
//                                            String[] split = reimbursement.getInvoiceDate().split(" ");
//                                            ccpmReimAmountAndFileDto.setInvoiceDate(split[0]);
//                                            ccpmReimAmountAndFileDto.setId(i.getId());
//                                            ccpmReimAmountAndFileDto.setCreateBy(SpringUtil.getBean(IUserApi.class).getById(i.getBy()));
//                                            invoiceReimbursementFiles.add(ccpmReimAmountAndFileDto);
//                                        }
//                                    }
//
//                                }
//
//                            }
//                        }
                    } else {
                        // 处理其他文件
                        processNonInvoiceFiles(i, files);
                    }
                }
            }
            dto.setFiles(files);
            List<ReimAmountAndFileDto> uniqueFilesList = new ArrayList<>(invoiceReimbursementFiles);
            uniqueFilesList.sort(
                    Comparator.comparing(
                            ReimAmountAndFileDto::getSort,
                            Comparator.nullsLast(Integer::compareTo) // null 放到最后
                    )
            );
            dto.setInvoiceReimbursementFiles(uniqueFilesList);
        }
        return dto;
    }

    // 针对 URL 匹配的文件进行处理的提取方法
    private void processMatchingFiles(WorkAttachmentInfo i, ReimbursementAmountInfo invoiceReimbursement, Set<ReimAmountAndFileDto> invoiceReimbursementFiles) {
        ReimAmountAndFileDto ccpmReimAmountAndFileDto = new ReimAmountAndFileDto();
        BeanUtils.copyProperties(i, ccpmReimAmountAndFileDto);
        BeanUtils.copyProperties(invoiceReimbursement, ccpmReimAmountAndFileDto);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if(StringUtils.isNotBlank(invoiceReimbursement.getInvoiceDate())){
            // 将字符串转换为 LocalDate
            LocalDate invoiceDate = LocalDate.parse(invoiceReimbursement.getInvoiceDate(), formatter);
            if (ObjectUtil.isNotEmpty(invoiceDate)){
                String year = String.valueOf(invoiceDate.getYear());
                String month = String.valueOf(invoiceDate.getMonthValue());
                String day = String.valueOf(invoiceDate.getDayOfMonth());
                // 设置到 ccpmReimAmountAndFileDto 中
                ccpmReimAmountAndFileDto.setInvoiceDate(year + "-" + month + "-" + day);
            }else {
                ccpmReimAmountAndFileDto.setInvoiceDate("");
            }
        }else {
            ccpmReimAmountAndFileDto.setInvoiceDate("");
        }
        ccpmReimAmountAndFileDto.setId(i.getId());
        ccpmReimAmountAndFileDto.setCreateBy(SpringUtil.getBean(IUserApi.class).getById(i.getBy()));
        invoiceReimbursementFiles.add(ccpmReimAmountAndFileDto);
    }

    // 处理其他文件的方法
    private void processNonInvoiceFiles(WorkAttachmentInfo i, List<WorkAttachmentInfo> files) {
        i.setCreateBy(SpringUtil.getBean(IUserApi.class).getById(i.getBy()));
        files.add(i);
    }

    public Boolean checkNumber(String number) {
        LambdaQueryWrapper<ReimbursementAmountInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReimbursementAmountInfo::getNumber, number);
        List<ReimbursementAmountInfo> infos = amountInfoMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(infos)) {
            return true;
        }
        return false;
    }

    public void updateStatusById(RetureListDto dto) {
        infoMapper.updateStatusById(dto.getId(), dto.getType());
    }

    //用户树形
    public List<TreeUserDto> userTree(String name) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        List<TreeUserDto> list = new ArrayList<>();
        List<TreeUserDto> officeList = Lists.newArrayList();
        boolean isSz = false;
        // 查询部门
        if(userDTO.isAdmin() || (null != userDTO.getTenantDTO() && "10002".equals(userDTO.getTenantDTO().getId()))){
            officeList = infoMapper.findOfficeListByNotTenantId("10000");
        }else{
            officeList = infoMapper.findOfficeListByCompanyId(userDTO.getCompanyDTO().getId());
        }
        //单独处理苏州分公司添加所需用户的问题
        if("苏州分公司".equals(userDTO.getCompanyDTO().getName())){
            isSz = true;
            List<TreeUserDto> officeListByTenantId = infoMapper.findOfficeListByTenantId("10003");
            List<TreeUserDto> tempOfficeList = officeListByTenantId.stream()
                    .filter(item -> "江苏兴光会计".equals(item.getName()) ||
                            "兴光审计一部".equals(item.getName()) ||
                            "兴光审计二部".equals(item.getName())
                    )
                    .collect(Collectors.toList());
            officeList.addAll(tempOfficeList);
        }
        List<TreeUserDto> filterList = new ArrayList<>();
        filterList.addAll(officeList);
        if(null != userDTO && null != userDTO.getOfficeDTO() && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId()) && ("1826176524081065985".equals(userDTO.getOfficeDTO().getId()) || "1826176609011527681".equals(userDTO.getOfficeDTO().getId()))) {
            List<TreeUserDto> officeList1 =  infoMapper.findOfficeListByTenantId("10003");
            filterList.addAll(officeList1);
        }
        //查询综合管理公司
        UserDTO dtoByName = SpringUtil.getBean(IUserApi.class).getByLoginNameNoTen("潘中");
        List<TreeUserDto> officeList1 = infoMapper.findOfficeListByCompanyId2(dtoByName.getCompanyDTO().getId());
        filterList.addAll(officeList1);
        //当前登录人是审计一部或审计二部员工
        List<TreeUserDto> offices = Lists.newArrayList();
        String zsOfficeName = "";
        if (userDTO != null && userDTO.getOfficeDTO() != null && StringUtils.isNotBlank(userDTO.getOfficeDTO().getName())){
            if (userDTO.getOfficeDTO().getName().contains("审计一部")){
                //获取中审公司的张宁部门
                offices =  infoMapper.findOfficeListByTenantId("10004");
                for (TreeUserDto office : offices) {
                    if (office.getName().equals("张宁部门") || office.getName().equals("中审江苏分所")){
                        filterList.add(office);
                    }
                    zsOfficeName = "张宁部门";
                }
            }else if (userDTO.getOfficeDTO().getName().contains("审计二部") ){
                //获取中审公司的孙文宝部门
                offices =  infoMapper.findOfficeListByTenantId("10004");
                for (TreeUserDto office : offices) {
                    if (office.getName().equals("孙文宝部门") || office.getName().equals("中审江苏分所")){
                        filterList.add(office);
                    }
                    zsOfficeName = "孙文宝部门";
                }
            }
        }


        ArrayList<TreeUserDto> treeUsers = new ArrayList<>();
        //如果当前登录人角色是多公司报销则查询全部公司
        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                RoleDTO roleDTOById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                if (null != roleDTOById && (roleDTOById.getEnName().equals("dgsbx")|| roleDTOById.getEnName().equals("zjbry"))){
                    List<TreeUserDto> officeList2 = infoMapper.findOfficeList2();
                    filterList.addAll(officeList2);
                    List<TreeUserDto> users=infoMapper.finduserAllList(name);
                    treeUsers.addAll(users);
                }
            }
        }
        /*if (userDTO.isAdmin ()) {
            filterList = officeList;
        } else {
            String parentIds = SpringUtil.getBean ( IOfficeApi.class ).selectById(userDTO.getOfficeDTO().getId()).getParentIds();
            String[] split = parentIds.split(",");
            if(split.length>2){
                // 公司id
                String companyId = split[2];
                // 过滤出登录人所属公司和集团
                List<TreeUserDto> finalFilterList5 = filterList;
                officeList.stream().forEach(o -> {
                    if (split[2].equals(o.getId())) {
                        finalFilterList5.add(o);
                    } else if(split[1].equals(o.getId())) {
                        finalFilterList5.add(o);
                    }
                });
                // 根据公司id找到其下部门
                List<Office> oList = SpringUtil.getBean ( IOfficeApi.class ).selectListByParentId(companyId);
                // 过滤出这些部门
                List<TreeUserDto> finalFilterList4 = filterList;
                oList.stream().forEach(item -> {
                    officeList.stream().forEach(o -> {
                        if (item.getId().equals(o.getId())) {
                            finalFilterList4.add(o);
                        }
                    });
                });
                // 找到所有的公有部门
                List<Office> publicOfficeList = SpringUtil.getBean ( IOfficeApi.class ).selectListByIsPublic("1");
                // 过滤出这些部门
                List<TreeUserDto> finalFilterList3 = filterList;
                publicOfficeList.stream().forEach(item -> {
                    officeList.stream().forEach(o -> {
                        if (item.getId().equals(o.getId())) {
                            finalFilterList3.add(o);
                        }
                    });
                });
            }else{
                // 私有的
                if ("0".equals(userDTO.getOfficeDTO().getIsPublic())) {
                    // 公司id
                    String companyId = userDTO.getOfficeDTO().getId();
                    // 过滤出登录人所属公司和集团
                    List<TreeUserDto> finalFilterList2 = filterList;
                    officeList.stream().forEach(o -> {
                        if (companyId.equals(o.getId())) {
                            finalFilterList2.add(o);
                        } else if(split[1].equals(o.getId()) && !split[1].equals(companyId)) {
                            finalFilterList2.add(o);
                        }
                    });
                    // 根据公司id找到其下部门
                    List<Office> oList = SpringUtil.getBean ( IOfficeApi.class ).selectListByParentId(companyId);
                    // 过滤出这些部门
                    List<TreeUserDto> finalFilterList1 = filterList;
                    oList.stream().forEach(item -> {
                        officeList.stream().forEach(o -> {
                            if (item.getId().equals(o.getId())) {
                                finalFilterList1.add(o);
                            }
                        });
                    });
                    // 找到所有的公有部门
                    List<Office> publicOfficeList = SpringUtil.getBean ( IOfficeApi.class ).selectListByIsPublic("1");
                    // 过滤出这些部门
                    List<TreeUserDto> finalFilterList = filterList;
                    publicOfficeList.stream().forEach(item -> {
                        officeList.stream().forEach(o -> {
                            if (item.getId().equals(o.getId())) {
                                finalFilterList.add(o);
                            }
                        });
                    });
                } else {
                    filterList = officeList;
                }
            }
        }*/

        /*if (CollectionUtils.isNotEmpty(officeList)) {
            list.addAll(officeList);
        }*/

        // 查询用户
        List<TreeUserDto> userList = infoMapper.findUserList(name);
        //如果当前用户为苏州公司的，则单独查询程爱国和李东信息添加至list
        if (isSz) {
            IUserApi userApi = SpringUtil.getBean(IUserApi.class);

            addUserToTree(userApi, "程爱国", userList);
            addUserToTree(userApi, "李东", userList);
        }

        //查询综合管理公司用户信息
        List<TreeUserDto> userList1=infoMapper.findZhglgsUserList(name);

        /*if (CollectionUtils.isNotEmpty(userList)) {
            list.addAll(userList);
        }*/
        ArrayList<TreeUserDto> treeUserDtos = new ArrayList<>();
        treeUserDtos.addAll(userList);
        treeUserDtos.addAll(userList1);
        //查询中审公司用户信息
        if (null != userDTO && null != userDTO.getOfficeDTO() && StringUtils.isNotBlank(userDTO.getOfficeDTO().getName()) && (userDTO.getOfficeDTO().getName().contains("审计一部") || userDTO.getOfficeDTO().getName().contains("审计二部"))){
            List<TreeUserDto> zsUserList=infoMapper.findZsUserList(name,zsOfficeName);
            treeUserDtos.addAll(zsUserList);
        }

        if(null != userDTO && null != userDTO.getOfficeDTO() && StringUtils.isNotBlank(userDTO.getOfficeDTO().getId()) && ("1826176524081065985".equals(userDTO.getOfficeDTO().getId()) || "1826176609011527681".equals(userDTO.getOfficeDTO().getId()))) {
            //查询会计公司用户信息
            List<TreeUserDto> userList2 = infoMapper.findCwglgsUserList(name);
            treeUserDtos.addAll(userList2);
        }

        treeUserDtos.addAll(treeUsers);
        list = disposeUserTree(treeUserDtos, filterList);
        for (TreeUserDto officeDto : officeList) {
            if("0".equals(officeDto.getParentId())){
                list.add(officeDto);
            }
        }
        for (TreeUserDto officeDto : officeList1) {
            if("0".equals(officeDto.getParentId())){
                list.add(officeDto);
            }
        }
        for (TreeUserDto officeDto : offices) {
            if("0".equals(officeDto.getParentId())){
                list.add(officeDto);
            }
        }
        //去重
        List<TreeUserDto> newList = list.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TreeUserDto::getId))), ArrayList::new)
        );
        return newList;
    }

    /**
     * 将指定用户添加到树形列表
     */
    private void addUserToTree(IUserApi userApi, String loginName, List<TreeUserDto> userList) {
        UserDTO user = userApi.getByLoginNameNotTenantId(loginName);
        if (user != null && user.getOfficeDTO() != null) {
            TreeUserDto treeUserDto = new TreeUserDto();
            treeUserDto.setId(user.getId());
            treeUserDto.setName(user.getName());
            treeUserDto.setParentId(user.getOfficeDTO().getId());
            treeUserDto.setOfficeName(user.getOfficeDTO().getName());
            treeUserDto.setIsUser(true);
            userList.add(treeUserDto);
        }
    }

    //用户树形(用于查询会计公司有资质的员工)
    public List<TreeUserDto> userTree2(String name) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        List<TreeUserDto> list = new ArrayList<>();
        List<TreeUserDto> officeList = Lists.newArrayList();
        // 查询部门
        if(userDTO.isAdmin() || (null != userDTO.getTenantDTO() && "10002".equals(userDTO.getTenantDTO().getId()))){
            officeList = infoMapper.findOfficeListByNotTenantId("10000");
        }else{
            officeList = infoMapper.findOfficeListByCompanyId(userDTO.getCompanyDTO().getId());
        }
        List<TreeUserDto> filterList = new ArrayList<>();
        filterList.addAll(officeList);
        //查询综合管理公司
        UserDTO dtoByName = SpringUtil.getBean(IUserApi.class).getByLoginNameNoTen("潘中");
        List<TreeUserDto> officeList1 = infoMapper.findOfficeListByCompanyId2(dtoByName.getCompanyDTO().getId());
        filterList.addAll(officeList1);
        ArrayList<TreeUserDto> treeUsers = new ArrayList<>();
        //如果当前登录人角色是多公司报销则查询全部公司
//        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
//            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
//                RoleDTO roleDTOById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
//                if (roleDTOById.getEnName().equals("dgsbx")|| roleDTOById.getEnName().equals("zjbry")){
//                    List<TreeUserDto> officeList2 = infoMapper.findOfficeList2();
//                    filterList.addAll(officeList2);
//                    List<TreeUserDto> users=infoMapper.finduserAllList(name);
//                    treeUsers.addAll(users);
//                }
//            }
//        }
        /*if (userDTO.isAdmin ()) {
            filterList = officeList;
        } else {
            String parentIds = SpringUtil.getBean ( IOfficeApi.class ).selectById(userDTO.getOfficeDTO().getId()).getParentIds();
            String[] split = parentIds.split(",");
            if(split.length>2){
                // 公司id
                String companyId = split[2];
                // 过滤出登录人所属公司和集团
                List<TreeUserDto> finalFilterList5 = filterList;
                officeList.stream().forEach(o -> {
                    if (split[2].equals(o.getId())) {
                        finalFilterList5.add(o);
                    } else if(split[1].equals(o.getId())) {
                        finalFilterList5.add(o);
                    }
                });
                // 根据公司id找到其下部门
                List<Office> oList = SpringUtil.getBean ( IOfficeApi.class ).selectListByParentId(companyId);
                // 过滤出这些部门
                List<TreeUserDto> finalFilterList4 = filterList;
                oList.stream().forEach(item -> {
                    officeList.stream().forEach(o -> {
                        if (item.getId().equals(o.getId())) {
                            finalFilterList4.add(o);
                        }
                    });
                });
                // 找到所有的公有部门
                List<Office> publicOfficeList = SpringUtil.getBean ( IOfficeApi.class ).selectListByIsPublic("1");
                // 过滤出这些部门
                List<TreeUserDto> finalFilterList3 = filterList;
                publicOfficeList.stream().forEach(item -> {
                    officeList.stream().forEach(o -> {
                        if (item.getId().equals(o.getId())) {
                            finalFilterList3.add(o);
                        }
                    });
                });
            }else{
                // 私有的
                if ("0".equals(userDTO.getOfficeDTO().getIsPublic())) {
                    // 公司id
                    String companyId = userDTO.getOfficeDTO().getId();
                    // 过滤出登录人所属公司和集团
                    List<TreeUserDto> finalFilterList2 = filterList;
                    officeList.stream().forEach(o -> {
                        if (companyId.equals(o.getId())) {
                            finalFilterList2.add(o);
                        } else if(split[1].equals(o.getId()) && !split[1].equals(companyId)) {
                            finalFilterList2.add(o);
                        }
                    });
                    // 根据公司id找到其下部门
                    List<Office> oList = SpringUtil.getBean ( IOfficeApi.class ).selectListByParentId(companyId);
                    // 过滤出这些部门
                    List<TreeUserDto> finalFilterList1 = filterList;
                    oList.stream().forEach(item -> {
                        officeList.stream().forEach(o -> {
                            if (item.getId().equals(o.getId())) {
                                finalFilterList1.add(o);
                            }
                        });
                    });
                    // 找到所有的公有部门
                    List<Office> publicOfficeList = SpringUtil.getBean ( IOfficeApi.class ).selectListByIsPublic("1");
                    // 过滤出这些部门
                    List<TreeUserDto> finalFilterList = filterList;
                    publicOfficeList.stream().forEach(item -> {
                        officeList.stream().forEach(o -> {
                            if (item.getId().equals(o.getId())) {
                                finalFilterList.add(o);
                            }
                        });
                    });
                } else {
                    filterList = officeList;
                }
            }
        }*/

        /*if (CollectionUtils.isNotEmpty(officeList)) {
            list.addAll(officeList);
        }*/
        //如果当前登录人是会计公司,则查询有资质的员工
        //if ("10003".equals(userDTO.getTenantDTO().getId())){
            List<TreeUserDto> certUserList = infoMapper.findCertUserList(name);
            treeUsers.addAll(certUserList);
        //}
        // 查询用户
//        List<TreeUserDto> userList = infoMapper.findUserList(name);
        //查询综合管理公司用户信息
        List<TreeUserDto> userList1=infoMapper.findZhglgsUserList2(name);
        /*if (CollectionUtils.isNotEmpty(userList)) {
            list.addAll(userList);
        }*/
        ArrayList<TreeUserDto> treeUserDtos = new ArrayList<>();
//        treeUserDtos.addAll(userList);
        treeUserDtos.addAll(userList1);
        treeUserDtos.addAll(treeUsers);
        list = disposeUserTree(treeUserDtos, filterList);
        for (TreeUserDto officeDto : officeList) {
            if("0".equals(officeDto.getParentId())){
                list.add(officeDto);
            }
        }
        for (TreeUserDto officeDto : officeList1) {
            if("0".equals(officeDto.getParentId())){
                list.add(officeDto);
            }
        }
        //去重
        List<TreeUserDto> newList = list.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TreeUserDto::getId))), ArrayList::new)
        );
        return newList;
    }

    //用户树形(用于查询会计公司有资质的员工)
    public List<TreeUserDto> userTreeSelectBySignatureScribe(String name) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        List<TreeUserDto> list = new ArrayList<>();
        List<TreeUserDto> officeList = Lists.newArrayList();
        List<String> strings = SpringUtil.getBean(IUserApi.class).hasUser();

        List<TreeUserDto> officeAllList = infoMapper.findOfficeListByIdList(strings);

        // 查询部门
        if(userDTO.isAdmin() || (null != userDTO.getTenantDTO() && "10002".equals(userDTO.getTenantDTO().getId()))|| (null != userDTO.getTenantDTO() && "10004".equals(userDTO.getTenantDTO().getId()))){
            officeList = infoMapper.findOfficeListByNotTenantId("10000");
        }else{
            officeList = infoMapper.findOfficeListByCompanyId(userDTO.getCompanyDTO().getId());
        }
        List<TreeUserDto> filterList = new ArrayList<>();
        filterList.addAll(officeList);
        filterList.addAll(officeAllList);
        //查询综合管理公司
        UserDTO dtoByName = SpringUtil.getBean(IUserApi.class).getByLoginNameNoTen("潘中");
        List<TreeUserDto> officeList1 = infoMapper.findOfficeListByCompanyId2(dtoByName.getCompanyDTO().getId());
        filterList.addAll(officeList1);
        //当前登录人所属部门是中审江苏分所下的管理咨询部时
        List<TreeUserDto> zsUserList = null;
        String officeId = "";
        for (TreeUserDto dto : officeList) {
            if (dto.getName().equals("管理咨询部")){
                officeId = dto.getId();
                break;
            }

        }
        if (userDTO.isAdmin() || (StringUtils.isNotBlank(officeId) && userDTO.getOfficeDTO().getId().equals(officeId))){
            List<TreeUserDto> zsOfficeList = infoMapper.findOfficeListByCompanyId2(officeId);
            filterList.addAll(zsOfficeList);
            //查询管理咨询部下的用户信息
            zsUserList=infoMapper.findZhglgsUserList3(name,officeId);
        }


        ArrayList<TreeUserDto> treeUsers = new ArrayList<>();

        //如果当前登录人是会计公司,则查询有资质的员工
        //if ("10003".equals(userDTO.getTenantDTO().getId())){
            List<TreeUserDto> certUserList = infoMapper.findCertUserList(name);
            treeUsers.addAll(certUserList);
        //}
        // 查询用户
//        List<TreeUserDto> userList = infoMapper.findUserList(name);
        //查询综合管理公司用户信息
        List<TreeUserDto> userList1=infoMapper.findZhglgsUserList2(name);
        /*if (CollectionUtils.isNotEmpty(userList)) {
            list.addAll(userList);
        }*/
        ArrayList<TreeUserDto> treeUserDtos = new ArrayList<>();
//        treeUserDtos.addAll(userList);
        treeUserDtos.addAll(userList1);
        treeUserDtos.addAll(treeUsers);
        if (zsUserList != null){
            treeUserDtos.addAll(zsUserList);
        }
        list = disposeUserTree(treeUserDtos, filterList);
        for (TreeUserDto officeDto : officeList) {
            if("0".equals(officeDto.getParentId())){
                list.add(officeDto);
            }
        }
        for (TreeUserDto officeDto : officeList1) {
            if("0".equals(officeDto.getParentId())){
                list.add(officeDto);
            }
        }
        //去重
        List<TreeUserDto> newList = list.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TreeUserDto::getId))), ArrayList::new)
        );
        return newList;
    }



    /**
     * 用户树形数据处理
     * @param userList
     * @param officeList
     * @return
     */
    public List<TreeUserDto> disposeUserTree(List<TreeUserDto> userList, List<TreeUserDto> officeList){
        List<TreeUserDto> list = new ArrayList<>();
        for (TreeUserDto userDto : userList) {

            for (TreeUserDto officeDto : officeList) {
                if(StringUtils.isNotBlank(userDto.getParentId()) && userDto.getParentId().equals(officeDto.getId())){
                    list.add(officeDto);
                    list.add(userDto);
                    List<TreeUserDto> treeUserDtos = disposeOfficeTree(officeDto, officeList);
                    if(null!= treeUserDtos && treeUserDtos.size()>0){
                        list.addAll(treeUserDtos);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 用户树形数据处理
     * @param officeInfo
     * @param officeList
     * @return
     */
    public List<TreeUserDto> disposeOfficeTree(TreeUserDto officeInfo, List<TreeUserDto> officeList){
        List<TreeUserDto> listAll = Lists.newArrayList();
            for (TreeUserDto officeDto : officeList) {
                if(officeInfo.getParentId().equals(officeDto.getId())){
                    listAll.add(officeDto);
                    disposeOfficeTree(officeDto,officeList);
                }
            }
        return listAll;
    }

    /**
     * 下载列表查询
     */
    public List<RetureListDto> exportList(QueryListDto dto) throws Exception{
        QueryWrapper<QueryListDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, QueryListDto.class);
        /**
         * a表是reimbursementInfo
         * b表是reimbursementDetailInfo
         * c表是sysUser
         */
        queryWrapper.eq("a.del_flag", 0);
        // 报销项目
        if (StringUtils.isNotEmpty(dto.getProject())) {
            queryWrapper.apply("(b.project_id = {0} OR p.project_name LIKE {1})", dto.getProject(), "%" + dto.getProject() + "%");
            queryWrapper.or().apply("(b4.project_id = {0} OR b4.project_name LIKE {1})", dto.getProject(), "%" + dto.getProject() + "%");
            queryWrapper.or().apply("(b5.project_id = {0} OR b5.project_name LIKE {1})", dto.getProject(), "%" + dto.getProject() + "%");

        }
        // 报销时间
        if (dto.getDates() != null) {
            queryWrapper.between("a.reim_date", dto.getDates()[0], dto.getDates()[1]);
        }
        // 经办人
        if (StringUtils.isNotEmpty(dto.getHandled())) {
            queryWrapper.apply("(a.create_by = {0} OR c.name LIKE {1})", dto.getHandled(), "%" + dto.getHandled() + "%");
        }
        // 报销人
        if (StringUtils.isNotEmpty(dto.getReimBy())) {
            queryWrapper.apply("( b.user_id = {0} OR us.name LIKE {1} )", dto.getReimBy(), "%" + dto.getReimBy() + "%");
            queryWrapper.or().apply("( b2.user_id = {0} OR us2.name LIKE {1} )", dto.getReimBy(), "%" + dto.getReimBy() + "%");
            queryWrapper.or().apply("( b4.user_id = {0} OR us4.name LIKE {1} )", dto.getReimBy(), "%" + dto.getReimBy() + "%");
            queryWrapper.or().apply("( b5.user_id = {0} OR us5.name LIKE {1} )", dto.getReimBy(), "%" + dto.getReimBy() + "%");
        }
        // 报销状态
        if (StringUtils.isNotEmpty(dto.getType())) {
            queryWrapper.eq("a.type", dto.getType());
        }
        // 报销部门
        if (StringUtils.isNotEmpty(dto.getDepartment())) {
            queryWrapper.apply("( b.dept_id = {0} OR so.name LIKE {1} )", dto.getDepartment(), "%" + dto.getDepartment() + "%");
            queryWrapper.or().apply("( b2.dept_id = {0} OR so2.name LIKE {1} )", dto.getDepartment(), "%" + dto.getDepartment() + "%");
            queryWrapper.or().apply("( b4.dept_id = {0} OR so4.name LIKE {1} )", dto.getDepartment(), "%" + dto.getDepartment() + "%");
            queryWrapper.or().apply("( b5.dept_id = {0} OR so5.name LIKE {1} )", dto.getDepartment(), "%" + dto.getDepartment() + "%");
        }
        // 报销类别
        if (StringUtils.isNotEmpty(dto.getRemiType())) {
            queryWrapper.apply(" (b.type_id = {0} OR t.name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b2.type_id = {0} OR t2.name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b4.type_id = {0} OR t4.name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b5.type_id = {0} OR t5.name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
        }
        // 报销金额
        if (dto.getAmounts() != null) {
            if (StringUtils.isNotEmpty(dto.getAmounts()[0])) {
                queryWrapper.and(w ->
                        w.ge("b.number", Double.parseDouble(dto.getAmounts()[0]))
                                .or().ge("b2.number", Double.parseDouble(dto.getAmounts()[0]))
                                .or().ge("b4.number", Double.parseDouble(dto.getAmounts()[0]))
                                .or().ge("b5.number", Double.parseDouble(dto.getAmounts()[0]))
                );
            }
            if (StringUtils.isNotEmpty(dto.getAmounts()[1])) {
                queryWrapper.and(w ->
                        w.le("b.number", Double.parseDouble(dto.getAmounts()[1]))
                                .or().le("b2.number", Double.parseDouble(dto.getAmounts()[1]))
                                .or().le("b4.number", Double.parseDouble(dto.getAmounts()[1]))
                                .or().le("b5.number", Double.parseDouble(dto.getAmounts()[1]))
                );
            }
        }
        // 报告号
        if (StringUtils.isNotEmpty(dto.getReportNumber())) {
            queryWrapper.like("b.report_number", dto.getReportNumber());
            queryWrapper.or().like("b2.report_number", dto.getReportNumber());
            queryWrapper.or().like("b4.report_number", dto.getReportNumber());
            queryWrapper.or().like("b5.report_number", dto.getReportNumber());
        }
        // 报销类型
        if (StringUtils.isNotBlank(dto.getSourceType())) {
            queryWrapper.eq("a.source_type", dto.getSourceType());
        }
        List<RetureListDto> exportList = infoMapper.findExportList(queryWrapper);
        if (CollectionUtils.isNotEmpty(exportList)) {
            for (RetureListDto retureListDto : exportList) {
                if ("1".equals(retureListDto.getType())) {
                    retureListDto.setType("暂存");
                }
                if ("2".equals(retureListDto.getType())) {
                    retureListDto.setType("审批中");
                }
                if ("3".equals(retureListDto.getType())) {
                    retureListDto.setType("撤回");
                }
                if ("4".equals(retureListDto.getType())) {
                    retureListDto.setType("驳回");
                }
                if ("5".equals(retureListDto.getType())) {
                    retureListDto.setType("已完成");
                }
                if (StringUtils.isNotBlank(retureListDto.getSourceType())) {
                    if ("2".equals(retureListDto.getSourceType())) {
                        retureListDto.setContractName(retureListDto.getProjectName());
                        retureListDto.setProjectName("");
                    }
                    retureListDto.setSourceType(SpringUtil.getBean ( IDictApi.class ).getDictLabel(retureListDto.getSourceType(),"pg_reimbursement_source_type",""));
                }
            }
        }
        return exportList;
    }

    /**
     * 关联报销
     */
    public IPage<RetureListDto> relationReimbursementList(Page<RetureListDto> page, String id) {
        IPage<RetureListDto> iPage = infoMapper.relationReimbursementList(page, id);
        return iPage;
    }

    /**
     * 报销审核
     * @param saveInfoDto
     * @return
     */
    public Map<String,Object> auditFunc(SaveInfoDto saveInfoDto) {
        Map<String,Object> result = new HashMap<>();
        result.put("success", "false");
        result.put("message", "操作失败");
        if (Objects.nonNull(saveInfoDto) && StringUtils.isNotBlank(saveInfoDto.getId()) && StringUtils.isNotBlank(saveInfoDto.getFlag())) {
            String id = saveInfoDto.getId(); // 报销数据id
            String flag = saveInfoDto.getFlag(); // 审核标记  yes通过  no驳回
            SaveInfoDto reim = this.findById(id);
            if (Objects.nonNull(reim) && StringUtils.isNotBlank(reim.getType()) && "2".equals(reim.getType())) { // 确保当时数据处于“待审核”状态
                if ( StringUtils.isNotBlank(reim.getProcInsId())) {
                    try {
                        RetureListDto upStatusParam = new RetureListDto();
                        upStatusParam.setId(id);
                        if ("yes".equals(flag)) {
                            boolean b = flowTaskService.checkIsLastTask(reim.getProcInsId());
                            // b为true则审核节点为最后一个审核节点
                            if (b) {
                                // 当前审核节点为最后节点
                                upStatusParam.setType("5"); // 审核状态设置为审核完成
                            } else {
                                upStatusParam.setType("2");
                            }
                        } else {
                            upStatusParam.setType("4"); // 审核状态设置为审核驳回
                        }
                        this.updateStatusById(upStatusParam); // 修改数据的审核状态
                        flowTaskService.auditByProcInsIdAndFlag(reim.getProcInsId(), flag, null, saveInfoDto.getComment()); // 审核操作
                        result.put("success", "false");
                        result.put("message", "操作成功");
                    }catch (Exception e) {
                        e.printStackTrace();
                        result.put("success", "false");
                        result.put("message", "操作失败");
                    }
                }
            } else {
                result.put("success", "false");
                result.put("message", "操作失败，数据已发生改变或不存在，请刷新数据");
            }
        }
        return result;
    }

    public List<ProgramProjectListInfo> queryByProIds(String ids) {
        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);
        List<ProgramProjectListInfo> list = projectListMapper.getListByidList(idList);
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(item -> {
                ProgramReportNo programReportNo = programReportNoMapper.selectByProgramId(item.getId());
                if (ObjectUtil.isNotEmpty(programReportNo) && StringUtils.isNotBlank(programReportNo.getReportNo())) {
                    item.setReportNo(programReportNo.getReportNo());
                } else {
                    item.setReportNo("无");
                }
            });
        }

        return list;
    }

    /**
     * 根据发票号查询是否已经或正在报销
     * @param invoiceNumber
     * @return
     */
    public Integer getEffectiveDataByInvoiceNumber(String invoiceNumber,String id){
        return infoMapper.getEffectiveDataByInvoiceNumber(invoiceNumber,id);
    }

    /**
     * 提交时根据发票号查询是否已经或正在报销
     * @param invoiceNumber
     * @return
     */
    public List<String> getEffectiveDataByNumbers(List<String> invoiceNumber,String id){
        return infoMapper.getEffectiveDataByNumbers(invoiceNumber,id);
    }

    /**
     * 提交时根据发票号查询是否已经或正在报销
     * @param invoiceNumber
     * @return
     */
    public List<String> getEffectiveDataByNumbers2(List<String> invoiceNumber,String id){
        return infoMapper.getEffectiveDataByNumbers2(invoiceNumber, id);
    }

    /**
     * 根据发票号查询是否已经或正在报销
     * @param invoiceNumber
     * @return
     */
    public Integer deleteByIdAndNumber(String invoiceNumber,String id){
        return infoMapper.deleteByIdAndNumber(invoiceNumber,id);
    }

    public List<ReimbursementAmountInfoDTO> getInvoiceReimbursementAmountList(List<String> idList) {
        List<ReimbursementAmountInfoDTO> list = infoMapper.getInvoiceReimbursementAmountList(idList);
        String cwReimbursementSourceTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("invoice_reimbursement_type");
        for (ReimbursementAmountInfoDTO info : list) {
            Map<String,Object> cwReimbursementSourceTypeValueDTOs = JSON.parseObject(cwReimbursementSourceTypeDatas, new TypeReference<Map<String,Object>>() {});
            if(org.apache.commons.lang3.StringUtils.isNotBlank(info.getInvoiceType())){
                for (String key : cwReimbursementSourceTypeValueDTOs.keySet()) {
                    if(info.getInvoiceType().equals(key)){
                        info.setInvoiceTypeStr(String.valueOf(cwReimbursementSourceTypeValueDTOs.get(key)));
                        break;
                    }
                }
            }
        }

        return list;
    }

    /**
     * 查询有无历史数据
     * @param id
     * @return
     */
    public List<ReimbursementInfoUpHi> findHistory(String id) {

        List<ReimbursementInfoUpHi> list = reimbursementInfoUpHiMapper.findHistory(id);
        return list;
    }

    /**
     * 根据id查询历史数据
     * @param id
     * @return
     */
    public SaveInfoDto findHiById(String id) {
        SaveInfoDto reimbursementInfoUpHi = new SaveInfoDto();
        ReimbursementInfoUpHi cwReimbursementInfoUpHi = reimbursementInfoUpHiMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(cwReimbursementInfoUpHi) && StringUtils.isNotBlank(cwReimbursementInfoUpHi.getJsonData())){
            reimbursementInfoUpHi = JSON.parseObject(cwReimbursementInfoUpHi.getJsonData(),SaveInfoDto.class);
        }
        return reimbursementInfoUpHi;
    }

    /**
     * 修改付款状态
     * @param id
     */
    public String updatePaymentStatus(String id,String paymentStatus) {
        //根据id查询报销信息
        ReimbursementInfo reimbursementInfo = infoMapper.selectById(id);
        //判断当前付款状态是付款还是撤回付款
        if ("1".equals(paymentStatus)){
            //判断付款时间是否存在
            if (null != reimbursementInfo.getPaymentTime()){
                return "该报销已经付款,请勿重复付款";
            }else {
                infoMapper.updatePaymentById(id,paymentStatus);
            }
            return "付款成功";
        }else if ("0".equals(paymentStatus)){
            infoMapper.updatePaymentById(id,paymentStatus);
            return "付款撤回成功";
        }else {
            return "付款失败,请确认后付款";
        }
    }


    /**
     * 根据id查询文件补充信息
     * @param id
     * @return
     */
    public SaveInfoDto findFileById(String id) {
        SaveInfoDto dto = new SaveInfoDto();
        String reimId = "";
        //查询文件补充信息
        ReimbursementFileSupplement supplement = reimbursementFileSupplementMapper.selectById(id);
        //获取报销id
        if (ObjectUtils.isNotEmpty(supplement)){
            dto.setFileSuppleId(supplement.getId());
            dto.setFileStatus(supplement.getStatus());
            dto.setProcInsIdFile(supplement.getProcInsId());
            reimId = supplement.getReimbursementId();
        }else {
            dto.setFileSuppleId("");
            dto.setFileStatus("0");
            dto.setProcInsIdFile("");
            reimId = id;
        }
        // 查询基础信息表
        ReimbursementInfo info = infoMapper.selectById(reimId);
        if (ObjectUtil.isNotEmpty(info)){
            BeanUtils.copyProperties(info, dto);
            dto.setUserId(info.getCreateById());
            if(StringUtils.isNotBlank(info.getDepartment())) {
                OfficeDTO byId = SpringUtil.getBean ( IOfficeApi.class ).getOfficeById(info.getDepartment());
                if (ObjectUtil.isNotEmpty(byId)) {
                    dto.setDepartmentName(byId.getName());
                }
            }
            IUserApi userApi = SpringUtil.getBean ( IUserApi.class );
            // 项目报销详情
            List<ReimbursementDetailInfo> detailList = infoMapper.getDetailList(reimId);
            detailList.stream().forEach(projectDetail -> {
                if (StringUtils.isNotBlank(projectDetail.getProjectId())) {
                    String proName = selectProjectByIds(projectDetail.getProjectId());
                    projectDetail.setProjectName(proName);
                    String reportNo = selectReportNoByIds(projectDetail.getProjectId());
                    projectDetail.setReportNumber(reportNo);
                } else {
                    projectDetail.setProjectName("");
                    projectDetail.setReportNumber("");
                }
                if (StringUtils.isBlank(projectDetail.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(projectDetail.getUserId());
                    projectDetail.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(projectDetail.getDeptId());
                    projectDetail.setDeptName(offices);
                }
            });
            dto.setDetailInfos(detailList);
            // 合同报销详情
            List<ReimbursementDetailInfoContract> contractDetailList = infoMapper.getContractDetailList(reimId);
            contractDetailList.stream().forEach(contract -> {
                if (StringUtils.isBlank(contract.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(contract.getUserId());
                    contract.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(contract.getDeptId());
                    contract.setDeptName(offices);
                }
            });
            dto.setDetailInfoContracts(contractDetailList);
            // 其他报销
            List<ReimbursementDetailInfoOther> otherDetailList = infoMapper.getOtherDetailList(reimId);
            otherDetailList.stream().forEach(details -> {
                if (StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            dto.setDetailInfoOthers(otherDetailList);
            // 采购报销
            List<ReimbursementDetailInfoProcured> procuredDetailList = infoMapper.getProcuredDetailList(reimId);
            procuredDetailList.stream().forEach(details -> {
                if (StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            dto.setDetailInfoProcured(procuredDetailList);
            // 查询专用发票信息列表
            LambdaQueryWrapper<ReimbursementAmountInfo> amountInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            amountInfoLambdaQueryWrapper.eq(ReimbursementAmountInfo::getInfoId, reimId);
            amountInfoLambdaQueryWrapper.eq(ReimbursementAmountInfo::getReimbursementType, "0");
            List<ReimbursementAmountInfo> amountInfos = amountInfoMapper.selectList(amountInfoLambdaQueryWrapper);
            dto.setAmountInfos(amountInfos);
            LambdaQueryWrapper<ReimbursementAmountInfo> invoiceReimbursementsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            invoiceReimbursementsLambdaQueryWrapper.eq(ReimbursementAmountInfo::getInfoId, reimId);
            invoiceReimbursementsLambdaQueryWrapper.eq(ReimbursementAmountInfo::getReimbursementType, "1");
            List<ReimbursementAmountInfo> invoiceReimbursements = amountInfoMapper.selectList(invoiceReimbursementsLambdaQueryWrapper);
//            dto.setInvoiceReimbursements(invoiceReimbursements);
            // 查询附件信息
            List<WorkAttachmentInfo> fileList = infoMapper.findFiles(reimId);
            List<WorkAttachmentInfo> files = Lists.newArrayList();
            Set<ReimAmountAndFileDto> invoiceReimbursementFiles = new HashSet<>(); // 使用 Set 去重

            if (CollectionUtils.isNotEmpty(fileList)) {
                // 提前为 invoiceReimbursements 构建 URL 到 invoiceReimbursement 的映射，减少嵌套循环
                Map<String, ReimbursementAmountInfo> reimbursementMap = new HashMap<>();
                for (ReimbursementAmountInfo invoiceReimbursement : invoiceReimbursements) {
                    if (com.jeeplus.utils.StringUtils.isNotBlank(invoiceReimbursement.getFileUrl())) {
                        reimbursementMap.put(invoiceReimbursement.getFileUrl(), invoiceReimbursement);
                    }
                }
                //查询数电发票解析后的数据
//                ArrayList<String> strings = new ArrayList<>();
//                strings.add(id);
//                Map<String, String> map = SpringUtil.getBean(IWorkAttachmentApi.class).disposeElectronicEngineeringInvoiceNumber(strings, "3");


                for (WorkAttachmentInfo i : fileList) {
                    if ("invoiceReimbursement".equals(i.getAttachmentFlag())) {
                        ReimbursementAmountInfo invoiceReimbursement = reimbursementMap.get(i.getUrl());

                        if (invoiceReimbursement != null) {
                            // 处理有 URL 匹配的文件
                            processMatchingFiles(i, invoiceReimbursement, invoiceReimbursementFiles);
                        }
//                        else {
//                            if (map !=null){
//                                for (Map.Entry<String, String> entry : map.entrySet()) {
//                                    for (ReimbursementAmountInfo reimbursement : invoiceReimbursements) {
//                                        String key = entry.getKey();
//                                        String value = entry.getValue();
//                                        if (reimbursement.getNumber().equals(key) && i.getUrl().equals(value)){
//                                            ReimAmountAndFileDto ccpmReimAmountAndFileDto = new ReimAmountAndFileDto();
//                                            BeanUtils.copyProperties(i, ccpmReimAmountAndFileDto);
//                                            BeanUtils.copyProperties(reimbursement, ccpmReimAmountAndFileDto);
//                                            String[] split = reimbursement.getInvoiceDate().split(" ");
//                                            ccpmReimAmountAndFileDto.setInvoiceDate(split[0]);
//                                            ccpmReimAmountAndFileDto.setId(i.getId());
//                                            ccpmReimAmountAndFileDto.setCreateBy(SpringUtil.getBean(IUserApi.class).getById(i.getBy()));
//                                            invoiceReimbursementFiles.add(ccpmReimAmountAndFileDto);
//                                        }
//                                    }
//
//                                }
//
//                            }
//                        }
                    } else {
                        // 处理其他文件
                        processNonInvoiceFiles(i, files);
                    }
                }
            }
            dto.setFiles(files);
            List<ReimAmountAndFileDto> uniqueFilesList = new ArrayList<>(invoiceReimbursementFiles);
            dto.setInvoiceReimbursementFiles(uniqueFilesList);
        }
        return dto;
    }


    /**
     * 新增/修改  文件补充
     * @param dto
     * @return
     * @throws Exception
     */
    public ReimbursementFileSupplement saveFile(SaveInfoDto dto) throws Exception{
        // 获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        ReimbursementInfo info = infoMapper.selectById(dto.getId());
        UserDTO user = SpringUtil.getBean(IUserApi.class).getById(info.getCreateById());
        if (StringUtils.isNotEmpty(dto.getFileSuppleId())) {
            // 修改专用发票信息列表
            // 删除原有数据
            LambdaQueryWrapper<ReimbursementAmountInfo> amountWrapper = new LambdaQueryWrapper<>();
            amountWrapper.eq(ReimbursementAmountInfo::getInfoId, dto.getId());
            amountInfoMapper.delete(amountWrapper);
            if(StringUtils.isNotBlank(dto.getReimbursementType())){
                if("0".equals(dto.getReimbursementType())){
                    // 保存专用发票列表信息
                    if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
                        for (ReimbursementAmountInfo amountInfo : dto.getAmountInfos()) {
                            //普通报销 发票信息
                            amountInfo.setReimbursementType("0");
                            // 生成id
                            String amountId = UUID.randomUUID().toString().replace("-", "");
                            amountInfo.setId(amountId);
                            amountInfo.setCreateById(userDTO.getId());
                            amountInfo.setCreateTime(new Date());
                            amountInfo.setUpdateById(userDTO.getId());
                            amountInfo.setUpdateTime(new Date());
                            amountInfo.setDelFlag(0);
                            // 保存基础表信息主键值
                            amountInfo.setInfoId(dto.getId());
                            amountInfoMapper.insert(amountInfo);
                        }
                    }
                    //清除电子发票信息
                    // 删除合同列表
                    LambdaQueryWrapper<ReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                    deleteInfo.eq(ReimbursementAmountInfo::getInfoId, dto.getId());
                    deleteInfo.ne(ReimbursementAmountInfo::getReimbursementType, "0");
                    amountInfoMapper.delete(deleteInfo);
                }else if("1".equals(dto.getReimbursementType())){
                    // 保存电子发票列表信息
                    if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                        for (ReimAmountAndFileDto amountInfo : dto.getInvoiceReimbursementFiles()) {
                            if (com.jeeplus.utils.StringUtils.isNotBlank(amountInfo.getUrl())){
                                ReimbursementAmountInfo reimbursementAmountInfo = new ReimbursementAmountInfo();
                                BeanUtils.copyProperties(amountInfo,reimbursementAmountInfo);
                                //电子发票报销 发票信息
                                reimbursementAmountInfo.setReimbursementType("1");
                                // 生成id
                                String amountId = UUID.randomUUID().toString().replace("-", "");
                                reimbursementAmountInfo.setId(amountId);
                                reimbursementAmountInfo.setCreateById(userDTO.getId());
                                reimbursementAmountInfo.setCreateTime(new Date());
                                reimbursementAmountInfo.setUpdateById(userDTO.getId());
                                reimbursementAmountInfo.setUpdateTime(new Date());
                                reimbursementAmountInfo.setDelFlag(0);
                                // 保存基础表信息主键值
                                reimbursementAmountInfo.setInfoId(dto.getId());
                                reimbursementAmountInfo.setFileUrl(amountInfo.getUrl());
                                //文件类型处理
                                List<String> strings = Arrays.asList(amountInfo.getName().split("\\."));
                                if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                                    reimbursementAmountInfo.setFileType(strings.get(strings.size() - 1));
                                }
                                reimbursementAmountInfo.setAttachmentName(amountInfo.getName());
                                reimbursementAmountInfo.setAttachmentFlag("invoiceReimbursement");
                                reimbursementAmountInfo.setFileSize(amountInfo.getSize());
                                amountInfoMapper.insert(reimbursementAmountInfo);
                            }

                        }
                    }
                    //清除专用发票信息
                    LambdaQueryWrapper<ReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                    deleteInfo.eq(ReimbursementAmountInfo::getInfoId, dto.getId());
                    deleteInfo.ne(ReimbursementAmountInfo::getReimbursementType, "1");
                    amountInfoMapper.delete(deleteInfo);


                    // 保存电子发票附件列表信息
                    if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                        this.updateFiles(dto.getInvoiceReimbursementFiles(), userDTO, dto.getId(),"invoiceReimbursement");
                    }
                }
            }
            // 修改附件信息列表
            if (CollectionUtils.isNotEmpty(dto.getFiles())) {
                workContractService.updateFiles(dto.getFiles(), userDTO, dto.getId(),"workcontract");
            }
            //修改文件补充信息
            ReimbursementFileSupplement fileSupplement = new ReimbursementFileSupplement();
            fileSupplement.setId(dto.getFileSuppleId());
            fileSupplement.setUpdateById(userDTO.getId());
            fileSupplement.setUpdateTime(new Date());
            fileSupplement.setStatus(dto.getFileStatus());
            reimbursementFileSupplementMapper.updateById(fileSupplement);

            fileSupplement.setNo(info.getNo());
            fileSupplement.setName(user.getName());
            return fileSupplement;
        } else {
            //修改报销基本信息
            ReimbursementInfo reimbursementInfo = new ReimbursementInfo();
            reimbursementInfo.setReimbursementType(dto.getReimbursementType());
            reimbursementInfo.setId(dto.getId());
            reimbursementInfo.setUpdateTime(new Date());
            infoMapper.updateById(reimbursementInfo);
            // 生成id
            String id = UUID.randomUUID().toString().replace("-", "");
            ReimbursementFileSupplement fileSupplement = new ReimbursementFileSupplement();
            fileSupplement.setId(id);
            fileSupplement.setCreateById(userDTO.getId());
            fileSupplement.setCreateTime(new Date());
            fileSupplement.setUpdateById(userDTO.getId());
            fileSupplement.setUpdateTime(new Date());
            fileSupplement.setDelFlag(0);
            fileSupplement.setStatus(dto.getFileStatus());
            fileSupplement.setReimbursementId(dto.getId());
            reimbursementFileSupplementMapper.insert(fileSupplement);
            fileSupplement.setNo(info.getNo());
            fileSupplement.setName(user.getName());
            return fileSupplement;
        }
    }

    /**
     * 修改文件补充状态
     * @param dto
     */
    public void updateFileStatusById(RetureListDto dto) {
        reimbursementFileSupplementMapper.updateFileStatusById(dto.getFileSuppleId(),dto.getFileStatus());
    }


    /**
     * 修改数电发票报销数据(对老数据进行调整)
     */
    public void updateOldData() {
        try {
            Set<String> infoIds = new HashSet<>(); // 使用 Set 去重

            // 查询所有的数电发票信息
            LambdaQueryWrapper<ReimbursementAmountInfo> invoiceReimbursementsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            invoiceReimbursementsLambdaQueryWrapper.eq(ReimbursementAmountInfo::getReimbursementType, "1");
            invoiceReimbursementsLambdaQueryWrapper.eq(ReimbursementAmountInfo::getDelFlag, "0");
            invoiceReimbursementsLambdaQueryWrapper.orderByDesc(ReimbursementAmountInfo::getCreateTime);
            List<ReimbursementAmountInfo> invoiceReimbursements = amountInfoMapper.selectList(invoiceReimbursementsLambdaQueryWrapper);

            if (CollectionUtil.isNotEmpty(invoiceReimbursements)) {
                // 将所有的报销id进行存储
                for (ReimbursementAmountInfo invoiceReimbursement : invoiceReimbursements) {
                    infoIds.add(invoiceReimbursement.getInfoId());
                }
                if (infoIds != null && invoiceReimbursements != null){
                    ArrayList<String> list = new ArrayList<>(infoIds);
                    for (String id : list) {
                        //查询数电发票解析后的数据
                        ArrayList<String> strings = new ArrayList<>();
                        strings.add(id);
                        Map<String, String> map = SpringUtil.getBean(IWorkAttachmentApi.class).disposeElectronicEngineeringInvoiceNumber(strings, "3");

                        List<WorkAttachmentInfo> fileList = infoMapper.findReimFiles(id, "invoiceReimbursement");
                        if (CollectionUtil.isNotEmpty(invoiceReimbursements) && CollectionUtil.isNotEmpty(fileList) && map !=null){
                            for (ReimbursementAmountInfo amountInfo : invoiceReimbursements) {
                                if (StringUtils.isBlank(amountInfo.getFileUrl())){
                                    for (Map.Entry<String, String> entry : map.entrySet()) {
                                        for (WorkAttachmentInfo i : fileList) {
                                            String key = entry.getKey();
                                            String value = entry.getValue();
                                            if (amountInfo.getNumber().equals(key) && i.getUrl().equals(value)){
                                                amountInfo.setFileUrl(i.getUrl());
                                                String type = i.getName().substring(i.getName().lastIndexOf(".") + 1);
                                                amountInfo.setFileType(type);
                                                amountInfo.setAttachmentFlag("invoiceReimbursement");
                                                amountInfo.setAttachmentName(i.getName());
                                                amountInfo.setFileSize(i.getFileSize());
                                                amountInfoMapper.updateById(amountInfo);
                                            }
                                        }
                                    }
                                }

                            }

                        }
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //单个用户查询(用于查询会计公司有资质的员工)
    public String getUserBySignatureScribe(String name,String userId) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(userId);
        List<TreeUserDto> list = new ArrayList<>();
        List<TreeUserDto> officeList = Lists.newArrayList();
        List<String> strings = SpringUtil.getBean(IUserApi.class).hasUser();

        List<TreeUserDto> officeAllList = infoMapper.findOfficeListByIdList(strings);

        // 查询部门
        if(userDTO.isAdmin() || (null != userDTO.getTenantDTO() && "10002".equals(userDTO.getTenantDTO().getId()))|| (null != userDTO.getTenantDTO() && "10004".equals(userDTO.getTenantDTO().getId()))){
            officeList = infoMapper.findOfficeListByNotTenantId("10000");
        }else{
            officeList = infoMapper.findOfficeListByCompanyId(userDTO.getCompanyDTO().getId());
        }
        List<TreeUserDto> filterList = new ArrayList<>();
        filterList.addAll(officeList);
        filterList.addAll(officeAllList);
        //查询综合管理公司
        UserDTO dtoByName = SpringUtil.getBean(IUserApi.class).getByLoginNameNoTen("潘中");
        List<TreeUserDto> officeList1 = infoMapper.findOfficeListByCompanyId2(dtoByName.getCompanyDTO().getId());
        filterList.addAll(officeList1);
        //当前登录人所属部门是中审江苏分所下的管理咨询部时
        List<TreeUserDto> zsUserList = null;
        String officeId = "";
        for (TreeUserDto dto : officeList) {
            if (dto.getName().equals("管理咨询部")){
                officeId = dto.getId();
                break;
            }

        }
        if (userDTO.isAdmin() || (StringUtils.isNotBlank(officeId) && userDTO.getOfficeDTO().getId().equals(officeId))){
            List<TreeUserDto> zsOfficeList = infoMapper.findOfficeListByCompanyId2(officeId);
            filterList.addAll(zsOfficeList);
            //查询管理咨询部下的用户信息
            zsUserList=infoMapper.findZhglgsUserList3(name,officeId);
        }
        //如果当前登录人是会计公司,则查询有资质的员工
        List<TreeUserDto> certUserList = infoMapper.findCertUserList(name);
        //查询综合管理公司用户信息
        List<TreeUserDto> userList1=infoMapper.findZhglgsUserList2(name);
        List<TreeUserDto> combinedList = new ArrayList<>();
        combinedList.addAll(certUserList);
        combinedList.addAll(userList1);
        if (zsUserList != null){
            combinedList.addAll(zsUserList);
        }
        Optional<TreeUserDto> user = combinedList.stream()
                .filter(u -> name.equals(u.getName()))
                .findFirst();
        if(user.isPresent()){
            return user.get().getId();
        }
        return null;
    }


    /**
     * 根据报销id查询最新一条文件补充信息
     * @param id
     * @return
     */
    public ReimbursementFileSupplement findFileByReimId(String id) {
        ReimbursementFileSupplement fileSupplement = reimbursementFileSupplementMapper.getByReimId(id);
        return fileSupplement;
    }

    /**
     * 根据流程id获取报销创建人id
     * @param id
     * @return
     */
    public String getReimbursementCreateUserIdByProcessInstanceId(String id) {
        String createUserId = reimbursementFileSupplementMapper.getReimbursementCreateUserIdByProcessInstanceId(id);
        return createUserId;
    }
}
