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 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.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.CwProjectClientContactDTO;
import com.jeeplus.finance.projectRecords.service.dto.CwProjectClientInfoDTO;
import com.jeeplus.finance.projectRecords.service.dto.CwProjectMembersDTO;
import com.jeeplus.finance.projectRecords.service.dto.CwProjectRecordsDTO;
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.workClientInfo.domain.CwWorkClientContact;
import com.jeeplus.finance.workClientInfo.service.CwWorkClientContactService;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBaseDTO;
import com.jeeplus.sys.domain.User;
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.util.*;
import java.util.stream.Collectors;

//import com.jeeplus.pubmodules.oss.service.OssService;
//import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
//import com.jeeplus.sys.mapper.UserMapper;

/**
 * 财务项目登记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;


    /**
     * 差选项目列表信息
     * @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());
            }
            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.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 (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;
    }
    /**
     * 查询项目数据集合,和上面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())
                            );
                        }
                    }
                }
            }
        }
        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->{
                                    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 (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) {
        // 查询项目是否被引用（报告、报销、发票）
        String idArray[] =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));
    }




    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) {
        List<CwProjectRecordsDTO> projectList=cwProjectRecordsMapper.getReportByProjectId(id);
        return projectList;
    }
}
