package com.jeeplus.assess.invoice.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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IRoleApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
//import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;
//import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.assess.invoice.domain.*;
import com.jeeplus.assess.invoice.mapper.*;
import com.jeeplus.assess.invoice.service.dto.FinanceInvoiceBaseDTO;
import com.jeeplus.assess.invoice.service.dto.FinanceInvoiceDTO;
import com.jeeplus.assess.invoice.service.dto.FinanceInvoiceDetailDTO;
import com.jeeplus.assess.invoice.service.dto.FinanceInvoiceReceivablesDTO;
import com.jeeplus.assess.invoice.service.mapstruct.*;
//import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
import com.jeeplus.assess.workContract.mapper.WorkContractInfoMapper;
//import com.jeeplus.pubmodules.oss.service.dto.WorkAttachmentDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class FinanceInvoiceService extends ServiceImpl<FinanceInvoiceMapper, FinanceInvoice> {

    @Resource
    private FinanceInvoiceMapper financeInvoiceMapper;
    @Resource
    private FinanceInvoiceBaseMapper financeInvoiceBaseMapper;
    @Resource
    private FinanceInvoiceDetailMapper financeInvoiceDetailMapper;
    @Resource
    private FinanceInvoiceReceivablesMapper financeInvoiceReceivablesMapper;
    @Resource
    private FinanceInvoiceInvalidMapper financeInvoiceInvalidMapper;
//    @Resource
//    private SerialnumTplService serialnumTplService;
//    @Resource
//    private OssServiceMapper ossServiceMapper;
    @Resource
    private WorkContractInfoMapper workContractInfoMapper;
//    @Resource
//    private UserService userService;
    @Resource
    private IFlowableApi flowTaskService;

    public List<String> getSearchList(ArrayList<String> searchIdList, List<String> ids) {
        List<String> newSearchIdList = searchIdList.stream().filter(item -> {
            AtomicInteger num = new AtomicInteger();
            ids.stream().forEach(id -> {
                if (item.equals(id)) {
                    num.getAndIncrement();
                }
            });
            if (num.get() > 0) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        return newSearchIdList;
    }

    public IPage<FinanceInvoiceDTO> findList(Page<FinanceInvoiceDTO> page, FinanceInvoiceDTO financeInvoiceDTO) throws Exception{
        QueryWrapper<FinanceInvoice> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( FinanceInvoiceWrapper.INSTANCE.toEntity(financeInvoiceDTO), FinanceInvoice.class );
        queryWrapper.eq("fi.del_flag","0");
        queryWrapper.orderByDesc("fi.create_time");
        ArrayList<String> searchIdList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        AtomicInteger checkNum = new AtomicInteger();
        if (ObjectUtil.isNotEmpty(financeInvoiceDTO)) {
            if (StringUtils.isNotBlank(financeInvoiceDTO.getNumber())) {
                List<FinanceInvoiceDetail> financeInvoiceDetails = financeInvoiceDetailMapper.selectList(new LambdaQueryWrapper<FinanceInvoiceDetail>().like(FinanceInvoiceDetail::getNumber, financeInvoiceDTO.getNumber()));
                List<String> ids = financeInvoiceDetails.stream().distinct().map(FinanceInvoiceDetail::getInvoiceId).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(ids)) {
                    return new Page<FinanceInvoiceDTO>();
                }else{
                    if (CollectionUtil.isNotEmpty(searchIdList)){
                        List<String> newSearchIdList = getSearchList(searchIdList,ids);
                        searchIdList = new ArrayList<String>();
                        for (String item : newSearchIdList) {
                            searchIdList.add(item);
                        }
                    }else{
                        if (checkNum.get() > 0){
                            return new Page<FinanceInvoiceDTO>();
                        }else{
                            for (String item : ids) {
                                searchIdList.add(item);
                            }
                        }
                    }
                    checkNum.getAndIncrement();
                }
            }
            if (StringUtils.isNotBlank(financeInvoiceDTO.getAccountBegin())&&StringUtils.isNotBlank(financeInvoiceDTO.getAccountEnd())) {
                List<FinanceInvoice> financeInvoices = financeInvoiceMapper.selectList(new LambdaQueryWrapper<FinanceInvoice>()
                        .between(FinanceInvoice::getAccount, new BigDecimal(financeInvoiceDTO.getAccountBegin()), new BigDecimal(financeInvoiceDTO.getAccountEnd())));
                List<String> ids = financeInvoices.stream().distinct().map(FinanceInvoice::getId).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(ids)) {
                    return new Page<FinanceInvoiceDTO>();
                }else{
                    if (CollectionUtil.isNotEmpty(searchIdList)){
                        List<String> newSearchIdList = getSearchList(searchIdList,ids);
                        searchIdList = new ArrayList<String>();
                        for (String item : newSearchIdList) {
                            searchIdList.add(item);
                        }
                    }else{
                        if (checkNum.get() > 0){
                            return new Page<FinanceInvoiceDTO>();
                        }else{
                            for (String item : ids) {
                                searchIdList.add(item);
                            }
                        }
                    }
                    checkNum.getAndIncrement();
                }
            }
            if (StringUtils.isNotBlank(financeInvoiceDTO.getBillingDateBegin())&&StringUtils.isNotBlank(financeInvoiceDTO.getBillingDateEnd())) {
                List<FinanceInvoice> financeInvoices = financeInvoiceMapper.selectList(new LambdaQueryWrapper<FinanceInvoice>()
                        .between(FinanceInvoice::getBillingDate, sdf.parse(financeInvoiceDTO.getBillingDateBegin()), sdf.parse(financeInvoiceDTO.getBillingDateEnd())));
                List<String> ids = financeInvoices.stream().distinct().map(FinanceInvoice::getId).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(ids)) {
                    return new Page<FinanceInvoiceDTO>();
                }else{
                    if (CollectionUtil.isNotEmpty(searchIdList)){
                        List<String> newSearchIdList = getSearchList(searchIdList,ids);
                        searchIdList = new ArrayList<String>();
                        for (String item : newSearchIdList) {
                            searchIdList.add(item);
                        }
                    }else{
                        if (checkNum.get() > 0){
                            return new Page<FinanceInvoiceDTO>();
                        }else{
                            for (String item : ids) {
                                searchIdList.add(item);
                            }
                        }
                    }
                    checkNum.getAndIncrement();
                }
            }
            if (StringUtils.isNotBlank(financeInvoiceDTO.getRemittanceDateBegin())&&StringUtils.isNotBlank(financeInvoiceDTO.getRemittanceDateEnd())) {
                List<FinanceInvoice> financeInvoices = financeInvoiceMapper.selectList(new LambdaQueryWrapper<FinanceInvoice>()
                        .between(FinanceInvoice::getReceivablesDate, sdf.parse(financeInvoiceDTO.getRemittanceDateBegin()), sdf.parse(financeInvoiceDTO.getRemittanceDateEnd())));
                List<String> ids = financeInvoices.stream().distinct().map(FinanceInvoice::getId).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(ids)) {
                    return new Page<FinanceInvoiceDTO>();
                }else{
                    if (CollectionUtil.isNotEmpty(searchIdList)){
                        List<String> newSearchIdList = getSearchList(searchIdList,ids);
                        searchIdList = new ArrayList<String>();
                        for (String item : newSearchIdList) {
                            searchIdList.add(item);
                        }
                    }else{
                        if (checkNum.get() > 0){
                            return new Page<FinanceInvoiceDTO>();
                        }else{
                            for (String item : ids) {
                                searchIdList.add(item);
                            }
                        }
                    }
                    checkNum.getAndIncrement();
                }
            }
            if (StringUtils.isNotBlank(financeInvoiceDTO.getProgramId())||StringUtils.isNotBlank(financeInvoiceDTO.getProgramName())) {
                if (StringUtils.isNotBlank(financeInvoiceDTO.getProgramId())){
                    List<FinanceInvoiceBase> financeInvoiceBaseList = financeInvoiceBaseMapper.selectList(new LambdaQueryWrapper<FinanceInvoiceBase>()
                            .eq(FinanceInvoiceBase::getProgramId,financeInvoiceDTO.getProgramId()));
                    List<String> ids = financeInvoiceBaseList.stream().distinct().map(FinanceInvoiceBase::getInvoiceId).collect(Collectors.toList());
                    if(CollectionUtil.isEmpty(ids)) {
                        return new Page<FinanceInvoiceDTO>();
                    }else{
                        if (CollectionUtil.isNotEmpty(searchIdList)){
                            List<String> newSearchIdList = getSearchList(searchIdList,ids);
                            searchIdList = new ArrayList<String>();
                            for (String item : newSearchIdList) {
                                searchIdList.add(item);
                            }
                        }else{
                            if (checkNum.get() > 0){
                                return new Page<FinanceInvoiceDTO>();
                            }else{
                                for (String item : ids) {
                                    searchIdList.add(item);
                                }
                            }
                        }
                        checkNum.getAndIncrement();
                    }
                }else{
                    List<FinanceInvoiceBase> financeInvoiceBaseList = financeInvoiceBaseMapper.selectList(new LambdaQueryWrapper<FinanceInvoiceBase>()
                            .like(FinanceInvoiceBase::getProgramName,financeInvoiceDTO.getProgramName()));
                    List<String> ids = financeInvoiceBaseList.stream().distinct().map(FinanceInvoiceBase::getInvoiceId).collect(Collectors.toList());
                    if(CollectionUtil.isEmpty(ids)) {
                        return new Page<FinanceInvoiceDTO>();
                    }else{
                        if (CollectionUtil.isNotEmpty(searchIdList)){
                            List<String> newSearchIdList = getSearchList(searchIdList,ids);
                            searchIdList = new ArrayList<String>();
                            for (String item : newSearchIdList) {
                                searchIdList.add(item);
                            }
                        }else{
                            if (checkNum.get() > 0){
                                return new Page<FinanceInvoiceDTO>();
                            }else{
                                for (String item : ids) {
                                    searchIdList.add(item);
                                }
                            }
                        }
                        checkNum.getAndIncrement();
                    }
                }
            }
            if (StringUtils.isNotBlank(financeInvoiceDTO.getOperator())){
                queryWrapper.eq("su.id",financeInvoiceDTO.getOperator());
            }
            if (StringUtils.isNotBlank(financeInvoiceDTO.getReconciliationPeopleName())) {
                List<User> users = SpringUtil.getBean ( IUserApi.class ).selectListByName(financeInvoiceDTO.getReconciliationPeopleName());
                List<String> userIdList = users.stream().distinct().map(User::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(userIdList)) {
                    queryWrapper.in("fi.reconciliation_people",userIdList);
                } else {
                    return new Page<FinanceInvoiceDTO>();
                }
            }
            if (StringUtils.isNotBlank(financeInvoiceDTO.getOperatorOffice())){
                List<User> userList = SpringUtil.getBean ( IUserApi.class ).getUserByOfficeAll(financeInvoiceDTO.getOperatorOffice());
                if (CollectionUtil.isNotEmpty(userList)) {
                    List<String> userIdList = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(userIdList)) {
                        queryWrapper.in("fi.create_by_id",userIdList);
                    } else {
                        return new Page<FinanceInvoiceDTO>();
                    }
                } else {
                    return new Page<FinanceInvoiceDTO>();
                }
            }
        }
        if (CollectionUtil.isNotEmpty(searchIdList)){
            List<String> ids = searchIdList.stream().distinct().collect(Collectors.toList());
            queryWrapper.in("fi.id",ids);
        } else{
            if (checkNum.get() > 0) {
                return new Page<FinanceInvoiceDTO>();
            }
        }

        IPage<FinanceInvoiceDTO> pageList = financeInvoiceMapper.findList(page, queryWrapper);
        pageList.getRecords().stream().forEach(item ->{
            // 发票申请
            if (StringUtils.isNotBlank(item.getTaskId()) && StringUtils.isNotBlank(item.getStatus())) {
                if ("2".equals(item.getStatus())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds(flowTaskService.getTaskAuditUsers(item.getTaskId()));  // 获取数据审核人
                }
            }
            // 发票作废
            if (StringUtils.isNotBlank(item.getTaskIdInvalid()) && StringUtils.isNotBlank(item.getStatus())) {
                if ("6".equals(item.getStatus())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIdsInvalid(flowTaskService.getTaskAuditUsers(item.getTaskIdInvalid()));  // 获取数据审核人
                }
            }
        });
        return pageList;
    }

//    public List<FinanceInvoiceDTO> exportList(Page<FinanceInvoiceDTO> page, FinanceInvoiceDTO financeInvoiceDTO) throws Exception{
//        IPage<FinanceInvoiceDTO> FinanceInvoiceDTOIPage = this.findList(page, financeInvoiceDTO);
//        List<FinanceInvoiceDTO> records = FinanceInvoiceDTOIPage.getRecords();
//        if(CollectionUtil.isNotEmpty(records)){
//            records.stream().forEach(record->{
//                if(CollectionUtil.isNotEmpty(record.getFinanceInvoiceBaseDTOList())){
//                    if(record.getFinanceInvoiceBaseDTOList().size() == 1 && StringUtils.isBlank(record.getFinanceInvoiceBaseDTOList().get(0).getProgramId())) {
//                        record.setProgramName("其他： " + record.getFinanceInvoiceBaseDTOList().get(0).getProgramName());
//                    } else {
//                        AtomicReference<String> programName = new AtomicReference<>("");
//                        AtomicInteger n = new AtomicInteger();
//                        record.getFinanceInvoiceBaseDTOList().stream().forEach((item)->{
//                            n.getAndIncrement();
//                            if (n.get() == record.getFinanceInvoiceBaseDTOList().size()){
//                                if(StringUtils.isNotBlank(item.getProgramName())){
//                                    programName.set(programName.get() + item.getProgramName());
//                                }
//                            } else {
//                                if(StringUtils.isNotBlank(item.getProgramName())){
//                                    programName.set(programName.get() + item.getProgramName() + ",");
//                                }
//                            }
//                        });
//                        record.setProgramName(programName.get());
//                    }
//                }else{
//                    record.setProgramName("");
//                }
//                if(CollectionUtil.isNotEmpty(record.getFinanceInvoiceDetailDTOList())){
//                    AtomicReference<String> programName = new AtomicReference<>("");
//                    AtomicInteger n = new AtomicInteger();
//                    record.getFinanceInvoiceBaseDTOList().stream().forEach((item)->{
//                        n.getAndIncrement();
//                        if (n.get() == record.getFinanceInvoiceBaseDTOList().size()){
//                            if(StringUtils.isNotBlank(item.getProgramName())){
//                                programName.set(programName.get() + item.getProgramName());
//                            }
//                        } else {
//                            if(StringUtils.isNotBlank(item.getProgramName())){
//                                programName.set(programName.get() + item.getProgramName() + ",");
//                            }
//                        }
//                    });
//                    record.setProgramName(programName.get());
//                }
//            });
//        }else{
//            return records;
//        }
//    }

    public FinanceInvoiceDTO queryById(String id) {

        FinanceInvoiceDTO financeInvoiceDTO = financeInvoiceMapper.queryById(id);

        // 查询附件信息
        List<WorkAttachmentInfo> fileList = workContractInfoMapper.findDtos(id);
        if (CollectionUtil.isNotEmpty(fileList)) {
            for (WorkAttachmentInfo i : fileList) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
        }
        if(CollectionUtil.isNotEmpty(fileList)){
            financeInvoiceDTO.setWorkAttachmentDtoList(fileList);
        }

        return financeInvoiceDTO;
    }

    public String saveForm(FinanceInvoiceDTO financeInvoiceDTO) throws Exception{
        FinanceInvoice financeInvoice = FinanceInvoiceWrapper.INSTANCE.toEntity(financeInvoiceDTO);
        if (ObjectUtil.isNotEmpty(financeInvoice)) {
            if(StringUtils.isBlank(financeInvoice.getId())){
                //获取当前登录人信息
                UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
                //发票编号生成
                String serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), FinanceInvoiceDTO.BIZ_CODE, TokenProvider.getCurrentToken());
                financeInvoice.setNo(serialNum);
                if (StringUtils.isBlank(financeInvoice.getInvalidStatus())){
                    financeInvoice.setInvalidStatus("0");
                }
                if (StringUtils.isBlank(financeInvoice.getReceivablesStatus())){
                    financeInvoice.setReceivablesStatus("0");
                }
            }
        }
        this.saveOrUpdate(financeInvoice);
        if (ObjectUtil.isNotEmpty(financeInvoiceDTO)) {
            // 如果当前是执行的是收款页面的保存方法
            if ("1".equals(financeInvoiceDTO.getIsReceivables())) {
                // 如果传过来的收款日期为空，则将本条发票的收款日期置空
                if (ObjectUtil.isEmpty(financeInvoiceDTO.getReceivablesDate())) {
                    // 根据发票id，置空发票的收款日期
                    financeInvoiceMapper.setReceivablesDateNull(financeInvoice.getId());
                }
            }
            // 基本信息保存
            if(CollectionUtil.isNotEmpty(financeInvoiceDTO.getFinanceInvoiceBaseDTOList())){
                List<String> delIds = financeInvoiceDTO.getFinanceInvoiceBaseDTOList().stream().distinct().filter(item->{
                    if(StringUtils.isNotBlank(item.getId())){
                        return true;
                    }
                    return false;
                }).map(FinanceInvoiceBaseDTO::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    financeInvoiceBaseMapper.delete(new QueryWrapper<FinanceInvoiceBase>().lambda()
                            .eq(FinanceInvoiceBase::getInvoiceId,financeInvoice.getId()).notIn(FinanceInvoiceBase::getId,delIds));
                }else{
                    financeInvoiceBaseMapper.delete(new QueryWrapper<FinanceInvoiceBase>().lambda()
                            .eq(FinanceInvoiceBase::getInvoiceId,financeInvoice.getId()));
                }
                financeInvoiceDTO.getFinanceInvoiceBaseDTOList().stream().forEach(item->{
                    FinanceInvoiceBase financeInvoiceBase = FinanceInvoiceBaseWrapper.INSTANCE.toEntity(item);
                    if(StringUtils.isNotBlank(financeInvoiceBase.getId())){
                        financeInvoiceBaseMapper.updateById(financeInvoiceBase);
                    }else{
                        financeInvoiceBase.setInvoiceId(financeInvoice.getId());
                        financeInvoiceBaseMapper.insert(financeInvoiceBase);
                    }
                });
            }else{
                financeInvoiceBaseMapper.delete(new QueryWrapper<FinanceInvoiceBase>().lambda()
                        .eq(FinanceInvoiceBase::getInvoiceId,financeInvoice.getId()));
            }
            // 附件保存
            if(CollectionUtil.isNotEmpty(financeInvoiceDTO.getWorkAttachmentDtoList())){
                List<String> delIds = financeInvoiceDTO.getWorkAttachmentDtoList().stream().distinct().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).map(WorkAttachmentInfo::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentIdNotInIds(financeInvoice.getId(),delIds);
                }else{
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(financeInvoice.getId());
                }
                //获取当前登录人信息
                UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
                AtomicInteger j = new AtomicInteger(1);
                List<WorkAttachmentInfo> collect = financeInvoiceDTO.getWorkAttachmentDtoList().stream().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return false;
                    }
                    return true;
                }).collect(Collectors.toList());
                collect.forEach(item->{
                    this.saveFiles(item,financeInvoice.getId(),userDTO,j);
                    j.getAndIncrement();
                });
            }else{
                SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(financeInvoice.getId());
            }
            // 发票明细保存
            if(CollectionUtil.isNotEmpty(financeInvoiceDTO.getFinanceInvoiceDetailDTOList())){
                List<String> delIds = financeInvoiceDTO.getFinanceInvoiceDetailDTOList().stream().distinct().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).map(FinanceInvoiceDetailDTO::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    financeInvoiceDetailMapper.delete(new QueryWrapper<FinanceInvoiceDetail>().lambda()
                            .eq(FinanceInvoiceDetail::getInvoiceId,financeInvoice.getId())
                            .notIn(FinanceInvoiceDetail::getId,delIds));
                }else{
                    financeInvoiceDetailMapper.delete(new QueryWrapper<FinanceInvoiceDetail>().lambda().eq(FinanceInvoiceDetail::getInvoiceId,financeInvoice.getId()));
                }
                financeInvoiceDTO.getFinanceInvoiceDetailDTOList().stream().forEach(item->{
                    FinanceInvoiceDetail financeInvoiceDetail = FinanceInvoiceDetailWrapper.INSTANCE.toEntity(item);
                    if(StringUtils.isNotBlank(financeInvoiceDetail.getId())){
                        financeInvoiceDetailMapper.updateById(financeInvoiceDetail);
                    }else{
                        financeInvoiceDetail.setInvoiceId(financeInvoice.getId());
                        financeInvoiceDetailMapper.insert(financeInvoiceDetail);
                    }
                });
            }else{
                financeInvoiceDetailMapper.delete(new QueryWrapper<FinanceInvoiceDetail>().lambda().eq(FinanceInvoiceDetail::getInvoiceId,financeInvoice.getId()));
            }
            // 收款明细保存
            if(CollectionUtil.isNotEmpty(financeInvoiceDTO.getFinanceInvoiceReceivablesDTOList())){
                List<String> delIds = financeInvoiceDTO.getFinanceInvoiceReceivablesDTOList().stream().distinct().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).map(FinanceInvoiceReceivablesDTO::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    financeInvoiceReceivablesMapper.delete(new QueryWrapper<FinanceInvoiceReceivables>().lambda()
                            .eq(FinanceInvoiceReceivables::getInvoiceId,financeInvoice.getId())
                            .notIn(FinanceInvoiceReceivables::getId,delIds));
                }else{
                    financeInvoiceReceivablesMapper.delete(new QueryWrapper<FinanceInvoiceReceivables>().lambda().eq(FinanceInvoiceReceivables::getInvoiceId,financeInvoice.getId()));
                }
                financeInvoiceDTO.getFinanceInvoiceReceivablesDTOList().stream().forEach(item->{
                    FinanceInvoiceReceivables financeInvoiceReceivables = FinanceInvoiceReceivablesWrapper.INSTANCE.toEntity(item);
                    if(StringUtils.isNotBlank(financeInvoiceReceivables.getId())){
                        financeInvoiceReceivablesMapper.updateById(financeInvoiceReceivables);
                    }else{
                        financeInvoiceReceivables.setInvoiceId(financeInvoice.getId());
                        financeInvoiceReceivablesMapper.insert(financeInvoiceReceivables);
                    }
                });
            }else{
                financeInvoiceReceivablesMapper.delete(new QueryWrapper<FinanceInvoiceReceivables>().lambda().eq(FinanceInvoiceReceivables::getInvoiceId,financeInvoice.getId()));
            }
            // 作废信息保存
            if(ObjectUtil.isNotEmpty(financeInvoiceDTO.getFinanceInvoiceInvalidDTO())){
                FinanceInvoiceInvalid financeInvoiceInvalid = FinanceInvoiceInvalidWrapper.INSTANCE.toEntity(financeInvoiceDTO.getFinanceInvoiceInvalidDTO());
                if(StringUtils.isNotBlank(financeInvoiceInvalid.getId())){
                    financeInvoiceInvalidMapper.update(financeInvoiceInvalid,
                            new QueryWrapper<FinanceInvoiceInvalid>().lambda().eq(FinanceInvoiceInvalid::getId,financeInvoiceInvalid.getId()));
                }else{
                    financeInvoiceInvalid.setInvalidStatus("0");
                    financeInvoiceInvalid.setInvoiceId(financeInvoice.getId());
                    financeInvoiceInvalidMapper.insert(financeInvoiceInvalid);
                }
            }else{
                financeInvoiceInvalidMapper.delete(new QueryWrapper<FinanceInvoiceInvalid>().lambda().eq(FinanceInvoiceInvalid::getInvoiceId,financeInvoice.getId()));
                FinanceInvoiceInvalid financeInvoiceInvalid = new FinanceInvoiceInvalid();
                financeInvoiceInvalid.setInvalidStatus("0");
                financeInvoiceInvalid.setInvoiceId(financeInvoice.getId());
                financeInvoiceInvalidMapper.insert(financeInvoiceInvalid);
            }
        }
        return financeInvoice.getId();
    }

    public ResponseEntity saveInvoice(FinanceInvoiceDTO financeInvoiceDTO) throws Exception{
        this.saveForm(financeInvoiceDTO);
        return ResponseEntity.ok("保存成功");
    }

    public String saveFormInvalid(FinanceInvoiceDTO financeInvoiceDTO) throws Exception{
        String invoiceId = this.saveForm(financeInvoiceDTO);
        List<FinanceInvoiceInvalid> financeInvoiceInvalids = financeInvoiceInvalidMapper.selectList(
                new QueryWrapper<FinanceInvoiceInvalid>().lambda().eq(FinanceInvoiceInvalid::getInvoiceId, invoiceId));
        return financeInvoiceInvalids.get(0).getId();
    }

    /**
     * 添加附件
     * @param item 要添加的附件信息
     * @param id 附件id: attachmentId
     * @param userDTO 当前登录人信息
     * @param j 排序序号
     */
    public void saveFiles(WorkAttachmentInfo item,String id,UserDTO userDTO,AtomicInteger j){
        WorkAttachmentInfo i = new WorkAttachmentInfo();
        //包含了url、size、name
        i.setId(UUID.randomUUID().toString().replace("-", ""));
        i.setCreateTime(new Date());
        i.setUpdateTime(new Date());
        i.setDelFlag(0);
        i.setUrl(item.getUrl());
        //文件类型处理
        List<String> strings = Arrays.asList(item.getName().split("\\."));
        if (CollectionUtil.isNotEmpty(strings)) {
            i.setType(strings.get(1));
        }
        i.setAttachmentId(id);
        i.setAttachmentName(item.getName());
        i.setAttachmentFlag("invoice");
        i.setFileSize(item.getSize());
        i.setSort(j.get());
        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);
    }

    public ResponseEntity deleteByIds(String ids) {
        String idArray[] =ids.split(",");
        this.removeByIds (Lists.newArrayList (idArray));
        return ResponseEntity.ok ("删除成功");
    }

    public Boolean queryByNumber(String number, String id) {
        List<FinanceInvoiceDetail> financeInvoiceDetails = financeInvoiceDetailMapper.selectList(new QueryWrapper<FinanceInvoiceDetail>().lambda()
                .eq(FinanceInvoiceDetail::getNumber, number)
                .eq(FinanceInvoiceDetail::getDelFlag, '0')
                .ne(StringUtils.isNotBlank(id),FinanceInvoiceDetail::getId,id));
        if (CollectionUtil.isNotEmpty(financeInvoiceDetails)) {
            return true;
        }
        return false;
    }

    public String queryIdByInvalidId(String id) {
        FinanceInvoiceInvalid financeInvoiceInvalid = financeInvoiceInvalidMapper.selectById(id);
        return financeInvoiceInvalid.getInvoiceId();
    }

    public String updateStatusById(FinanceInvoiceDTO financeInvoiceDTO) {
        FinanceInvoice financeInvoice = FinanceInvoiceWrapper.INSTANCE.toEntity(financeInvoiceDTO);
        financeInvoiceMapper.update(financeInvoice, new QueryWrapper<FinanceInvoice>().lambda().eq(FinanceInvoice::getId, financeInvoice.getId()));
        return "操作成功";
    }

    public String isReceivables(FinanceInvoiceDTO financeInvoiceDTO) {
        FinanceInvoice financeInvoice = FinanceInvoiceWrapper.INSTANCE.toEntity(financeInvoiceDTO);
        financeInvoiceMapper.update(financeInvoice, new QueryWrapper<FinanceInvoice>().lambda().eq(FinanceInvoice::getId, financeInvoice.getId()));
        return "操作成功";
    }

    public String importDecide(List<FinanceInvoiceDetailDTO> list, ArrayList<FinanceInvoiceDetailDTO> arrayList, HashMap<String,String> hashMap){
        for (FinanceInvoiceDetailDTO financeInvoiceDetailDTO : list) {
            if(ObjectUtil.isEmpty(financeInvoiceDetailDTO)){
                continue;
            }

            if(StringUtils.isBlank(financeInvoiceDetailDTO.getNumber())){
                return "文件中有发票号为空，请重新填写";
            }
            if(StringUtils.isNotBlank(financeInvoiceDetailDTO.getNumber())){
                try {
                    Integer integer = new Integer(financeInvoiceDetailDTO.getNumber());
                    if (integer < 0) {
                        return "文件中有发票号填写不正确，请重新填写";
                    }
                }catch (Exception e){
                    return "文件中有发票号填写不正确，请重新填写";
                }
                List<FinanceInvoiceDetail> financeInvoiceDetailList = financeInvoiceDetailMapper.selectList(new QueryWrapper<FinanceInvoiceDetail>().eq("number", financeInvoiceDetailDTO.getNumber()));
                if(CollectionUtil.isNotEmpty(financeInvoiceDetailList)){
                    return "文件中有发票号已在系统中存在，请重新填写";
                }
            }
//            if (StringUtils.isBlank(financeInvoiceDetailDTO.getRate())) {
//                return "文件中有税率为空，请重新填写";
//            }
            if (StringUtils.isNotBlank(financeInvoiceDetailDTO.getRate())) {
                try {
                    if ((new BigDecimal(financeInvoiceDetailDTO.getRate())).compareTo(new BigDecimal(1)) == -1
                            || (new BigDecimal(financeInvoiceDetailDTO.getRate())).compareTo(new BigDecimal(100)) == 1) {
                        return "文件中有税率填写不正确，请重新填写";
                    }
                }catch (Exception e){
                    return "文件中有税率填写不正确，请重新填写";
                }
            }
            if (StringUtils.isBlank(financeInvoiceDetailDTO.getAccount())) {
                return "文件中有开票金额为空，请重新填写";
            } else {
                try {
                    financeInvoiceDetailDTO.setAccount(new BigDecimal(financeInvoiceDetailDTO.getAccount()).toString());
                }catch (Exception e){
                    return "文件中有开票金额填写不正确，请重新填写";
                }
            }

            hashMap.put(financeInvoiceDetailDTO.getNumber(),null);

            arrayList.add(financeInvoiceDetailDTO);
        }
        return null;
    }
}
