package com.jeeplus.business.reimbursement.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
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.business.payment.mapper.PaymentMapper;
import com.jeeplus.business.payment.service.dto.PaymentDTO;
import com.jeeplus.business.project.domain.JyProject;
import com.jeeplus.business.project.mapper.JyProjectMapper;
import com.jeeplus.business.project.service.JyProjectService;
import com.jeeplus.business.project.service.dto.JyProjectDTO;
import com.jeeplus.business.reimbursement.domain.*;
import com.jeeplus.business.reimbursement.mapper.*;
import com.jeeplus.business.reimbursement.service.dto.JyReimbursementInfoDTO;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IOfficeApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class JyReimbursementInfoService {
    @Resource
    private JyReimbursementInfoMapper jyReimbursementInfoMapper;

    @Resource
    private JyProjectService jyProjectService;

    @Resource
    private JyReimbursementInfoPaymentMapper jyReimbursementInfoPaymentMapper;

    @Resource
    private JyReimbursementInfoProjectMapper jyReimbursementInfoProjectMapper;

    @Resource
    private JyReimbursementInfoBorrowMapper jyReimbursementInfoBorrowMapper;

    @Resource
    private JyReimbursementInfoOtherMapper jyReimbursementInfoOtherMapper;

    @Resource
    private JyReimbursementAmountInfoMapper jyReimbursementAmountInfoMapper;

    @Resource
    private JyProjectMapper jyProjectMapper;

    @Resource
    private PaymentMapper paymentMapper;


    /**
     * 列表查询
     * @param page
     * @param dto
     * @return
     */
    public IPage<JyReimbursementInfoDTO> list(Page<JyReimbursementInfoDTO> page, JyReimbursementInfoDTO dto) throws Exception {
        QueryWrapper<JyReimbursementInfoDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, JyReimbursementInfoDTO.class);
        queryWrapper.eq("a.del_flag", 0);
        // 报销时间
        if (dto.getDates() != null) {
            queryWrapper.between("a.create_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() + "%");
        }
        // 报销状态
        if (StringUtils.isNotEmpty(dto.getStatus())) {
            queryWrapper.eq("a.status", dto.getStatus());
        }
        // 报销部门
        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() + "%");

        }
        // 报销类别
        if (StringUtils.isNotEmpty(dto.getRemiType())) {
            queryWrapper.apply(" (b.type_id = {0} OR b.type_name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b2.type_id = {0} OR b.type_name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b3.type_id = {0} OR b.type_name LIKE {1}) ", dto.getRemiType(), "%" + dto.getRemiType() + "%");
            queryWrapper.or().apply(" (b4.type_id = {0} OR b.type_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]))
                );
            }
            if (dto.getAmounts().length>1 && 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]))
                );
            }
        }
        // 报销类型
        if (StringUtils.isNotBlank(dto.getApplyType())) {
            queryWrapper.eq("a.apply_type", dto.getApplyType());
        }
        IPage<JyReimbursementInfoDTO> list = jyReimbursementInfoMapper.findPageList(page, queryWrapper);
        list.getRecords().stream().forEach(item -> {
            if (StringUtils.isNotBlank(item.getApplyType()) && "4".equals(item.getApplyType())) { //项目报销
                if (StringUtils.isNotBlank(item.getProjectId())) {
                    String proName = selectProjectByIds(item.getProjectId());
                    item.setProjectName(proName);
                }
            }
        });
        return list;

    }

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


    /**
     * 新增/修改
     * @param dto
     * @return
     */
    public String save(JyReimbursementInfoDTO 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 String add(JyReimbursementInfoDTO dto, UserDTO userDTO) throws Exception{
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE, TokenProvider.getCurrentToken());
        // 保存基础信息表信息
        JyReimbursementInfo jyReimbursementInfo = new JyReimbursementInfo();
        BeanUtils.copyProperties(dto, jyReimbursementInfo);
        jyReimbursementInfo.setId(id);
        jyReimbursementInfo.setNo(no);
        jyReimbursementInfo.setCreateById(userDTO.getId());
        jyReimbursementInfo.setCreateTime(new Date());
        jyReimbursementInfo.setUpdateById(userDTO.getId());
        jyReimbursementInfo.setUpdateTime(new Date());
        jyReimbursementInfo.setDelFlag(0);
        jyReimbursementInfoMapper.insert(jyReimbursementInfo);
        // 保存项目详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getInfoProjects())) {
            for (JyReimbursementDetailInfoProject detailInfo : dto.getInfoProjects()) {
                // 保存基础表信息主键值
                String pid = UUID.randomUUID().toString().replace("-", "");
                detailInfo.setId(pid);
                detailInfo.setInfoId(id);
                jyReimbursementInfoProjectMapper.insert(detailInfo);
            }
        }
        // 保存借款详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getInfoborrows())) {
            for (JyReimbursementDetailInfoBorrow detailInfo : dto.getInfoborrows()) {
                // 保存基础表信息主键值
                String pid = UUID.randomUUID().toString().replace("-", "");
                detailInfo.setId(pid);
                detailInfo.setInfoId(id);
                jyReimbursementInfoBorrowMapper.insert(detailInfo);
            }
        }
        // 保存付款详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getInfoPayments())) {
            for (JyReimbursementDetailInfoPayment detailInfo : dto.getInfoPayments()) {
                // 保存基础表信息主键值
                String pid = UUID.randomUUID().toString().replace("-", "");
                detailInfo.setId(pid);
                detailInfo.setInfoId(id);
                jyReimbursementInfoPaymentMapper.insert(detailInfo);
            }
        }
        // 保存其他报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getInfoOthers())) {
            for (JyReimbursementDetailInfoOther detailInfo : dto.getInfoOthers()) {
                // 保存基础表信息主键值
                String pid = UUID.randomUUID().toString().replace("-", "");
                detailInfo.setId(pid);
                detailInfo.setInfoId(id);
                jyReimbursementInfoOtherMapper.insert(detailInfo);
            }
        }
        // 保存专用发票列表信息
        if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
            for (JyReimbursementAmountInfo 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(id);
                jyReimbursementAmountInfoMapper.insert(amountInfo);
            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            saveFiles(dto.getFiles(), userDTO, id);
        }
        return id;
    }

    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentInfo dto : list) {
            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(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("jyReimbursement");
            i.setFileSize(dto.getSize());
            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 String update(JyReimbursementInfoDTO dto, UserDTO userDTO) {
        // 修改基础信息
        JyReimbursementInfo info = new JyReimbursementInfo();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        jyReimbursementInfoMapper.updateById(info);
        // 修改报销详情列表信息
        // 删除原有数据
        LambdaQueryWrapper<JyReimbursementDetailInfoProject> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(JyReimbursementDetailInfoProject::getInfoId, dto.getId());
        jyReimbursementInfoProjectMapper.delete(detailWrapper);
        // 删除借款列表
        LambdaQueryWrapper<JyReimbursementDetailInfoBorrow> detailWrapperContract = new LambdaQueryWrapper<>();
        detailWrapperContract.eq(JyReimbursementDetailInfoBorrow::getInfoId, dto.getId());
        jyReimbursementInfoBorrowMapper.delete(detailWrapperContract);
        // 删除付款列表
        LambdaQueryWrapper<JyReimbursementDetailInfoPayment> detailWrapperReport = new LambdaQueryWrapper<>();
        detailWrapperReport.eq(JyReimbursementDetailInfoPayment::getInfoId, dto.getId());
        jyReimbursementInfoPaymentMapper.delete(detailWrapperReport);
        // 删除其他报销表
        LambdaQueryWrapper<JyReimbursementDetailInfoOther> detailWrapperOthers = new LambdaQueryWrapper<>();
        detailWrapperOthers.eq(JyReimbursementDetailInfoOther::getInfoId, dto.getId());
        jyReimbursementInfoOtherMapper.delete(detailWrapperOthers);

        // 保存项目详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getInfoProjects())) {
            for (JyReimbursementDetailInfoProject detailInfo : dto.getInfoProjects()) {
                // 保存基础表信息主键值
                String id = UUID.randomUUID().toString().replace("-", "");
                detailInfo.setId(id);
                detailInfo.setInfoId(dto.getId());
                jyReimbursementInfoProjectMapper.insert(detailInfo);
            }
        }
        // 保存借款详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getInfoborrows())) {
            for (JyReimbursementDetailInfoBorrow detailInfo : dto.getInfoborrows()) {
                // 保存基础表信息主键值
                String id = UUID.randomUUID().toString().replace("-", "");
                detailInfo.setId(id);
                detailInfo.setInfoId(dto.getId());
                jyReimbursementInfoBorrowMapper.insert(detailInfo);
            }
        }
        // 保存付款详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getInfoPayments())) {
            for (JyReimbursementDetailInfoPayment detailInfo : dto.getInfoPayments()) {
                // 保存基础表信息主键值
                String id = UUID.randomUUID().toString().replace("-", "");
                detailInfo.setId(id);
                detailInfo.setInfoId(dto.getId());
                jyReimbursementInfoPaymentMapper.insert(detailInfo);
            }
        }
        // 保存其他报销详情列表信息
        if (CollectionUtils.isNotEmpty(dto.getInfoOthers())) {
            for (JyReimbursementDetailInfoOther detailInfo : dto.getInfoOthers()) {
                // 保存基础表信息主键值
                String id = UUID.randomUUID().toString().replace("-", "");
                detailInfo.setId(id);
                detailInfo.setInfoId(dto.getId());
                jyReimbursementInfoOtherMapper.insert(detailInfo);
            }
        }

        // 修改专用发票信息列表
        // 删除原有数据
        LambdaQueryWrapper<JyReimbursementAmountInfo> amountWrapper = new LambdaQueryWrapper<>();
        amountWrapper.eq(JyReimbursementAmountInfo::getInfoId, dto.getId());
        jyReimbursementAmountInfoMapper.delete(amountWrapper);
        if (CollectionUtils.isNotEmpty(dto.getAmountInfos())) {
            for (JyReimbursementAmountInfo 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());
                jyReimbursementAmountInfoMapper.insert(amountInfo);
            }
        }
        // 修改附件信息列表
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        return dto.getId();
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentInfo dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = jyReimbursementInfoMapper.findList(id);
        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 (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = jyReimbursementInfoMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                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(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("jyReimbursement");
                i.setFileSize(dto.getSize());
                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++;
            }
        }
    }


    /**
     * 删除
     * @param id
     * @return
     */
    public String remove(String id) {
        //删除基本信息
        jyReimbursementInfoMapper.deleteById(id);
        // 修改报销详情列表信息
        // 删除原有数据
        LambdaQueryWrapper<JyReimbursementDetailInfoProject> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(JyReimbursementDetailInfoProject::getInfoId,id);
        jyReimbursementInfoProjectMapper.delete(detailWrapper);
        // 删除借款列表
        LambdaQueryWrapper<JyReimbursementDetailInfoBorrow> detailWrapperContract = new LambdaQueryWrapper<>();
        detailWrapperContract.eq(JyReimbursementDetailInfoBorrow::getInfoId, id);
        jyReimbursementInfoBorrowMapper.delete(detailWrapperContract);
        // 删除付款列表
        LambdaQueryWrapper<JyReimbursementDetailInfoPayment> detailWrapperReport = new LambdaQueryWrapper<>();
        detailWrapperReport.eq(JyReimbursementDetailInfoPayment::getInfoId,id);
        jyReimbursementInfoPaymentMapper.delete(detailWrapperReport);
        // 删除其他报销表
        LambdaQueryWrapper<JyReimbursementDetailInfoOther> detailWrapperOthers = new LambdaQueryWrapper<>();
        detailWrapperOthers.eq(JyReimbursementDetailInfoOther::getInfoId, id);
        jyReimbursementInfoOtherMapper.delete(detailWrapperOthers);
        // 修改专用发票信息列表
        // 删除原有数据
        LambdaQueryWrapper<JyReimbursementAmountInfo> amountWrapper = new LambdaQueryWrapper<>();
        amountWrapper.eq(JyReimbursementAmountInfo::getInfoId, id);
        jyReimbursementAmountInfoMapper.delete(amountWrapper);
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "操作成功";
    }

    public JyReimbursementInfoDTO findById(String id) {
        JyReimbursementInfoDTO jyReimbursementInfoDTO = new JyReimbursementInfoDTO();
        // 查询基础信息表
        JyReimbursementInfo info = jyReimbursementInfoMapper.findById(id);
            // 项目报销详情
            List<JyReimbursementDetailInfoProject> detailList = jyReimbursementInfoMapper.getProjectDetailList(id);
            detailList.stream().forEach(projectDetail -> {
                if (StringUtils.isNotBlank(projectDetail.getProjectId())) {
                    String proName = selectProjectByIds(projectDetail.getProjectId());
                    projectDetail.setProjectName(proName);
                } else {
                    projectDetail.setProjectName("");
                }
            });
        jyReimbursementInfoDTO.setInfoProjects(detailList);
            // 借款报销详情
        jyReimbursementInfoDTO.setInfoborrows(jyReimbursementInfoMapper.getBorrowDetailList(id));
            // 付款报销详情
        jyReimbursementInfoDTO.setInfoPayments(jyReimbursementInfoMapper.getPaymentDetailList(id));
            // 其他报销
        jyReimbursementInfoDTO.setInfoOthers(jyReimbursementInfoMapper.getOtherDetailList(id));
            // 查询专用发票信息列表
            LambdaQueryWrapper<JyReimbursementAmountInfo> amountInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            amountInfoLambdaQueryWrapper.eq(JyReimbursementAmountInfo::getInfoId, id);
            List<JyReimbursementAmountInfo> amountInfos = jyReimbursementAmountInfoMapper.selectList(amountInfoLambdaQueryWrapper);
        jyReimbursementInfoDTO.setAmountInfos(amountInfos);
            // 查询附件信息
            List<WorkAttachmentInfo> files = jyReimbursementInfoMapper.findFiles(id);
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentInfo i : files) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
        jyReimbursementInfoDTO.setFiles(files);
            if (ObjectUtils.isNotEmpty(info)){
                jyReimbursementInfoDTO.setApplyType(info.getApplyType());
                jyReimbursementInfoDTO.setRemarks(info.getRemarks());
                jyReimbursementInfoDTO.setUserId(info.getUserId());
                jyReimbursementInfoDTO.setCreateName(info.getCreateName());
                jyReimbursementInfoDTO.setDepartment(info.getDepartment());
                jyReimbursementInfoDTO.setDepartmentName(info.getDepartmentName());
                jyReimbursementInfoDTO.setCreateTime(info.getCreateTime());
                jyReimbursementInfoDTO.setNo(info.getNo());
                jyReimbursementInfoDTO.setId(info.getId());
                jyReimbursementInfoDTO.setStatus(info.getStatus());
                jyReimbursementInfoDTO.setProcInsId(info.getProcInsId());
            }

        return jyReimbursementInfoDTO;
    }


    public void updateStatusById(JyReimbursementInfoDTO dto) {
        jyReimbursementInfoMapper.updateStatusById(dto.getStatus(),dto.getId());
    }


    public List<JyProjectDTO> queryByProIds(String ids) {
        String[] split = ids.split(",");
        ArrayList<JyProjectDTO> projects = new ArrayList<>();
        for (String s : split) {
            JyProjectDTO byId = jyProjectService.findById(s);
            projects.add(byId);
        }
        return projects;
    }

    /**
     * 根据项目id查询报销信息
     * @param projectId
     * @return
     */
    public List<JyReimbursementInfoDTO> queryByProjectId(String projectId) {
        //查询项目报销数据
        List<JyReimbursementInfoDTO> list = jyReimbursementInfoMapper.queryByProjectId(projectId);
        //若报销为多项目报销,则需要对报销金额做一个平均处理
        if (CollectionUtils.isNotEmpty(list)){
            for (JyReimbursementInfoDTO infoDTO : list) {
                if (infoDTO.getProjectId() != null && infoDTO.getProjectId().contains(",")) {
                    // 先对项目id进行切割,获取项目数量
                    String[] ids = infoDTO.getProjectId().split(",");
                    int totalProjects = ids.length;

                    // infoDTO.getNumber()返回一个BigDecimal对象
                    BigDecimal originalNumber = infoDTO.getNumber();
                    if (originalNumber != null) {
                        // 对报销金额做平均处理
                        BigDecimal size = BigDecimal.valueOf(totalProjects);
                        // 使用setScale方法来保留两位小数，并四舍五入
                        BigDecimal finalNumber = originalNumber.divide(size, 2, RoundingMode.HALF_UP);
                        infoDTO.setNumber(finalNumber);
                    }
                }
            }
        }


        //存放报销冲抵完成的集合
        ArrayList<JyReimbursementInfoDTO> successList = new ArrayList<>();
        //根据项目id查找付款信息
        List<PaymentDTO> paymentDTOList = paymentMapper.queryByProjectId(projectId);
        if (CollectionUtils.isNotEmpty(paymentDTOList)){
            for (PaymentDTO paymentDTO : paymentDTOList) {
                //付款金额
                BigDecimal payment = new BigDecimal(paymentDTO.getPaymentLower());
                //根据付款id查询报销信息
                List<JyReimbursementInfoDTO> payReimList = jyReimbursementInfoMapper.queryByProjectId(paymentDTO.getId());
                BigDecimal total = BigDecimal.ZERO;
                if (CollectionUtils.isNotEmpty(payReimList)){
                    //将所有的报销金额汇总
                    for (JyReimbursementInfoDTO reim : payReimList) {
                        BigDecimal originalNumber = reim.getNumber();
                        total = total.add(originalNumber);
                    }
                }
                //判断报销总金额与付款金额是否冲抵完成
                if (payment.equals(total)){
                    list.addAll(payReimList);
                }
            }
        }
        //去重,避免有重复的数据
        List<JyReimbursementInfoDTO> infoDTOList = list.stream().distinct().collect(Collectors.toList());
        return infoDTOList;
    }
}
