package com.jeeplus.finance.workClientInfo.service;

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.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.finance.invoice.util.FlowTaskUtil;
import com.jeeplus.finance.projectRecords.domain.CwProjectClientInfo;
import com.jeeplus.finance.projectRecords.mapper.CwProjectClientInfoMapper;
import com.jeeplus.finance.workClientInfo.domain.*;
import com.jeeplus.finance.workClientInfo.mapper.CwWorkClientBaseMapper;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBaseDTO;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBillingDTO;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientContactDTO;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientTempDTO;
import com.jeeplus.finance.workClientInfo.service.mapstruct.CwWorkClientBaseWrapper;
import com.jeeplus.finance.workClientInfo.service.mapstruct.CwWorkClientBillingWrapper;
import com.jeeplus.finance.workClientInfo.service.mapstruct.CwWorkClientContactWrapper;
import com.jeeplus.finance.workClientInfo.service.mapstruct.CwWorkClientTypeWrapper;
import com.jeeplus.flowable.feign.IFlowableApi;
//import com.jeeplus.pubmodules.oss.service.OssService;
//import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
//import com.jeeplus.sys.mapper.UserMapper;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Array;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class CwWorkClientService extends ServiceImpl<CwWorkClientBaseMapper, CwWorkClientBase> {

    @Resource
    private CwWorkClientBaseMapper cwWorkClientBaseMapper;
    @Resource
    private CwWorkClientBillingService cwWorkClientBillingService;
    @Resource
    private CwWorkClientContactService cwWorkClientContactService;
    @Resource
    private CwWorkClientTypeService cwWorkClientTypeService;
    @Resource
    private CwManageLevelTypeService cwManageLevelTypeService;
    @Resource
    private CwOrganizationTypeService cwOrganizationTypeService;
//    @Resource
//    private SerialnumTplService serialnumTplService;
//    @Resource
//    private OssService ossService;
    @Resource
    private CwProjectClientInfoMapper cwProjectClientInfoMapper;
    @Resource
    private CwWorkClientTempService cwWorkClientTempService;
//    @Resource
//    private UserMapper userMapper;

    @Autowired
    private IFlowableApi iFlowableApi;


    public IPage<CwWorkClientBaseDTO> findList(Page<CwWorkClientBaseDTO> page, CwWorkClientBaseDTO cwWorkClientBaseDTO) throws Exception{
        QueryWrapper<CwWorkClientBase> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( CwWorkClientBaseWrapper.INSTANCE.toEntity(cwWorkClientBaseDTO), CwWorkClientBase.class );
        queryWrapper.eq("cw_wcb.del_flag","0");
        queryWrapper.orderByDesc("cw_wcb.create_time");
        if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO)) {
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getIsTrue())) {
                if ("1".equals(cwWorkClientBaseDTO.getIsTrue())){
                    queryWrapper.and(w -> w.eq("cw_wcb.status","0").or().eq("cw_wcb.status","5"));
                }
            }
            if (ArrayUtil.isNotEmpty(cwWorkClientBaseDTO.getCreateDates())) {
                queryWrapper.between("cw_wcb.create_time", cwWorkClientBaseDTO.getCreateDates()[0], cwWorkClientBaseDTO.getCreateDates()[1]);
            }
            if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO.getCwWorkClientTypeDTO())){
                if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getCwWorkClientTypeDTO().getOwnershipType())) {
                    queryWrapper.eq("cw_wct.ownership_type",cwWorkClientBaseDTO.getCwWorkClientTypeDTO().getOwnershipType());
                }
            }
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getProjectId())){
                List<CwProjectClientInfo> cwProjectClientInfos = cwProjectClientInfoMapper.selectList(new QueryWrapper<CwProjectClientInfo>().lambda().eq(CwProjectClientInfo::getProjectId, cwWorkClientBaseDTO.getProjectId()));
                List<String> ids = cwProjectClientInfos.stream().distinct().map(CwProjectClientInfo::getClientId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(ids)) {
                    queryWrapper.in("cw_wcb.id",ids);
                } else {
                    return new Page<>();
                }
            }
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getUpdateUserName())) {
                List<User> userList = SpringUtil.getBean ( IUserApi.class ).selectListByName(cwWorkClientBaseDTO.getUpdateUserName());
                if (CollectionUtil.isNotEmpty(userList)) {
                    List<String> userIds = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(userIds)) {
                        queryWrapper.in("cw_wcb.update_user",userIds);
                    } else {
                        return new Page<>();
                    }
                } else {
                    return new Page<>();
                }
            }
        }
        IPage<CwWorkClientBaseDTO> list = cwWorkClientBaseMapper.findList(page, queryWrapper);
        List<CwWorkClientBaseDTO> records = list.getRecords();
        //处理数据
        Map<String,String> map = new HashMap<>();
        String data = JSON.toJSONString((records));
        String currentToken = TokenProvider.getCurrentToken();

        map.put("data",data);
        map.put("currentToken",currentToken);


        String datas = iFlowableApi.taskDispose(map);
        List<CwWorkClientBaseDTO> cwWorkClientBaseDTOS = JSON.parseObject(datas, new TypeReference<List<CwWorkClientBaseDTO>>() {});
        list.setRecords(cwWorkClientBaseDTOS);
        return list;
    }

    public IPage<CwWorkClientContactDTO> getContractClientList(Page<CwWorkClientContactDTO> page, CwWorkClientContactDTO cwWorkClientContactDTO) throws Exception{
        IPage<CwWorkClientContactDTO> list = cwWorkClientBaseMapper.getContractClientList(page, cwWorkClientContactDTO);
        return list;
    }

    public IPage<CwWorkClientBaseDTO> findListTree(Page<CwWorkClientBaseDTO> page, CwWorkClientBaseDTO cwWorkClientBaseDTO) throws Exception{
        long l1 = System.currentTimeMillis();
        QueryWrapper<CwWorkClientBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cw_wcb.del_flag","0");
        queryWrapper.orderByDesc("cw_wcb.create_time");
        if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO)) {
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getName()) ||
                    StringUtils.isNotBlank(cwWorkClientBaseDTO.getNo()) ||
                    StringUtils.isNotBlank(cwWorkClientBaseDTO.getType()) ||
                    StringUtils.isNotBlank(cwWorkClientBaseDTO.getIndustry())) {
                List<String> ids = new ArrayList<>();
                List<CwWorkClientBase> list = this.list(new QueryWrapper<CwWorkClientBase>().lambda()
                        .like(StringUtils.isNotBlank(cwWorkClientBaseDTO.getName()),CwWorkClientBase::getName, cwWorkClientBaseDTO.getName())
                        .like(StringUtils.isNotBlank(cwWorkClientBaseDTO.getNo()),CwWorkClientBase::getNo, cwWorkClientBaseDTO.getNo())
                        .eq(StringUtils.isNotBlank(cwWorkClientBaseDTO.getType()),CwWorkClientBase::getType, cwWorkClientBaseDTO.getType())
                        .eq(StringUtils.isNotBlank(cwWorkClientBaseDTO.getIndustry()),CwWorkClientBase::getIndustry, cwWorkClientBaseDTO.getIndustry())
                );
                list.stream().forEach(item->{
                    ids.add(item.getId());
                    if (StringUtils.isNotBlank(item.getOneUpCompany())) {
                        String parentId = item.getOneUpCompany();
                        while (true) {
                            CwWorkClientBase byId = this.getOne(new QueryWrapper<CwWorkClientBase>().lambda().eq(CwWorkClientBase::getId, parentId));
                            if (ObjectUtil.isNotEmpty(byId)) {
                                ids.add(byId.getId());
                                if (StringUtils.isBlank(byId.getOneUpCompany())) {
                                    break;
                                } else {
                                    parentId = byId.getOneUpCompany();
                                }
                            } else {
                                break;
                            }
                        }
                    }
                    List<String> childIdList = this.list(new QueryWrapper<CwWorkClientBase>().lambda().eq(CwWorkClientBase::getOneUpCompany, item.getId())).stream().map(CwWorkClientBase::getId).collect(Collectors.toList());
                    while (true) {
                        if (CollectionUtil.isNotEmpty(childIdList)) {
                            childIdList.stream().forEach(childId->{
                                ids.add(childId);
                            });
                            List<String> childIdS = this.list(new QueryWrapper<CwWorkClientBase>().lambda().in(CwWorkClientBase::getOneUpCompany, childIdList)).stream().map(CwWorkClientBase::getId).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(childIdS)) {
                                childIdList = childIdS;
                            } else {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                });
                List<String> lastIdList = ids.stream().distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(lastIdList)){
                    queryWrapper.in("cw_wcb.id",lastIdList);
                } else {
                    return new Page<>();
                }
            }
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getStatus())) {
                queryWrapper.eq("cw_wcb.status",cwWorkClientBaseDTO.getStatus());
            }
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getIsTrue())) {
                if ("1".equals(cwWorkClientBaseDTO.getIsTrue())){
                    queryWrapper.eq("cw_wcb.status","0").or().eq("cw_wcb.status","5");
                }
            }
        }
        long l2 = System.currentTimeMillis();
        System.out.println("查询客户信息列表treeService1:" + (l2-l1));
        IPage<CwWorkClientBaseDTO> list = cwWorkClientBaseMapper.getInfoList(page, queryWrapper);
        list.getRecords().forEach(li->{
            if (StringUtils.isNotBlank(li.getClientId())){
                List<CwWorkClientBillingDTO> billing = cwWorkClientBaseMapper.getBilling(li.getClientId());
                li.setCwWorkClientBillingDTOList(billing);
            }
        });
        long l3 = System.currentTimeMillis();
        System.out.println("查询客户信息列表treeService2:" + (l3-l2));
        return list;
    }


    public IPage<CwWorkClientBaseDTO> findAllList(Page<CwWorkClientBaseDTO> page, CwWorkClientBaseDTO cwWorkClientBaseDTO) throws Exception{
        long l1 = System.currentTimeMillis();
        QueryWrapper<CwWorkClientBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cw_wcb.del_flag","0");
        queryWrapper.orderByDesc("cw_wcb.create_time");
        if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO)) {
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getName()) ||
                    StringUtils.isNotBlank(cwWorkClientBaseDTO.getNo()) ||
                    StringUtils.isNotBlank(cwWorkClientBaseDTO.getType()) ||
                    StringUtils.isNotBlank(cwWorkClientBaseDTO.getIndustry())) {
                List<String> ids = new ArrayList<>();
                List<CwWorkClientBase> list = this.list(new QueryWrapper<CwWorkClientBase>().lambda()
                        .like(StringUtils.isNotBlank(cwWorkClientBaseDTO.getName()),CwWorkClientBase::getName, cwWorkClientBaseDTO.getName())
                        .like(StringUtils.isNotBlank(cwWorkClientBaseDTO.getNo()),CwWorkClientBase::getNo, cwWorkClientBaseDTO.getNo())
                        .eq(StringUtils.isNotBlank(cwWorkClientBaseDTO.getType()),CwWorkClientBase::getType, cwWorkClientBaseDTO.getType())
                        .eq(StringUtils.isNotBlank(cwWorkClientBaseDTO.getIndustry()),CwWorkClientBase::getIndustry, cwWorkClientBaseDTO.getIndustry())
                );
                list.stream().forEach(item->{
                    ids.add(item.getId());
                    if (StringUtils.isNotBlank(item.getOneUpCompany())) {
                        String parentId = item.getOneUpCompany();
                        while (true) {
                            CwWorkClientBase byId = this.getOne(new QueryWrapper<CwWorkClientBase>().lambda().eq(CwWorkClientBase::getId, parentId));
                            if (ObjectUtil.isNotEmpty(byId)) {
                                ids.add(byId.getId());
                                if (StringUtils.isBlank(byId.getOneUpCompany())) {
                                    break;
                                } else {
                                    parentId = byId.getOneUpCompany();
                                }
                            } else {
                                break;
                            }
                        }
                    }
                    List<String> childIdList = this.list(new QueryWrapper<CwWorkClientBase>().lambda().eq(CwWorkClientBase::getOneUpCompany, item.getId())).stream().map(CwWorkClientBase::getId).collect(Collectors.toList());
                    while (true) {
                        if (CollectionUtil.isNotEmpty(childIdList)) {
                            childIdList.stream().forEach(childId->{
                                ids.add(childId);
                            });
                            List<String> childIdS = this.list(new QueryWrapper<CwWorkClientBase>().lambda().in(CwWorkClientBase::getOneUpCompany, childIdList)).stream().map(CwWorkClientBase::getId).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(childIdS)) {
                                childIdList = childIdS;
                            } else {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                });
                List<String> lastIdList = ids.stream().distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(lastIdList)){
                    queryWrapper.in("cw_wcb.id",lastIdList);
                } else {
                    return new Page<>();
                }
            }
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getStatus())) {
                queryWrapper.eq("cw_wcb.status",cwWorkClientBaseDTO.getStatus());
            }
            if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getIsTrue())) {
                if ("1".equals(cwWorkClientBaseDTO.getIsTrue())){
                    queryWrapper.eq("cw_wcb.status","0").or().eq("cw_wcb.status","5");
                }
            }
        }
        long l2 = System.currentTimeMillis();
        System.out.println("查询客户信息列表treeService1:" + (l2-l1));
        IPage<CwWorkClientBaseDTO> list = cwWorkClientBaseMapper.findAllList(page, queryWrapper);
        list.getRecords().forEach(li->{
            if (StringUtils.isNotBlank(li.getClientId())){
                List<CwWorkClientBillingDTO> billing = cwWorkClientBaseMapper.getBilling(li.getClientId());
                li.setCwWorkClientBillingDTOList(billing);
            }
        });
        long l3 = System.currentTimeMillis();
        System.out.println("查询客户信息列表treeService2:" + (l3-l2));
        return list;
    }


    public CwWorkClientBaseDTO queryById(String id) {

        CwWorkClientBaseDTO cwWorkClientBaseDTO = cwWorkClientBaseMapper.queryById(id);
        if (null != cwWorkClientBaseDTO && StringUtils.isNotBlank(cwWorkClientBaseDTO.getRepresentativeParty())){
            List<String> representativePartyList = Arrays.asList(cwWorkClientBaseDTO.getRepresentativeParty().split(","));
            cwWorkClientBaseDTO.setRepresentativePartys(representativePartyList);
        }

        return cwWorkClientBaseDTO;
    }

    public String saveForm(CwWorkClientBaseDTO cwWorkClientBaseDTO) throws Exception{
        if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO)) {
            if (StringUtils.isEmpty(cwWorkClientBaseDTO.getId())) {
                cwWorkClientBaseDTO.setCreateBy(new UserDTO());
            }
        }
        CwWorkClientBase cwWorkClientBase = CwWorkClientBaseWrapper.INSTANCE.toEntity(cwWorkClientBaseDTO);
        if (null == cwWorkClientBase.getRepresentativeParty()) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < cwWorkClientBaseDTO.getRepresentativePartys().size(); i++) {
                if (i > 0) {
                    builder.append(",");
                }
                builder.append(cwWorkClientBaseDTO.getRepresentativePartys().get(i));
            }
            String value = builder.toString();

            cwWorkClientBase.setRepresentativeParty(value);
        }
        if(ObjectUtil.isNotEmpty(cwWorkClientBase)){
            if(StringUtils.isBlank(cwWorkClientBase.getId())){
                UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
                String no = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), CwWorkClientBaseDTO.BIZ_CODE,TokenProvider.getCurrentToken());
                cwWorkClientBase.setNo(no);
                cwWorkClientBase.setUpdateUser(userDTO.getId());
                cwWorkClientBase.setStatus("0");
            }
        }
        this.saveOrUpdate(cwWorkClientBase);
        if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO)) {
            // 附件
//            ossService.saveOrUpdateFileList(cwWorkClientBaseDTO.getWorkAttachmentDtoList(),cwWorkClientBase.getId(),"cw_work_client");
            Map<String,String> map = new HashMap<>();
            String fileList = JSON.toJSONString((cwWorkClientBaseDTO.getWorkAttachmentDtoList()));
            String attachmentId = cwWorkClientBase.getId();
            String attachmentFlag = "cw_work_client";
            map.put("fileList",fileList);
            map.put("attachmentId",attachmentId);
            map.put("attachmentFlag",attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken ( ));
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);
            // 客户类型
            if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO.getCwWorkClientTypeDTO())){
                CwWorkClientType cwWorkClientType = CwWorkClientTypeWrapper.INSTANCE.toEntity(cwWorkClientBaseDTO.getCwWorkClientTypeDTO());
                cwWorkClientType.setClientId(cwWorkClientBase.getId());
                cwWorkClientTypeService.saveOrUpdate(cwWorkClientType);
            }
            // 开票信息
            if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO.getCwWorkClientBillingDTOList())){
                List<String> ids = cwWorkClientBaseDTO.getCwWorkClientBillingDTOList().stream().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).distinct().map(CwWorkClientBillingDTO::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(ids)){
                    cwWorkClientBillingService.remove(new QueryWrapper<CwWorkClientBilling>().lambda()
                            .eq(CwWorkClientBilling::getClientId,cwWorkClientBase.getId()).notIn(CwWorkClientBilling::getId,ids));
                } else {
                    cwWorkClientBillingService.remove(new QueryWrapper<CwWorkClientBilling>().lambda().eq(CwWorkClientBilling::getClientId,cwWorkClientBase.getId()));
                }
                cwWorkClientBaseDTO.getCwWorkClientBillingDTOList().stream().forEach(item->{
                    CwWorkClientBilling cwWorkClientBilling = CwWorkClientBillingWrapper.INSTANCE.toEntity(item);
                    if (StringUtils.isEmpty(item.getId())) {
                        cwWorkClientBilling.setClientId(cwWorkClientBase.getId());
                    }
                    cwWorkClientBillingService.saveOrUpdate(cwWorkClientBilling);
                });
            } else {
                cwWorkClientBillingService.remove(new QueryWrapper<CwWorkClientBilling>().lambda().eq(CwWorkClientBilling::getClientId,cwWorkClientBase.getId()));
            }
            // 联系人信息
            if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO.getCwWorkClientContactDTOList())){
                List<String> ids = cwWorkClientBaseDTO.getCwWorkClientContactDTOList().stream().filter(item -> {
                    if (StringUtils.isNotBlank(item.getId())) {
                        return true;
                    }
                    return false;
                }).distinct().map(CwWorkClientContactDTO::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(ids)){
                    cwWorkClientContactService.remove(new QueryWrapper<CwWorkClientContact>().lambda()
                            .eq(CwWorkClientContact::getClientId,cwWorkClientBase.getId()).notIn(CwWorkClientContact::getId,ids));
                } else {
                    cwWorkClientContactService.remove(new QueryWrapper<CwWorkClientContact>().lambda().eq(CwWorkClientContact::getClientId,cwWorkClientBase.getId()));
                }
                cwWorkClientBaseDTO.getCwWorkClientContactDTOList().stream().forEach(item->{
                    CwWorkClientContact cwWorkClientContact = CwWorkClientContactWrapper.INSTANCE.toEntity(item);
                    if (StringUtils.isEmpty(item.getId())) {
                        cwWorkClientContact.setClientId(cwWorkClientBase.getId());
                    }
                    cwWorkClientContactService.saveOrUpdate(cwWorkClientContact);
                });
            } else {
                cwWorkClientContactService.remove(new QueryWrapper<CwWorkClientContact>().lambda().eq(CwWorkClientContact::getClientId,cwWorkClientBase.getId()));
            }
        }
        return cwWorkClientBase.getId();
    }

    public ResponseEntity saveClient(CwWorkClientBaseDTO cwWorkClientBaseDTO) throws Exception{
        this.saveForm(cwWorkClientBaseDTO);
        return ResponseEntity.ok("保存成功");
    }

    public ResponseEntity deleteByIds(String ids) {
        // 查询客户是否被引用  （合同-委托方、合同-参与签约方、项目-被服务单位、报告-被服务单位、发票-实际开票单位）
        String idArray[] =ids.split(",");
        // 根据客户的id数组查询客户的no(编号)
        List<String> noList = cwWorkClientBaseMapper.getNoByIdArray(idArray);

        List<String> useClient = new ArrayList<>();

        // 查询客户是否被引用（合同-委托方）
        List<String> useByClientContacts = cwWorkClientBaseMapper.isUseByClientContacts(idArray);
        if (CollectionUtil.isNotEmpty(useByClientContacts)) {
            useByClientContacts.stream().forEach(item -> {
                useClient.add(item);
            });
        }
        // 查询客户是否被引用（合同-参与签约方）
        List<String> useByContactParty = cwWorkClientBaseMapper.isUseByContactParty(noList);
        if (CollectionUtil.isNotEmpty(useByContactParty)) {
            useByContactParty.stream().forEach(item -> {
                useClient.add(item);
            });
        }
        // 查询客户是否被引用（项目-被服务单位）
        List<String> useByProject = cwWorkClientBaseMapper.isUseByProject(idArray);
        if (CollectionUtil.isNotEmpty(useByProject)) {
            useByProject.stream().forEach(item -> {
                useClient.add(item);
            });
        }
        // 查询客户是否被引用（报告-被服务单位）
        List<String> useByReport = cwWorkClientBaseMapper.isUseByReport(idArray);
        if (CollectionUtil.isNotEmpty(useByReport)) {
            useByReport.stream().forEach(item -> {
                useClient.add(item);
            });
        }
        // 查询客户是否被引用（发票-实际开票单位）
        List<String> useByInvoice = cwWorkClientBaseMapper.isUseByInvoice(idArray);
        if (CollectionUtil.isNotEmpty(useByInvoice)) {
            useByInvoice.stream().forEach(item -> {
                useClient.add(item);
            });
        }

        if (CollectionUtil.isNotEmpty(useClient)) {
            List<String> collect = useClient.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 ("删除成功");
    }

    public String updateStatusById(CwWorkClientBaseDTO cwWorkClientBaseDTO) {
        CwWorkClientBase cwWorkClientBase = CwWorkClientBaseWrapper.INSTANCE.toEntity(cwWorkClientBaseDTO);
        cwWorkClientBaseMapper.update(cwWorkClientBase, new QueryWrapper<CwWorkClientBase>().lambda().eq(CwWorkClientBase::getId, cwWorkClientBase.getId()));
        return "操作成功";
    }

    // 其他人发起修改申请
    public synchronized ResponseEntity<Map<String,String>> pushUpdate(String id) {
        CwWorkClientBaseDTO cwWorkClientBaseDTO = this.queryById(id);
        String jsonString = JSON.toJSONString(cwWorkClientBaseDTO);
        CwWorkClientTemp temp = new CwWorkClientTemp();
        temp.setSourceData(jsonString);
        temp.setClientId(id);
        temp.setStatus("2");
        cwWorkClientTempService.save(temp);
        Map<String,String> map = new HashMap<>();
        map.put("id", temp.getId());
        return ResponseEntity.ok (map);
    }

    // 终止修改申请
    public ResponseEntity stopUpdate(String id) throws Exception{
        CwWorkClientBase cwWorkClientBase = this.getById(id);
        CwWorkClientTemp cwWorkClientTemp = cwWorkClientTempService.getById(cwWorkClientBase.getUpdateRequestId());
        cwWorkClientTemp.setStatus("6"); // 6取消申请
        cwWorkClientTempService.updateById(cwWorkClientTemp);
        CwWorkClientBaseDTO cwWorkClientBaseDTO = JSON.parseObject(cwWorkClientTemp.getSourceData(), CwWorkClientBaseDTO.class);
        cwWorkClientBaseDTO.setUpdateRequestId("");
        cwWorkClientBaseDTO.setRequestUserId("");
        this.saveForm(cwWorkClientBaseDTO);
        return ResponseEntity.ok ("操作成功");
    }

    // 驳回/修改/通过申请
    public ResponseEntity rebackOrAgreeUpdate(String id, String type) {
        CwWorkClientBase cwWorkClientBase = this.getById(id);
        CwWorkClientTemp cwWorkClientTemp = cwWorkClientTempService.getById(cwWorkClientBase.getUpdateRequestId());
        if ("reject".equals(type)){
            cwWorkClientTemp.setStatus("4");
        }
        if ("reback".equals(type)){
            cwWorkClientTemp.setStatus("3");
        }
        if ("reback_push".equals(type)){
            // 撤回后重新发起修改
            cwWorkClientTemp.setStatus("2");
        }
        if ("agree".equals(type)){
            cwWorkClientTemp.setStatus("5");
            cwWorkClientBase.setUpdateUser(cwWorkClientBase.getRequestUserId()); // 审核通过后，拥有人改为当前申请人
            cwWorkClientBase.setRequestUserId(""); // 审核通过后，当前申请人清空
            cwWorkClientBase.setUpdateRequestId(""); // 审核通过后，修改申请临时表id清空
            this.updateById(cwWorkClientBase);
        }
        if ("reapply".equals(type)){
            cwWorkClientTemp.setStatus("2");
        }
        cwWorkClientTempService.updateById(cwWorkClientTemp);
        return ResponseEntity.ok ("操作成功");
    }

    // 查询社会统一信用代码是否存在
    public ResponseEntity<Map<String,String>> queryUscCodeIsUse(String uscCode) {
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        Map<String,String> map = new HashMap<>();
        // 根据社会统一信用代码查询
        List<CwWorkClientBase> list = this.list(new QueryWrapper<CwWorkClientBase>().lambda().eq(CwWorkClientBase::getUscCode, uscCode).orderByDesc(CwWorkClientBase::getCreateTime).last("limit 1"));
        if (CollectionUtil.isNotEmpty(list)) {
            CwWorkClientBase cwWorkClientBase = list.get(0);
            if (ObjectUtil.isNotEmpty(cwWorkClientBase)) {
                // 客户数据拥有人不是空时,按正常流程走数据，数据的拥有人是不可能为空的
                if (StringUtils.isNotBlank(cwWorkClientBase.getUpdateUser())){
                    // updateUser和当前登录人相等，说明这条数据的拥有人是自己，反之不是自己
                    if (userDTO.getId().equals(cwWorkClientBase.getUpdateUser())) {
                        map.put("use","1"); // 数据拥有人是自己，则返回1，打开修改弹出框
                    } else {
                        map.put("use","0"); // 数据拥有人不是自己，则返回0，打开修改申请
                    }
                    if ("0".equals(cwWorkClientBase.getStatus()) || "5".equals(cwWorkClientBase.getStatus())) {
                        map.put("isUpdate","true"); // 查询到的数据目前可修改
                    } else {
                        map.put("isUpdate","false"); // 查询到的数据目前不可修改，数据正在修改中
                    }
                }
                map.put("id",cwWorkClientBase.getId());
                return ResponseEntity.ok(map);
            }
        }
        map.put("use","false"); // 能走到这行代码，说明就没查到数据，uscCode不存在，可以使用
        return ResponseEntity.ok(map);
    }

    // 查询客户名称是否存在
    public ResponseEntity<Map<String,String>> queryNameIsUse(String name) {
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        Map<String,String> map = new HashMap<>();
        // 根据客户名称查询
        List<CwWorkClientBase> list = this.list(new QueryWrapper<CwWorkClientBase>().lambda().eq(CwWorkClientBase::getName, name).orderByDesc(CwWorkClientBase::getCreateTime).last("limit 1"));
        if (CollectionUtil.isNotEmpty(list)) {
            CwWorkClientBase cwWorkClientBase = list.get(0);
            if (ObjectUtil.isNotEmpty(cwWorkClientBase)) {
                // 客户数据拥有人不是空时,按正常流程走数据，正确数据的拥有人是不可能为空的
                if (StringUtils.isNotBlank(cwWorkClientBase.getUpdateUser())){
                    // updateUser和当前登录人相等，说明这条数据的拥有人是自己，反之不是自己
                    if (userDTO.getId().equals(cwWorkClientBase.getUpdateUser())) {
                        map.put("use","1"); // 数据拥有人是自己，则返回1，打开修改弹出框
                    } else {
                        map.put("use","0"); // 数据拥有人不是自己，则返回0，打开修改申请
                    }
                    if ("0".equals(cwWorkClientBase.getStatus()) || "5".equals(cwWorkClientBase.getStatus())) {
                        map.put("isUpdate","true"); // 查询到的数据目前可修改
                    } else {
                        map.put("isUpdate","false"); // 查询到的数据目前不可修改，数据正在修改中
                    }
                }
                map.put("id",cwWorkClientBase.getId());
                return ResponseEntity.ok(map);
            }
        }
        map.put("use","false"); // 能走到这行代码，说明就没查到数据，客户名称不存在，可以使用
        return ResponseEntity.ok(map);
    }

    // 根据客户id查询
    public Map<String,Object> queryUscCodeById(String id) {
        Map map = new HashMap();
        CwWorkClientBase cwWorkClientBase = this.getById(id);
        if (ObjectUtil.isNotEmpty(cwWorkClientBase)) {
            map.put("uscCode",cwWorkClientBase.getUscCode());
            return map;
        } else {
            map.put("uscCode","");
            return map;
        }
    }

    // 根据客户id查询
    public ResponseEntity<String> queryNameById(String id) {
        CwWorkClientBase cwWorkClientBase = this.getById(id);
        if (ObjectUtil.isNotEmpty(cwWorkClientBase)) {
            return ResponseEntity.ok(cwWorkClientBase.getName());
        } else {
            return ResponseEntity.ok("");
        }
    }

    // 根据客户id查询修改历史
    public ResponseEntity<List<CwWorkClientTempDTO>> queryUpdateLogList(CwWorkClientTempDTO tempDto) {
        QueryWrapper<CwWorkClientTemp> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("temp.create_time");
        if (ObjectUtil.isNotEmpty(tempDto)) {
            if (StringUtils.isNotBlank(tempDto.getClientId())) {
                queryWrapper.eq("temp.client_id", tempDto.getClientId());
            }
            if (StringUtils.isNotBlank(tempDto.getCreateName())) {
                List<User> userList = SpringUtil.getBean ( IUserApi.class ).selectListByName(tempDto.getCreateName());
                if (CollectionUtil.isNotEmpty(userList)) {
                    List<String> userIds = userList.stream().distinct().map(User::getId).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(userIds)) {
                        queryWrapper.in("temp.create_by_id",userIds);
                    } else {
                        return ResponseEntity.ok(new ArrayList<CwWorkClientTempDTO>());
                    }
                } else {
                    return ResponseEntity.ok(new ArrayList<CwWorkClientTempDTO>());
                }
            }
            if (StringUtils.isNotBlank(tempDto.getStatus())) {
                queryWrapper.eq("temp.status",tempDto.getStatus());
            }
            if (StringUtils.isNotBlank(tempDto.getClientNo())) {
                queryWrapper.like("cw_wcb.no",tempDto.getClientNo());
            }
        }
        return ResponseEntity.ok(cwWorkClientBaseMapper.queryUpdateLogList(queryWrapper));
    }

}
