package com.jeeplus.test.reimbursementProject.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.test.reimbursementProject.domain.dto.ProjectReimbursementDTO;
import com.jeeplus.test.reimbursementProject.mapper.ProjectReimbursementSysMapper;
import com.jeeplus.test.reimbursementProject.service.ProjectReimbursementBusinessService;
import com.jeeplus.test.reimbursementProject.service.ProjectReimbursementSysService;
import com.jeeplus.test.reimbursementAccountant.utils.MyBeanUtils;
import com.jeeplus.test.reimbursementsys.domain.dto.ReimbursementDTO;
import com.jeeplus.test.reimbursementsys.utils.PublicUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author li-peike
 * @version 1.0.0
 * @ClassName ReimbursementSysServiceImpl.java
 * @Description TODO
 * @createTime 2022年05月06日 10:38:00
 */
@Service
@Transactional(readOnly = true)
public class ProjectReimbursementSysServiceImpl implements ProjectReimbursementSysService {

    @Autowired
    private ProjectReimbursementSysMapper mapper;
    @Autowired
    private ProjectReimbursementBusinessService reimbursementBusinessService;


    @Override
    public ProjectReimbursementDTO queryBusinessById(String id) {
        //根据发票id查询业务具体信息
        ProjectReimbursementDTO reimbursementDTO = mapper.queryBusinessById(id);
        //如果没有随即类型，则将随即类型默认为非随机（即指定业务编码）
        if(StringUtils.isBlank(reimbursementDTO.getRandomType())){
            reimbursementDTO.setRandomType("0");
        }
        return reimbursementDTO;
    }

    @Override
    public ProjectReimbursementDTO queryBusinessByInvoiceId(String id) {
        //根据发票id查询业务具体信息
        ProjectReimbursementDTO projectReimbursementDTO = mapper.queryBusinessByInvoiceId(id);
        //如果没有随即类型，则将随即类型默认为非随机（即指定业务编码）
        if(null != projectReimbursementDTO && StringUtils.isBlank(projectReimbursementDTO.getRandomType())){
            projectReimbursementDTO.setRandomType("0");
        }
        return projectReimbursementDTO;
    }

    @Override
    public ProjectReimbursementDTO queryInvoiceById(String id) {
        return mapper.queryInvoiceById(id);
    }

    @Override
    public IPage<ProjectReimbursementDTO> findList(Page<ProjectReimbursementDTO> page, ProjectReimbursementDTO reimbursement) {
        IPage<ProjectReimbursementDTO> list = mapper.findList(page, reimbursement);
        return list;
    }

    @Override
    public List<ProjectReimbursementDTO> findPage(Page<ProjectReimbursementDTO> page, ProjectReimbursementDTO reimbursement) {
        IPage<ProjectReimbursementDTO> pageList = new Page();
        List<ProjectReimbursementDTO> returnList =  Lists.newArrayList();
        //如果筛选项含有发票号码，则需先查询对应的发票信息
        if(StringUtils.isNotBlank(reimbursement.getInvoiceNumber()) ||
                StringUtils.isNotBlank(reimbursement.getProposer()) ||
                StringUtils.isNotBlank(reimbursement.getPartner()) ||
                null != reimbursement.getBeginDate() ||
                null != reimbursement.getEndDate() ||
                StringUtils.isNotBlank(reimbursement.getBeginIncome()) ||
                StringUtils.isNotBlank(reimbursement.getEndIncome()) ||
                StringUtils.isNotBlank(reimbursement.getFirmName())){
            List<ProjectReimbursementDTO> invoiceList =  mapper.getInvoiceList(reimbursement);
            //如果存在发票信息，则根据发票的父节点查询对应的业务信息
            if(invoiceList.size()>0){
                Set<String> idSet = new HashSet<String>();
                for (ProjectReimbursementDTO  info : invoiceList) {
                    idSet.add(info.getParentId());
                }
                reimbursement.setIdList(new ArrayList<>(idSet));
                pageList = mapper.queryAllList(page,reimbursement);

                List<ProjectReimbursementDTO> list =  pageList.getRecords();
                if(list.size()>0){
                    //将子节点信息进行分组
                    Map<String, List<ProjectReimbursementDTO>> invoiceListMap = dataMessageDispose(invoiceList);
                    //将分组后的子节点信息通过遍历的方式添加到父节点中的children中
                    for (ProjectReimbursementDTO info:list) {
                        /*ProjectReimbursementDTO businessById = reimbursementBusinessService.getBusinessById(info.getId());
                        if(null != businessById){
                            info.setAllAlreadyReimbursementQuota(businessById.getAllAlreadyReimbursementQuota());
                            info.setCanReimbursementAmount(businessById.getCanReimbursementAmount());
                            info.setSurplusReimbursementAmount(businessById.getSurplusReimbursementAmount());
                        }
                        returnList.add(info);*/
                        for (String key : invoiceListMap.keySet()) {
                            if (info.getId().equals(key)) {
                                List<ProjectReimbursementDTO> children = invoiceListMap.get(key);
                                for (ProjectReimbursementDTO childrenInfo : children) {
                                    childrenInfo.setBusinessCode(info.getBusinessCode());
                                    returnList.add(childrenInfo);
                                }
                                info.setChildren(children);
                            }
                        }
                    }
                }
            }else{
                return page.getRecords();
            }
        }else{
            pageList = mapper.queryAllList(page,reimbursement);
            List<ProjectReimbursementDTO> list =  pageList.getRecords();
            if(list.size()>0){
                //获取所有发票信息表中的数据
                List<String> parentIdList = Lists.newArrayList();
                for (ProjectReimbursementDTO info:list) {
                    parentIdList.add(info.getId());
                }
                //根据查询的父节点信息查询对应的子节点信息
                List<ProjectReimbursementDTO> invoiceList =  mapper.getInvoiceByParentIdList(parentIdList);
                if(list.size()>0){
                    //将子节点信息进行分组
                    Map<String, List<ProjectReimbursementDTO>> invoiceListMap = dataMessageDispose(invoiceList);
                    //将分组后的子节点信息通过遍历的方式添加到父节点中的children中
                    for (ProjectReimbursementDTO info:list) {
                        /*ProjectReimbursementDTO businessById = reimbursementBusinessService.getBusinessById(info.getId());
                        if(null != businessById){
                            info.setAllAlreadyReimbursementQuota(businessById.getAllAlreadyReimbursementQuota());
                            info.setCanReimbursementAmount(businessById.getCanReimbursementAmount());
                            info.setSurplusReimbursementAmount(businessById.getSurplusReimbursementAmount());
                        }
                        returnList.add(info);*/
                        for (String key : invoiceListMap.keySet()) {
                            if (info.getId().equals(key)) {
                                List<ProjectReimbursementDTO> children = invoiceListMap.get(key);
                                for (ProjectReimbursementDTO childrenInfo : children) {
                                    childrenInfo.setBusinessCode(info.getBusinessCode());
                                    returnList.add(childrenInfo);
                                }
                                info.setChildren(children);
                            }
                        }
                    }
                }
            }
        }

        return returnList;
    }


    @Override
    public IPage<ProjectReimbursementDTO> treeData(Page<ProjectReimbursementDTO> page, ProjectReimbursementDTO reimbursement) {
        IPage<ProjectReimbursementDTO> pageList = new Page();
        //如果筛选项含有发票号码，则需先查询对应的发票信息
        if(StringUtils.isNotBlank(reimbursement.getInvoiceNumber()) ||
                StringUtils.isNotBlank(reimbursement.getProposer()) ||
                StringUtils.isNotBlank(reimbursement.getPartner()) ||
                null != reimbursement.getBeginDate() ||
                null != reimbursement.getEndDate() ||
                StringUtils.isNotBlank(reimbursement.getBeginIncome()) ||
                StringUtils.isNotBlank(reimbursement.getReimbursementBatch()) ||
                StringUtils.isNotBlank(reimbursement.getEndIncome()) ||
                StringUtils.isNotBlank(reimbursement.getFirmName())){
            List<ProjectReimbursementDTO> invoiceList =  mapper.getInvoiceList(reimbursement);
            //如果存在发票信息，则根据发票的父节点查询对应的业务信息
            if(invoiceList.size()>0){
                Set<String> idSet = new HashSet<String>();
                for (ProjectReimbursementDTO  info : invoiceList) {
                    idSet.add(info.getParentId());
                }
                reimbursement.setIdList(new ArrayList<>(idSet));
                pageList = mapper.queryAllList(page,reimbursement);

                List<ProjectReimbursementDTO> list =  pageList.getRecords();
                if(list.size()>0){
                    //将子节点信息进行分组
                    Map<String, List<ProjectReimbursementDTO>> invoiceListMap = dataMessageDispose(invoiceList);
                    //将分组后的子节点信息通过遍历的方式添加到父节点中的children中
                    for (ProjectReimbursementDTO info:list) {
                        for (String key : invoiceListMap.keySet()) {
                            if (info.getId().equals(key)) {
                                List<ProjectReimbursementDTO> children = invoiceListMap.get(key);
                                if(StringUtils.isNotBlank(info.getBusinessCode()) || "1".equals(info.getBatchFlag())){
                                    info.setChildren(children);
                                    info.setBusinessFlag("0");
                                }else{
                                    //空业务编码添加状态
                                    info.setBusinessFlag("1");
                                    MyBeanUtils.copyBeanNotNull2Bean(children.get(0), info);//将编辑表单中的非NULL值覆盖数据库记录中的值
                                }
                            }
                        }
                        ProjectReimbursementDTO businessById = reimbursementBusinessService.getBusinessById(info.getId());
                        if(null != businessById){
                            info.setAllAlreadyReimbursementQuota(businessById.getAllAlreadyReimbursementQuota());
                            info.setCanReimbursementAmount(businessById.getCanReimbursementAmount());
                            info.setSurplusReimbursementAmount(businessById.getSurplusReimbursementAmount());
                        }
                    }
                }
            }else{
                return page;
            }
        }else{
            pageList = mapper.queryAllList(page,reimbursement);
            List<ProjectReimbursementDTO> list =  pageList.getRecords();
            if(list.size()>0){
                //获取所有发票信息表中的数据
                List<String> parentIdList = Lists.newArrayList();
                for (ProjectReimbursementDTO info:list) {
                    parentIdList.add(info.getId());
                }
                //根据查询的父节点信息查询对应的子节点信息
                List<ProjectReimbursementDTO> invoiceList =  mapper.getInvoiceByParentIdList(parentIdList);
                if(invoiceList.size()>0){
                    //将子节点信息进行分组
                    Map<String, List<ProjectReimbursementDTO>> invoiceListMap = dataMessageDispose(invoiceList);
                    //将分组后的子节点信息通过遍历的方式添加到父节点中的children中
                    for (ProjectReimbursementDTO info:list) {
                        for (String key : invoiceListMap.keySet()) {
                            if (info.getId().equals(key)) {
                                List<ProjectReimbursementDTO> children = invoiceListMap.get(key);
                                if(StringUtils.isNotBlank(info.getBusinessCode()) || "1".equals(info.getBatchFlag())){
                                    info.setChildren(children);
                                    info.setBusinessFlag("0");
                                }else{
                                    //空业务编码添加状态
                                    info.setBusinessFlag("1");
                                    MyBeanUtils.copyBeanNotNull2Bean(children.get(0), info);//将编辑表单中的非NULL值覆盖数据库记录中的值
                                }
                            }
                        }
                        ProjectReimbursementDTO businessById = reimbursementBusinessService.getBusinessById(info.getId());
                        if(null != businessById){
                            info.setAllAlreadyReimbursementQuota(businessById.getAllAlreadyReimbursementQuota());
                            info.setCanReimbursementAmount(businessById.getCanReimbursementAmount());
                            info.setSurplusReimbursementAmount(businessById.getSurplusReimbursementAmount());
                        }
                    }
                }
            }
        }

        return pageList;
    }

    /**
     * 文件数据分组
     * @param dataList
     * @return
     */
    public Map<String, List<ProjectReimbursementDTO>> dataMessageDispose(List<ProjectReimbursementDTO> dataList) {
        //所有有效数据均添加到list中，下边将list中的数据根据店号和收银员的id进行分割处理
        Map<String, List<ProjectReimbursementDTO>> result = listGroup2Map(dataList);
        return result;
    }

    private Map<String, List<ProjectReimbursementDTO>> listGroup2Map(List<ProjectReimbursementDTO> list) {
        Map<String, List<ProjectReimbursementDTO>> userSignSerialMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            // 分组
            for (ProjectReimbursementDTO vo : list) {
                List<ProjectReimbursementDTO> tempList = userSignSerialMap.get(vo.getParentId());
                /*如果取不到数据,那么直接new一个空的ArrayList**/
                if (tempList == null) {
                    tempList = new ArrayList<>();
                    tempList.add(vo);
                    userSignSerialMap.put(vo.getParentId(), tempList);
                }
                else {
                    /*某个vo之前已经存放过了,则直接追加数据到原来的List里**/
                    tempList.add(vo);
                }
            }
        }
        return userSignSerialMap;
    }

    /**
     * 保存
     * @param reimbursementList
     */
    @Override
    @Transactional(readOnly = false)
    public Map<String,Object> save(List<ProjectReimbursementDTO> reimbursementList) {
        Map<String,Object> map = new HashMap<>();
        Set<String> invoiceNumberSet = new HashSet<String>();
        for (ProjectReimbursementDTO info : reimbursementList) {
            if(StringUtils.isBlank(info.getBusinessCode())){
                info.setBusinessCode("");
            }
            invoiceNumberSet.add(info.getInvoiceNumber());
        }
        //如果发票编号数量不等于总数量，则表示所传数据中存在重复的发票编号，则进行抛出
        if(invoiceNumberSet.size() != reimbursementList.size()){
            map.put("success", false);
            map.put("message", "数据中存在相同的发票号，请重新验证上传");
            return map;
        }
        //set转list
        List<String> invoiceNumberList = new ArrayList<String>(invoiceNumberSet);
        //查询发票号是否存在，若含有已存在发票号，则直接进行抛出
        List<String> oldInvoiceNumberList = mapper.selectOldInvoiceNumber(invoiceNumberList);
        if(oldInvoiceNumberList.size()>0){
            String oldInvoiceNumber = String.join(",", oldInvoiceNumberList);
            map.put("success", false);
            map.put("message", "发票号码：" + oldInvoiceNumber + " 已存在。无法再次上传");
            return map;
        }

        //业务编号对应的数据集合
        List<ProjectReimbursementDTO> businessCodeInfoList = Lists.newArrayList();
        List<ProjectReimbursementDTO> businessCodeNullList = Lists.newArrayList();
        List<String> businessCodeList = Lists.newArrayList();
        //循环遍历reimbursementList 整理出相同的业务编号（null或者空字符串除外），并将这些业务编号进行去重，保存到数据库
        Map<String, List<ProjectReimbursementDTO>> businessCodeListMap = dataDisposeOnSaveByBusinessCode(reimbursementList);
        for (String key : businessCodeListMap.keySet()) {
            if("".equals(key)){
                List<ProjectReimbursementDTO> infoList = businessCodeListMap.get(key);
                businessCodeNullList.addAll(infoList);
            }else{
                List<ProjectReimbursementDTO> infoList = businessCodeListMap.get(key);
                businessCodeInfoList.add(infoList.get(0));
                businessCodeList.add(key);
            }
        }

        //获取当前年份
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));

        //查询非空的业务编号数据在数据库中是否存在，若存在，返回已存在的业务编号集合
        List<ProjectReimbursementDTO> oldBusinessCodeList = mapper.selectOldBusinessCodeByInfo(businessCodeList,year);
        if (oldBusinessCodeList.size()>0){
            //如果数据库已存在部分业务编号信息，则去除该部分的业务编号信息
            for (ProjectReimbursementDTO oldBusinessCode: oldBusinessCodeList) {
                Iterator iterator = businessCodeInfoList.iterator();
                while (iterator.hasNext()) {
                    ProjectReimbursementDTO data = (ProjectReimbursementDTO) iterator.next();
                    if (oldBusinessCode.getBusinessCode().equals(data.getBusinessCode())){
                        data.setId(oldBusinessCode.getId());
                    }
                }
            }

        }

        //将空的业务编号 的信息添加到集合中
        businessCodeInfoList.addAll(businessCodeNullList);
        List<ProjectReimbursementDTO> newBusinessCodeInfoList = Lists.newArrayList();
        newBusinessCodeInfoList.addAll(businessCodeInfoList);

        //对业务编号的数据进行新增保存
        Iterator iterator = businessCodeInfoList.iterator();
        while (iterator.hasNext()) {
            ProjectReimbursementDTO data = (ProjectReimbursementDTO) iterator.next();
            if (StringUtils.isBlank(data.getId())){
                data.preInsert();
                data.setParentId("0");
                data.setParentIds("0,");
                data.setYear(year);
                data.setRandomType("0");
            }else{
                iterator.remove();
            }
        }
        if(businessCodeInfoList.size()>0){
            mapper.insertBusinessCodeList(businessCodeInfoList);
        }


        //业务编号对应的数据集合
        List<ProjectReimbursementDTO> invoiceInfoList = Lists.newArrayList();

        for (ProjectReimbursementDTO info : newBusinessCodeInfoList) {
            if(StringUtils.isNotBlank(info.getBusinessCode())){
                //处理业务编号不为空的数据
                for (String key : businessCodeListMap.keySet()) {
                    if(info.getBusinessCode().equals(key)){
                        List<ProjectReimbursementDTO> infoList = businessCodeListMap.get(key);
                        for (ProjectReimbursementDTO childrenInfo : infoList) {
                            childrenInfo.setParentId(info.getId());
                            String parentIds = "0," + info.getId() + ",";
                            childrenInfo.setParentIds(parentIds);
                            //childrenInfo.preInsert();
                            invoiceInfoList.add(childrenInfo);
                        }
                    }
                }

            }else{
                //处理业务编号为空的数据
                info.setParentId(info.getId());
                String parentIds = "0," + info.getId() + ",";
                info.setParentIds(parentIds);
                //info.preInsert();
                invoiceInfoList.add(info);
            }
        }
        for (ProjectReimbursementDTO childrenInfo : invoiceInfoList) {
            childrenInfo.preInsert();
        }
        //新增
        mapper.insertInvoiceList(invoiceInfoList);

        map.put("success", true);
        map.put("message", "数据上传成功");
        return map;
    }

    @Override
    @Transactional(readOnly = false)
    public void saveBusiness(ProjectReimbursementDTO reimbursement) {
        //获取当前年份
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        reimbursement.setYear(year);

        if("1".equals(reimbursement.getRandomType())){

            //根据id查询业务信息是否已经是随机生成的业务编码
            ProjectReimbursementDTO reimbursementInfo = mapper.queryBusinessById(reimbursement.getId());
            if("1".equals(reimbursementInfo.getRandomType()) || StringUtils.isNotBlank(reimbursementInfo.getBusinessCode())){
                return;
            }

            //根据id查询对应发票信息
            List<String> parentIdList = Lists.newArrayList();
            parentIdList.add(reimbursement.getId());
            List<ProjectReimbursementDTO> invoiceByParentIdList = mapper.getInvoiceByParentIdList(parentIdList);
            if(invoiceByParentIdList.size()>0){
                List<ProjectReimbursementDTO> updateInvoiceData = Lists.newArrayList();
                for (ProjectReimbursementDTO invoiceInfo: invoiceByParentIdList) {
                    synchronized (this){
                        //生成随机业务编号
                        //查询最后一个业务编号信息
                        String lastRandomBusinessCodeIndex = mapper.getLastRandomBusinessCodeIndex(year);
                        if(StringUtils.isBlank(lastRandomBusinessCodeIndex)){
                            lastRandomBusinessCodeIndex = "0";
                        }
                        Integer randomBusinessCodeIndex = Integer.parseInt(lastRandomBusinessCodeIndex) + 1;
                        reimbursement.setRandomBusinessCodeIndex(randomBusinessCodeIndex.toString());
                        //将新的序列号进行向左补齐4位
                        String padLeft = PublicUtil.padLeft(randomBusinessCodeIndex.toString(), 4, '0');
                        //生成新的随机业务编号
                        StringBuilder sbCode = new StringBuilder().append(year).append("-kjxm-").append(padLeft);
                        reimbursement.setBusinessCode(sbCode.toString());
                    }

                    invoiceInfo.setBusinessCode(reimbursement.getBusinessCode());
                    invoiceInfo.preUpdate();
                    updateInvoiceData.add(invoiceInfo);
                }
                mapper.updateInvoiceList(updateInvoiceData);
            }
            reimbursement.preUpdate();
            mapper.saveBusiness(reimbursement);
        }else{
            //查询该业务编码在数据库中是否存在(当年)
            ProjectReimbursementDTO infoByBusinessCode = mapper.getInfoByBusinessCode(reimbursement);
            if(null != infoByBusinessCode){
                //如果存在该业务编码 则将该业务编码对应的发票数据的父节点变更为已存在的业务编码的id信息
                //根据id 查询对应的发票信息
                List<String> parentIdList = Lists.newArrayList();
                parentIdList.add(reimbursement.getId());
                List<ProjectReimbursementDTO> invoiceByParentIdList = mapper.getInvoiceByParentIdList(parentIdList);
                if(invoiceByParentIdList.size()>0){
                    List<ProjectReimbursementDTO> updateInvoiceData = Lists.newArrayList();
                    for (ProjectReimbursementDTO invoiceInfo: invoiceByParentIdList) {
                        invoiceInfo.setBusinessCode(infoByBusinessCode.getBusinessCode());
                        invoiceInfo.setParentId(infoByBusinessCode.getId());
                        invoiceInfo.setParentIds("0," + infoByBusinessCode.getId() + ",");
                        invoiceInfo.preUpdate();
                        updateInvoiceData.add(invoiceInfo);
                    }
                    mapper.updateInvoiceList(updateInvoiceData);
                }
                //删除该业务编码信息
                mapper.deleteBusinessById(reimbursement.getId());
            }else{
                //根据id查询对应发票信息
                List<String> parentIdList = Lists.newArrayList();
                parentIdList.add(reimbursement.getId());
                List<ProjectReimbursementDTO> invoiceByParentIdList = mapper.getInvoiceByParentIdList(parentIdList);
                if(invoiceByParentIdList.size()>0){
                    List<ProjectReimbursementDTO> updateInvoiceData = Lists.newArrayList();
                    for (ProjectReimbursementDTO invoiceInfo: invoiceByParentIdList) {
                        invoiceInfo.setBusinessCode(reimbursement.getBusinessCode());
                        invoiceInfo.preUpdate();
                        updateInvoiceData.add(invoiceInfo);
                    }
                    mapper.updateInvoiceList(updateInvoiceData);
                }
                reimbursement.preUpdate();
                mapper.saveBusiness(reimbursement);
            }
        }

    }

    @Override
    @Transactional(readOnly = false)
    public Map<String,Object> saveGatheringTime(ProjectReimbursementDTO reimbursement) {
        Map<String,Object> map = new HashMap<String,Object>();
        String[] idArray =reimbursement.getId().split(",");
        ArrayList<String> idList = Lists.newArrayList(idArray);
        //根据id查询发票是否已经填写过收款时间信息
        List<ProjectReimbursementDTO> invoiceList =  mapper.getGatheringTimeInvoiceList(idList);
        if(invoiceList.size()>0){
            List<String> invoiceNumber = Lists.newArrayList();
            for (ProjectReimbursementDTO invoice : invoiceList) {
                invoiceNumber.add(invoice.getInvoiceNumber());
            }
            String invoiceNumberStr = StringUtils.join(invoiceNumber, ",");
            map.put("message","发票号：" + invoiceNumberStr + " 已经填写过收款日期，无法重复填写。<br/> 本次收款操作失败");
            map.put("success",false);
            return map;
        }
        //修改发票收款时间
        reimbursement.preUpdate();
        mapper.updateGatheringTime(idList,reimbursement);

        for (String id : idList) {
            reimbursement.setBusinessCode(id);

            //根据该条发票信息查询同业务编号下的没有收款的发票信息
            List<ProjectReimbursementDTO> notGatheringTimeInvoice = mapper.getNotGatheringTimeInvoice(reimbursement);
            if(notGatheringTimeInvoice.size() == 0){
                //查询该发票信息
                ProjectReimbursementDTO reimbursementDTO = mapper.queryInvoiceById(id);
                //如果所有的发票均已收款，则将业务信息添加全部收款状态
                if(null != reimbursementDTO){
                    mapper.updateGatheringStatusById(reimbursementDTO.getParentId());
                }
            }
        }


        map.put("success",true);
        map.put("message","收款成功");
        return map;
    }

    @Override
    @Transactional(readOnly = false)
    public void saveInvoice(ProjectReimbursementDTO reimbursement) {
        reimbursement.preUpdate();
        mapper.saveInvoice(reimbursement);
        //根据该条发票信息查询同业务编号下的没有收款的发票信息
        List<ProjectReimbursementDTO> notGatheringTimeInvoice = mapper.getNotGatheringTimeInvoice(reimbursement);
        if(notGatheringTimeInvoice.size() == 0){
            //查询该发票信息
            ProjectReimbursementDTO reimbursementDTO = mapper.queryInvoiceById(reimbursement.getId());
            //如果所有的发票均已收款，则将业务信息添加全部收款状态
            mapper.updateGatheringStatusById(reimbursementDTO.getParentId());
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void modifyInvoice(ProjectReimbursementDTO reimbursement) {
        reimbursement.preUpdate();
        mapper.modifyInvoice(reimbursement);
    }

    @Override
    @Transactional(readOnly = false)
    public void removeByIds(List<String> idList) {
        //删除业务信息
        mapper.removeBusinessByIds(idList);
        //删除发票信息
        mapper.removeInvoiceByIds(idList);
    }

    @Override
    @Transactional(readOnly = false)
    public void removeBusinessByIds(List<String> idList) {
        if(idList.size()>0){
            //删除业务信息
            mapper.removeBusinessByIds(idList);
            //删除发票信息
            mapper.removeBusinessByParentIds(idList);
            this.removeInvoiceByIds(idList);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void removeInvoiceByIds(List<String> idList) {
        //删除发票信息
        if(idList.size()>0) {
            mapper.removeInvoiceByIds(idList);
            Set<String> set = new HashSet<>();
            //遍历发票id查询对应得业务信息下是否存在有效的发票信息，若不存在，则将对应的业务信息同时删除
            for (String id : idList) {
                //查询该发票信息下是否存在有效的同级数据信息
                String businessId = mapper.getValidBusinessIdByInvoiceId(id);

                if (StringUtils.isBlank(businessId)) {
                    ProjectReimbursementDTO ProjectReimbursementDTO = this.queryBusinessByInvoiceId(id);
                    if (null != ProjectReimbursementDTO) {
                        set.add(ProjectReimbursementDTO.getId());
                    }
                }
            }
            if (set.size() > 0) {
                mapper.removeBusinessByIds(new ArrayList<>(set));
            }
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void updateReimbursementRatio(ProjectReimbursementDTO reimbursement) {
        mapper.updateReimbursementRatio(reimbursement);
    }

    @Override
    @Transactional(readOnly = false)
    public Map<String,Object> addBatchReimbursement(List<String> idList) {
        Map<String,Object> map = new HashMap<String,Object>();
        //根据发票id查询对应的发票信息
        List<ProjectReimbursementDTO> invoiceList = mapper.getInvoiceByIdList(idList);
        if(invoiceList.size()>0){
            String firstParentId = invoiceList.get(0).getParentId();
            String firstParentIds = invoiceList.get(0).getParentIds();
            Set<String> reimbursementIdSet = new HashSet<String>();
            for (ProjectReimbursementDTO info : invoiceList) {
                reimbursementIdSet.add(info.getParentId());
            }
            reimbursementIdSet.remove(firstParentId);
            //删除除第一个以外的所有业务信息
            if(reimbursementIdSet.size()>0){
                mapper.deleteBusinessByIdList(new ArrayList<>(reimbursementIdSet));
            }
            //将所有发票信息的父节点变更为存在的业务信息id
            for (ProjectReimbursementDTO info : invoiceList) {
                info.setParentId(firstParentId);
                info.setParentIds(firstParentIds);
                info.setBatchFlag("1");
                info.preUpdate();
            }
            //批量修改发票信息
            mapper.updateInvoiceList(invoiceList);
            //修改业务信息（添加状态）
            ProjectReimbursementDTO info = new ProjectReimbursementDTO();
            info.setId(firstParentId);
            info.setBatchFlag("1");
            info.preUpdate();
            mapper.updateById(info);

        } else {
            map.put("success", false);
            map.put("message", "未查询到符合条件的发票信息");
        }
        return map;
    }

    /**
     * 文件数据分组
     * @param dataList
     * @return
     */
    public Map<String, List<ProjectReimbursementDTO>> dataDisposeOnSaveByBusinessCode(List<ProjectReimbursementDTO> dataList) {
        Map<String, List<ProjectReimbursementDTO>> result = listMapOnSaveByBusinessCode(dataList);
        return result;
    }

    private Map<String, List<ProjectReimbursementDTO>> listMapOnSaveByBusinessCode(List<ProjectReimbursementDTO> list) {
        Map<String, List<ProjectReimbursementDTO>> userSignSerialMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            // 分组
            for (ProjectReimbursementDTO vo : list) {
                List<ProjectReimbursementDTO> tempList = userSignSerialMap.get(vo.getBusinessCode());
                /*如果取不到数据,那么直接new一个空的ArrayList**/
                if (tempList == null) {
                    tempList = new ArrayList<>();
                    tempList.add(vo);
                    userSignSerialMap.put(vo.getBusinessCode(), tempList);
                }
                else {
                    /*某个vo之前已经存放过了,则直接追加数据到原来的List里**/
                    tempList.add(vo);
                }
            }
        }
        return userSignSerialMap;
    }

}
