package com.jeeplus.test.reimbursementsys.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.reimbursementAccountant.utils.MyBeanUtils;
import com.jeeplus.test.reimbursementsys.domain.dto.ReimbursementDTO;
import com.jeeplus.test.reimbursementsys.domain.dto.WuHanReimbursementDTO;
import com.jeeplus.test.reimbursementsys.mapper.WuHanReimbursementSysMapper;
import com.jeeplus.test.reimbursementsys.service.ReimbursementBusinessService;
import com.jeeplus.test.reimbursementsys.service.WuHanReimbursementSysService;
import com.jeeplus.test.reimbursementsys.utils.PublicUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author li-peike
 * @version 1.0.0
 * @ClassName ReimbursementSysServiceImpl.java
 * @Description TODO
 * @createTime 2022年05月06日 10:38:00
 */
@Service
public class WuHanReimbursementSysServiceImpl implements WuHanReimbursementSysService {

    @Resource
    private WuHanReimbursementSysMapper mapper;
    @Resource
    private ReimbursementBusinessService reimbursementBusinessService;


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

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

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

    @Override
    public WuHanReimbursementDTO queryBusinessByInvoiceId(String id) {

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


    @Override
    public IPage<WuHanReimbursementDTO> treeData(Page<WuHanReimbursementDTO> page, WuHanReimbursementDTO reimbursement) {
        IPage<WuHanReimbursementDTO> 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.getEndIncome()) ||
                StringUtils.isNotBlank(reimbursement.getFirmName())){
            List<WuHanReimbursementDTO> invoiceList =  mapper.getInvoiceList(reimbursement);
            //如果存在发票信息，则根据发票的父节点查询对应的业务信息
            if(invoiceList.size()>0){
                Set<String> idSet = new HashSet<String>();
                for (WuHanReimbursementDTO  info : invoiceList) {
                    idSet.add(info.getParentId());
                }
                reimbursement.setIdList(new ArrayList<>(idSet));
                pageList = mapper.queryAllList(page,reimbursement);

                List<WuHanReimbursementDTO> list =  pageList.getRecords();
                if(list.size()>0){
                    //将子节点信息进行分组
                    Map<String, List<WuHanReimbursementDTO>> invoiceListMap = dataMessageDispose(invoiceList);
                    //将分组后的子节点信息通过遍历的方式添加到父节点中的children中
                    for (WuHanReimbursementDTO info:list) {
                        for (String key : invoiceListMap.keySet()) {
                            if (info.getId().equals(key)) {
                                List<WuHanReimbursementDTO> 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值覆盖数据库记录中的值
                                }
                            }
                        }
                        WuHanReimbursementDTO businessById = reimbursementBusinessService.getWuHanBusinessById(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<WuHanReimbursementDTO> list =  pageList.getRecords();
            if(list.size()>0){
                //获取所有发票信息表中的数据
                List<String> parentIdList = Lists.newArrayList();
                for (WuHanReimbursementDTO info:list) {
                    parentIdList.add(info.getId());
                }
                //根据查询的父节点信息查询对应的子节点信息
                List<WuHanReimbursementDTO> invoiceList =  mapper.getInvoiceByParentIdList(parentIdList);
                if(invoiceList.size()>0){
                    //将子节点信息进行分组
                    Map<String, List<WuHanReimbursementDTO>> invoiceListMap = dataMessageDispose(invoiceList);
                    //将分组后的子节点信息通过遍历的方式添加到父节点中的children中
                    for (WuHanReimbursementDTO info:list) {
                        for (String key : invoiceListMap.keySet()) {
                            if (info.getId().equals(key)) {
                                List<WuHanReimbursementDTO> 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值覆盖数据库记录中的值
                                }
                            }
                        }
                        WuHanReimbursementDTO businessById = reimbursementBusinessService.getWuHanBusinessById(info.getId());
                        if(null != businessById){
                            info.setAllAlreadyReimbursementQuota(businessById.getAllAlreadyReimbursementQuota());
                            info.setCanReimbursementAmount(businessById.getCanReimbursementAmount());
                            info.setSurplusReimbursementAmount(businessById.getSurplusReimbursementAmount());
                        }
                    }
                }
            }
        }

        return pageList;
    }

    @Override
    public List<WuHanReimbursementDTO> findPage(Page<WuHanReimbursementDTO> page, WuHanReimbursementDTO reimbursement) {
        IPage<WuHanReimbursementDTO> pageList = new Page();
        List<WuHanReimbursementDTO> 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<WuHanReimbursementDTO> invoiceList =  mapper.getInvoiceList(reimbursement);
            //如果存在发票信息，则根据发票的父节点查询对应的业务信息
            if(invoiceList.size()>0){
                Set<String> idSet = new HashSet<String>();
                for (WuHanReimbursementDTO  info : invoiceList) {
                    idSet.add(info.getParentId());
                }
                reimbursement.setIdList(new ArrayList<>(idSet));
                pageList = mapper.queryAllList(page,reimbursement);

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

        return returnList;
    }

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

    private Map<String, List<WuHanReimbursementDTO>> listGroup2Map(List<WuHanReimbursementDTO> list) {
        Map<String, List<WuHanReimbursementDTO>> userSignSerialMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            // 分组
            for (WuHanReimbursementDTO vo : list) {
                List<WuHanReimbursementDTO> 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
    public Map<String,Object> save(List<WuHanReimbursementDTO> reimbursementList) {
        Map<String,Object> map = new HashMap<>();
        Set<String> invoiceNumberSet = new HashSet<String>();
        for (WuHanReimbursementDTO info : reimbursementList) {
            if(StringUtils.isBlank(info.getBusinessCode())){
                info.setBusinessCode("");
            }
            invoiceNumberSet.add(info.getInvoiceNumber());
            info.setExistence("0");
        }
        //如果发票编号数量不等于总数量，则表示所传数据中存在重复的发票编号，则进行抛出
        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 oldInvoiceNumberListStr = String.join(",", oldInvoiceNumberList);
            //找到上传的发票信息中已存在的报告号 并对其存在状态进行修改
            for (WuHanReimbursementDTO info : reimbursementList) {
                if(oldInvoiceNumberListStr.contains(info.getInvoiceNumber())){
                    info.setExistence("1");
                }
            }

            /*String oldInvoiceNumber = String.join(",", oldInvoiceNumberList);
            map.put("success", false);
            map.put("message", "发票号码：" + oldInvoiceNumber + " 已存在。无法再次上传");
            return map;*/
        }

        //业务编号对应的数据集合
        List<WuHanReimbursementDTO> businessCodeInfoList = Lists.newArrayList();
        List<WuHanReimbursementDTO> businessCodeNullList = Lists.newArrayList();
        List<String> businessCodeList = Lists.newArrayList();
        //循环遍历reimbursementList 整理出相同的业务编号（null或者空字符串除外），并将这些业务编号进行去重，保存到数据库
        Map<String, List<WuHanReimbursementDTO>> businessCodeListMap = dataDisposeOnSaveByBusinessCode(reimbursementList);
        for (String key : businessCodeListMap.keySet()) {
            if("".equals(key)){
                List<WuHanReimbursementDTO> infoList = businessCodeListMap.get(key);
                businessCodeNullList.addAll(infoList);
            }else{
                List<WuHanReimbursementDTO> 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<WuHanReimbursementDTO> oldBusinessCodeList = mapper.selectOldBusinessCodeByInfo(businessCodeList,year);
        if (oldBusinessCodeList.size()>0){
            //如果数据库已存在部分业务编号信息，则去除该部分的业务编号信息
            for (WuHanReimbursementDTO oldBusinessCode: oldBusinessCodeList) {
                Iterator iterator = businessCodeInfoList.iterator();
                while (iterator.hasNext()) {
                    WuHanReimbursementDTO data = (WuHanReimbursementDTO) iterator.next();
                    if (oldBusinessCode.getBusinessCode().equals(data.getBusinessCode())){
                        data.setId(oldBusinessCode.getId());
                    }
                }
            }

        }

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

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

        //对数据进行分组
        Map<String, List<WuHanReimbursementDTO>> existenceCodeListMap = dataDisposeOnSaveByExistence(businessCodeInfoList);
        for (String key : existenceCodeListMap.keySet()) {
            switch(key){
                case "0":
                    List<WuHanReimbursementDTO> noExistenceList = existenceCodeListMap.get(key);
                    if(noExistenceList.size()>0){
                        mapper.insertBusinessCodeList(noExistenceList);
                    }
                    break;
                case "1":
                    break;
            }
        }



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

        for (WuHanReimbursementDTO info : newBusinessCodeInfoList) {
            if(StringUtils.isNotBlank(info.getBusinessCode())){
                //处理业务编号不为空的数据
                for (String key : businessCodeListMap.keySet()) {
                    if(info.getBusinessCode().equals(key)){
                        List<WuHanReimbursementDTO> infoList = businessCodeListMap.get(key);
                        for (WuHanReimbursementDTO 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 (WuHanReimbursementDTO childrenInfo : invoiceInfoList) {
            childrenInfo.preInsert();
        }

        //对发票数据进行分组（根据存在状态）
        Map<String, List<WuHanReimbursementDTO>> existenceListMap = dataDisposeOnSaveByExistence(invoiceInfoList);
        for (String key : existenceListMap.keySet()) {
            switch(key){
                case "0":
                    List<WuHanReimbursementDTO> noExistenceList = existenceListMap.get(key);
                    //新增
                    mapper.insertInvoiceList(noExistenceList);
                    break;
                case "1":
                    List<WuHanReimbursementDTO> existenceList = existenceListMap.get(key);
                    for (WuHanReimbursementDTO info : existenceList) {
                        //更新收款时间
                        if(StringUtils.isNotBlank(info.getGatheringTime())){
                            info.preUpdate();
                            mapper.updateInvoiceGatheringTime(info);
                        }
                    }
                    break;
            }
        }

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

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

        if("1".equals(reimbursement.getRandomType())){
            //根据id查询业务信息是否已经是随机生成的业务编码
            WuHanReimbursementDTO 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<WuHanReimbursementDTO> invoiceByParentIdList = mapper.getInvoiceByParentIdList(parentIdList);
            if(invoiceByParentIdList.size()>0){
                List<WuHanReimbursementDTO> updateInvoiceData = Lists.newArrayList();
                for (WuHanReimbursementDTO 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("-whsj-").append(padLeft);
                        reimbursement.setBusinessCode(sbCode.toString());
                    }

                    invoiceInfo.setBusinessCode(reimbursement.getBusinessCode());
                    invoiceInfo.preUpdate();
                    updateInvoiceData.add(invoiceInfo);
                }
                mapper.updateInvoiceList(updateInvoiceData);
            }
            reimbursement.preUpdate();
            mapper.saveBusiness(reimbursement);

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

    }
    @Override
    public Map<String,Object> saveGatheringTime(WuHanReimbursementDTO reimbursement) {
        Map<String,Object> map = new HashMap<String,Object>();
        String[] idArray =reimbursement.getId().split(",");
        ArrayList<String> idList = Lists.newArrayList(idArray);
        //根据id查询发票是否已经填写过收款时间信息
        List<WuHanReimbursementDTO> invoiceList =  mapper.getGatheringTimeInvoiceList(idList);
        if(invoiceList.size()>0){
            List<String> invoiceNumber = Lists.newArrayList();
            for (WuHanReimbursementDTO 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<WuHanReimbursementDTO> notGatheringTimeInvoice = mapper.getNotGatheringTimeInvoice(reimbursement);
            if(notGatheringTimeInvoice.size() == 0){
                //查询该发票信息
                WuHanReimbursementDTO reimbursementDTO = mapper.queryInvoiceById(id);
                //如果所有的发票均已收款，则将业务信息添加全部收款状态
                if(null != reimbursementDTO){
                    mapper.updateGatheringStatusById(reimbursementDTO.getParentId());
                }
            }
        }


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

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

    @Override
    public void modifyInvoice(WuHanReimbursementDTO reimbursement) {
        reimbursement.preUpdate();
        mapper.modifyInvoice(reimbursement);
    }

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

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

    }

    @Override
    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)){
                    mapper.removeBusinessById(id);
                }
            }
        }
    }

    @Override
    public void updateReimbursementRatio(WuHanReimbursementDTO reimbursement) {
        mapper.updateReimbursementRatio(reimbursement);
    }

    @Override
    public Map<String, Object> addBatchReimbursement(List<String> idList) {
        Map<String,Object> map = new HashMap<String,Object>();
        //根据发票id查询对应的发票信息
        List<WuHanReimbursementDTO> 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 (WuHanReimbursementDTO info : invoiceList) {
                reimbursementIdSet.add(info.getParentId());
            }
            reimbursementIdSet.remove(firstParentId);
            //删除除第一个以外的所有业务信息
            if(reimbursementIdSet.size()>0){
                mapper.deleteBusinessByIdList(new ArrayList<>(reimbursementIdSet));
            }
            //将所有发票信息的父节点变更为存在的业务信息id
            for (WuHanReimbursementDTO info : invoiceList) {
                info.setParentId(firstParentId);
                info.setParentIds(firstParentIds);
                info.setBatchFlag("1");
                info.preUpdate();
            }
            //批量修改发票信息
            mapper.updateInvoiceList(invoiceList);
            //修改业务信息（添加状态）
            WuHanReimbursementDTO info = new WuHanReimbursementDTO();
            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<WuHanReimbursementDTO>> dataDisposeOnSaveByBusinessCode(List<WuHanReimbursementDTO> dataList) {
        Map<String, List<WuHanReimbursementDTO>> result = listMapOnSaveByBusinessCode(dataList);
        return result;
    }

    private Map<String, List<WuHanReimbursementDTO>> listMapOnSaveByBusinessCode(List<WuHanReimbursementDTO> list) {
        Map<String, List<WuHanReimbursementDTO>> userSignSerialMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            // 分组
            for (WuHanReimbursementDTO vo : list) {
                List<WuHanReimbursementDTO> 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;
    }

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

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

}
