package com.jeeplus.centrecareful.approvalInfo.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.jeeplus.centrecareful.approvalType.mapper.ZsReimbursementTypeMapper;
import com.jeeplus.centrecareful.approvalType.service.ZsReimbursementTypeService;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.centrecareful.approvalInfo.domain.*;
import com.jeeplus.centrecareful.approvalInfo.mapper.*;
import com.jeeplus.centrecareful.approvalInfo.service.dto.*;
import com.jeeplus.core.query.QueryWrapperGenerator;
//import com.jeeplus.finance.contractRegistration.service.ContractInfoService;
//import com.jeeplus.finance.reimbursementApproval.approvalInfo.service.dto.QueryListDto;
import com.jeeplus.flowable.feign.IFinanceApi;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.Office;
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.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.baomidou.mybatisplus.*;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author: 王强
 * @create: 2022-11-24 16:11
 **/
@Service
public class ZsReimbursementInfoService {

    @Resource
    private ZsReimbursementInfoMapper infoMapper;

    @Resource
    private ZsReimbursementDetailInfoContractMapper zsReimbursementDetailInfoContractMapper;

    @Resource
    private ZsReimbursementDetailInfoReportMapper zsReimbursementDetailInfoReportMapper;

    @Resource
    private ZsReimbursementDetailInfoOtherMapper zsReimbursementDetailInfoOtherMapper;

    @Resource
    private ZsReimbursementDetailInfoProcuredMapper zsReimbursementDetailInfoProcuredMapper;

    @Resource
    private ZsReimbursementDetailInfoProjectMapper zsReimbursementDetailInfoProjectMapper;

    @Resource
    private ZsReimbursementDetailInfoMapper detailInfoMapper;

    @Resource
    private ZsReimbursementAmountInfoMapper amountInfoMapper;



//    @Resource
//    private SerialnumTplService serialnumTplService;

//    @Resource
//    private ContractInfoService infoService;

   /* @Resource
    private MaterialBasicMapper materialBasicMapper;*/

    @Resource
    private ZsReimbursementTypeService typeService;

    @Resource
    private ZsReimbursementInfoUpHiMapper reimbursementInfoUpHiMapper;

    @Resource
    private ZsReimbursementFileSupplementMapper zsReimbursementFileSupplementMapper;

    @Resource
    private ZsReimbursementTypeMapper mapper;

    /**
     * 报告号查询
     */
    public IPage<ZsReportNoDto> getReportNoList(Page<ZsReportNoDto> page , ZsReportNoDto dto) throws Exception{
        QueryWrapper<ZsReportNoDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, ZsReportNoDto.class);
        /**
         * a表是reimbursementInfo
         * b表是reimbursementDetailInfo
         * c表是sysUser
         */
        queryWrapper.eq("a.del_flag", 0);
        queryWrapper.eq("c.id", dto.getProjectId());
        return infoMapper.getReportNoList(page, queryWrapper);
    }

    /**
     * 列表查询
     */
    public IPage<ZsRetureListDto> list(Page<ZsRetureListDto> page , ZsQueryListDto dto,Boolean isExport) throws Exception{
        IOfficeApi officeApi = SpringUtil.getBean(IOfficeApi.class);
        IUserApi userApi = SpringUtil.getBean(IUserApi.class);
        QueryWrapper<ZsQueryListDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, ZsQueryListDto.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("(b3.project_id = {0} OR p3.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() + "%");
        }

        // 报销时间 - 根据综合管理部主任角色审核时间筛选
        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 (com.jeeplus.utils.StringUtils.isNotEmpty(dto.getNo())) {
            queryWrapper.like("a.no", dto.getNo());
        }
        // 经办人
        if (StringUtils.isNotEmpty(dto.getHandled())) {
            queryWrapper.apply("(a.create_by_id = {0} OR c.name LIKE {1})", dto.getHandled(), "%" + dto.getHandled() + "%");
        }
        // 报销人
        if (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("b3.user_id", u.getId())
                                .or().like("b4.user_id", u.getId())
                                .or().like("zs1.user_id", u.getId())
                                .or().like("r4.user_id", u.getId())
                                .or().like("us.name", dto.getReimBy())
                                .or().like("us3.name", dto.getReimBy())
                                .or().like("us4.name", dto.getReimBy())
                                .or().like("uszs.name", dto.getReimBy())
                                .or().like("us44.name", dto.getReimBy())
                        );
                    }
                });
            }
        }
        // 报销状态
        if (StringUtils.isNotEmpty(dto.getType())) {
            queryWrapper.eq("a.type", dto.getType());
        }
        // 报销部门
        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("( b3.dept_id like {0} OR so3.name LIKE {1} )", "%" +officeDto.getId()+ "%", "%" + dto.getDepartment() + "%");
            queryWrapper.or().apply("( b4.dept_id like {0} OR so4.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(" (b3.type_id = {0} OR t3.name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b4.type_id = {0} OR t4.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("b3.number", Double.parseDouble(dto.getAmounts()[0]))
                                .or().ge("b4.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("b3.number", Double.parseDouble(dto.getAmounts()[1]))
                                .or().le("b4.number", Double.parseDouble(dto.getAmounts()[1]))
                );
            }
        }
        // 报告号
        if (StringUtils.isNotEmpty(dto.getReportNumber())) {
            queryWrapper.like("b.report_number", dto.getReportNumber());
            queryWrapper.or().like("b3.report_number", dto.getReportNumber());
            queryWrapper.or().like("b4.report_number", dto.getReportNumber());
        }
        // 报销类型
        if (StringUtils.isNotBlank(dto.getSourceType())) {
            queryWrapper.eq("a.source_type", dto.getSourceType());
        }
        // 报销项状态
        if (StringUtils.isNotEmpty(dto.getReimbursementType())) {
            queryWrapper.eq("a.reimbursement_type", dto.getReimbursementType());
        }
        // 付款状态
        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 zs_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("zsyg".equals(roleDTOById.getEnName()) && "中审员工".equals(roleDTOById.getName())){
                queryWrapper.eq("a.create_by_id", userDTO.getId());
                break;
            }else if("zsbmzr".equals(roleDTOById.getEnName()) && "中审部门主任".equals(roleDTOById.getName())){
                queryWrapper.eq("c.office_id", userDTO.getOfficeDTO().getId());
                break;
            }
        }*/
        IPage<ZsRetureListDto> list = infoMapper.findList(page, queryWrapper);
        if(!isExport){
            list.getRecords().stream().forEach(item ->{
                if (StringUtils.isNotBlank(item.getSourceType()) && "1".equals(item.getSourceType())) { //项目报销
                    if (StringUtils.isNotBlank(item.getProjectId())) {
                        String proName = SpringUtil.getBean(IFinanceApi.class).getCwProjectNameByIds(item.getProjectId());
                        item.setProjectName(proName);
                    }
                    if (StringUtils.isBlank(item.getDeptName())){
                        String name = infoMapper.findUserById(item.getProjectUser());
                        item.setName(name);
                        String office = infoMapper.findOfficeById(item.getProjectOffice());
                        item.setDeptName(office);
                    }
                }
                if (StringUtils.isNotBlank(item.getSourceType()) && "3".equals(item.getSourceType())){//报告报销
                    if (org.apache.commons.lang3.StringUtils.isBlank(item.getDeptName())){
                        String name = infoMapper.findUserById(item.getReportUser());
                        item.setName(name);
                        String office = infoMapper.findOfficeById(item.getReportOffice());
                        item.setDeptName(office);
                    }
                }
                //文件补充
                ZsReimbursementFileSupplement reimbursementFileSupplement = zsReimbursementFileSupplementMapper.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.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 list;
    }

    public IPage<ZSProgramProjectListInfo> projectList(Page<ZSProgramProjectListInfo> page, ZSProgramProjectListInfo info, String tabType) throws Exception{

        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());


        QueryWrapper<ZSProgramProjectListInfo> wrapper = QueryWrapperGenerator.buildQueryCondition(info, ZSProgramProjectListInfo.class);
        wrapper.eq("a.del_flag", "0");
        wrapper.eq("a.tab_type", tabType);
        wrapper.eq("b.office_id", userDTO.getOfficeDTO().getId());
        if (info.getCreateDates() != null) {
            wrapper.between("a.create_date", info.getCreateDates()[0], info.getCreateDates()[1]);
        }
        IPage<ZSProgramProjectListInfo> pageList = infoMapper.findProjectList(page, wrapper);
        pageList.getRecords().stream().forEach(item ->{
            String isInvoice = infoMapper.selectInvoiceFlag(item.getId());
            item.setIsInvoice(isInvoice);
        });
        return pageList;
    }

    public ZsReimbursementInfo save(ZsSaveInfoDto 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 ZsReimbursementInfo add(ZsSaveInfoDto 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 ? ZsSaveInfoDto.NEW_BIZ_CODE : ZsSaveInfoDto.BIZ_CODE;
        // 生成编号
        String no = SpringUtil.getBean(IWorkAttachmentApi.class)
                .genSerialNum(
                        userDTO.getCompanyDTO().getId(),
                        bizCode,
                        TokenProvider.getCurrentToken()
                );
        // 保存基础信息表信息
        ZsReimbursementInfo info = new ZsReimbursementInfo();
        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 (ZsReimbursementDetailInfo detailInfo : dto.getDetailInfos()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                detailInfoMapper.insert(detailInfo);
                i++;
            }
        }
        // 保存合同详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoContracts())) {
            for (ZsReimbursementDetailInfoContract detailInfo : dto.getDetailInfoContracts()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                zsReimbursementDetailInfoContractMapper.insert(detailInfo);
            }
        }
        // 保存报告详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoReports())) {
            for (ZsReimbursementDetailInfoReport detailInfo : dto.getDetailInfoReports()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                zsReimbursementDetailInfoReportMapper.insert(detailInfo);
            }
        }
        // 保存其他报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoOthers())) {
            for (ZsReimbursementDetailInfoOther detailInfo : dto.getDetailInfoOthers()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                zsReimbursementDetailInfoOtherMapper.insert(detailInfo);
            }
        }
        // 保存中审项目报销详情
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoProject())) {
            for (ZsReimbursementDetailInfoProject detailInfo : dto.getDetailInfoProject()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                zsReimbursementDetailInfoProjectMapper.insert(detailInfo);
            }
        }
        // 保存采购报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoProcured())) {
            for (ZsReimbursementDetailInfoProcured detailInfo : dto.getDetailInfoProcured()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(id);
                zsReimbursementDetailInfoProcuredMapper.insert(detailInfo);
            }
        }
        if(StringUtils.isNotBlank(dto.getReimbursementType())){
            if("0".equals(dto.getReimbursementType())){
                // 保存专用发票列表信息
                if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
                    for (ZsReimbursementAmountInfo 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<ZsReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                deleteInfo.eq(ZsReimbursementAmountInfo::getInfoId, dto.getId());
                deleteInfo.ne(ZsReimbursementAmountInfo::getReimbursementType, "0");
                amountInfoMapper.delete(deleteInfo);
            }else if("1".equals(dto.getReimbursementType())){
                // 保存电子发票列表信息
                if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                    for (ZsReimAmountAndFileDto amountInfo : dto.getInvoiceReimbursementFiles()) {
                        if (com.jeeplus.utils.StringUtils.isNotBlank(amountInfo.getUrl())){
                            ZsReimbursementAmountInfo reimbursementAmountInfo = new ZsReimbursementAmountInfo();
                            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<ZsReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                deleteInfo.eq(ZsReimbursementAmountInfo::getInfoId, dto.getId());
                deleteInfo.ne(ZsReimbursementAmountInfo::getReimbursementType, "1");
                amountInfoMapper.delete(deleteInfo);

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


    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<ZsReimAmountAndFileDto> list, UserDTO userDTO, String id, String attachmentFlag) {
        int j = 1;
        for (ZsReimAmountAndFileDto 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.setSort(j);
                i.setRemarks(dto.getRemarks());

//            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 ZsReimbursementInfo update(ZsSaveInfoDto dto, UserDTO userDTO) {
        boolean admin = userDTO.isAdmin();
        //判断当前登录人是否是管理员,管理员修改时需要生成一条历史记录
        if (admin){
            ZsSaveInfoDto byId = this.findById(dto.getId());
            String data=JSON.toJSONString(byId);
            ZsReimbursementInfoUpHi cwReimbursementInfoUpHi = new ZsReimbursementInfoUpHi();
            cwReimbursementInfoUpHi.setCreateTime(new Date());
            cwReimbursementInfoUpHi.setInfoId(dto.getId());
            cwReimbursementInfoUpHi.setJsonData(data);
            reimbursementInfoUpHiMapper.insert(cwReimbursementInfoUpHi);
        }
        // 修改基础信息
        ZsReimbursementInfo info = new ZsReimbursementInfo();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        //根据id查询申请日期是否存在
        ZsReimbursementInfo zsReimbursementInfo = infoMapper.selectById(dto.getId());
        if ("2".equals(dto.getType())){
            if (ObjectUtil.isEmpty(zsReimbursementInfo.getApprovalTime())){
                info.setApprovalTime(new Date());
            }
        }
        //获取当前审核节点
        String currentTaskName = SpringUtil.getBean(IFlowableApi.class).getCurrentTaskName(dto.getProcInsId());
        //当前节点为财务审批且通过
        if ("财务审批".equals(currentTaskName) && "2".equals(dto.getType())){
            //判断付款时间存不存在,不存在则添加
            if (null == zsReimbursementInfo.getPaymentTime()){
                info.setPaymentStatus("1");
                info.setPaymentTime(new Date());
            }
        }
        infoMapper.updateById(info);
        // 修改报销详情列表信息
        // 删除原有数据
        LambdaQueryWrapper<ZsReimbursementDetailInfo> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(ZsReimbursementDetailInfo::getInfoId, dto.getId());
        detailInfoMapper.delete(detailWrapper);
        // 删除合同列表
        LambdaQueryWrapper<ZsReimbursementDetailInfoContract> detailWrapperContract = new LambdaQueryWrapper<>();
        detailWrapperContract.eq(ZsReimbursementDetailInfoContract::getInfoId, dto.getId());
        zsReimbursementDetailInfoContractMapper.delete(detailWrapperContract);
        // 删除报告列表
        LambdaQueryWrapper<ZsReimbursementDetailInfoReport> detailWrapperReport = new LambdaQueryWrapper<>();
        detailWrapperReport.eq(ZsReimbursementDetailInfoReport::getInfoId, dto.getId());
        zsReimbursementDetailInfoReportMapper.delete(detailWrapperReport);
        // 删除其他报销表
        LambdaQueryWrapper<ZsReimbursementDetailInfoOther> detailWrapperOthers = new LambdaQueryWrapper<>();
        detailWrapperOthers.eq(ZsReimbursementDetailInfoOther::getInfoId, dto.getId());
        zsReimbursementDetailInfoOtherMapper.delete(detailWrapperOthers);
        // 删除采购报销表
        LambdaQueryWrapper<ZsReimbursementDetailInfoProcured> detailWrapperProcured = new LambdaQueryWrapper<>();
        detailWrapperProcured.eq(ZsReimbursementDetailInfoProcured::getInfoId, dto.getId());
        zsReimbursementDetailInfoProcuredMapper.delete(detailWrapperProcured);
        //删除中审项目报销表
        LambdaQueryWrapper<ZsReimbursementDetailInfoProject> detailWrapperProject = new LambdaQueryWrapper<>();
        detailWrapperProject.eq(ZsReimbursementDetailInfoProject::getInfoId, dto.getId());
        zsReimbursementDetailInfoProjectMapper.delete(detailWrapperProject);

        // 保存项目详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfos())) {
            for (ZsReimbursementDetailInfo detailInfo : dto.getDetailInfos()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                detailInfoMapper.insert(detailInfo);
            }
        }
        // 保存合同详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoContracts())) {
            for (ZsReimbursementDetailInfoContract detailInfo : dto.getDetailInfoContracts()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                zsReimbursementDetailInfoContractMapper.insert(detailInfo);
            }
        }
        // 保存报告详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoReports())) {
            for (ZsReimbursementDetailInfoReport detailInfo : dto.getDetailInfoReports()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                zsReimbursementDetailInfoReportMapper.insert(detailInfo);
            }
        }
        // 保存其他报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoOthers())) {
            for (ZsReimbursementDetailInfoOther detailInfo : dto.getDetailInfoOthers()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                zsReimbursementDetailInfoOtherMapper.insert(detailInfo);
            }
        }
        // 保存中审项目报销详情
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoProject())) {
            for (ZsReimbursementDetailInfoProject detailInfo : dto.getDetailInfoProject()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                zsReimbursementDetailInfoProjectMapper.insert(detailInfo);
            }
        }
        // 保存采购报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getDetailInfoProcured())) {
            for (ZsReimbursementDetailInfoProcured detailInfo : dto.getDetailInfoProcured()) {
                // 保存基础表信息主键值
                detailInfo.setInfoId(dto.getId());
                detailInfo.setId("");
                zsReimbursementDetailInfoProcuredMapper.insert(detailInfo);
            }
        }
        // 修改专用发票信息列表
        // 删除原有数据
        LambdaQueryWrapper<ZsReimbursementAmountInfo> amountWrapper = new LambdaQueryWrapper<>();
        amountWrapper.eq(ZsReimbursementAmountInfo::getInfoId, dto.getId());
        amountInfoMapper.delete(amountWrapper);
        if(StringUtils.isNotBlank(dto.getReimbursementType())){
            if("0".equals(dto.getReimbursementType())){
                // 保存专用发票列表信息
                if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
                    for (ZsReimbursementAmountInfo 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<ZsReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                deleteInfo.eq(ZsReimbursementAmountInfo::getInfoId, dto.getId());
                deleteInfo.ne(ZsReimbursementAmountInfo::getReimbursementType, "0");
                amountInfoMapper.delete(deleteInfo);
            }else if("1".equals(dto.getReimbursementType())){
                // 保存电子发票列表信息
                if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                    for (ZsReimAmountAndFileDto amountInfo : dto.getInvoiceReimbursementFiles()) {
                        if (com.jeeplus.utils.StringUtils.isNotBlank(amountInfo.getUrl())){
                            ZsReimbursementAmountInfo reimbursementAmountInfo = new ZsReimbursementAmountInfo();
                            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<ZsReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                deleteInfo.eq(ZsReimbursementAmountInfo::getInfoId, dto.getId());
                deleteInfo.ne(ZsReimbursementAmountInfo::getReimbursementType, "1");
                amountInfoMapper.delete(deleteInfo);

                // 保存电子发票附件列表信息
                if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                    updateFiles(dto.getInvoiceReimbursementFiles(), userDTO, dto.getId(),"invoiceReimbursement");
                }
            }
        }
        /*if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
            for (ZsReimbursementAmountInfo 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())) {
            typeService.updateFiles(dto.getFiles(), userDTO, dto.getId(),"cwWorkContract");
        }
        return info;
    }


    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<ZsReimAmountAndFileDto> list, UserDTO userDTO, String id, String attachmentFlag) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (ZsReimAmountAndFileDto 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 (ZsReimAmountAndFileDto 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<ZsReimbursementDetailInfo>()
                .in(ZsReimbursementDetailInfo::getInfoId, idList));
        // 删除合同列表
        zsReimbursementDetailInfoContractMapper.delete(new LambdaQueryWrapper<ZsReimbursementDetailInfoContract>()
                .in(ZsReimbursementDetailInfoContract::getInfoId, idList));
        // 删除报告列表
        zsReimbursementDetailInfoReportMapper.delete(new LambdaQueryWrapper<ZsReimbursementDetailInfoReport>()
                .in(ZsReimbursementDetailInfoReport::getInfoId, idList));
        // 删除其他报销列表
        zsReimbursementDetailInfoOtherMapper.delete(new LambdaQueryWrapper<ZsReimbursementDetailInfoOther>()
                .in(ZsReimbursementDetailInfoOther::getInfoId, idList));
        // 删除采购报销列表
        zsReimbursementDetailInfoProcuredMapper.delete(new LambdaQueryWrapper<ZsReimbursementDetailInfoProcured>()
                .in(ZsReimbursementDetailInfoProcured::getInfoId, idList));
        // 删除中审项目报销列表
        zsReimbursementDetailInfoProjectMapper.delete(new LambdaQueryWrapper<ZsReimbursementDetailInfoProject>()
                .in(ZsReimbursementDetailInfoProject::getInfoId, idList));

        // 删除专用发票信息列表
        amountInfoMapper.delete(new LambdaQueryWrapper<ZsReimbursementAmountInfo>()
                .in(ZsReimbursementAmountInfo::getInfoId, idList));
        // 删除附件信息
        idList.forEach(id ->
                SpringUtil.getBean(IWorkAttachmentApi.class)
                        .deleteByAttachmentId(id)
        );        return "操作成功";
    }

    /**
     * 根据部门id查询
     * @param ids
     * @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 ZsSaveInfoDto findById(String id) {
        ZsSaveInfoDto dto = new ZsSaveInfoDto();
        // 查询基础信息表
        ZsReimbursementInfo 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);

            // 查询详情列表
//        LambdaQueryWrapper<ZsReimbursementDetailInfo> detailInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        detailInfoLambdaQueryWrapper.eq(ZsReimbursementDetailInfo::getInfoId, id);
//        detailInfoLambdaQueryWrapper.orderByAsc(ZsReimbursementDetailInfo::getNumber);
//        List<ZsReimbursementDetailInfo> detailInfos = detailInfoMapper.selectList(detailInfoLambdaQueryWrapper);
            // 项目报销详情
            List<ZsReimbursementDetailInfo> detailList = infoMapper.getDetailList(id);
            detailList.stream().forEach(projectDetail -> {
                if (org.apache.commons.lang3.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<ZsReimbursementDetailInfoContract> contractDetailList = infoMapper.getContractDetailList(id);
            contractDetailList.stream().forEach(contract -> {
                if (org.apache.commons.lang3.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<ZsReimbursementDetailInfoReport> reportDetailList = infoMapper.getReportDetailList(id);
            reportDetailList.stream().forEach(details -> {
                if (org.apache.commons.lang3.StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            dto.setDetailInfoReports(reportDetailList);
            // 其他报销
            List<ZsReimbursementDetailInfoOther> otherDetailList = infoMapper.getOtherDetailList(id);
            otherDetailList.stream().forEach(details -> {
                if (org.apache.commons.lang3.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<ZsReimbursementDetailInfoProcured> procuredDetailList = infoMapper.getProcuredDetailList(id);
            procuredDetailList.stream().forEach(details -> {
                if (org.apache.commons.lang3.StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            // 中审项目报销
            List<ZsReimbursementDetailInfoProject> zsProjectDetailList = infoMapper.getZsProjectDetailList(id);
            zsProjectDetailList.stream().forEach(details -> {
                if (org.apache.commons.lang3.StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            dto.setDetailInfoProject(zsProjectDetailList);

            // 查询专用发票信息列表
            LambdaQueryWrapper<ZsReimbursementAmountInfo> amountInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            amountInfoLambdaQueryWrapper.eq(ZsReimbursementAmountInfo::getInfoId, id);
            amountInfoLambdaQueryWrapper.eq(ZsReimbursementAmountInfo::getReimbursementType, "0");
            List<ZsReimbursementAmountInfo> amountInfos = amountInfoMapper.selectList(amountInfoLambdaQueryWrapper);
            dto.setAmountInfos(amountInfos);
            LambdaQueryWrapper<ZsReimbursementAmountInfo> invoiceReimbursementsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            invoiceReimbursementsLambdaQueryWrapper.eq(ZsReimbursementAmountInfo::getInfoId, id);
            invoiceReimbursementsLambdaQueryWrapper.eq(ZsReimbursementAmountInfo::getReimbursementType, "1");
            List<ZsReimbursementAmountInfo> invoiceReimbursements = amountInfoMapper.selectList(invoiceReimbursementsLambdaQueryWrapper);
//            dto.setInvoiceReimbursements(invoiceReimbursements);
            // 查询附件信息
            List<WorkAttachmentInfo> fileList = infoMapper.findFiles(id);
            List<WorkAttachmentInfo> files = com.google.common.collect.Lists.newArrayList();
            Set<ZsReimAmountAndFileDto> invoiceReimbursementFiles = new HashSet<>(); // 使用 Set 去重

            if (CollectionUtils.isNotEmpty(fileList)) {
                // 提前为 invoiceReimbursements 构建 URL 到 invoiceReimbursement 的映射，减少嵌套循环
                Map<String, ZsReimbursementAmountInfo> reimbursementMap = new HashMap<>();
                for (ZsReimbursementAmountInfo 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())) {
                        ZsReimbursementAmountInfo invoiceReimbursement = reimbursementMap.get(i.getUrl());
                        if (invoiceReimbursement != null) {
                            // 处理有 URL 匹配的文件
                            processMatchingFiles(i, invoiceReimbursement, invoiceReimbursementFiles);
                        }
                    } else {
                        // 处理其他文件
                        processNonInvoiceFiles(i, files);
                    }
                }
            }
            dto.setFiles(files);
            List<ZsReimAmountAndFileDto> uniqueFilesList = new ArrayList<>(invoiceReimbursementFiles);
            // 按 sort 升序排序
            uniqueFilesList.sort(
                    Comparator.comparing(
                            ZsReimAmountAndFileDto::getSort,
                            Comparator.nullsLast(Integer::compareTo) // null 放到最后
                    )
            );
            dto.setInvoiceReimbursementFiles(uniqueFilesList);
        }
        return dto;
    }


    // 针对 URL 匹配的文件进行处理的提取方法
    private void processMatchingFiles(WorkAttachmentInfo i, ZsReimbursementAmountInfo invoiceReimbursement, Set<ZsReimAmountAndFileDto> invoiceReimbursementFiles) {
        ZsReimAmountAndFileDto ccpmReimAmountAndFileDto = new ZsReimAmountAndFileDto();
        BeanUtils.copyProperties(i, ccpmReimAmountAndFileDto);
        BeanUtils.copyProperties(invoiceReimbursement, ccpmReimAmountAndFileDto);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串转换为 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("");
        }
        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<ZsReimbursementAmountInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZsReimbursementAmountInfo::getNumber, number);
        List<ZsReimbursementAmountInfo> infos = amountInfoMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(infos)) {
            return true;
        }
        return false;
    }

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

    //用户树形
    public List<ZsTreeUserDto> userTree(String name) {
        List<ZsTreeUserDto> list = new ArrayList<>();
        // 查询部门
        List<ZsTreeUserDto> officeList = infoMapper.findOfficeList();
        if (CollectionUtils.isNotEmpty(officeList)) {
            list.addAll(officeList);
        }
        // 查询用户
        List<ZsTreeUserDto> userList = infoMapper.findUserList(name);
        if (CollectionUtils.isNotEmpty(userList)) {
            list.addAll(userList);
        }
        return list;
    }

    /**
     * 下载列表查询
     */
    public List<ZsRetureListDto> exportList(ZsQueryListDto dto) throws Exception{
        QueryWrapper<ZsQueryListDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, ZsQueryListDto.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("(b3.project_id = {0} OR p3.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.approval_time", dto.getDates()[0], dto.getDates()[1]);
        }
        // 经办人
        if (StringUtils.isNotEmpty(dto.getHandled())) {
            queryWrapper.apply("(a.create_by_id = {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("( b3.user_id = {0} OR us3.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("( b3.dept_id = {0} OR so3.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(" (b3.type_id = {0} OR t3.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("b3.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("b3.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("b3.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<ZsRetureListDto> exportList = infoMapper.findExportList(queryWrapper);
        if (CollectionUtils.isNotEmpty(exportList)) {
            for (ZsRetureListDto 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(),"cw_reimbursement_source_type",""));
                }
            }
        }
        return exportList;
    }

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

    /**
     * 根据发票号查询是否已经或正在报销
     * @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<ZsReimbursementAmountInfoDTO> getInvoiceReimbursementAmountList(List<String> idList) {
        List<ZsReimbursementAmountInfoDTO> list = infoMapper.getInvoiceReimbursementAmountList(idList);
        String cwReimbursementSourceTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("invoice_reimbursement_type");
        for (ZsReimbursementAmountInfoDTO 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<ZsReimbursementInfoUpHi> findHistory(String id) {

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

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

    /**
     * 修改付款状态
     * @param id
     */
    public String updatePaymentStatus(String id,String paymentStatus) {
        //根据id查询报销信息
        ZsReimbursementInfo 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 ZsSaveInfoDto findFileById(String id) {
        ZsSaveInfoDto dto = new ZsSaveInfoDto();
        String reimId = "";
        //查询文件补充信息
        ZsReimbursementFileSupplement supplement = zsReimbursementFileSupplementMapper.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;
        }
        // 查询基础信息表
        ZsReimbursementInfo 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 );
            // 查询详情列表
//        LambdaQueryWrapper<ZsReimbursementDetailInfo> detailInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        detailInfoLambdaQueryWrapper.eq(ZsReimbursementDetailInfo::getInfoId, id);
//        detailInfoLambdaQueryWrapper.orderByAsc(ZsReimbursementDetailInfo::getNumber);
//        List<ZsReimbursementDetailInfo> detailInfos = detailInfoMapper.selectList(detailInfoLambdaQueryWrapper);
            // 项目报销详情
            List<ZsReimbursementDetailInfo> detailList = infoMapper.getDetailList(reimId);
            detailList.stream().forEach(projectDetail -> {
                if (org.apache.commons.lang3.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<ZsReimbursementDetailInfoContract> contractDetailList = infoMapper.getContractDetailList(reimId);
            contractDetailList.stream().forEach(contract -> {
                if (org.apache.commons.lang3.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<ZsReimbursementDetailInfoReport> reportDetailList = infoMapper.getReportDetailList(reimId);
            reportDetailList.stream().forEach(details -> {
                if (org.apache.commons.lang3.StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            dto.setDetailInfoReports(reportDetailList);
            // 其他报销
            List<ZsReimbursementDetailInfoOther> otherDetailList = infoMapper.getOtherDetailList(reimId);
            otherDetailList.stream().forEach(details -> {
                if (org.apache.commons.lang3.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<ZsReimbursementDetailInfoProcured> procuredDetailList = infoMapper.getProcuredDetailList(reimId);
            procuredDetailList.stream().forEach(details -> {
                if (org.apache.commons.lang3.StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            // 中审项目报销
            List<ZsReimbursementDetailInfoProject> zsProjectDetailList = infoMapper.getZsProjectDetailList(reimId);
            zsProjectDetailList.stream().forEach(details -> {
                if (org.apache.commons.lang3.StringUtils.isBlank(details.getUserName())){
                    //处理用户名
                    String names = userApi.getNamesByIds(details.getUserId());
                    details.setUserName(names);
                    //处理部门名
                    String offices = getOfficeNameByIds(details.getDeptId());
                    details.setDeptName(offices);
                }
            });
            dto.setDetailInfoProject(zsProjectDetailList);
            // 查询专用发票信息列表
            LambdaQueryWrapper<ZsReimbursementAmountInfo> amountInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            amountInfoLambdaQueryWrapper.eq(ZsReimbursementAmountInfo::getInfoId, reimId);
            amountInfoLambdaQueryWrapper.eq(ZsReimbursementAmountInfo::getReimbursementType, "0");
            List<ZsReimbursementAmountInfo> amountInfos = amountInfoMapper.selectList(amountInfoLambdaQueryWrapper);
            dto.setAmountInfos(amountInfos);
            LambdaQueryWrapper<ZsReimbursementAmountInfo> invoiceReimbursementsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            invoiceReimbursementsLambdaQueryWrapper.eq(ZsReimbursementAmountInfo::getInfoId, reimId);
            invoiceReimbursementsLambdaQueryWrapper.eq(ZsReimbursementAmountInfo::getReimbursementType, "1");
            List<ZsReimbursementAmountInfo> invoiceReimbursements = amountInfoMapper.selectList(invoiceReimbursementsLambdaQueryWrapper);
//            dto.setInvoiceReimbursements(invoiceReimbursements);
            // 查询附件信息
            List<WorkAttachmentInfo> fileList = infoMapper.findFiles(reimId);
            List<WorkAttachmentInfo> files = com.google.common.collect.Lists.newArrayList();
            Set<ZsReimAmountAndFileDto> invoiceReimbursementFiles = new HashSet<>(); // 使用 Set 去重

            if (CollectionUtils.isNotEmpty(fileList)) {
                // 提前为 invoiceReimbursements 构建 URL 到 invoiceReimbursement 的映射，减少嵌套循环
                Map<String, ZsReimbursementAmountInfo> reimbursementMap = new HashMap<>();
                for (ZsReimbursementAmountInfo 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())) {
                        ZsReimbursementAmountInfo 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 (ZsReimbursementAmountInfo reimbursement : invoiceReimbursements) {
//                                        String key = entry.getKey();
//                                        String value = entry.getValue();
//                                        if (reimbursement.getNumber().equals(key) && i.getUrl().equals(value)){
//                                            ZsReimAmountAndFileDto ccpmReimAmountAndFileDto = new ZsReimAmountAndFileDto();
//                                            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<ZsReimAmountAndFileDto> uniqueFilesList = new ArrayList<>(invoiceReimbursementFiles);
            dto.setInvoiceReimbursementFiles(uniqueFilesList);
        }
        return dto;
    }


    /**
     * 新增/修改  文件补充
     * @param dto
     * @return
     * @throws Exception
     */
    public ZsReimbursementFileSupplement saveFile(ZsSaveInfoDto dto) throws Exception{
        // 获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        ZsReimbursementInfo info = infoMapper.selectById(dto.getId());
        UserDTO user = SpringUtil.getBean(IUserApi.class).getById(info.getCreateById());
        if (StringUtils.isNotEmpty(dto.getFileSuppleId())) {
            // 修改专用发票信息列表
            // 删除原有数据
            LambdaQueryWrapper<ZsReimbursementAmountInfo> amountWrapper = new LambdaQueryWrapper<>();
            amountWrapper.eq(ZsReimbursementAmountInfo::getInfoId, dto.getId());
            amountInfoMapper.delete(amountWrapper);
            if(StringUtils.isNotBlank(dto.getReimbursementType())){
                if("0".equals(dto.getReimbursementType())){
                    // 保存专用发票列表信息
                    if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
                        for (ZsReimbursementAmountInfo 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<ZsReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                    deleteInfo.eq(ZsReimbursementAmountInfo::getInfoId, dto.getId());
                    deleteInfo.ne(ZsReimbursementAmountInfo::getReimbursementType, "0");
                    amountInfoMapper.delete(deleteInfo);
                }else if("1".equals(dto.getReimbursementType())){
                    // 保存电子发票列表信息
                    if (CollectionUtils.isNotEmpty(dto.getInvoiceReimbursementFiles())) {
                        for (ZsReimAmountAndFileDto amountInfo : dto.getInvoiceReimbursementFiles()) {
                            if (com.jeeplus.utils.StringUtils.isNotBlank(amountInfo.getUrl())){
                                ZsReimbursementAmountInfo reimbursementAmountInfo = new ZsReimbursementAmountInfo();
                                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<ZsReimbursementAmountInfo> deleteInfo = new LambdaQueryWrapper<>();
                    deleteInfo.eq(ZsReimbursementAmountInfo::getInfoId, dto.getId());
                    deleteInfo.ne(ZsReimbursementAmountInfo::getReimbursementType, "1");
                    amountInfoMapper.delete(deleteInfo);

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

            fileSupplement.setNo(info.getNo());
            fileSupplement.setName(user.getName());
            return fileSupplement;
        } else {
            //修改报销基本信息
            ZsReimbursementInfo reimbursementInfo = new ZsReimbursementInfo();
            reimbursementInfo.setReimbursementType(dto.getReimbursementType());
            reimbursementInfo.setId(dto.getId());
            reimbursementInfo.setUpdateTime(new Date());
            infoMapper.updateById(reimbursementInfo);
            // 生成id
            String id = UUID.randomUUID().toString().replace("-", "");
            ZsReimbursementFileSupplement fileSupplement = new ZsReimbursementFileSupplement();
            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());
            zsReimbursementFileSupplementMapper.insert(fileSupplement);
            fileSupplement.setNo(info.getNo());
            fileSupplement.setName(user.getName());
            return fileSupplement;
        }
    }

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


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

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

            if (CollectionUtil.isNotEmpty(invoiceReimbursements)) {
                // 将所有的报销id进行存储
                for (ZsReimbursementAmountInfo 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 (ZsReimbursementAmountInfo 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();
        }
    }


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


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