package com.jeeplus.finance.projectRecords.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.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.common.constant.CacheNames;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.finance.contractRegistration.domain.ContractInfo;
import com.jeeplus.finance.contractRegistration.mapper.ContractInfoMapper;
import com.jeeplus.finance.contractRegistration.service.ContractInfoService;
import com.jeeplus.finance.projectRecords.domain.CwProjectClientContact;
import com.jeeplus.finance.projectRecords.domain.CwProjectMembers;
import com.jeeplus.finance.projectRecords.domain.CwProjectRecords;
import com.jeeplus.finance.projectRecords.mapper.CwProjectClientContactMapper;
import com.jeeplus.finance.projectRecords.mapper.CwProjectRecordsMapper;
import com.jeeplus.finance.projectRecords.service.dto.*;
import com.jeeplus.finance.projectRecords.service.mapstruct.CwProjectClientContactWrapper;
import com.jeeplus.finance.projectRecords.service.mapstruct.CwProjectMembersWrapper;
import com.jeeplus.finance.projectRecords.service.mapstruct.CwProjectRecordsWrapper;
import com.jeeplus.finance.projectReport.domain.CwProjectReportData;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportMapper;
import com.jeeplus.finance.workClientInfo.domain.CwWorkClientContact;
import com.jeeplus.finance.workClientInfo.mapper.CwWorkClientBaseMapper;
import com.jeeplus.finance.workClientInfo.mapper.CwWorkClientContactMapper;
import com.jeeplus.finance.workClientInfo.service.CwWorkClientContactService;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBaseDTO;
import com.jeeplus.flowable.feign.IAssessApi;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.feign.IDictApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
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.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 财务项目登记service
 *
 * @author: 徐滕
 * @version: 2022-11-10 14:56
 */
@Service
@Transactional
public class CwProjectRecordsService extends ServiceImpl<CwProjectRecordsMapper, CwProjectRecords> {

    @Resource
    private CwProjectRecordsMapper cwProjectRecordsMapper;
    //    @Resource
//    private OssService ossService;
    @Resource
    private CwProjectClientContactMapper cwProjectClientContactMapper;
    @Resource
    private CwProjectClientContactService cwProjectClientContactService;
    @Resource
    private ContractInfoMapper contractInfoMapper;
    //    @Resource
//    private SerialnumTplService serialnumTplService;
//    @Resource
//    private UserMapper userMapper;
    @Resource
    private CwWorkClientContactService cwWorkClientContactService;
    @Resource
    private CwProjectMembersService cwProjectMembersService;
    @Resource
    private CwProjectReportMapper cwProjectReportMapper;
    @Resource
    private ContractInfoService contractInfoService;
    @Resource
    private CwWorkClientBaseMapper cwWorkClientBaseMapper; ;
    @Resource
    private CwWorkClientContactMapper cwWorkClientContactMapper; ;


    /**
     * 差选项目列表信息
     *
     * @param page
     * @param cwProjectRecordsDTO
     * @return
     * @throws Exception
     */
    public IPage<CwProjectRecordsDTO> findList(Page<CwProjectRecordsDTO> page, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        QueryWrapper<CwProjectRecords> queryWrapper = QueryWrapperGenerator.buildQueryCondition(CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO), CwProjectRecords.class);
        queryWrapper.eq("a.del_flag", "0");
        if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO)) {
            if (ArrayUtil.isNotEmpty(cwProjectRecordsDTO.getCreateDates())) {
                queryWrapper.between("a.create_time", cwProjectRecordsDTO.getCreateDates()[0], cwProjectRecordsDTO.getCreateDates()[1]);
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName())) {
                queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName()).or().like("su2.name", cwProjectRecordsDTO.getProjectMasterName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getBusinessType())) {
                queryWrapper.eq("a.business_type", cwProjectRecordsDTO.getBusinessType());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName2())) {
                List<User> userList = SpringUtil.getBean(IUserApi.class).selectListByName(cwProjectRecordsDTO.getProjectMasterName2());
                if (CollectionUtils.isNotEmpty(userList)) {
                    List<String> ids = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(ids)) {
                        queryWrapper.in("a.project_master_id", ids);
                    } else {
                        return new Page<>();
                    }
                } else {
                    queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
                }
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getRealHeaderName())) {
                queryWrapper.in("a.real_header", cwProjectRecordsDTO.getRealHeaderName()).or().like("su3.name", cwProjectRecordsDTO.getRealHeaderName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateId())) {
                queryWrapper.eq("a.create_by_id", cwProjectRecordsDTO.getCreateId());
            }
            // 创建人
            if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO.getCreateBy())) {
                if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateBy().getName())) {
                    queryWrapper.in("a.create_by_id", cwProjectRecordsDTO.getCreateBy().getId()).or().like("su.name", cwProjectRecordsDTO.getCreateBy().getName());
                }
            }
            //报告日期
            if (ArrayUtil.isNotEmpty(cwProjectRecordsDTO.getReportDates())) {
                queryWrapper.between("nl.report_date", cwProjectRecordsDTO.getReportDates()[0], cwProjectRecordsDTO.getReportDates()[1]);
            }
            //报告类型
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCwReportType())) {
                queryWrapper.eq("nl.report_type", cwProjectRecordsDTO.getCwReportType());
            }
            //项目分类
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectClassification())) {
                queryWrapper.eq("a.project_classification", cwProjectRecordsDTO.getProjectClassification());
            }
            //报备类型
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getReportType())) {
                queryWrapper.eq("a.report_type", cwProjectRecordsDTO.getReportType());
            }
            //合同名称
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getContractName())) {
                if("暂无合同".equals(cwProjectRecordsDTO.getContractName())) {
                    queryWrapper.and(wrapper -> wrapper.isNull("a.contract_id").or().eq("a.contract_id", ""));
                }else{
                    queryWrapper.like("cw_wci.contract_name", cwProjectRecordsDTO.getContractName());
                }

            }
            //客户名称
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getClientContactsName())) {
                queryWrapper.like("cw_wcb.name", cwProjectRecordsDTO.getClientContactsName());
            }
        }

        IPage<CwProjectRecordsDTO> list = cwProjectRecordsMapper.findList(page, queryWrapper);
//        List<UserDTO> allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();

        List<UserDTO> allUserInfo = (List<UserDTO>) RedisUtils.getInstance().get(CacheNames.USER_CACHE_USER_ALL_INFO);
        if (null == allUserInfo || allUserInfo.size() == 0) {
            allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        }
        List<UserDTO> finalAllUserInfo = allUserInfo;
        list.getRecords().forEach(li -> {
            if (null != li.getCreateBy() && StringUtils.isBlank(li.getCreateBy().getName())) {
                //根据项目经理1的id去查项目经理去名称
                if (StringUtils.isNotBlank(li.getProjectMasterId())) {
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getCreateBy().getId().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String createUserName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.getCreateBy().setName(createUserName);
                    }
                }
            }
            if (StringUtils.isBlank(li.getProjectMasterName())) {
                //根据项目经理1的id去查项目经理去名称
                if (StringUtils.isNotBlank(li.getProjectMasterId())) {
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMasterId().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMasterName(projectMasterName);
                    }
                }
            }
            if (StringUtils.isBlank(li.getRealHeaderName())) {
                if (StringUtils.isNotBlank(li.getRealHeader())) {
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getRealHeader().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }

                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setRealHeaderName(projectMasterName);
                    }
                }
            }

        });
        return list;
    }

    /**
     * 查询有报告项目及老项目列表信息
     *
     * @param page
     * @param cwProjectRecordsDTO
     * @return
     * @throws Exception
     */
    public IPage<CwProjectRecordsDTO> findNewList(Page<CwProjectRecordsDTO> page, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        QueryWrapper<CwProjectRecords> queryWrapper = QueryWrapperGenerator.buildQueryCondition(CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO), CwProjectRecords.class);
        queryWrapper.eq("a.del_flag", "0");
        // 时间分割线
        String splitTime = "2026-03-24 00:00:00";

        queryWrapper.and(wrapper -> {
            // ================== 2026-03-15 及以后 → 你的旧权限（项目经理1/2/执行人） ==================
            wrapper.nested(w1 -> {
                        w1.ge("a.create_time", splitTime)
                                .and(w2 -> {
                                    w2.eq("a.project_master_id", userDTO.getId())
                                            .or()
                                            .eq("a.real_header", userDTO.getId())
                                            .or()
                                            .eq("a.project_executor", userDTO.getId());
                                });
                    })

                    // ================== 2026-03-15 之前 → 你的新权限（创建人/项目成员） ==================
                    .or()
                    .nested(w1 -> {
                        w1.lt("a.create_time", splitTime)
                                .and(w2 -> {
                                    w2.eq("a.create_by_id", userDTO.getId())
                                            .or()
                                            .eq("b.user_id", userDTO.getId());
                                });
                    });
        });
        if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO)) {
            if (ArrayUtil.isNotEmpty(cwProjectRecordsDTO.getCreateDates())) {
                queryWrapper.between("a.create_time", cwProjectRecordsDTO.getCreateDates()[0], cwProjectRecordsDTO.getCreateDates()[1]);
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName())) {
                queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getBusinessType())) {
                queryWrapper.eq("a.business_type", cwProjectRecordsDTO.getBusinessType());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName2())) {
                List<User> userList = SpringUtil.getBean(IUserApi.class).selectListByName(cwProjectRecordsDTO.getProjectMasterName2());
                if (CollectionUtils.isNotEmpty(userList)) {
                    List<String> ids = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(ids)) {
                        queryWrapper.in("a.project_master_id", ids);
                    } else {
                        return new Page<>();
                    }
                } else {
                    queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
                }
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getRealHeaderName())) {
                queryWrapper.in("a.real_header", cwProjectRecordsDTO.getRealHeaderName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateId())) {
                queryWrapper.eq("a.create_by_id", cwProjectRecordsDTO.getCreateId());
            }
            // 创建人
            if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO.getCreateBy())) {
                if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateBy().getName())) {
                    queryWrapper.in("a.create_by_id", cwProjectRecordsDTO.getCreateBy().getName());
                }
            }
        }
        //查找有报告的新项目及老项目
        IPage<CwProjectRecordsDTO> list = cwProjectRecordsMapper.findNewList(page, queryWrapper);
        List<UserDTO> allUserInfo = (List<UserDTO>) RedisUtils.getInstance().get(CacheNames.USER_CACHE_USER_ALL_INFO);
        if (null == allUserInfo || allUserInfo.size() == 0) {
            allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        }
        List<UserDTO> finalAllUserInfo = allUserInfo;
        list.getRecords().forEach(li -> {
            if (StringUtils.isBlank(li.getProjectMasterName())) {
                //根据项目经理1的id去查项目经理去名称
                if (StringUtils.isNotBlank(li.getProjectMasterId())) {
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMasterId().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMasterName(projectMasterName);
                    }
                }
            }
            if (StringUtils.isBlank(li.getRealHeaderName())) {
                if (StringUtils.isNotBlank(li.getRealHeader())) {
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getRealHeader().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }

                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setRealHeaderName(projectMasterName);
                    }
                }
            }

        });
        return list;
    }

    /**
     * 查询无报告项目及老项目列表信息
     *
     * @param page
     * @param cwProjectRecordsDTO
     * @return
     * @throws Exception
     */
    public IPage<CwProjectRecordsDTO> findNoReportList(Page<CwProjectRecordsDTO> page, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        QueryWrapper<CwProjectRecords> queryWrapper = QueryWrapperGenerator.buildQueryCondition(CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO), CwProjectRecords.class);
        queryWrapper.eq("a.del_flag", "0");
        if(!userDTO.isAdmin()){
            queryWrapper.eq("a.create_by_id", userDTO.getId());
        }
        if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO)) {
            if (ArrayUtil.isNotEmpty(cwProjectRecordsDTO.getCreateDates())) {
                queryWrapper.between("a.create_time", cwProjectRecordsDTO.getCreateDates()[0], cwProjectRecordsDTO.getCreateDates()[1]);
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName())) {
                queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getBusinessType())) {
                queryWrapper.eq("a.business_type", cwProjectRecordsDTO.getBusinessType());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName2())) {
                List<User> userList = SpringUtil.getBean(IUserApi.class).selectListByName(cwProjectRecordsDTO.getProjectMasterName2());
                if (CollectionUtils.isNotEmpty(userList)) {
                    List<String> ids = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(ids)) {
                        queryWrapper.in("a.project_master_id", ids);
                    } else {
                        return new Page<>();
                    }
                } else {
                    queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
                }
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getRealHeaderName())) {
                queryWrapper.in("a.real_header", cwProjectRecordsDTO.getRealHeaderName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateId())) {
                queryWrapper.eq("a.create_by_id", cwProjectRecordsDTO.getCreateId());
            }
            // 创建人
            if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO.getCreateBy())) {
                if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateBy().getName())) {
                    queryWrapper.in("a.create_by_id", cwProjectRecordsDTO.getCreateBy().getName());
                }
            }
        }
        //查找有报告的新项目及老项目
        IPage<CwProjectRecordsDTO> list = cwProjectRecordsMapper.findNoReportList(page, queryWrapper);
        List<UserDTO> allUserInfo = (List<UserDTO>) RedisUtils.getInstance().get(CacheNames.USER_CACHE_USER_ALL_INFO);
        if (null == allUserInfo || allUserInfo.size() == 0) {
            allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        }
        List<UserDTO> finalAllUserInfo = allUserInfo;
        list.getRecords().forEach(li -> {
            if (StringUtils.isBlank(li.getProjectMasterName())) {
                //根据项目经理1的id去查项目经理去名称
                if (StringUtils.isNotBlank(li.getProjectMasterId())) {
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMasterId().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMasterName(projectMasterName);
                    }
                }
            }
            if (StringUtils.isBlank(li.getRealHeaderName())) {
                if (StringUtils.isNotBlank(li.getRealHeader())) {
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getRealHeader().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }

                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setRealHeaderName(projectMasterName);
                    }
                }
            }

        });
        return list;
    }

    /**
     * 查询报告号不为空的项目列表信息
     *
     * @param page
     * @param cwProjectRecordsDTO
     * @return
     * @throws Exception
     */
    public IPage<CwProjectRecordsDTO> getList(Page<CwProjectRecordsDTO> page, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        QueryWrapper<CwProjectRecords> queryWrapper = QueryWrapperGenerator.buildQueryCondition(CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO), CwProjectRecords.class);
        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.eq("a.create_by_id", userDTO.getId());
        if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO)) {
            if (ArrayUtil.isNotEmpty(cwProjectRecordsDTO.getCreateDates())) {
                queryWrapper.between("a.create_time", cwProjectRecordsDTO.getCreateDates()[0], cwProjectRecordsDTO.getCreateDates()[1]);
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName())) {
                queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getBusinessType())) {
                queryWrapper.eq("a.business_type", cwProjectRecordsDTO.getBusinessType());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName2())) {
                List<User> userList = SpringUtil.getBean(IUserApi.class).selectListByName(cwProjectRecordsDTO.getProjectMasterName2());
                if (CollectionUtils.isNotEmpty(userList)) {
                    List<String> ids = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(ids)) {
                        queryWrapper.in("a.project_master_id", ids);
                    } else {
                        return new Page<>();
                    }
                } else {
                    queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
                }
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getRealHeaderName())) {
                queryWrapper.in("a.real_header", cwProjectRecordsDTO.getRealHeaderName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateId())) {
                queryWrapper.eq("a.create_by_id", cwProjectRecordsDTO.getCreateId());
            }
            // 创建人
            if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO.getCreateBy())) {
                if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateBy().getName())) {
                    queryWrapper.in("a.create_by_id", cwProjectRecordsDTO.getCreateBy().getName());
                }
            }
        }

        IPage<CwProjectRecordsDTO> list = cwProjectRecordsMapper.getList(page, queryWrapper);
        return list;
    }

    /**
     * 查询是否有预开票的项目
     *
     * @param page
     * @param cwProjectRecordsDTO
     * @return
     * @throws Exception
     */
    public IPage<CwProjectRecordsDTO> findPreInvoiceList(Page<CwProjectRecordsDTO> page, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        QueryWrapper<CwProjectRecords> queryWrapper = QueryWrapperGenerator.buildQueryCondition(CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO), CwProjectRecords.class);
        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.eq("a.create_by_id", userDTO.getId());
        queryWrapper.eq("a.is_pre_invoice", "1");
        if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO)) {
            if (ArrayUtil.isNotEmpty(cwProjectRecordsDTO.getCreateDates())) {
                queryWrapper.between("a.create_time", cwProjectRecordsDTO.getCreateDates()[0], cwProjectRecordsDTO.getCreateDates()[1]);
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName())) {
                queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getBusinessType())) {
                queryWrapper.eq("a.business_type", cwProjectRecordsDTO.getBusinessType());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName2())) {
                List<User> userList = SpringUtil.getBean(IUserApi.class).selectListByName(cwProjectRecordsDTO.getProjectMasterName2());
                if (CollectionUtils.isNotEmpty(userList)) {
                    List<String> ids = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(ids)) {
                        queryWrapper.in("a.project_master_id", ids);
                    } else {
                        return new Page<>();
                    }
                } else {
                    queryWrapper.in("a.project_master_id", cwProjectRecordsDTO.getProjectMasterName());
                }
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getRealHeaderName())) {
                queryWrapper.in("a.real_header", cwProjectRecordsDTO.getRealHeaderName());
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateId())) {
                queryWrapper.eq("a.create_by_id", cwProjectRecordsDTO.getCreateId());
            }
            // 创建人
            if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO.getCreateBy())) {
                if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateBy().getName())) {
                    queryWrapper.in("a.create_by_id", cwProjectRecordsDTO.getCreateBy().getName());
                }
            }
        }

        IPage<CwProjectRecordsDTO> list = cwProjectRecordsMapper.findPreInvoiceList(page, queryWrapper);
        List<CwProjectRecordsDTO> recordsToKeep = new ArrayList<>();
        Set<String> projectIdsWithPendingReports = new HashSet<>();
        List<String> recordsToRemove = new ArrayList<>();
        //查询出未关联完成的项目,完成替换
        for (CwProjectRecordsDTO record : list.getRecords()) {
            List<CwProjectReportData> reportData = cwProjectReportMapper.getByProjectId(record.getId());
            if (CollectionUtils.isNotEmpty(reportData)) {
                for (CwProjectReportData data : reportData) {
                    if ("2".equals(data.getIsCompleteInvoice()) || "1".equals(data.getIsCompleteInvoice())) {
                        // 保存到待处理的proId中
                        projectIdsWithPendingReports.add(record.getId());
                        recordsToRemove.add(record.getId());
                        continue; // 如果一个报告已完成，就跳出循环，不再检查其他报告
                    } else if ("0".equals(data.getApplyStatus()) || "1".equals(data.getApplyStatus()) || StringUtils.isBlank(data.getApplyStatus())) {//报告号申请未完成的项目
                        // 如果找到还未发起的报告，则将该记录的ID添加到集合中
                        if (ObjectUtil.isNotEmpty(record)) {
                            projectIdsWithPendingReports.add(record.getId());
                        }
                    } else if ("0".equals(data.getIsCompleteInvoice())) {
                        projectIdsWithPendingReports.add(record.getId());
                    }

                }
            } else {
                projectIdsWithPendingReports.add(record.getId());
            }
        }
        list.getRecords().removeIf(record -> recordsToRemove.contains(record.getId()));
        // 根据集合中的ID来过滤出需要保留的records
        for (CwProjectRecordsDTO record : list.getRecords()) {
            if (projectIdsWithPendingReports.contains(record.getId())) {
                recordsToKeep.add(record);
            }
        }
        // 替换原列表的内容
        list.setRecords(recordsToKeep);
        list.setTotal(recordsToKeep.size());
        return list;
    }


    /**
     * 查询项目数据集合,和上面findList是一样的，目的是跳过findList接口的数据规则（比如仅部门可见、仅自己可见之类的）
     */
    public IPage<CwProjectRecordsDTO> findList2(Page<CwProjectRecordsDTO> page, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        QueryWrapper<CwProjectRecords> queryWrapper = QueryWrapperGenerator.buildQueryCondition(CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO), CwProjectRecords.class);
        queryWrapper.eq("a.del_flag", "0");
//        queryWrapper.orderByDesc("a.create_date");
        if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO)) {
            if (ArrayUtil.isNotEmpty(cwProjectRecordsDTO.getCreateDates())) {
                queryWrapper.between("a.create_time", cwProjectRecordsDTO.getCreateDates()[0], cwProjectRecordsDTO.getCreateDates()[1]);
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterName())) {
                List<User> userList = SpringUtil.getBean(IUserApi.class).selectListByName(cwProjectRecordsDTO.getProjectMasterName());
                List<String> ids = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(ids)) {
                    queryWrapper.in("a.project_master_id", ids);
                } else {
                    return new Page<>();
                }
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getRealHeaderName())) {
                List<User> userList = SpringUtil.getBean(IUserApi.class).selectListByName(cwProjectRecordsDTO.getRealHeaderName());
                List<String> ids = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(ids)) {
                    queryWrapper.in("a.real_header", ids);
                } else {
                    return new Page<>();
                }
            }
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getCreateId())) {
                queryWrapper.eq("a.create_by_id", cwProjectRecordsDTO.getCreateId());
            }
        }

        IPage<CwProjectRecordsDTO> list = cwProjectRecordsMapper.findList2(page, queryWrapper);
        return list;
    }

    /**
     * 根据id查询项目详情
     *
     * @param id
     * @return
     */
    public CwProjectRecordsDTO queryById(String id) {
        CwProjectRecordsDTO cwProjectRecordsDTO = cwProjectRecordsMapper.queryById(id);
        if (null != cwProjectRecordsDTO && null != cwProjectRecordsDTO.getCwProjectClientContactDTOList() && cwProjectRecordsDTO.getCwProjectClientContactDTOList().size() > 0) {
            for (CwProjectClientContactDTO clientContact : cwProjectRecordsDTO.getCwProjectClientContactDTOList()) {
                //判断项目联系人是否是从客户联系人中选择出来的
                if (StringUtils.isNotBlank(clientContact.getClientContactId())) {
                    CwWorkClientContact clientContactInfo = cwWorkClientContactService.getInfoById(clientContact.getClientContactId());
                    //若数据存在则将查询出来的数据信息进行替换
                    if (null != clientContactInfo && StringUtils.isNotBlank(clientContactInfo.getId())) {
                        clientContact.setName(clientContactInfo.getName());
                        clientContact.setSex(clientContactInfo.getSex());
                        clientContact.setOfficeId(clientContactInfo.getOfficeId());
                        clientContact.setPosition(clientContactInfo.getPosition());
                        clientContact.setContactFirst(clientContactInfo.getContactFirst());
                        clientContact.setContactSecond(clientContactInfo.getContactSecond());
                        clientContact.setRemarks(clientContactInfo.getRemarks());
                        clientContact.setFax(clientContactInfo.getFax());
                        clientContact.setEmail(clientContactInfo.getEmail());
                    }
                }
            }
        }
        if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO)) {
            if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO.getPlanStartDate()) && ObjectUtil.isNotEmpty(cwProjectRecordsDTO.getPlanEndDate())) {
                Date[] planDate = new Date[2];
                planDate[0] = cwProjectRecordsDTO.getPlanStartDate();
                planDate[1] = cwProjectRecordsDTO.getPlanEndDate();
                cwProjectRecordsDTO.setPlanDate(planDate);
            }
        }
        return cwProjectRecordsDTO;
    }

    /**
     * 保存项目以及其他相关信息
     *
     * @param cwProjectRecordsDTO
     * @return
     * @throws Exception
     */
    public String saveForm(CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (StringUtils.isBlank(cwProjectRecordsDTO.getId())) {
//            UserDTO userDTO = UserUtils.getCurrentUserDTO();
            //项目编号生成
            String serialNum = SpringUtil.getBean(IWorkAttachmentApi.class).genSerialNum(userDTO.getCompanyDTO().getId(), CwProjectRecordsDTO.BIZ_CODE, TokenProvider.getCurrentToken());
//            String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), CwProjectRecordsDTO.BIZ_CODE);
            cwProjectRecordsDTO.setProjectNumber(serialNum);
            //cwProjectRecordsDTO.setStatus("5");
        } else {
            //把原项目关联的客户联系人从客户表删除
            CwProjectRecords project = this.getById(cwProjectRecordsDTO.getId());
            if (ObjectUtil.isNotEmpty(project)) {
                if (StringUtils.isNotBlank(project.getContractId())) {
                    ContractInfo contractInfo = contractInfoMapper.selectById(project.getContractId());
                    if (ObjectUtil.isNotEmpty(contractInfo)) {
                        if (StringUtils.isNotBlank(contractInfo.getClientContacts())) {
                            // 删除客户的联系人表中与此项目关联的联系人
                            cwWorkClientContactService.remove(new QueryWrapper<CwWorkClientContact>().lambda()
                                    .eq(CwWorkClientContact::getClientId, contractInfo.getClientContacts())
                                    .eq(CwWorkClientContact::getProjectId, cwProjectRecordsDTO.getId())
                            );
                        }
                    }
                }
            }
        }
        //如果报备类型不为10（专项审计业务），则项目分类数据清除
        if (!"10".equals(cwProjectRecordsDTO.getReportType())) {
            cwProjectRecordsDTO.setProjectClassification("");
        }
        CwProjectRecords cwProjectRecords = CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO);
        if (ObjectUtil.isNotEmpty(cwProjectRecords)) {
            if (StringUtils.isBlank(cwProjectRecords.getCreateById())) {
                cwProjectRecords.setCreateById(userDTO.getId());
            }
        }
        this.saveOrUpdate(cwProjectRecords);
        if (ObjectUtil.isNotEmpty(cwProjectRecordsDTO)) {
            // 附件
//            ossService.saveOrUpdateFileList(cwProjectRecordsDTO.getWorkAttachmentDtoList(),cwProjectRecords.getId(),"cw_project_records");

            Map<String, String> map = new HashMap<>();
            String fileList = JSON.toJSONString((cwProjectRecordsDTO.getWorkAttachmentDtoList()));
            String attachmentId = cwProjectRecords.getId();
            String attachmentFlag = "cw_project_records";
            map.put("fileList", fileList);
            map.put("attachmentId", attachmentId);
            map.put("attachmentFlag", attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken());
            SpringUtil.getBean(IWorkAttachmentApi.class).saveOrUpdateFileList(map);

            // 被服务单位
            //根据项目id删除原有的被服务单位数据信息
            cwProjectRecordsMapper.deleteProjectClientInfoByProjectId(cwProjectRecords.getId());

            if (null != cwProjectRecordsDTO.getCwProjectClientInfoDTOList() && cwProjectRecordsDTO.getCwProjectClientInfoDTOList().size() > 0) {
                //根据项目id添加新的被服务单位信息
                List<CwWorkClientBaseDTO> cwWorkClientBaseDTOList = cwProjectRecordsDTO.getCwProjectClientInfoDTOList();
                List<CwProjectClientInfoDTO> cwProjectClientInfoDTOList = new ArrayList<>();
                for (CwWorkClientBaseDTO c : cwWorkClientBaseDTOList) {
                    CwProjectClientInfoDTO cwProjectClientInfoDTO = new CwProjectClientInfoDTO();
                    cwProjectClientInfoDTO.setProjectId(cwProjectRecords.getId());
                    cwProjectClientInfoDTO.setClientId(c.getId());
                    cwProjectClientInfoDTOList.add(cwProjectClientInfoDTO);
                }
                //对数据进行批量插入
                cwProjectRecordsMapper.insertProjectClientInfoList(cwProjectClientInfoDTOList);
            }

            // 客户联系人
            if (CollectionUtil.isNotEmpty(cwProjectRecordsDTO.getCwProjectClientContactDTOList())) {
                if (CollectionUtil.isNotEmpty(cwProjectRecordsDTO.getCwProjectClientContactDTOList())) {
                    // 1. 查看数据是否有合同信息，
                    // 如果有合同信息,有委托人，则把所有的联系人client_id替换为合同的委托人id
                    // 如果有合同信息,但是没有委托人，则把所有的联系人client_id置空""
                    // 如果有合同信息id,但是并没有通过合同信息id查询到数据，则把所有的联系人client_id置空""
                    // 如果没有合同信息,则把所有的联系人client_id置空""
                    if (StringUtils.isNotBlank(cwProjectRecords.getContractId())) {
                        ContractInfo contractInfo = contractInfoMapper.selectById(cwProjectRecords.getContractId());
                        if (ObjectUtil.isNotEmpty(contractInfo)) {
                            if (StringUtils.isNotBlank(contractInfo.getClientContacts())) {
                                cwProjectRecordsDTO.getCwProjectClientContactDTOList().stream().forEach(item -> {
                                    //改成如果是选择的联系人，前端会一并带来clientId，如果是手填的，后端就会判断填入clientId
                                    if(StringUtils.isBlank(item.getClientId())){
                                            item.setClientId(contractInfo.getClientContacts());
                                    }
                                });
                            } else {
                                cwProjectRecordsDTO.getCwProjectClientContactDTOList().stream().forEach(item -> {
                                    item.setClientId("");
                                });
                            }
                        } else {
                            cwProjectRecordsDTO.getCwProjectClientContactDTOList().stream().forEach(item -> {
                                item.setClientId("");
                            });
                        }
                    } else {
                        cwProjectRecordsDTO.getCwProjectClientContactDTOList().stream().forEach(item -> {
                            item.setClientId("");
                        });
                    }
                    // 2. 联系人的添加或修改
                    List<String> liveIds = cwProjectRecordsDTO.getCwProjectClientContactDTOList().stream().filter(item -> {
                        if (StringUtils.isNotBlank(item.getId())) {
                            return true;
                        }
                        return false;
                    }).map(CwProjectClientContactDTO::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(liveIds)) {
                        cwProjectClientContactMapper.delete(new QueryWrapper<CwProjectClientContact>().lambda().notIn(CwProjectClientContact::getId, liveIds).eq(CwProjectClientContact::getProjectId, cwProjectRecords.getId()));
                    } else {
                        cwProjectClientContactMapper.delete(new QueryWrapper<CwProjectClientContact>().lambda().eq(CwProjectClientContact::getProjectId, cwProjectRecords.getId()));
                    }
                    List<CwProjectClientContact> updateBatchById = new ArrayList<>();
                    List<CwProjectClientContact> insertBatchById = new ArrayList<>();
                    List<CwWorkClientContact> saveBatchClient = new ArrayList<>();
                    cwProjectRecordsDTO.getCwProjectClientContactDTOList().stream().forEach(item -> {

                        //遍历查询是否在客户联系人中存在
                        CwWorkClientContact infoByData = cwWorkClientContactService.getInfoByData(item);
                        if (null != infoByData && StringUtils.isNotBlank(infoByData.getId())) {
                            item.setClientContactId(infoByData.getId());
                        } else {
                            CwWorkClientContact cwWorkClientContact = new CwWorkClientContact();
                            BeanUtil.copyProperties(item, cwWorkClientContact);
                            cwWorkClientContact.setId(UUID.randomUUID().toString().replace("-", ""));
                            cwWorkClientContact.setCreateById(userDTO.getId());
                            cwWorkClientContact.setCreateTime(new Date());
                            cwWorkClientContact.setUpdateById(userDTO.getId());
                            cwWorkClientContact.setUpdateTime(new Date());
                            cwWorkClientContactService.save(cwWorkClientContact);
                            item.setClientContactId(cwWorkClientContact.getId());
                        }

                        item.setProjectId(cwProjectRecords.getId());
                        if (StringUtils.isNotBlank(item.getId())) {
                            // 有id进行修改操作
                            updateBatchById.add(CwProjectClientContactWrapper.INSTANCE.toEntity(item));
                        } else {
                            // 无id进行新增操作
                            insertBatchById.add(CwProjectClientContactWrapper.INSTANCE.toEntity(item));
                        }
                        CwWorkClientContact cwWorkClientContact = new CwWorkClientContact();
                        BeanUtil.copyProperties(item, cwWorkClientContact);
                        cwWorkClientContact.setProjectId(cwProjectRecords.getId());
                        cwWorkClientContact.setId("");
                        saveBatchClient.add(cwWorkClientContact);
                    });
                    // 批量根据id修改数据
                    if (CollectionUtil.isNotEmpty(updateBatchById)) {
                        cwProjectClientContactService.updateBatchById(updateBatchById);
                    }
                    // 批量新增数据
                    if (CollectionUtil.isNotEmpty(insertBatchById)) {

                        cwProjectClientContactService.saveBatch(insertBatchById);
                    }
                    // 将数据添加到客户的联系人表中
                    /*if (CollectionUtil.isNotEmpty(saveBatchClient)){
                        for (CwWorkClientContact info : saveBatchClient) {
                            if(StringUtils.isBlank(info.getClientContactId())){
                                cwWorkClientContactService.save(info);
                            }
                        }
                        //cwWorkClientContactService.saveBatch(saveBatchClient);
                    }*/
                } else {
                    cwProjectClientContactMapper.delete(new QueryWrapper<CwProjectClientContact>().lambda().eq(CwProjectClientContact::getProjectId, cwProjectRecords.getId()));
                }
            }
            // 项目保存的时候，将主要成员添加到项目组成员中
            // 先删除当前项目的主要成员
            cwProjectMembersService.remove(new LambdaQueryWrapper<CwProjectMembers>().eq(CwProjectMembers::getProjectId, cwProjectRecords.getId()).eq(CwProjectMembers::getIsImportant, "1"));
            List<String> mlist = new ArrayList<>();
            // 项目经理1
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectMasterId())) {
                mlist.add(cwProjectRecordsDTO.getProjectMasterId());
            }
            // 项目经理2
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getRealHeader())) {
                mlist.add(cwProjectRecordsDTO.getRealHeader());
            }
            // 现场负责人
            if (StringUtils.isNotBlank(cwProjectRecordsDTO.getProjectLeaderId())) {
                mlist.add(cwProjectRecordsDTO.getProjectLeaderId());
            }
            // 项目发起人
            if (StringUtils.isNotBlank(cwProjectRecords.getCreateById())) {
                mlist.add(cwProjectRecords.getCreateById());
            }
            // 项目实际负责人
            if (StringUtils.isNotBlank(cwProjectRecords.getProjectExecutor())) {
                mlist.add(cwProjectRecords.getProjectExecutor());
            }
            if (CollectionUtil.isNotEmpty(mlist)) {
                List<CwProjectMembers> haveList = cwProjectMembersService.list(new LambdaQueryWrapper<CwProjectMembers>().eq(CwProjectMembers::getProjectId, cwProjectRecords.getId()));
                // 将已有的成员（不是主要成员），剔除掉，不重复新增
                Iterator<String> it = mlist.iterator();
                while (it.hasNext()) {
                    String x = it.next();
                    haveList.stream().forEach(have -> {
                        if (x.equals(have.getUserId())) {
                            it.remove();
                        }
                    });
                }
                // 新增主要成员
                List<CwProjectMembers> members = new ArrayList<>();
                List<String> collect = mlist.stream().distinct().collect(Collectors.toList());
                collect.stream().forEach(item -> {
                    CwProjectMembers cwProjectMembers = new CwProjectMembers();
                    cwProjectMembers.setIsImportant("1");
                    cwProjectMembers.setProjectId(cwProjectRecords.getId());
                    cwProjectMembers.setUserId(item);
                    cwProjectMembers.setStatus("0");
                    members.add(cwProjectMembers);
                });
                cwProjectMembersService.saveBatch(members);
            }
        }
        return cwProjectRecords.getId();
    }

    /**
     * 保存项目信息
     *
     * @param cwProjectRecordsDTO
     * @return
     * @throws Exception
     */
    public ResponseEntity save(CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        this.saveForm(cwProjectRecordsDTO);
        return ResponseEntity.ok("保存成功");
    }

    /**
     * 根据id删除项目信息
     *
     * @param ids
     * @return
     */
    public ResponseEntity deleteByIds(String ids) {
        // 查询项目是否被引用（报告、报销、发票）
        List<String> idArray = Arrays.asList(ids.split(","));
        List<String> useProjects = new ArrayList<>();
        // 查询项目是否被引用（报告）
        List<String> useByReport = cwProjectRecordsMapper.isUseByReport(idArray);
        if (CollectionUtil.isNotEmpty(useByReport)) {
            useByReport.stream().forEach(item -> {
                useProjects.add(item);
            });
        }
        // 查询项目是否被引用（报销）
        List<String> useByReim = cwProjectRecordsMapper.isUseByReim(idArray);
        if (CollectionUtil.isNotEmpty(useByReim)) {
            useByReim.stream().forEach(item -> {
                useProjects.add(item);
            });
        }
        // 查询项目是否被引用（发票）
        List<String> useByFinance = cwProjectRecordsMapper.isUseByFinance(idArray);
        if (CollectionUtil.isNotEmpty(useByFinance)) {
            useByFinance.stream().forEach(item -> {
                useProjects.add(item);
            });
        }
        if (CollectionUtil.isNotEmpty(useProjects)) {
            List<String> collect = useProjects.stream().distinct().filter(item -> {
                if (StringUtils.isNotBlank(item)) {
                    return true;
                }
                return false;
            }).collect(Collectors.toList());
            String join = StringUtils.join(collect, ",");
            return ResponseEntity.ok("项目: " + join + " 被引用，不可删除");
        }
        this.removeByIds(Lists.newArrayList(idArray));
        return ResponseEntity.ok("删除成功");
    }

    /**
     * 修改状态
     *
     * @param cwProjectRecordsDTO
     * @return
     */
    public String updateStatusById(CwProjectRecordsDTO cwProjectRecordsDTO) {
        CwProjectRecords cwProjectRecords = CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO);
        cwProjectRecordsMapper.update(cwProjectRecords, new QueryWrapper<CwProjectRecords>().lambda().eq(CwProjectRecords::getId, cwProjectRecords.getId()));
        return "操作成功";
    }

    /**
     * 根据客户id获取关联的项目信息
     *
     * @param clientId
     * @return
     */
    public List<CwProjectRecordsDTO> getByClientId(String clientId, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        if (StringUtils.isNotBlank(clientId)) {
            List<String> projectIdByClientId = cwProjectRecordsMapper.getProjectIdByClientId(clientId);
            List<String> projectList = projectIdByClientId.stream().distinct().collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(projectList)) {
                QueryWrapper<CwProjectRecords> queryWrapper = QueryWrapperGenerator.buildQueryCondition(CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO), CwProjectRecords.class);
                queryWrapper.in("a.id", projectList);
                queryWrapper.eq("a.del_flag", "0");
                queryWrapper.eq("a.status", "5");
                queryWrapper.orderByDesc("a.create_time");
                return cwProjectRecordsMapper.getProjectByIdList(queryWrapper);
            } else {
                return new ArrayList<>();
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 根据客户id获取关联的项目信息
     *
     * @param ids
     * @return
     */
    public List<CwProjectRecords> getListByIds(List ids) {
        return cwProjectRecordsMapper.getListByIds(ids);
    }

    /**
     * 根据合同id获取关联的项目信息
     *
     * @param contractId
     * @return
     */
    public List<CwProjectRecordsDTO> getByContractId(String contractId, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        if (StringUtils.isNotBlank(contractId)) {
            QueryWrapper<CwProjectRecords> queryWrapper = QueryWrapperGenerator.buildQueryCondition(CwProjectRecordsWrapper.INSTANCE.toEntity(cwProjectRecordsDTO), CwProjectRecords.class);
            queryWrapper.eq("a.contract_id", contractId);
            queryWrapper.eq("a.del_flag", "0");
            queryWrapper.eq("a.status", "5");
            queryWrapper.orderByDesc("a.create_time");
            return cwProjectRecordsMapper.getByContractId(queryWrapper);
        }
        return new ArrayList<>();
    }

    /**
     * 根据项目id修改项目组成员信息
     * 注：项目id必须不为空
     *
     * @param cwProjectRecordsDTO
     * @return
     */
    public ResponseEntity updateMembers(CwProjectRecordsDTO cwProjectRecordsDTO) {
        if (CollectionUtil.isNotEmpty(cwProjectRecordsDTO.getCwProjectMembersDTOList())) {
            List<String> liveIds = cwProjectRecordsDTO.getCwProjectMembersDTOList().stream().filter(item -> {
                if (StringUtils.isNotBlank(item.getId())) {
                    return true;
                }
                return false;
            }).map(CwProjectMembersDTO::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(liveIds)) {
                cwProjectMembersService.remove(new QueryWrapper<CwProjectMembers>().lambda()
                        .eq(CwProjectMembers::getProjectId, cwProjectRecordsDTO.getId())
                        .notIn(CwProjectMembers::getId, liveIds));

            } else {
                cwProjectMembersService.remove(new QueryWrapper<CwProjectMembers>().lambda().eq(CwProjectMembers::getProjectId, cwProjectRecordsDTO.getId()));
            }
            List<CwProjectMembers> updateBatchById = new ArrayList<>();
            List<CwProjectMembers> insertBatchById = new ArrayList<>();
            cwProjectRecordsDTO.getCwProjectMembersDTOList().stream().forEach(item -> {
                item.setProjectId(cwProjectRecordsDTO.getId());
                if (StringUtils.isNotBlank(item.getId())) {
                    // 有id进行修改操作
                    updateBatchById.add(CwProjectMembersWrapper.INSTANCE.toEntity(item));
                } else {
                    // 无id进行新增操作
                    insertBatchById.add(CwProjectMembersWrapper.INSTANCE.toEntity(item));
                }
            });
            // 批量根据id修改数据
            if (CollectionUtil.isNotEmpty(updateBatchById)) {
                cwProjectMembersService.updateBatchById(updateBatchById);
            }
            // 批量新增数据
            if (CollectionUtil.isNotEmpty(insertBatchById)) {
                cwProjectMembersService.saveBatch(insertBatchById);
            }
        } else {
            cwProjectMembersService.remove(new QueryWrapper<CwProjectMembers>().lambda().eq(CwProjectMembers::getProjectId, cwProjectRecordsDTO.getId()));
        }
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 查询当前登录人创建的项目以及所属项目组的项目
     *
     * @return
     */
    public ResponseEntity<List<String>> getHaveProjectIds() {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        return ResponseEntity.ok(cwProjectRecordsMapper.getHaveProjectIds(userDTO));
    }

    /**
     * 查询当前登录人创建的项目以及所属项目组的项目
     *
     * @return
     */
    public ResponseEntity<List<String>> getUserWhereIsCpaById() {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        return ResponseEntity.ok(cwProjectRecordsMapper.getUserWhereIsCpaById(userDTO));
    }


    public List<CwProjectRecordsDTO> getReportById(String id, CwProjectRecordsDTO cwProjectRecordsDTO) throws Exception {
        List<CwProjectRecordsDTO> reportById = cwProjectRecordsMapper.getReportById(id, cwProjectRecordsDTO);
        return reportById;


    }

    public List<CwProjectRecordsDTO> getReportByProjectId(String id, String projectId) {
        List<CwProjectRecordsDTO> projectList = cwProjectRecordsMapper.getReportByProjectId(id, projectId);
        return projectList;
    }

    /**
     * 查询所有的项目组成员id
     *
     * @param id
     * @return
     */
    public List<String> getMembersId(String id) {
        return cwProjectRecordsMapper.getMembersId(id);
    }

    /**
     * 添加项目组成员信息
     *
     * @param projectId
     * @param membersId
     */
    public void addMembers(String projectId, String membersId, String userId) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(userId);

        CwProjectMembers members = new CwProjectMembers();
        members.setCreateById(userDTO.getId());
        members.setCreateTime(new Date());
        members.setUpdateById(userDTO.getId());
        members.setUpdateTime(new Date());
        members.setUserId(membersId);
        members.setProjectId(projectId);
        members.setStatus("0");
        members.setIsImportant("1");

        cwProjectMembersService.save(members);
    }

    /**
     * 根据用户id查询所有的项目信息
     *
     * @return
     */
    public List<String> findAllList(String id) {
        return cwProjectRecordsMapper.findAllList(id);
    }

    /**
     * 查询项目下是否存在已开票信息
     *
     * @param id
     * @return
     */
    public CwProjectRecordsDTO getInvoiceTotal(String id) {
        CwProjectRecordsDTO cwProjectRecordsDTO = cwProjectRecordsMapper.getInvoiceTotal(id);
        return cwProjectRecordsDTO;
    }

    /**
     * 查询预开票项目下的报告是否已关联完成
     *
     * @return
     */
    public List<CwProjectRecordsDTO> getCompleteCollection() {
        List<CwProjectRecordsDTO> list = cwProjectRecordsMapper.getCompleteCollection();
        List<CwProjectRecordsDTO> recordsToKeep = new ArrayList<>();
        Set<String> projectIdsWithPendingReports = new HashSet<>();

        for (CwProjectRecordsDTO record : list) {
            List<CwProjectReportData> reportData = cwProjectReportMapper.getByProjectId(record.getId());
            if (CollectionUtils.isNotEmpty(reportData)) {
                for (CwProjectReportData reportDatum : reportData) {
                    if (!"5".equals(reportDatum.getStatus())) {
                        // 如果找到一个状态不是 "5" 的报告，则将该记录的ID添加到集合中
                        projectIdsWithPendingReports.add(record.getId());
                        break; // 不需要继续检查其他报告
                    }
                }
            } else {
                projectIdsWithPendingReports.add(record.getId());
            }
        }
        // 根据集合中的ID来过滤出需要保留的records
        for (CwProjectRecordsDTO record : list) {
            if (projectIdsWithPendingReports.contains(record.getId())) {
                recordsToKeep.add(record);
            }
        }
        return recordsToKeep;
    }


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

    /**
     * 导入发票数据
     *
     * @param list
     * @return
     */
    public String importProjectRecords(List<CwProjectRecordsImportDTO> list)  {
        try {
            //获取当前登录人信息
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            if (null == userDTO || StringUtils.isBlank(userDTO.getId())) {
                return "登录信息已失效，请重新登录后再进行导入信息";
            }
            if (null == list || list.size() == 0) {
                return "导入的数据为空，请确认后重新导入";
            }

            //数据校验
            Set<String> projectNames = new HashSet<>();
            for (CwProjectRecordsImportDTO item : list) {
                String message = projectValidation(item);
                if(StringUtils.isNotBlank(message)){
                    return "项目名为："+ item.getProjectName()+"的数据存在以下问题："+message+",请修正后重新导入";
                }
                if (!projectNames.add(item.getProjectName())) {
                    return "导入数据中项目名称重复，请修正后重新导入";
                }
            }
            //根据合同名称进行去重，并根据去重后的合同名称进行查询，若查询出来的数据量小于去重后的合同量，则表示有合同没有进行录入，则不进行导入
            LinkedHashSet contractNameSet = new LinkedHashSet();
            for (CwProjectRecordsImportDTO cwProjectRecordsImportDTO : list) {
                contractNameSet.add(cwProjectRecordsImportDTO.getContractName());
            }
            List contractNameList = Lists.newArrayList(contractNameSet);

            List<ContractInfo> contractInfoList = Lists.newArrayList();
            //根据contractList进行查询合同信息
            //分批处理
            if (contractNameList != null && !contractNameList.isEmpty()) {
                int pointsDataLimit = 10; // 限制每批查询条数
                int size = contractNameList.size();
                int part = (size + pointsDataLimit - 1) / pointsDataLimit; // 计算需要分多少批

                for (int i = 0; i < part; i++) {
                    int fromIndex = i * pointsDataLimit;
                    int toIndex = Math.min(fromIndex + pointsDataLimit, size);
                    List<String> subContractNameList = contractNameList.subList(fromIndex, toIndex);

                    // 查询
                    List<ContractInfo> contractList = contractInfoService.getByContractNameList(subContractNameList, userDTO.getId());
                    contractInfoList.addAll(contractList);
                }
            } else {
                return "导入数据中的合同名称不存在，请修正后重新导入";
            }
            //对比查询出来的合同信息，如果查询出来的合同信息比去重后的合同信息少，则表示合同信息存在没有录入系统的情况，则直接抛出
            if (contractInfoList.size() != contractNameList.size()) {
                return "导入数据中的合同名称存在未录入系统或填写错误的情况，请修正后重新导入";
            }
            List<CwProjectRecordsDTO> cwProjectRecordsDTOS =  new ArrayList<>();
            //根据合同信息查询对应的客户联系人数据
            for(ContractInfo contractInfo :contractInfoList){
                CwProjectRecordsDTO cwProjectRecordsDTO = new CwProjectRecordsDTO();
                List<CwProjectClientContactDTO> contractClientListByName = cwWorkClientBaseMapper.getContractClientListByName(contractInfo.getContractName());
                cwProjectRecordsDTO.setContractName(contractInfo.getContractName());
                cwProjectRecordsDTO.setCwProjectClientContactDTOList(contractClientListByName);
                cwProjectRecordsDTOS.add(cwProjectRecordsDTO);
            }

            //根据项目名称进行去重，若去重后的数量小于原数据量，则表示项目名称有重复，则不进行导入
            LinkedHashSet projectNameSet = new LinkedHashSet();
            for (CwProjectRecordsImportDTO cwProjectRecordsImportDTO : list) {
                projectNameSet.add(cwProjectRecordsImportDTO.getProjectName());
            }
            List projectNameList = Lists.newArrayList(projectNameSet);

            List<CwProjectRecordsDTO> projectInfoList = Lists.newArrayList();
            //根据contractList进行查询合同信息
            //分批处理
            if (projectNameList != null && !projectNameList.isEmpty()) {
                int pointsDataLimit = 10; // 每批查询的数量
                int size = projectNameList.size();
                int part = (size + pointsDataLimit - 1) / pointsDataLimit; // 计算需要分多少批

                for (int i = 0; i < part; i++) {
                    int fromIndex = i * pointsDataLimit;
                    int toIndex = Math.min(fromIndex + pointsDataLimit, size);
                    List<String> subProjectNameList = projectNameList.subList(fromIndex, toIndex);

                    // 查询数据
                    List<CwProjectRecordsDTO> contractList = cwProjectRecordsMapper.getByProjectNameList(subProjectNameList, userDTO.getId());
                    projectInfoList.addAll(contractList);
                }
            }else {
                return "导入数据中的项目名称不存在，请修正后重新导入";
            }
            
            //对比查询出来的合同信息，如果查询出来的合同信息比去重后的合同信息少，则表示合同信息存在没有录入系统的情况，则直接抛出
            if (projectInfoList.size() > 0) {
                List<String> repeatedProjectNameList = Lists.newArrayList();
                for (CwProjectRecordsDTO cwProjectRecordsDTO : projectInfoList) {
                    repeatedProjectNameList.add(cwProjectRecordsDTO.getProjectName());
                }
                String repeatedProjectNameStr = String.join(",", repeatedProjectNameList);
                return "导入数据中的项目名称为: " + repeatedProjectNameStr + "  已存在，请修正后重新导入";
            }

            //查询风险等级字典
            JSONObject riskLevelDatas = JSONUtil.parseObj(SpringUtil.getBean(IDictApi.class).getDictValueListMapByDict("cw_project_risk_level"));

            //查询有无报告字典
            JSONObject isHaveReportDatas = JSONUtil.parseObj(SpringUtil.getBean(IDictApi.class).getDictValueListMapByDict("is_have_report"));

            //查询报备类型字典
            JSONObject reportTypeDatas = JSONUtil.parseObj(SpringUtil.getBean(IDictApi.class).getDictValueListMapByDict("cw_work_client_report_type"));

            for (CwProjectRecordsImportDTO cwProjectRecordsImportDTO : list) {

                CwProjectRecordsDTO cwProjectRecordsDTO = new CwProjectRecordsDTO();
                //对比风险等级的key
                String riskLevel = riskLevelDatas.getStr(cwProjectRecordsImportDTO.getRiskLevel());
                //对比有无报告的key
                String isHaveReport = isHaveReportDatas.getStr(cwProjectRecordsImportDTO.getIsHaveReport());
                //对比报备类型的key
                String reportType = reportTypeDatas.getStr(cwProjectRecordsImportDTO.getReportType());
                //现场负责人若没填写，则默认为上传人
                if (StringUtils.isBlank(cwProjectRecordsImportDTO.getProjectLeaderId())) {
                    cwProjectRecordsDTO.setProjectLeaderId(userDTO.getId());
                } else {
                    String userId = SpringUtil.getBean(IUserApi.class).getUserIdByName(cwProjectRecordsImportDTO.getProjectLeaderId());
                    if (StringUtils.isNotBlank(userId)) {
                        cwProjectRecordsDTO.setProjectLeaderId(userId);
                    } else {
                        return "导入数据中的现场负责人，系统中不存在，请修正后重新导入";
                    }
                }
                //项目经理1 和项目经理2 至少填写一个，且必须有效，否则不进行导入
                String projectManagerOne = cwProjectRecordsImportDTO.getProjectMasterId();
                String projectManagerTwo = cwProjectRecordsImportDTO.getRealHeader();

                IAssessApi iAssessApi = SpringUtil.getBean(IAssessApi.class);
                // 查询用户 ID
                if (StringUtils.isNotBlank(projectManagerOne)) {
                    String userId = iAssessApi.getUserBySignatureScribe(projectManagerOne, userDTO.getId());
                    if(StringUtils.isBlank(userId)){
                        return "确保导入数据中的项目经理1和项目经理2填写正确，请修正后重新导入";
                    }
                    projectManagerOne = userId;
                }
                if (StringUtils.isNotBlank(projectManagerTwo)) {
                    String userId = iAssessApi.getUserBySignatureScribe(projectManagerTwo, userDTO.getId());
                    if(StringUtils.isBlank(userId)){
                        return "确保导入数据中的项目经理1和项目经理2填写正确，请修正后重新导入";
                    }
                    projectManagerTwo = userId;

                }
                if (StringUtils.isAllBlank(projectManagerOne, projectManagerTwo)) {
                    return "导入数据中的项目经理1和项目经理2，至少填写一个，请修正后重新导入";
                }
                //根据客户联系人-姓名和部门、手机号和合同信息进行查询并嵌入
                //设置基本信息
                cwProjectRecordsDTO.setRiskLevel(riskLevel);
                cwProjectRecordsDTO.setIsHaveReport(isHaveReport);
                cwProjectRecordsDTO.setReportType(reportType);
                cwProjectRecordsDTO.setProjectMasterId(projectManagerOne);
                cwProjectRecordsDTO.setRealHeader(projectManagerTwo);
                cwProjectRecordsDTO.setContractName(cwProjectRecordsImportDTO.getContractName());
                cwProjectRecordsDTO.setAuditYear(cwProjectRecordsImportDTO.getAuditYear());
                //根据合同名称找到合同id
                ContractInfo foundContract = contractInfoList.stream()
                        .filter(contractInfo -> cwProjectRecordsImportDTO.getContractName().equals(contractInfo.getContractName()))
                        .findFirst()
                        .orElse(null);  // 如果找不到返回 null
                if(foundContract == null){
                    return "导入数据中的对应的合同未找到，请修正后重新导入";
                }
                //设置合同id和合同份数
                cwProjectRecordsDTO.setContractId(foundContract.getId());
                cwProjectRecordsDTO.setContractNum(foundContract.getContractNum());
                //查询被服务单位信息
                List<CwWorkClientBaseDTO> contractClient = cwWorkClientBaseMapper.getContractClient(cwProjectRecordsImportDTO.getContractName());
                cwProjectRecordsDTO.setCwProjectClientInfoDTOList(contractClient);
                //根据合同名称找到之前查询的客户联系人
                Optional<CwProjectRecordsDTO> contractResult = cwProjectRecordsDTOS.stream()
                        .filter(dto -> cwProjectRecordsImportDTO.getContractName().equals(dto.getContractName()))
                        .findFirst();
                List<CwProjectClientContactDTO> cwProjectClientContactList = new ArrayList<>();
                CwProjectClientContactDTO cwProjectClientContactDTO = new CwProjectClientContactDTO();
                if (!contractResult.isPresent()) {
                    return "导入数据中的合同对应被服务单位未找到，请修正后重新导入";
                }else{
                    CwProjectRecordsDTO cwCurrentContract = contractResult.get();
                    //通过excel中的姓名，职位，手机号找到对应的联系人
                    //List<CwProjectClientContactDTO> cwProjectClientContactDTOList = cwCurrentContract.getCwProjectClientContactDTOList();
                    //Optional<CwProjectClientContactDTO> result = cwProjectClientContactDTOList.stream()
                    //        .filter(dto -> cwProjectRecordsImportDTO.getCwProjectClientName().equals(dto.getName()) &&
                    //                cwProjectRecordsImportDTO.getCwProjectClientPhone().equals(dto.getContactFirst()) &&
                    //                cwProjectRecordsImportDTO.getCwProjectClientOffice().equals(dto.getOfficeId()))
                    //        .findFirst();
                    CwProjectClientContactDTO cwProjectClientContactDTO1 = new CwProjectClientContactDTO();
                    cwProjectClientContactDTO1.setContactFirst(cwProjectRecordsImportDTO.getCwProjectClientPhone());
                    cwProjectClientContactDTO1.setName(cwProjectRecordsImportDTO.getCwProjectClientName());
                    cwProjectClientContactDTO1.setOfficeId(cwProjectRecordsImportDTO.getCwProjectClientOffice());
                    CwWorkClientContact foundContactDTO = cwWorkClientContactService.getInfoByData(cwProjectClientContactDTO1);
                    if (foundContactDTO != null) {
                        //添加已存在的联系人数据
                        //通过id获取到对应联系人的详细数据，并添加到新对象中，在saveForm方法里会对联系人进行校验
                        //CwWorkClientContact contractInfo = cwWorkClientContactMapper.getInfoById(foundContactDTO.getId());
                        cwProjectClientContactDTO.setName(foundContactDTO.getName());
                        cwProjectClientContactDTO.setContactFirst(foundContactDTO.getContactFirst());
                        cwProjectClientContactDTO.setOfficeId(foundContactDTO.getOfficeId());
                        cwProjectClientContactDTO.setClientId(foundContactDTO.getClientId());
                        cwProjectClientContactDTO.setFax(foundContactDTO.getFax());
                        cwProjectClientContactDTO.setSex(foundContactDTO.getSex());
                        cwProjectClientContactDTO.setPosition(foundContactDTO.getPosition());
                        cwProjectClientContactDTO.setEmail(foundContactDTO.getEmail());
                        cwProjectClientContactDTO.setRemarks(foundContactDTO.getRemarks());
                        cwProjectClientContactDTO.setContactSecond(foundContactDTO.getContactSecond());
                    } else {
                        //如果联系人不存在，直接新增联系人数据
                        cwProjectClientContactDTO.setName(cwProjectRecordsImportDTO.getCwProjectClientName());
                        cwProjectClientContactDTO.setContactFirst(cwProjectRecordsImportDTO.getCwProjectClientPhone());
                        cwProjectClientContactDTO.setOfficeId(cwProjectRecordsImportDTO.getCwProjectClientOffice());
                    }
                }
                cwProjectClientContactList.add(cwProjectClientContactDTO);
                cwProjectRecordsDTO.setCwProjectClientContactDTOList(cwProjectClientContactList);
                //基本数据
                cwProjectRecordsDTO.setPlanStartDate(cwProjectRecordsImportDTO.getPlanStartDate());
                cwProjectRecordsDTO.setPlanEndDate(cwProjectRecordsImportDTO.getPlanEndDate());
                cwProjectRecordsDTO.setPayerSubject(foundContract.getPayerSubject());
                //处理项目规模，保留两位小数
                String projectMoneyStr = cwProjectRecordsImportDTO.getProjectMoney();
                if (StringUtils.isNotBlank(projectMoneyStr)) {
                    BigDecimal projectMoney = new BigDecimal(projectMoneyStr).setScale(2, RoundingMode.HALF_UP);
                    String formattedMoney = projectMoney.toPlainString();
                    cwProjectRecordsDTO.setProjectMoney(formattedMoney);
                }
                cwProjectRecordsDTO.setProjectName(cwProjectRecordsImportDTO.getProjectName());
                //保存
                saveForm(cwProjectRecordsDTO);
            }
        }catch (Exception e){
            //throw new RuntimeException(e);
            return "数据异常，请联系管理员";
        }
        return "";
    }

    public String projectValidation(CwProjectRecordsImportDTO cwProjectRecordsImportDTO) {
        StringBuilder errorMsg = new StringBuilder();

        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getContractName())) {
            errorMsg.append("合同名称不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getProjectName())) {
            errorMsg.append("项目名称不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getRiskLevel())) {
            errorMsg.append("风险等级不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getProjectMoney())) {
            errorMsg.append("项目规模不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getIsHaveReport())) {
            errorMsg.append("有无报告不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getReportType())) {
            errorMsg.append("报备类型不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getAuditYear())) {
            errorMsg.append("审计期间不能为空");
        }
        if (cwProjectRecordsImportDTO.getPlanStartDate() == null) {
            errorMsg.append("项目预计开始时间不能为空");
        }
        if (cwProjectRecordsImportDTO.getPlanEndDate() == null) {
            errorMsg.append("项目预计结束时间不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getCwProjectClientName())) {
            errorMsg.append("客户联系人姓名不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getCwProjectClientOffice())) {
            errorMsg.append("客户联系人部门不能为空");
        }
        if (StringUtils.isBlank(cwProjectRecordsImportDTO.getCwProjectClientPhone())) {
            errorMsg.append("客户联系人电话不能为空");
        }
        return errorMsg.length() > 0 ? errorMsg.toString() : "";
    }

}
