package com.jeeplus.test.cw.invoice.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
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.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.common.CommonUtils;
import com.jeeplus.test.cw.invoice.domain.*;
import com.jeeplus.test.cw.invoice.mapper.*;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceInvoiceBaseDTO;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceInvoiceDTO;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceInvoiceDetailDTO;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceInvoiceReceivablesDTO;
import com.jeeplus.test.cw.invoice.service.mapstruct.*;
import com.jeeplus.test.cw.workClientInfo.domain.CwWorkClientBase;
import com.jeeplus.test.cw.workClientInfo.domain.CwWorkClientBilling;
import com.jeeplus.test.cw.workClientInfo.service.CwWorkClientBillingService;
import com.jeeplus.test.cw.workClientInfo.service.CwWorkClientService;
import com.jeeplus.test.mould.service.SerialnumTplService;
import com.jeeplus.test.oss.mapper.OssServiceMapper;
import com.jeeplus.test.oss.service.OssService;
import com.jeeplus.test.workContract.mapper.WorkContractInfoMapper;
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 CwFinanceInvoiceService extends ServiceImpl<CwFinanceInvoiceMapper, CwFinanceInvoice> {

    @Resource
    private CwFinanceInvoiceMapper cwFinanceInvoiceMapper;
    @Resource
    private CwFinanceInvoiceBaseMapper cwFinanceInvoiceBaseMapper;
    @Resource
    private CwFinanceInvoiceDetailMapper cwFinanceInvoiceDetailMapper;
    @Resource
    private CwFinanceInvoiceReceivablesMapper cwFinanceInvoiceReceivablesMapper;
    @Resource
    private CwFinanceInvoiceInvalidMapper cwFinanceInvoiceInvalidMapper;
    @Resource
    private SerialnumTplService serialnumTplService;
    @Resource
    private OssServiceMapper ossServiceMapper;
    @Resource
    private WorkContractInfoMapper workContractInfoMapper;
    @Resource
    private UserService userService;
    @Resource
    private OssService ossService;
    @Resource
    private CwWorkClientBillingService cwWorkClientBillingService;
    @Resource
    private CwWorkClientService cwWorkClientService;

    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<CwFinanceInvoiceDTO> findList(Page<CwFinanceInvoiceDTO> page, CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception{
        QueryWrapper<CwFinanceInvoice> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( CwFinanceInvoiceWrapper.INSTANCE.toEntity(cwFinanceInvoiceDTO), CwFinanceInvoice.class );
        queryWrapper.eq("fi.del_flag","0");
        ArrayList<String> searchIdList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        AtomicInteger checkNum = new AtomicInteger();
        if (ObjectUtil.isNotEmpty(cwFinanceInvoiceDTO)) {
            // 发票号查询
            if (StringUtils.isNotBlank(cwFinanceInvoiceDTO.getNumber())) {
                List<CwFinanceInvoiceDetail> cwFinanceInvoiceDetails = cwFinanceInvoiceDetailMapper.selectList(new LambdaQueryWrapper<CwFinanceInvoiceDetail>().like(CwFinanceInvoiceDetail::getNumber, cwFinanceInvoiceDTO.getNumber()));
                List<String> ids = cwFinanceInvoiceDetails.stream().distinct().map(CwFinanceInvoiceDetail::getInvoiceId).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(ids)) {
                    return new Page<CwFinanceInvoiceDTO>();
                }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<CwFinanceInvoiceDTO>();
                        }else{
                            for (String item : ids) {
                                searchIdList.add(item);
                            }
                        }
                    }
                    checkNum.getAndIncrement();
                }
            }
            // 开票总金额
            if (StringUtils.isNotBlank(cwFinanceInvoiceDTO.getAccountBegin())&&StringUtils.isNotBlank(cwFinanceInvoiceDTO.getAccountEnd())) {
                List<CwFinanceInvoice> cwFinanceInvoices = cwFinanceInvoiceMapper.selectList(new LambdaQueryWrapper<CwFinanceInvoice>()
                        .between(CwFinanceInvoice::getAccount, new BigDecimal(cwFinanceInvoiceDTO.getAccountBegin()), new BigDecimal(cwFinanceInvoiceDTO.getAccountEnd())));
                List<String> ids = cwFinanceInvoices.stream().distinct().map(CwFinanceInvoice::getId).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(ids)) {
                    return new Page<CwFinanceInvoiceDTO>();
                }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<CwFinanceInvoiceDTO>();
                        }else{
                            for (String item : ids) {
                                searchIdList.add(item);
                            }
                        }
                    }
                    checkNum.getAndIncrement();
                }
            }
            // 开票日期
            if (StringUtils.isNotBlank(cwFinanceInvoiceDTO.getBillingDateBegin())&&StringUtils.isNotBlank(cwFinanceInvoiceDTO.getBillingDateEnd())) {
                List<CwFinanceInvoice> cwFinanceInvoices = cwFinanceInvoiceMapper.selectList(new LambdaQueryWrapper<CwFinanceInvoice>()
                        .between(CwFinanceInvoice::getBillingDate, sdf.parse(cwFinanceInvoiceDTO.getBillingDateBegin()), sdf.parse(cwFinanceInvoiceDTO.getBillingDateEnd())));
                List<String> ids = cwFinanceInvoices.stream().distinct().map(CwFinanceInvoice::getId).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(ids)) {
                    return new Page<CwFinanceInvoiceDTO>();
                }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<CwFinanceInvoiceDTO>();
                        }else{
                            for (String item : ids) {
                                searchIdList.add(item);
                            }
                        }
                    }
                    checkNum.getAndIncrement();
                }
            }
            // 收款日期
            if (StringUtils.isNotBlank(cwFinanceInvoiceDTO.getRemittanceDateBegin())&&StringUtils.isNotBlank(cwFinanceInvoiceDTO.getRemittanceDateEnd())) {
                List<CwFinanceInvoice> cwFinanceInvoices = cwFinanceInvoiceMapper.selectList(new LambdaQueryWrapper<CwFinanceInvoice>()
                        .between(CwFinanceInvoice::getReceivablesDate, sdf.parse(cwFinanceInvoiceDTO.getRemittanceDateBegin()), sdf.parse(cwFinanceInvoiceDTO.getRemittanceDateEnd())));
                List<String> ids = cwFinanceInvoices.stream().distinct().map(CwFinanceInvoice::getId).collect(Collectors.toList());
                if(CollectionUtil.isEmpty(ids)) {
                    return new Page<CwFinanceInvoiceDTO>();
                }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<CwFinanceInvoiceDTO>();
                        }else{
                            for (String item : ids) {
                                searchIdList.add(item);
                            }
                        }
                    }
                    checkNum.getAndIncrement();
                }
            }
            // 项目名称
            if (StringUtils.isNotBlank(cwFinanceInvoiceDTO.getProgramId())){
                    List<CwFinanceInvoiceBase> cwFinanceInvoiceBaseList = cwFinanceInvoiceBaseMapper.selectList(new LambdaQueryWrapper<CwFinanceInvoiceBase>()
                            .eq(CwFinanceInvoiceBase::getProgramId, cwFinanceInvoiceDTO.getProgramId()));
                    List<String> ids = cwFinanceInvoiceBaseList.stream().distinct().map(CwFinanceInvoiceBase::getInvoiceId).collect(Collectors.toList());
                    if(CollectionUtil.isEmpty(ids)) {
                        return new Page<CwFinanceInvoiceDTO>();
                    }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<CwFinanceInvoiceDTO>();
                            }else{
                                for (String item : ids) {
                                    searchIdList.add(item);
                                }
                            }
                        }
                        checkNum.getAndIncrement();
                    }
                }
            // 经办人
            if (StringUtils.isNotBlank(cwFinanceInvoiceDTO.getOperator())){
                queryWrapper.like("su.name", cwFinanceInvoiceDTO.getOperator());
            }
            // 对账人
            if (StringUtils.isNotBlank(cwFinanceInvoiceDTO.getReconciliationPeopleName())) {
                List<User> users = userService.list(new QueryWrapper<User>().lambda().like(User::getName, cwFinanceInvoiceDTO.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<CwFinanceInvoiceDTO>();
                }
            }
            // 经办人部门
            if (StringUtils.isNotBlank(cwFinanceInvoiceDTO.getOperatorOffice())){
                List<User> userList = userService.getUserByOfficeAll(cwFinanceInvoiceDTO.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",userIdList);
                    } else {
                        return new Page<CwFinanceInvoiceDTO>();
                    }
                } else {
                    return new Page<CwFinanceInvoiceDTO>();
                }
            }
        }
        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<CwFinanceInvoiceDTO>();
            }
        }
        // 如果当前用户是部门主任，则可以查看部门所有的项目、自己创建的项目以及所属项目组的项目
        // 如果当前用户是员工，则可以查看自己创建的项目以及所属项目组的项目
        StringBuilder officeIds = new StringBuilder();
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();
        //判定是否为会计所长
        /*if(CommonUtils.haveRoleKjsz()){
            //获取当前人管理的部门id
            if(StringUtils.isNotBlank(userDTO.getManageOfficeIds())){
                manageOfficeIdList = Arrays.asList(userDTO.getManageOfficeIds().split(","));
            }else{
                manageOfficeIdList.add(userDTO.getOfficeDTO().getId());
            }
            for (int i = 0; i <manageOfficeIdList.size(); i++){
                officeIds.append("'").append(manageOfficeIdList.get(i)).append("'");
                if(i < manageOfficeIdList.size()-1){
                    officeIds.append(",");
                }
            }
        }*/
        return cwFinanceInvoiceMapper.findList(page,queryWrapper,officeIds.toString());
    }

    public CwFinanceInvoiceDTO queryById(String id) {

        CwFinanceInvoiceDTO cwFinanceInvoiceDTO = cwFinanceInvoiceMapper.queryById(id);

        // 电话号获取
        if (ObjectUtil.isNotEmpty(cwFinanceInvoiceDTO) && StringUtils.isNotBlank(cwFinanceInvoiceDTO.getBillingId())) {
            CwWorkClientBilling cwWorkClientBilling = cwWorkClientBillingService.getById(cwFinanceInvoiceDTO.getBillingId());
            if (ObjectUtil.isNotEmpty(cwWorkClientBilling) && StringUtils.isNotBlank(cwWorkClientBilling.getPhone())) {
                // 如果通过billingId(开票信息id)可以查询到数据，并且数据的phone(电话)有值的话，那么就将方法返回结果的telPhone替换为查询到的phone
                cwFinanceInvoiceDTO.setTelPhone(cwWorkClientBilling.getPhone());
            } else {
                // 如果通过billingId(开票信息id)查询不到数据或者查询到数据的phone值为空
                // 将billingId(开票信息id)置空，因为前端根据billingId是否有值来判断->是否允许电话号码可以手填
                cwFinanceInvoiceDTO.setBillingId("");
                // 将telPhone(电话号)置空
//                cwFinanceInvoiceDTO.setTelPhone("");
            }
        }

        // 实际开票单位名称获取
        if (ObjectUtil.isNotEmpty(cwFinanceInvoiceDTO) && StringUtils.isNotBlank(cwFinanceInvoiceDTO.getBillingWorkplaceRealId())) {
            CwWorkClientBase cwWorkClientBase = cwWorkClientService.getById(cwFinanceInvoiceDTO.getBillingWorkplaceRealId());
            if (ObjectUtil.isNotEmpty(cwWorkClientBase) && StringUtils.isNotBlank(cwWorkClientBase.getName())) {
                // 如果通过billingWorkplaceRealId(实际开票单位id)可以查询到数据，并且数据的name(实际开票单位名称)有值的话，
                // 那么就将方法返回结果的billingWorkplaceReal替换
                cwFinanceInvoiceDTO.setBillingWorkplaceReal(cwWorkClientBase.getName());
            }
        }

        return cwFinanceInvoiceDTO;
    }

    public CwFinanceInvoice saveForm(CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception{
        CwFinanceInvoice cwFinanceInvoice = CwFinanceInvoiceWrapper.INSTANCE.toEntity(cwFinanceInvoiceDTO);
        if (ObjectUtil.isNotEmpty(cwFinanceInvoice)) {
            if(StringUtils.isBlank(cwFinanceInvoice.getId())){
                //获取当前登录人信息
                UserDTO userDTO = UserUtils.getCurrentUserDTO();
                //发票编号生成
                String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), CwFinanceInvoiceDTO.BIZ_CODE);
                cwFinanceInvoice.setNo(serialNum);
                if (StringUtils.isBlank(cwFinanceInvoice.getInvalidStatus())){
                    cwFinanceInvoice.setInvalidStatus("0");
                }
                if (StringUtils.isBlank(cwFinanceInvoice.getReceivablesStatus())){
                    cwFinanceInvoice.setReceivablesStatus("0");
                }
            }
        }
        this.saveOrUpdate(cwFinanceInvoice);

        if (ObjectUtil.isNotEmpty(cwFinanceInvoiceDTO)) {
            // 如果当前是执行的是收款页面的保存方法
            if ("1".equals(cwFinanceInvoiceDTO.getIsReceivables())) {
                // 如果传过来的收款日期为空，则将本条发票的收款日期置空
                if (ObjectUtil.isEmpty(cwFinanceInvoiceDTO.getReceivablesDate())) {
                    // 根据发票id，置空发票的收款日期
                    cwFinanceInvoiceMapper.setReceivablesDateNull(cwFinanceInvoice.getId());
                }
            }
            // 基本信息保存
            if(CollectionUtil.isNotEmpty(cwFinanceInvoiceDTO.getFinanceInvoiceBaseDTOList())){
                List<String> delIds = cwFinanceInvoiceDTO.getFinanceInvoiceBaseDTOList().stream().distinct().filter(item->{
                    if(StringUtils.isNotBlank(item.getId())){
                        return true;
                    }
                    return false;
                }).map(CwFinanceInvoiceBaseDTO::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    cwFinanceInvoiceBaseMapper.delete(new QueryWrapper<CwFinanceInvoiceBase>().lambda()
                            .eq(CwFinanceInvoiceBase::getInvoiceId, cwFinanceInvoice.getId()).notIn(CwFinanceInvoiceBase::getId,delIds));
                }else{
                    cwFinanceInvoiceBaseMapper.delete(new QueryWrapper<CwFinanceInvoiceBase>().lambda()
                            .eq(CwFinanceInvoiceBase::getInvoiceId, cwFinanceInvoice.getId()));
                }
                cwFinanceInvoiceDTO.getFinanceInvoiceBaseDTOList().stream().forEach(item->{
                    CwFinanceInvoiceBase cwFinanceInvoiceBase = CwFinanceInvoiceBaseWrapper.INSTANCE.toEntity(item);
                    if(StringUtils.isNotBlank(cwFinanceInvoiceBase.getId())){
                        cwFinanceInvoiceBaseMapper.updateById(cwFinanceInvoiceBase);
                    }else{
                        cwFinanceInvoiceBase.setInvoiceId(cwFinanceInvoice.getId());
                        cwFinanceInvoiceBaseMapper.insert(cwFinanceInvoiceBase);
                    }
                });
            }else{
                cwFinanceInvoiceBaseMapper.delete(new QueryWrapper<CwFinanceInvoiceBase>().lambda()
                        .eq(CwFinanceInvoiceBase::getInvoiceId, cwFinanceInvoice.getId()));
            }
            // 附件
            ossService.saveOrUpdateFileList(cwFinanceInvoiceDTO.getWorkAttachmentDtoList(), cwFinanceInvoice.getId(),"cw_invoice");
            // 发票明细保存
            if(CollectionUtil.isNotEmpty(cwFinanceInvoiceDTO.getFinanceInvoiceDetailDTOList())){
                List<String> delIds = cwFinanceInvoiceDTO.getFinanceInvoiceDetailDTOList().stream().distinct().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).map(CwFinanceInvoiceDetailDTO::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    cwFinanceInvoiceDetailMapper.delete(new QueryWrapper<CwFinanceInvoiceDetail>().lambda()
                            .eq(CwFinanceInvoiceDetail::getInvoiceId, cwFinanceInvoice.getId())
                            .notIn(CwFinanceInvoiceDetail::getId,delIds));
                }else{
                    cwFinanceInvoiceDetailMapper.delete(new QueryWrapper<CwFinanceInvoiceDetail>().lambda().eq(CwFinanceInvoiceDetail::getInvoiceId, cwFinanceInvoice.getId()));
                }
                cwFinanceInvoiceDTO.getFinanceInvoiceDetailDTOList().stream().forEach(item->{
                    CwFinanceInvoiceDetail cwFinanceInvoiceDetail = CwFinanceInvoiceDetailWrapper.INSTANCE.toEntity(item);
                    if(StringUtils.isNotBlank(cwFinanceInvoiceDetail.getId())){
                        cwFinanceInvoiceDetailMapper.updateById(cwFinanceInvoiceDetail);
                    }else{
                        cwFinanceInvoiceDetail.setInvoiceId(cwFinanceInvoice.getId());
                        cwFinanceInvoiceDetailMapper.insert(cwFinanceInvoiceDetail);
                    }
                });
            }else{
                cwFinanceInvoiceDetailMapper.delete(new QueryWrapper<CwFinanceInvoiceDetail>().lambda().eq(CwFinanceInvoiceDetail::getInvoiceId, cwFinanceInvoice.getId()));
            }
            // 收款明细保存
            if(CollectionUtil.isNotEmpty(cwFinanceInvoiceDTO.getFinanceInvoiceReceivablesDTOList())){
                List<String> delIds = cwFinanceInvoiceDTO.getFinanceInvoiceReceivablesDTOList().stream().distinct().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).map(CwFinanceInvoiceReceivablesDTO::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(delIds)){
                    cwFinanceInvoiceReceivablesMapper.delete(new QueryWrapper<CwFinanceInvoiceReceivables>().lambda()
                            .eq(CwFinanceInvoiceReceivables::getInvoiceId, cwFinanceInvoice.getId())
                            .notIn(CwFinanceInvoiceReceivables::getId,delIds));
                }else{
                    cwFinanceInvoiceReceivablesMapper.delete(new QueryWrapper<CwFinanceInvoiceReceivables>().lambda().eq(CwFinanceInvoiceReceivables::getInvoiceId, cwFinanceInvoice.getId()));
                }
                cwFinanceInvoiceDTO.getFinanceInvoiceReceivablesDTOList().stream().forEach(item->{
                    CwFinanceInvoiceReceivables cwFinanceInvoiceReceivables = CwFinanceInvoiceReceivablesWrapper.INSTANCE.toEntity(item);
                    if(StringUtils.isNotBlank(cwFinanceInvoiceReceivables.getId())){
                        cwFinanceInvoiceReceivablesMapper.updateById(cwFinanceInvoiceReceivables);
                    }else{
                        cwFinanceInvoiceReceivables.setInvoiceId(cwFinanceInvoice.getId());
                        cwFinanceInvoiceReceivablesMapper.insert(cwFinanceInvoiceReceivables);
                    }
                });
            }else{
                cwFinanceInvoiceReceivablesMapper.delete(new QueryWrapper<CwFinanceInvoiceReceivables>().lambda().eq(CwFinanceInvoiceReceivables::getInvoiceId, cwFinanceInvoice.getId()));
            }
            // 作废信息保存
            if(ObjectUtil.isNotEmpty(cwFinanceInvoiceDTO.getFinanceInvoiceInvalidDTO())){
                CwFinanceInvoiceInvalid cwFinanceInvoiceInvalid = CwFinanceInvoiceInvalidWrapper.INSTANCE.toEntity(cwFinanceInvoiceDTO.getFinanceInvoiceInvalidDTO());
                if(StringUtils.isNotBlank(cwFinanceInvoiceInvalid.getId())){
                    cwFinanceInvoiceInvalidMapper.update(cwFinanceInvoiceInvalid,
                            new QueryWrapper<CwFinanceInvoiceInvalid>().lambda().eq(CwFinanceInvoiceInvalid::getId, cwFinanceInvoiceInvalid.getId()));
                }else{
                    cwFinanceInvoiceInvalid.setInvalidStatus("0");
                    cwFinanceInvoiceInvalid.setInvoiceId(cwFinanceInvoice.getId());
                    cwFinanceInvoiceInvalidMapper.insert(cwFinanceInvoiceInvalid);
                }
            }else{
                cwFinanceInvoiceInvalidMapper.delete(new QueryWrapper<CwFinanceInvoiceInvalid>().lambda().eq(CwFinanceInvoiceInvalid::getInvoiceId, cwFinanceInvoice.getId()));
                CwFinanceInvoiceInvalid cwFinanceInvoiceInvalid = new CwFinanceInvoiceInvalid();
                cwFinanceInvoiceInvalid.setInvalidStatus("0");
                cwFinanceInvoiceInvalid.setInvoiceId(cwFinanceInvoice.getId());
                cwFinanceInvoiceInvalidMapper.insert(cwFinanceInvoiceInvalid);
            }
        }
        return cwFinanceInvoice;
    }

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

    public String saveFormInvalid(CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception{
        String invoiceId = this.saveForm(cwFinanceInvoiceDTO).getId();
        List<CwFinanceInvoiceInvalid> cwFinanceInvoiceInvalids = cwFinanceInvoiceInvalidMapper.selectList(
                new QueryWrapper<CwFinanceInvoiceInvalid>().lambda().eq(CwFinanceInvoiceInvalid::getInvoiceId, invoiceId));
        return cwFinanceInvoiceInvalids.get(0).getId();
    }

    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<CwFinanceInvoiceDetail> cwFinanceInvoiceDetails = cwFinanceInvoiceDetailMapper.selectList(new QueryWrapper<CwFinanceInvoiceDetail>().lambda()
                .eq(CwFinanceInvoiceDetail::getNumber, number)
                .eq(CwFinanceInvoiceDetail::getDelFlag, '0')
                .ne(StringUtils.isNotBlank(id), CwFinanceInvoiceDetail::getId,id));
        if (CollectionUtil.isNotEmpty(cwFinanceInvoiceDetails)) {
            return true;
        }
        return false;
    }

    public String queryIdByInvalidId(String id) {
        CwFinanceInvoiceInvalid cwFinanceInvoiceInvalid = cwFinanceInvoiceInvalidMapper.selectById(id);
        return cwFinanceInvoiceInvalid.getInvoiceId();
    }

    public String updateStatusById(CwFinanceInvoiceDTO cwFinanceInvoiceDTO) {
        CwFinanceInvoice cwFinanceInvoice = CwFinanceInvoiceWrapper.INSTANCE.toEntity(cwFinanceInvoiceDTO);
        cwFinanceInvoiceMapper.update(cwFinanceInvoice, new QueryWrapper<CwFinanceInvoice>().lambda().eq(CwFinanceInvoice::getId, cwFinanceInvoice.getId()));
        return "操作成功";
    }

    public String isReceivables(CwFinanceInvoiceDTO cwFinanceInvoiceDTO) {
        CwFinanceInvoice cwFinanceInvoice = CwFinanceInvoiceWrapper.INSTANCE.toEntity(cwFinanceInvoiceDTO);
        cwFinanceInvoiceMapper.update(cwFinanceInvoice, new QueryWrapper<CwFinanceInvoice>().lambda().eq(CwFinanceInvoice::getId, cwFinanceInvoice.getId()));
        return "操作成功";
    }

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

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

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

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

    public List<CwFinanceInvoiceDTO> getByIds(String projectId,CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception{
        if(StringUtils.isNotBlank(projectId)){
            List<String> idByProjectId = cwFinanceInvoiceMapper.getIdByProjectId(projectId);
            if (CollectionUtil.isNotEmpty(idByProjectId)){
                QueryWrapper<CwFinanceInvoice> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( CwFinanceInvoiceWrapper.INSTANCE.toEntity(cwFinanceInvoiceDTO), CwFinanceInvoice.class );
                queryWrapper.in("fi.id", idByProjectId);
                queryWrapper.eq("fi.del_flag","0");
                queryWrapper.eq("fi.status","5"); // 发票申请流程已通过
                queryWrapper.orderByDesc("fi.create_date");
                queryWrapper.eq("fi.invalid_status","0"); // 未作废
                return cwFinanceInvoiceMapper.getByIds(queryWrapper);
            }
        }
        return new ArrayList<>();
    }

    public List<CwFinanceInvoiceDTO> getByContractId(String contractId,CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception{
        if(StringUtils.isNotBlank(contractId)){
            List<String> idByContractId = cwFinanceInvoiceMapper.getIdByContractId(contractId);
            if (CollectionUtil.isNotEmpty(idByContractId)){
                QueryWrapper<CwFinanceInvoice> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( CwFinanceInvoiceWrapper.INSTANCE.toEntity(cwFinanceInvoiceDTO), CwFinanceInvoice.class );
                queryWrapper.in("fi.id", idByContractId);
                queryWrapper.eq("fi.del_flag","0");
                queryWrapper.eq("fi.status","5"); // 发票申请流程已通过
                queryWrapper.orderByDesc("fi.create_date");
                queryWrapper.eq("fi.invalid_status","0"); // 未作废
                return cwFinanceInvoiceMapper.getByIds(queryWrapper);
            }
        }
        return new ArrayList<>();
    }

    public List<CwFinanceInvoiceDTO> getIdByClientId(String clientId,CwFinanceInvoiceDTO cwFinanceInvoiceDTO) throws Exception{
        if(StringUtils.isNotBlank(clientId)){
            List<String> idByClientId = cwFinanceInvoiceMapper.getIdByClientId(clientId);
            if (CollectionUtil.isNotEmpty(idByClientId)){
                QueryWrapper<CwFinanceInvoice> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( CwFinanceInvoiceWrapper.INSTANCE.toEntity(cwFinanceInvoiceDTO), CwFinanceInvoice.class );
                queryWrapper.in("fi.id", idByClientId);
                queryWrapper.eq("fi.del_flag","0");
                queryWrapper.eq("fi.status","5"); // 发票申请流程已通过
                queryWrapper.orderByDesc("fi.create_date");
                queryWrapper.eq("fi.invalid_status","0"); // 未作废
                return cwFinanceInvoiceMapper.getByIds(queryWrapper);
            }
        }
        return new ArrayList<>();
    }
}
