package com.storlead.sales.service.impl.target;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.StringUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.sales.pojo.entity.customer.LiaisonEntity;
import com.storlead.sales.pojo.vo.customer.LiaisonListVO;
import com.storlead.sales.pojo.dto.target.TargetPlanAddDTO;
import com.storlead.sales.pojo.dto.target.TargetPlanScopeSettingDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.sales.pojo.dto.target.TargetPlanSearchDTO;
import com.storlead.sales.pojo.dto.target.TargetRankingDTO;
import com.storlead.sales.pojo.entity.target.TargetPlanEntity;
import com.storlead.sales.pojo.entity.target.TargetQuotaEntity;
import com.storlead.sales.pojo.vo.target.TargetPlanDetailVO;
import com.storlead.sales.pojo.vo.target.TargetPlanListVO;
import com.storlead.sales.service.customer.MessageAssembleService;
import com.storlead.sales.mapper.target.TargetPlanMapper;
import com.storlead.sales.service.target.TargetPlanService;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.service.target.TargetQuotaService;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.SubCompanyEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.pojo.vo.DepartmentTree;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.ISubCompanyService;
import com.storlead.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 目标方案主表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-12-11
 */
@Service
public class TargetPlanServiceImpl extends MyBaseServiceImpl<TargetPlanMapper, TargetPlanEntity> implements TargetPlanService {

    @Resource
    private TargetQuotaService targetQuotaService;
    @Resource
    private IDepartService deptService;
    @Resource
    private IUserService userService;
    @Resource
    private ISubCompanyService subCompanyService;
    @Resource
    private MessageAssembleService assembleService;
    @Override
    public Result<?> addPlan(TargetPlanAddDTO targetPlanAddDTO) {

        TargetPlanEntity targetPlanEntity = new TargetPlanEntity();
        BeanUtils.copyProperties(targetPlanAddDTO,targetPlanEntity);
//        查询重复
        if (this.count(new LambdaQueryWrapper<TargetPlanEntity>().eq(TargetPlanEntity::getYear, targetPlanAddDTO.getYear()).eq(TargetPlanEntity::getType, targetPlanAddDTO.getType()).eq(TargetPlanEntity::getIsDelete, CommonConstant.DEL_FLAG_0)) > 0){
            return Result.error("已存在当前指标！");
        }
        boolean isOk = this.save(targetPlanEntity);
        if (!isOk){
            return Result.error("保存失败");
        }
        TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
        targetQuotaEntity.setTargetPlanId(targetPlanEntity.getId());
        targetQuotaEntity.setOrganizationalType(1);
        targetQuotaEntity.setOrganizationalId(1L);
        targetQuotaService.save(targetQuotaEntity);
        return Result.ok();
    }

    @Override
    public Result<?> editPlan(TargetPlanAddDTO targetPlanAddDTO) {

        TargetPlanEntity targetPlanEntity = new TargetPlanEntity();
        BeanUtils.copyProperties(targetPlanAddDTO,targetPlanEntity);
        boolean isOk = this.updateById(targetPlanEntity);
        if (!isOk){
            return Result.error("修改失败");
        }
        return Result.ok();
    }

    @Override
    //添加事务
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addScopeSetting(TargetPlanScopeSettingDTO targetPlanScopeSettingDTO) {

        TargetPlanEntity targetPlanOld = this.getById(targetPlanScopeSettingDTO.getTargetPlanId());
//        TargetPlanEntity targetPlanEntity = new TargetPlanEntity();
//        BeanUtils.copyProperties(targetPlanScopeSettingDTO,targetPlanEntity);
        if (targetPlanOld.getMethod()==1){
            //汇总
            return scopeSettingA(targetPlanScopeSettingDTO,targetPlanOld);
        }
        if (targetPlanOld.getMethod()==2){
            //分配
            return scopeSettingB(targetPlanScopeSettingDTO,targetPlanOld);
        }
        if (targetPlanOld.getMethod()==3){
            //认领
            return scopeSettingC(targetPlanScopeSettingDTO,targetPlanOld);
        }

        return Result.error("分配参数异常！");
    }

    private Result<?> scopeSettingA(TargetPlanScopeSettingDTO targetPlanScopeSettingDTO, TargetPlanEntity targetPlanOld) {
        //汇总
        TargetPlanEntity targetPlanEntity = new TargetPlanEntity();

        TargetQuotaEntity targetQuotaOld = targetQuotaService.getById(targetPlanScopeSettingDTO.getId());
        targetPlanEntity.setId(targetPlanScopeSettingDTO.getTargetPlanId());

//            统计需要新增的公司分配指标
        List<Long> targetQuotaAddIdList = new ArrayList<>();

//            统计需要删除的公司分配指标
        List<Long> targetQuotaDelIdList = new ArrayList<>();

//            统计需要修改的公司分配指标
        List<Long> targetQuotaEditIdList = new ArrayList<>();
        List<Long> deleteIdList = new ArrayList<>();
        boolean isOk = false;

        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(1)){
            //集团
            String companyScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getCompanyScopeIdList());
            String companyScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getCompanyScopeNameList());
            targetPlanEntity.setCompanyScopeId(companyScopeId);
            targetPlanEntity.setCompanyScopeName(companyScopeName);
            this.updateById(targetPlanEntity);

            targetQuotaOld.setSubScopeId(companyScopeId);
            targetQuotaOld.setSubScopeName(companyScopeName);

            List<Long> companyScopeIdOldList = StringUtil.stringToLongList(targetPlanOld.getCompanyScopeId());
            List<Long> companyScopeIdList = targetPlanScopeSettingDTO.getCompanyScopeIdList();

            // 1、新增的部分
            targetQuotaAddIdList = companyScopeIdList.stream()
                    .filter(id -> !companyScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = companyScopeIdOldList.stream()
                    .filter(id -> !companyScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = companyScopeIdOldList.stream()
                    .filter(companyScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(2);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());

                    targetQuotaAddListTemp.add(targetQuotaEntity);
                }
                targetQuotaService.saveBatch(targetQuotaAddListTemp);

                //新增消息
                //通过分公司id查询分公司负责人id
                List<Long> subCompanyIdList = targetQuotaAddListTemp.stream().map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toList());
                Set<Long> companyLeaderIdList = subCompanyService.list(new LambdaQueryWrapper<SubCompanyEntity>().in(SubCompanyEntity::getId,subCompanyIdList)).stream().map(SubCompanyEntity::getLeaderId).collect(Collectors.toSet());
                assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "CREATE_GOAL" ,companyLeaderIdList,"company");
            }
            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){
                //查询部门id
                List<DeptEntity> deptList = deptService.list(new LambdaQueryWrapper<DeptEntity>().in(DeptEntity::getSubCompanyId,targetQuotaDelIdList));
                List<Long> deptIdList = deptList.stream().map(DeptEntity::getId).collect(Collectors.toList());
//                List<Long> deleteIdList = new ArrayList<>();
                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperC = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getOrganizationalType,2);
                targetQuotaDelQueryWrapperC.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetQuotaDelListC = targetQuotaService.list(targetQuotaDelQueryWrapperC);
                if (!CollectionUtils.isEmpty(targetQuotaDelListC)){
                    Set<Long> userIds = new HashSet<>();
                    List<Long> deleteIdListC = targetQuotaDelListC.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                    deleteIdList.addAll(deleteIdListC);

                    List<Long> subCompanyIdList = targetQuotaDelListC.stream().map(e->e.getOrganizationalId()).collect(Collectors.toList());
                    Set<Long> companyLeaderIdList = subCompanyService.list(new LambdaQueryWrapper<SubCompanyEntity>().in(SubCompanyEntity::getId,subCompanyIdList)).stream().map(SubCompanyEntity::getLeaderId).collect(Collectors.toSet());
//                    userIds.addAll(companyLeaderIdList);

                    List<TargetQuotaEntity> targetQuotaDelListD = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListC));
                    if (!CollectionUtils.isEmpty(targetQuotaDelListD)){
                        List<Long> deleteIdListD = targetQuotaDelListD.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                        deleteIdList.addAll(deleteIdListD);

                        List<Long> deptDelIdList = targetQuotaDelListD.stream().map(e->e.getOrganizationalId()).collect(Collectors.toList());
                        Set<Long> deptLeaderIdList = deptService.list(new LambdaQueryWrapper<DeptEntity>().in(DeptEntity::getId,deptDelIdList)).stream().map(DeptEntity::getManagerId).collect(Collectors.toSet());
//                        userIds.addAll(deptLeaderIdList);

                        List<TargetQuotaEntity> targetQuotaDelListU = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListD));
                        if (!CollectionUtils.isEmpty(targetQuotaDelListU)){
                            List<Long> deleteIdListU = targetQuotaDelListU.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                            deleteIdList.addAll(deleteIdListU);
                            //过滤掉已删除的
                            Set<Long> userIdList = targetQuotaDelListU.stream().filter(e->e.getIsDelete().equals(CommonConstant.DEL_FLAG_0)).map(e->e.getOrganizationalId()).collect(Collectors.toSet());
                            userIds.addAll(userIdList);
                        }
                    }

                    assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "ADJUST_DELETE" ,userIds,null);
                }
                if (!CollectionUtils.isEmpty(deleteIdList)){
                    targetQuotaService.removeByIds(deleteIdList);
                }
                //删除消息
//                assembleService.sendTargetEventMessages(liaisonId, "DUPLICATE_WARNING_LIAISON");

            }
            isOk = targetQuotaService.updateById(targetQuotaOld);
            targetQuotaService.updateQuarterById(targetQuotaOld.getId());
        }
        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(2)){
            //公司
            String deptScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getDeptScopeIdList());
            String deptScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getDeptScopeNameList());

            //获取该公司下的部门信息
            List<Long> deptIdList = deptService.list(new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getSubCompanyId,targetQuotaOld.getOrganizationalId())).stream().map(DeptEntity::getId).collect(Collectors.toList());
            //重新写入部门id数据
            String deptIds = StringUtil.updateStringList(targetPlanOld.getDeptScopeId(),deptIdList,targetPlanScopeSettingDTO.getDeptScopeIdList());
            targetPlanEntity.setDeptScopeId(deptIds);
            targetPlanEntity.setDeptScopeName(deptScopeName);
            this.updateById(targetPlanEntity);

//            List<Long> deptScopeIdOldList = StringUtil.stringToLongList(targetPlanOld.getDeptScopeId());
            List<Long> deptScopeIdOldList = StringUtil.stringToLongList(targetQuotaOld.getSubScopeId());
            List<Long> deptScopeIdList = targetPlanScopeSettingDTO.getDeptScopeIdList();

            targetQuotaOld.setSubScopeId(deptScopeId);
            targetQuotaOld.setSubScopeName(deptScopeName);
            // 1、新增的部分
            targetQuotaAddIdList = deptScopeIdList.stream()
                    .filter(id -> !deptScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = deptScopeIdOldList.stream()
                    .filter(id -> !deptScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = deptScopeIdOldList.stream()
                    .filter(deptScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(3);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());
                    targetQuotaAddListTemp.add(targetQuotaEntity);
                }
                targetQuotaService.saveBatch(targetQuotaAddListTemp);
                //新增消息
                //通过分公司id查询分公司负责人id
                List<Long> deptAddIdList = targetQuotaAddListTemp.stream().map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toList());
                Set<Long> deptLeaderIdList = deptService.list(new LambdaQueryWrapper<DeptEntity>().in(DeptEntity::getId,deptAddIdList)).stream().map(DeptEntity::getManagerId).collect(Collectors.toSet());
                assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "CREATE_GOAL" ,deptLeaderIdList,"dept");

            }
            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){

                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperD = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperD.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperD.eq(TargetQuotaEntity::getOrganizationalType,3);
                targetQuotaDelQueryWrapperD.eq(TargetQuotaEntity::getParentId,targetPlanScopeSettingDTO.getId());
                targetQuotaDelQueryWrapperD.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetQuotaDelListD = targetQuotaService.list(targetQuotaDelQueryWrapperD);
                if (!CollectionUtils.isEmpty(targetQuotaDelListD)){
                    Set<Long> userIds = new HashSet<>();
                    List<Long> deleteIdListD = targetQuotaDelListD.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                    deleteIdList.addAll(deleteIdListD);

                    List<Long> deptDelIdList = targetQuotaDelListD.stream().map(e->e.getOrganizationalId()).collect(Collectors.toList());
                    Set<Long> deptLeaderIdList = deptService.list(new LambdaQueryWrapper<DeptEntity>().in(DeptEntity::getId,deptDelIdList)).stream().map(DeptEntity::getManagerId).collect(Collectors.toSet());
//                    userIds.addAll(deptLeaderIdList);
                    List<TargetQuotaEntity> targetQuotaDelListU = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListD));
                    if (!CollectionUtils.isEmpty(targetQuotaDelListU)){
                        List<Long> deleteIdListU = targetQuotaDelListU.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                        deleteIdList.addAll(deleteIdListU);
                        Set<Long> userIdList = targetQuotaDelListU.stream().filter(e->e.getIsDelete().equals(CommonConstant.DEL_FLAG_0)).map(e->e.getOrganizationalId()).collect(Collectors.toSet());
                        userIds.addAll(userIdList);
                    }
                    assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "ADJUST_DELETE" ,userIds,null);
                }
                if (!CollectionUtils.isEmpty(deleteIdList)) {
                    targetQuotaService.removeByIds(deleteIdList);
                }

            }
            isOk = targetQuotaService.updateById(targetQuotaOld);
            targetQuotaService.updateQuarterById(targetQuotaOld.getId());
            //写入对应的公司值
            targetQuotaService.updateQuarterById(targetQuotaOld.getParentId());
        }

        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(3)){
            //部门
            String userScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getUserScopeIdList());
            String userScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getUserScopeNameList());
            //获取该公司下的用户信息
            List<Long> userIdList = userService.list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getDeptId,targetQuotaOld.getOrganizationalId())).stream().map(UserEntity::getId).collect(Collectors.toList());
            //重新写入用户id数据
            String userIds = StringUtil.updateStringList(targetPlanOld.getUserScopeId(),userIdList,targetPlanScopeSettingDTO.getUserScopeIdList());
            targetPlanEntity.setUserScopeId(userIds);

//            targetPlanEntity.setUserScopeId(userScopeId);
            targetPlanEntity.setUserScopeName(userScopeName);
            this.updateById(targetPlanEntity);



            List<Long> userScopeIdOldList = StringUtil.stringToLongList(targetQuotaOld.getSubScopeId());
            List<Long> userScopeIdList = targetPlanScopeSettingDTO.getUserScopeIdList();

            targetQuotaOld.setSubScopeId(userScopeId);
            targetQuotaOld.setSubScopeName(userScopeName);
            // 1、新增的部分
            targetQuotaAddIdList = userScopeIdList.stream()
                    .filter(id -> !userScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = userScopeIdOldList.stream()
                    .filter(id -> !userScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = userScopeIdOldList.stream()
                    .filter(userScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(4);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());
                    targetQuotaAddListTemp.add(targetQuotaEntity);
                }
                targetQuotaService.saveBatch(targetQuotaAddListTemp);
                //新增消息
                //通过分公司id查询分公司负责人id
                Set<Long> userAddIdList = targetQuotaAddListTemp.stream().map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toSet());
                assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "CREATE_GOAL" ,userAddIdList,"person");

            }
            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){
                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperU = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperU.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperU.eq(TargetQuotaEntity::getOrganizationalType,4);
                targetQuotaDelQueryWrapperU.eq(TargetQuotaEntity::getParentId,targetPlanScopeSettingDTO.getId());
                targetQuotaDelQueryWrapperU.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetQuotaDelListU = targetQuotaService.list(targetQuotaDelQueryWrapperU);
                targetQuotaService.remove(targetQuotaDelQueryWrapperU);
                if (!CollectionUtils.isEmpty(targetQuotaDelListU)){
//                    targetQuotaDelListU.forEach(e->e.setIsDelete(CommonConstant.DEL_FLAG_1));
//                    targetQuotaService.updateBatchById(targetQuotaDelListU);

                    Set<Long> userDelIdList = targetQuotaDelListU.stream().filter(e->e.getIsDelete().equals(CommonConstant.DEL_FLAG_0)).map(e->e.getOrganizationalId()).collect(Collectors.toSet());
                    assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "ADJUST_DELETE" ,userDelIdList,null);

                }
            }
            isOk = targetQuotaService.updateById(targetQuotaOld);
            targetQuotaService.updateQuarterById(targetQuotaOld.getId());
            //写入对应的公司值
            TargetQuotaEntity targetQuotaSC = targetQuotaService.getById(targetQuotaOld.getParentId());
            targetQuotaService.updateQuarterById(targetQuotaSC.getId());
            targetQuotaService.updateQuarterById(targetQuotaSC.getParentId());

        }
        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(4)){
            //个人，添加值
            if(CollectionUtils.isEmpty(targetPlanScopeSettingDTO.getTargetQuotaList())){
                return Result.error("请写入个人目标！");
            }
            TargetQuotaEntity targetQuota = targetPlanScopeSettingDTO.getTargetQuotaList().get(0);
            targetQuota.setParentId(targetQuotaOld.getParentId());
            targetQuota.setStatus(1);
            targetQuotaService.saveOrUpdate(targetQuota);
            //写入对应的部门值
            TargetQuotaEntity targetQuotaD = targetQuotaService.getById(targetQuota.getParentId());
            targetQuotaService.updateQuarterById(targetQuota.getParentId());
            //判断有没有修改，如果有修改，通知部门领导
            if(hasUpdate(targetQuotaOld,targetQuota)){
                DeptEntity department = deptService.getById(targetQuotaD.getOrganizationalId());
                assembleService.sendTargetEventMessages(targetQuota.getParentId(), "SUMMARY_CHANGE_GOAL_VALUE" ,Collections.singleton(department.getManagerId()),"dept");
            }


            //写入对应的公司值
            TargetQuotaEntity targetQuotaSC = targetQuotaService.getById(targetQuotaD.getParentId());
            targetQuotaService.updateQuarterById(targetQuotaD.getParentId());
//            通知分公司领导
//            assembleService.sendTargetEventMessages(targetQuotaD.getParentId(), "SUMMARY_CHANGE_GOAL_VALUE" ,Collections.singleton(targetQuotaSC.getOrganizationalId()),"target/dept");

            //写入对应的集团值
//            TargetQuotaEntity targetQuotaC = targetQuotaService.getById(targetQuotaSC.getParentId());
            targetQuotaService.updateQuarterById(targetQuotaSC.getParentId());
            //写入总目标值到主表
            TargetQuotaEntity targetQuotaC = targetQuotaService.getById(targetQuotaSC.getParentId());
            TargetPlanEntity targetPlanNew = new TargetPlanEntity();
            targetPlanNew.setId(targetQuotaC.getTargetPlanId());
            targetPlanNew.setTargetValue(targetQuotaC.getTotal());
            isOk = this.updateById(targetPlanNew);
        }

//        boolean isOk = targetQuotaService.updateById(targetQuotaOld);
        //更新全部的状态
        updateStatusByTargetPlanId(targetPlanScopeSettingDTO.getTargetPlanId());
        if (isOk){
            return Result.ok();
        }
        return Result.error("业绩目标设置失败！");
    }

    private boolean hasUpdate(TargetQuotaEntity targetQuotaOld, TargetQuotaEntity targetQuota) {
        if (ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter1()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter1())){
            return true;
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter1()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter1())) {
            if (targetQuotaOld.getMonthOrQuarter1().compareTo(targetQuota.getMonthOrQuarter1()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter2()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter2())) {
            if (targetQuotaOld.getMonthOrQuarter2().compareTo(targetQuota.getMonthOrQuarter2()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter3()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter3())) {
            if (targetQuotaOld.getMonthOrQuarter3().compareTo(targetQuota.getMonthOrQuarter3()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter4()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter4())) {
            if (targetQuotaOld.getMonthOrQuarter4().compareTo(targetQuota.getMonthOrQuarter4()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter5()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter5())) {
            if (targetQuotaOld.getMonthOrQuarter5().compareTo(targetQuota.getMonthOrQuarter5()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter6()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter6())) {
            if (targetQuotaOld.getMonthOrQuarter6().compareTo(targetQuota.getMonthOrQuarter6()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter7()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter7())) {
            if (targetQuotaOld.getMonthOrQuarter7().compareTo(targetQuota.getMonthOrQuarter7()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter8()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter8())) {
            if (targetQuotaOld.getMonthOrQuarter8().compareTo(targetQuota.getMonthOrQuarter8()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter9()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter9())) {
            if (targetQuotaOld.getMonthOrQuarter9().compareTo(targetQuota.getMonthOrQuarter9()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter10()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter10())) {
            if (targetQuotaOld.getMonthOrQuarter10().compareTo(targetQuota.getMonthOrQuarter10()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter11()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter11())) {
            if (targetQuotaOld.getMonthOrQuarter11().compareTo(targetQuota.getMonthOrQuarter11()) != 0) {
                return true;
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaOld.getMonthOrQuarter12()) && !ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter12())) {
            if (targetQuotaOld.getMonthOrQuarter12().compareTo(targetQuota.getMonthOrQuarter12()) != 0) {
                return true;
            }
        }
        return false;
    }


    private Result<?> scopeSettingB(TargetPlanScopeSettingDTO targetPlanScopeSettingDTO, TargetPlanEntity targetPlanOld) {
        //分配
        TargetPlanEntity targetPlanEntity = new TargetPlanEntity();

        TargetQuotaEntity targetQuotaOld = targetQuotaService.getById(targetPlanScopeSettingDTO.getId());
        targetPlanEntity.setId(targetPlanScopeSettingDTO.getTargetPlanId());
        Map<String,TargetQuotaEntity> targetQuotaMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(targetPlanScopeSettingDTO.getTargetQuotaList())){
            for (TargetQuotaEntity targetQuotaEntity : targetPlanScopeSettingDTO.getTargetQuotaList()){
                targetQuotaEntity.setTargetPlanId(targetPlanScopeSettingDTO.getTargetPlanId());
            }
            targetQuotaMap = targetPlanScopeSettingDTO.getTargetQuotaList().stream().collect(Collectors.toMap(targetQuotaEntity->targetQuotaEntity.getOrganizationalType()+"-"+targetQuotaEntity.getOrganizationalId(), targetQuotaEntity -> targetQuotaEntity));
        }

//            统计需要新增的公司分配指标
        List<Long> targetQuotaAddIdList = new ArrayList<>();

//            统计需要删除的公司分配指标
        List<Long> targetQuotaDelIdList = new ArrayList<>();

//            统计需要修改的公司分配指标
        List<Long> targetQuotaEditIdList = new ArrayList<>();
        List<Long> deleteIdList = new ArrayList<>();

        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(1)){
            //集团
            String companyScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getCompanyScopeIdList());
            String companyScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getCompanyScopeNameList());
            targetPlanEntity.setCompanyScopeId(companyScopeId);
            targetPlanEntity.setCompanyScopeName(companyScopeName);
            this.updateById(targetPlanEntity);



            List<Long> companyScopeIdOldList = StringUtil.stringToLongList(targetPlanOld.getCompanyScopeId());
//            List<Long> companyScopeIdOldList = StringUtil.stringToLongList(targetQuotaOld.getSubScopeId());
            List<Long> companyScopeIdList = targetPlanScopeSettingDTO.getCompanyScopeIdList();

            targetQuotaOld.setSubScopeId(companyScopeId);
            targetQuotaOld.setSubScopeName(companyScopeName);
            // 1、新增的部分
            targetQuotaAddIdList = companyScopeIdList.stream()
                    .filter(id -> !companyScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = companyScopeIdOldList.stream()
                    .filter(id -> !companyScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = companyScopeIdOldList.stream()
                    .filter(companyScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                        //如果是分配，添加分配指标数据
                        BeanUtils.copyProperties(targetQuotaMap.get(2+"-"+id),targetQuotaEntity);
                        targetQuotaEntity.setTotal(targetQuotaEntity.addTotal());
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(2);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());

                    targetQuotaAddListTemp.add(targetQuotaEntity);
                    //获取分公司领导id
                    SubCompanyEntity subCompanyEntity = subCompanyService.getById(id);
                    assembleService.sendTargetEventMessages(targetQuotaEntity, "CREATE_GOAL" ,Collections.singleton(subCompanyEntity.getLeaderId()),"company");
                }
                targetQuotaService.saveBatch(targetQuotaAddListTemp);
//                分配变更目标值
//                assembleService.sendTargetEventMessages(targetQuotaD.getParentId(), "ASSIGN_CHANGE_GOAL_VALUE" ,targetQuota.getOrganizationalId(),"target/dept");

            }

            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){

                //查询部门id
                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperC = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getOrganizationalType,2);
                targetQuotaDelQueryWrapperC.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetQuotaDelListC = targetQuotaService.list(targetQuotaDelQueryWrapperC);
                if (!CollectionUtils.isEmpty(targetQuotaDelListC)){
                    List<Long> deleteIdListC = targetQuotaDelListC.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                    deleteIdList.addAll(deleteIdListC);
                    List<TargetQuotaEntity> targetQuotaDelListD = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListC));
                    if (!CollectionUtils.isEmpty(targetQuotaDelListD)){
                        List<Long> deleteIdListD = targetQuotaDelListD.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                        deleteIdList.addAll(deleteIdListD);
                        List<TargetQuotaEntity> targetQuotaDelListU = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListD));
                        if (!CollectionUtils.isEmpty(targetQuotaDelListU)){
                            List<Long> deleteIdListU = targetQuotaDelListU.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                            deleteIdList.addAll(deleteIdListU);
                            Set<Long> userIds = targetQuotaDelListU.stream().filter(e->e.getIsDelete().equals(CommonConstant.DEL_FLAG_0)).map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toSet());
                            assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "ADJUST_DELETE" ,userIds,null);

                        }
                    }
                }
                if (!CollectionUtils.isEmpty(deleteIdList)){
                    targetQuotaService.removeByIds(deleteIdList);
                }
            }

            if (!CollectionUtils.isEmpty(targetQuotaEditIdList)){
                List<TargetQuotaEntity> targetQuotaEditListTemp = new ArrayList<>();
                for (Long id : targetQuotaEditIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                    //如果是分配，添加分配指标数据
                    BeanUtils.copyProperties(targetQuotaMap.get(2+"-"+id),targetQuotaEntity);
                    targetQuotaEntity.setTotal(targetQuotaEntity.addTotal());
                    targetQuotaEditListTemp.add(targetQuotaEntity);
                    TargetQuotaEntity targetQuotaUpdateOld = targetQuotaService.getById(targetQuotaEntity.getId());
                    if(hasUpdate(targetQuotaUpdateOld,targetQuotaEntity)) {
                        SubCompanyEntity subCompanyEntity = subCompanyService.getById(id);
                        assembleService.sendTargetEventMessages(targetQuotaEntity, "ASSIGN_CHANGE_GOAL_VALUE", Collections.singleton(subCompanyEntity.getLeaderId()), "company");
                    }
                }
                targetQuotaService.saveOrUpdateBatch(targetQuotaEditListTemp);

            }
                addQuarterList(targetQuotaOld,targetPlanScopeSettingDTO.getTargetQuotaList());
                TargetPlanEntity targetPlanNew = new TargetPlanEntity();
                targetPlanNew.setId(targetPlanOld.getId());
                targetPlanNew.setTargetValue(targetQuotaOld.getTotal());
                this.updateById(targetPlanNew);

        }
        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(2)){
            //判断下级是否超过上级总额
            boolean isOver = isOverTotal(targetPlanScopeSettingDTO.getTargetQuotaList(),targetQuotaOld);
            if (isOver){
                return Result.error("下级指标总额不能超过上级指标总额");
            }
            //公司
            String deptScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getDeptScopeIdList());
            String deptScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getDeptScopeNameList());
            //获取该公司下的部门信息
            List<Long> deptIdList = deptService.list(new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getSubCompanyId,targetQuotaOld.getOrganizationalId())).stream().map(DeptEntity::getId).collect(Collectors.toList());
            //重新写入部门id数据
            String deptIds = StringUtil.updateStringList(targetPlanOld.getDeptScopeId(),deptIdList,targetPlanScopeSettingDTO.getDeptScopeIdList());
            targetPlanEntity.setDeptScopeId(deptIds);
            targetPlanEntity.setDeptScopeName(deptScopeName);
            this.updateById(targetPlanEntity);

//            List<Long> deptScopeIdOldList = StringUtil.stringToLongList(targetPlanOld.getDeptScopeId());
            List<Long> deptScopeIdOldList = StringUtil.stringToLongList(targetQuotaOld.getSubScopeId());
            List<Long> deptScopeIdList = targetPlanScopeSettingDTO.getDeptScopeIdList();

            targetQuotaOld.setSubScopeId(deptScopeId);
            targetQuotaOld.setSubScopeName(deptScopeName);

            // 1、新增的部分
            targetQuotaAddIdList = deptScopeIdList.stream()
                    .filter(id -> !deptScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = deptScopeIdOldList.stream()
                    .filter(id -> !deptScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = deptScopeIdOldList.stream()
                    .filter(deptScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                        //如果是分配，添加分配指标数据
                        BeanUtils.copyProperties(targetQuotaMap.get(3+"-"+id),targetQuotaEntity);
                        targetQuotaEntity.setTotal(targetQuotaEntity.addTotal());
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(3);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());
                    targetQuotaAddListTemp.add(targetQuotaEntity);
                    //获取部门领导id
                    DeptEntity deptEntity = deptService.getById(id);
                    assembleService.sendTargetEventMessages(targetQuotaEntity, "CREATE_GOAL" ,Collections.singleton(deptEntity.getManagerId()),"dept");

                }
                targetQuotaService.saveBatch(targetQuotaAddListTemp);

            }
            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){

                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperC = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getOrganizationalType,3);
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getParentId,targetPlanScopeSettingDTO.getId());
                targetQuotaDelQueryWrapperC.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetQuotaDelListC = targetQuotaService.list(targetQuotaDelQueryWrapperC);
                if (!CollectionUtils.isEmpty(targetQuotaDelListC)){
                    List<Long> deleteIdListC = targetQuotaDelListC.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                    deleteIdList.addAll(deleteIdListC);
                    List<TargetQuotaEntity> targetQuotaDelListD = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListC));
                    if (!CollectionUtils.isEmpty(targetQuotaDelListD)){
                        List<Long> deleteIdListD = targetQuotaDelListD.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                        deleteIdList.addAll(deleteIdListD);
                        Set<Long> userIds = targetQuotaDelListD.stream().filter(e->e.getIsDelete().equals(CommonConstant.DEL_FLAG_0)).map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toSet());
                        assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "ADJUST_DELETE" ,userIds,null);

                    }
                }
                if (!CollectionUtils.isEmpty(deleteIdList)) {
                    targetQuotaService.removeByIds(deleteIdList);
                }
            }
            if (!CollectionUtils.isEmpty(targetQuotaEditIdList)){
                    List<TargetQuotaEntity> targetQuotaEditListTemp = new ArrayList<>();
                    for (Long id : targetQuotaEditIdList){
                        TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                        BeanUtils.copyProperties(targetQuotaMap.get(3+"-"+id),targetQuotaEntity);
                        targetQuotaEntity.setTotal(targetQuotaEntity.addTotal());

                        targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
//                        targetQuotaEntity.setOrganizationalType(3);
//                        targetQuotaEntity.setOrganizationalId(id);
                        targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());

                        targetQuotaEditListTemp.add(targetQuotaEntity);
                        TargetQuotaEntity targetQuotaUpdateOld = targetQuotaService.getById(targetQuotaEntity.getId());
                        if(hasUpdate(targetQuotaUpdateOld,targetQuotaEntity)) {
                            //获取部门领导id
                            DeptEntity deptEntity = deptService.getById(id);
                            assembleService.sendTargetEventMessages(targetQuotaEntity, "ASSIGN_CHANGE_GOAL_VALUE", Collections.singleton(deptEntity.getManagerId()), "dept");
                        }
                    }
                    targetQuotaService.saveOrUpdateBatch(targetQuotaEditListTemp);

            }
//            addQuarterList(targetQuotaOld,targetPlanScopeSettingDTO.getTargetQuotaList());
        }

        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(3)){
            //判断下级是否超过上级总额
            boolean isOver = isOverTotal(targetPlanScopeSettingDTO.getTargetQuotaList(),targetQuotaOld);
            if (isOver){
                return Result.error("下级指标总额不能超过上级指标总额");
            }
            //部门
            String userScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getUserScopeIdList());
            String userScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getUserScopeNameList());
            //获取该公司下的用户信息
            List<Long> userIdList = userService.list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getDeptId,targetQuotaOld.getOrganizationalId())).stream().map(UserEntity::getId).collect(Collectors.toList());
            //重新写入用户id数据
            String userIds = StringUtil.updateStringList(targetPlanOld.getUserScopeId(),userIdList,targetPlanScopeSettingDTO.getUserScopeIdList());
            targetPlanEntity.setUserScopeId(userIds);
//            targetPlanEntity.setUserScopeId(userScopeId);
            targetPlanEntity.setUserScopeName(userScopeName);
            this.updateById(targetPlanEntity);



//            List<Long> userScopeIdOldList = StringUtil.stringToLongList(targetPlanOld.getUserScopeId());
            List<Long> userScopeIdOldList = StringUtil.stringToLongList(targetQuotaOld.getSubScopeId());
            List<Long> userScopeIdList = targetPlanScopeSettingDTO.getUserScopeIdList();

            targetQuotaOld.setSubScopeId(userScopeId);
            targetQuotaOld.setSubScopeName(userScopeName);

            // 1、新增的部分
            targetQuotaAddIdList = userScopeIdList.stream()
                    .filter(id -> !userScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = userScopeIdOldList.stream()
                    .filter(id -> !userScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = userScopeIdOldList.stream()
                    .filter(userScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                        //如果是分配，添加分配指标数据
                        BeanUtils.copyProperties(targetQuotaMap.get(4+"-"+id),targetQuotaEntity);
                        targetQuotaEntity.setTotal(targetQuotaEntity.addTotal());
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(4);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setStatus(1);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());
                    targetQuotaAddListTemp.add(targetQuotaEntity);
                    //获取部门领导id
                    assembleService.sendTargetEventMessages(targetQuotaEntity, "CREATE_GOAL" ,Collections.singleton(id),"person");

                }
                targetQuotaService.saveBatch(targetQuotaAddListTemp);

            }
            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){
                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperC = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getOrganizationalType,4);
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getParentId,targetPlanScopeSettingDTO.getId());
                targetQuotaDelQueryWrapperC.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetQuotaDelListTemp = targetQuotaService.list(targetQuotaDelQueryWrapperC);
                targetQuotaService.remove(targetQuotaDelQueryWrapperC);
                if (!CollectionUtils.isEmpty(targetQuotaDelListTemp)){
                    for (TargetQuotaEntity targetQuotaEntity : targetQuotaDelListTemp){
                        assembleService.sendTargetEventMessages(targetQuotaEntity, "ADJUST_DELETE" ,Collections.singleton(targetQuotaEntity.getOrganizationalId()),"person");
                    }
                }
//                assembleService.sendTargetPlanEventMessages(targetPlanEntity.getId(), "ADJUST_DELETE" ,Collections.singleton(targetPlanScopeSettingDTO.getId()),null);

            }
            if (!CollectionUtils.isEmpty(targetQuotaEditIdList)){
                    List<TargetQuotaEntity> targetQuotaEditListTemp = new ArrayList<>();
                    for (Long id : targetQuotaEditIdList){
                        TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                        BeanUtils.copyProperties(targetQuotaMap.get(4+"-"+id),targetQuotaEntity);
                        targetQuotaEntity.setTotal(targetQuotaEntity.addTotal());
                        targetQuotaEditListTemp.add(targetQuotaEntity);
                        TargetQuotaEntity targetQuotaUpdateOld = targetQuotaService.getById(targetQuotaEntity.getId());
                        if(hasUpdate(targetQuotaUpdateOld,targetQuotaEntity)) {
                            //获取部门领导id
                            assembleService.sendTargetEventMessages(targetQuotaOld, "ASSIGN_CHANGE_GOAL_VALUE", Collections.singleton(id), "person");
                        }
                    }
                    targetQuotaService.saveOrUpdateBatch(targetQuotaEditListTemp);

            }
//            addQuarterList(targetQuotaOld,targetPlanScopeSettingDTO.getTargetQuotaList());

        }
        targetQuotaOld.setStatus(1);
        boolean isOk = targetQuotaService.updateById(targetQuotaOld);
        //更新全部的状态
        updateStatusByTargetPlanId(targetPlanScopeSettingDTO.getTargetPlanId());
        if (isOk){
            return Result.ok();
        }
        return Result.error("业绩目标设置失败！");
    }

    private boolean isOverTotal(List<TargetQuotaEntity> targetQuotaList, TargetQuotaEntity targetQuota) {
        if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter1).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter1()) > 0){
            return true;
        }
        if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter2).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter2()) > 0){
            return true;
        }
        if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter3).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter3()) > 0){
            return true;
        }
        if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter4).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter4()) > 0){
            return true;
        }
        if (!ObjectUtils.isEmpty(targetQuota.getMonthOrQuarter5())) {
            if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter5).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter5()) > 0) {
                return true;
            }
            if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter6).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter6()) > 0) {
                return true;
            }
            if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter7).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter7()) > 0) {
                return true;
            }
            if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter8).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter8()) > 0) {
                return true;
            }
            if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter9).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter9()) > 0) {
                return true;
            }
            if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter10).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter10()) > 0) {
                return true;
            }
            if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter11).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter11()) > 0) {
                return true;
            }
            if (targetQuotaList.stream().map(TargetQuotaEntity::getMonthOrQuarter12).reduce(BigDecimal.ZERO, BigDecimal::add).compareTo(targetQuota.getMonthOrQuarter12()) > 0) {
                return true;
            }
        }
        return false;
    }


    private Result<?> scopeSettingC(TargetPlanScopeSettingDTO targetPlanScopeSettingDTO, TargetPlanEntity targetPlanOld) {
        //认领
        TargetPlanEntity targetPlanEntity = new TargetPlanEntity();

        TargetQuotaEntity targetQuotaOld = targetQuotaService.getById(targetPlanScopeSettingDTO.getId());
        targetPlanEntity.setId(targetPlanScopeSettingDTO.getTargetPlanId());
//        Map<String,TargetQuotaEntity> targetQuotaMap = new HashMap<>();
////        targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().eq(TargetQuotaEntity::getTargetPlanId,targetPlanScopeSettingDTO.getTargetPlanId())).stream().collect(Collectors.toMap(TargetQuotaEntity::getOrganizationalId, targetQuotaEntity -> targetQuotaEntity));
//        if (!CollectionUtils.isEmpty(targetPlanScopeSettingDTO.getTargetQuotaList())){
//            targetQuotaMap = targetPlanScopeSettingDTO.getTargetQuotaList().stream().collect(Collectors.toMap(targetQuotaEntity->targetQuotaEntity.getOrganizationalType()+"-"+targetQuotaEntity.getOrganizationalId(), targetQuotaEntity -> targetQuotaEntity));
//        }
        boolean hasUpdate = hasUpdate(targetQuotaOld,targetPlanScopeSettingDTO.getTargetQuotaList().get(0));
        if (!CollectionUtils.isEmpty(targetPlanScopeSettingDTO.getTargetQuotaList())){
            TargetQuotaEntity targetQuotaNew = targetPlanScopeSettingDTO.getTargetQuotaList().get(0);
            targetQuotaOld.setMonthOrQuarter1(targetQuotaNew.getMonthOrQuarter1());
            targetQuotaOld.setMonthOrQuarter2(targetQuotaNew.getMonthOrQuarter2());
            targetQuotaOld.setMonthOrQuarter3(targetQuotaNew.getMonthOrQuarter3());
            targetQuotaOld.setMonthOrQuarter4(targetQuotaNew.getMonthOrQuarter4());
            targetQuotaOld.setMonthOrQuarter5(targetQuotaNew.getMonthOrQuarter5());
            targetQuotaOld.setMonthOrQuarter6(targetQuotaNew.getMonthOrQuarter6());
            targetQuotaOld.setMonthOrQuarter7(targetQuotaNew.getMonthOrQuarter7());
            targetQuotaOld.setMonthOrQuarter8(targetQuotaNew.getMonthOrQuarter8());
            targetQuotaOld.setMonthOrQuarter9(targetQuotaNew.getMonthOrQuarter9());
            targetQuotaOld.setMonthOrQuarter10(targetQuotaNew.getMonthOrQuarter10());
            targetQuotaOld.setMonthOrQuarter11(targetQuotaNew.getMonthOrQuarter11());
            targetQuotaOld.setMonthOrQuarter12(targetQuotaNew.getMonthOrQuarter12());
            targetQuotaOld.setTotal(targetQuotaNew.addTotal());
        }

//            统计需要新增的公司分配指标
        List<Long> targetQuotaAddIdList = new ArrayList<>();

//            统计需要删除的公司分配指标
        List<Long> targetQuotaDelIdList = new ArrayList<>();

//            统计需要修改的公司分配指标
        List<Long> targetQuotaEditIdList = new ArrayList<>();

        List<Long> deleteIdList = new ArrayList<>();

        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(1)){
            //集团
            String companyScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getCompanyScopeIdList());
            String companyScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getCompanyScopeNameList());
            targetPlanEntity.setCompanyScopeId(companyScopeId);
            targetPlanEntity.setCompanyScopeName(companyScopeName);

            List<Long> companyScopeIdOldList = StringUtil.stringToLongList(targetPlanOld.getCompanyScopeId());
            List<Long> companyScopeIdList = targetPlanScopeSettingDTO.getCompanyScopeIdList();

            targetQuotaOld.setSubScopeId(companyScopeId);
            targetQuotaOld.setSubScopeName(companyScopeName);

            // 1、新增的部分
            targetQuotaAddIdList = companyScopeIdList.stream()
                    .filter(id -> !companyScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = companyScopeIdOldList.stream()
                    .filter(id -> !companyScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = companyScopeIdOldList.stream()
                    .filter(companyScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(2);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());

                    targetQuotaAddListTemp.add(targetQuotaEntity);
                    targetQuotaService.save(targetQuotaEntity);
                    SubCompanyEntity subCompanyEntity = subCompanyService.getById(id);
                    if (Objects.nonNull(subCompanyEntity.getLeaderId())){
                        assembleService.sendTargetEventMessages(targetQuotaEntity, "CREATE_GOAL" ,Collections.singleton(subCompanyEntity.getLeaderId()),"company");
                    }
                }
//                targetQuotaService.saveBatch(targetQuotaAddListTemp);


            }
            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){
                //查询部门id
                List<TargetQuotaEntity> targetMessageQuotaDelListU = new ArrayList<>();
                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperC = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getOrganizationalType,2);
                targetQuotaDelQueryWrapperC.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetQuotaDelListC = targetQuotaService.list(targetQuotaDelQueryWrapperC);
                if (!CollectionUtils.isEmpty(targetQuotaDelListC)){
                    List<Long> deleteIdListC = targetQuotaDelListC.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                    deleteIdList.addAll(deleteIdListC);
                    List<TargetQuotaEntity> targetQuotaDelListD = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListC));
                    if (!CollectionUtils.isEmpty(targetQuotaDelListD)){
                        List<Long> deleteIdListD = targetQuotaDelListD.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                        deleteIdList.addAll(deleteIdListD);
                        List<TargetQuotaEntity> targetQuotaDelListU = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListD));
                        if (!CollectionUtils.isEmpty(targetQuotaDelListU)){
                            List<Long> deleteIdListU = targetQuotaDelListU.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                            targetMessageQuotaDelListU.addAll(targetQuotaDelListU);
                            deleteIdList.addAll(deleteIdListU);
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(deleteIdList)){
                    targetQuotaService.removeByIds(deleteIdList);
                    if (!CollectionUtils.isEmpty(targetMessageQuotaDelListU)){
                        for (TargetQuotaEntity targetQuotaEntity : targetMessageQuotaDelListU){
                            assembleService.sendTargetEventMessages(targetQuotaEntity, "ADJUST_DELETE" ,Collections.singleton(targetQuotaEntity.getOrganizationalId()),"person");
                        }
                    }
                }
            }

                if (!CollectionUtils.isEmpty(targetPlanScopeSettingDTO.getTargetQuotaList())){
                    addQuarter(targetQuotaOld,targetPlanScopeSettingDTO.getTargetQuotaList().get(0));
                }
            targetPlanEntity.setTargetValue(targetQuotaOld.getTotal());
            this.updateById(targetPlanEntity);

        }
        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(2)){
            //公司
            String deptScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getDeptScopeIdList());
            String deptScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getDeptScopeNameList());
            //获取该公司下的部门信息
            List<Long> deptIdList = deptService.list(new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getSubCompanyId,targetQuotaOld.getOrganizationalId())).stream().map(DeptEntity::getId).collect(Collectors.toList());
            //重新写入部门id数据
            String deptIds = StringUtil.updateStringList(targetPlanOld.getDeptScopeId(),deptIdList,targetPlanScopeSettingDTO.getDeptScopeIdList());
            targetPlanEntity.setDeptScopeId(deptIds);
            targetPlanEntity.setDeptScopeName(deptScopeName);
            this.updateById(targetPlanEntity);

//            List<Long> deptScopeIdOldList = StringUtil.stringToLongList(targetPlanOld.getDeptScopeId());
            List<Long> deptScopeIdOldList = StringUtil.stringToLongList(targetQuotaOld.getSubScopeId());
            List<Long> deptScopeIdList = targetPlanScopeSettingDTO.getDeptScopeIdList();

            targetQuotaOld.setSubScopeId(deptScopeId);
            targetQuotaOld.setSubScopeName(deptScopeName);

            // 1、新增的部分
            targetQuotaAddIdList = deptScopeIdList.stream()
                    .filter(id -> !deptScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = deptScopeIdOldList.stream()
                    .filter(id -> !deptScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = deptScopeIdOldList.stream()
                    .filter(deptScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(3);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());
                    targetQuotaAddListTemp.add(targetQuotaEntity);
                    targetQuotaService.save(targetQuotaEntity);

                    //发给部门领导
//                    123
                    DeptEntity deptEntity = deptService.getById(id);
                    if (!ObjectUtils.isEmpty(deptEntity.getManagerId())){
                        assembleService.sendTargetEventMessages(targetQuotaEntity, "CREATE_GOAL" ,Collections.singleton(deptEntity.getManagerId()),"dept");
                    }

                }
//                targetQuotaService.saveBatch(targetQuotaAddListTemp);

            }
            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){

                List<TargetQuotaEntity> targetMessageQuotaDelListU = new ArrayList<>();
                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperC = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getOrganizationalType,3);
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getParentId,targetPlanScopeSettingDTO.getId());
                targetQuotaDelQueryWrapperC.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetQuotaDelListC = targetQuotaService.list(targetQuotaDelQueryWrapperC);
                if (!CollectionUtils.isEmpty(targetQuotaDelListC)){
                    List<Long> deleteIdListC = targetQuotaDelListC.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                    deleteIdList.addAll(deleteIdListC);
                    List<TargetQuotaEntity> targetQuotaDelListD = targetQuotaService.list(new LambdaQueryWrapper<TargetQuotaEntity>().in(TargetQuotaEntity::getParentId,deleteIdListC));
                    if (!CollectionUtils.isEmpty(targetQuotaDelListD)){
                        List<Long> deleteIdListD = targetQuotaDelListD.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
                        deleteIdList.addAll(deleteIdListD);
                        targetMessageQuotaDelListU.addAll(targetQuotaDelListD);
                    }
                }
                if (!CollectionUtils.isEmpty(deleteIdList)) {
                    targetQuotaService.removeByIds(deleteIdList);
                    if (!CollectionUtils.isEmpty(targetMessageQuotaDelListU)){
                        for (TargetQuotaEntity targetQuotaEntity : targetMessageQuotaDelListU){
                            assembleService.sendTargetEventMessages(targetQuotaEntity, "ADJUST_DELETE" ,Collections.singleton(targetQuotaEntity.getOrganizationalId()),"person");
                        }
                    }
                }
            }
//            if (!CollectionUtils.isEmpty(targetQuotaEditIdList)){
//                List<TargetQuotaEntity> targetQuotaEditListTemp = new ArrayList<>();
//                for (Long id : targetQuotaEditIdList){
//                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
//                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
//                    targetQuotaEntity.setOrganizationalType(3);
//                    targetQuotaEntity.setOrganizationalId(id);
//                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());
//                    targetQuotaEditListTemp.add(targetQuotaEntity);
//                }
//                targetQuotaService.saveBatch(targetQuotaEditListTemp);
//            }

//            if(hasUpdate) {
//                //获取集团领导id
////                TargetQuotaEntity targetQuotaParentEntity = targetQuotaService.getById(targetQuotaOld.getParentId());
////                assembleService.sendTargetEventMessages(targetQuotaParentEntity, "CLAIM_CHANGE_GOAL_VALUE", Collections.singleton(202L), "group");
//            }
        }

        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(3)){
            //部门
            String userScopeId = StringUtil.longListToString(targetPlanScopeSettingDTO.getUserScopeIdList());
            String userScopeName = StringUtil.stringListToString(targetPlanScopeSettingDTO.getUserScopeNameList());
            //获取该公司下的用户信息
            List<Long> userIdList = userService.list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getDeptId,targetQuotaOld.getOrganizationalId())).stream().map(UserEntity::getId).collect(Collectors.toList());
            //重新写入用户id数据
            String userIds = StringUtil.updateStringList(targetPlanOld.getUserScopeId(),userIdList,targetPlanScopeSettingDTO.getUserScopeIdList());
            targetPlanEntity.setUserScopeId(userIds);
//            targetPlanEntity.setUserScopeId(userScopeId);
            targetPlanEntity.setUserScopeName(userScopeName);
            this.updateById(targetPlanEntity);

//            List<Long> userScopeIdOldList = StringUtil.stringToLongList(targetPlanOld.getUserScopeId());
            List<Long> userScopeIdOldList = StringUtil.stringToLongList(targetQuotaOld.getSubScopeId());
            List<Long> userScopeIdList = targetPlanScopeSettingDTO.getUserScopeIdList();

            targetQuotaOld.setSubScopeId(userScopeId);
            targetQuotaOld.setSubScopeName(userScopeName);

            // 1、新增的部分
            targetQuotaAddIdList = userScopeIdList.stream()
                    .filter(id -> !userScopeIdOldList.contains(id))
                    .collect(Collectors.toList());
            // 2、删除的部分
            targetQuotaDelIdList = userScopeIdOldList.stream()
                    .filter(id -> !userScopeIdList.contains(id))
                    .collect(Collectors.toList());
            // 3、修改的部分
            targetQuotaEditIdList = userScopeIdOldList.stream()
                    .filter(userScopeIdList::contains)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(targetQuotaAddIdList)){
                List<TargetQuotaEntity> targetQuotaAddListTemp = new ArrayList<>();
                for (Long id : targetQuotaAddIdList){
                    TargetQuotaEntity targetQuotaEntity = new TargetQuotaEntity();
                    targetQuotaEntity.setTargetPlanId(targetPlanOld.getId());
                    targetQuotaEntity.setOrganizationalType(4);
                    targetQuotaEntity.setOrganizationalId(id);
                    targetQuotaEntity.setParentId(targetPlanScopeSettingDTO.getId());
                    targetQuotaAddListTemp.add(targetQuotaEntity);
                    targetQuotaService.save(targetQuotaEntity);
                    assembleService.sendTargetEventMessages(targetQuotaEntity, "CREATE_GOAL" ,Collections.singleton(id),"person");
                }
//                targetQuotaService.saveBatch(targetQuotaAddListTemp);

            }
            if (!CollectionUtils.isEmpty(targetQuotaDelIdList)){
                LambdaQueryWrapper<TargetQuotaEntity> targetQuotaDelQueryWrapperC = new LambdaQueryWrapper<>();
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getTargetPlanId,targetPlanOld.getId());
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getOrganizationalType,4);
                targetQuotaDelQueryWrapperC.eq(TargetQuotaEntity::getParentId,targetPlanScopeSettingDTO.getId());
                targetQuotaDelQueryWrapperC.in(TargetQuotaEntity::getOrganizationalId,targetQuotaDelIdList);
                List<TargetQuotaEntity> targetMessageQuotaDelListU = targetQuotaService.list(targetQuotaDelQueryWrapperC);
                targetQuotaService.remove(targetQuotaDelQueryWrapperC);
                if (!CollectionUtils.isEmpty(targetMessageQuotaDelListU)){
                    for (TargetQuotaEntity targetQuotaEntity : targetMessageQuotaDelListU){
                        if (targetQuotaEntity.getIsDelete()==CommonConstant.DEL_FLAG_0){
                            assembleService.sendTargetEventMessages(targetQuotaEntity, "ADJUST_DELETE" ,Collections.singleton(targetQuotaEntity.getOrganizationalId()),"person");
                        }

                    }
                }
            }

            //获取集团领导id
            if(hasUpdate) {
                TargetQuotaEntity targetQuotaParentEntity = targetQuotaService.getById(targetQuotaOld.getParentId());
                SubCompanyEntity subCompanyEntity = subCompanyService.getById(targetQuotaParentEntity.getOrganizationalId());
                assembleService.sendTargetEventMessages(targetQuotaParentEntity, "CLAIM_CHANGE_GOAL_VALUE", Collections.singleton(subCompanyEntity.getLeaderId()), "company");
            }

        }
        if (targetPlanScopeSettingDTO.getOrganizationalType().equals(4)){
            //获取集团领导id
            if(hasUpdate) {
                TargetQuotaEntity targetQuotaParentEntity = targetQuotaService.getById(targetQuotaOld.getParentId());
                DeptEntity dept = deptService.getById(targetQuotaParentEntity.getOrganizationalId());
                assembleService.sendTargetEventMessages(targetQuotaParentEntity, "CLAIM_CHANGE_GOAL_VALUE", Collections.singleton(dept.getManagerId()), "dept");
            }
        }

        targetQuotaOld.setStatus(1);
        boolean isOk = targetQuotaService.updateById(targetQuotaOld);
        //更新全部的状态
        updateStatusByTargetPlanId(targetPlanScopeSettingDTO.getTargetPlanId());
        if (isOk){
            return Result.ok();
        }
        return Result.error("业绩目标设置失败！");
    }

    private void updateStatusByTargetPlanId(Long targetPlanId) {
        //获取目标方案
        TargetPlanEntity targetPlan = this.getById(targetPlanId);
        LambdaQueryWrapper<TargetQuotaEntity> targetQuotaQueryWrapper = new LambdaQueryWrapper<>();
        targetQuotaQueryWrapper.eq(TargetQuotaEntity::getTargetPlanId,targetPlanId);
        targetQuotaQueryWrapper.eq(TargetQuotaEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        List<TargetQuotaEntity> targetQuotaList = targetQuotaService.list(targetQuotaQueryWrapper);
        if (CollectionUtils.isEmpty(targetQuotaList)){
            return;
        }
        List<TargetQuotaEntity> userQuotaList = targetQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getOrganizationalType().equals(4)).collect(Collectors.toList());
        List<TargetQuotaEntity> deptQuotaList = targetQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getOrganizationalType().equals(3)).collect(Collectors.toList());
        List<TargetQuotaEntity> subCompanyQuotaList = targetQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getOrganizationalType().equals(2)).collect(Collectors.toList());
        List<TargetQuotaEntity> companyQuotaList = targetQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getOrganizationalType().equals(1)).collect(Collectors.toList());

        if (targetPlan.getMethod()==1){
            //要更改状态的id列表
            List<Long> targetQuotaIdList = new ArrayList<>();
            //汇总
            //目标中的集团全部子级状态为1，公司子级全部状态为1，部门子级全部状态为1
            List<Long> userIdList = userQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getStatus().equals(1)).map(e->e.getOrganizationalId()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(userIdList)){
                return;
            }
            List<Long> deptUpdateIdList = new ArrayList<>();
            for (TargetQuotaEntity targetQuotaEntity : deptQuotaList){
                String subScopeId = targetQuotaEntity.getSubScopeId();
//                List<Long> subScopeIdList = StringUtil.stringToStringList(subScopeId);
                //如果subScopeIdList和userIdList一致，则修改状态为1
                if (StringUtil.containsAllIds(userIdList,subScopeId)){
                    targetQuotaIdList.add(targetQuotaEntity.getId());
                    deptUpdateIdList.add(targetQuotaEntity.getOrganizationalId());
                }
            }
            if (CollectionUtils.isEmpty(deptUpdateIdList)){
                return;
            }

            List<Long> subCompanyUpdateIdList = new ArrayList<>();
            for (TargetQuotaEntity targetQuotaEntity : subCompanyQuotaList){
                String subScopeId = targetQuotaEntity.getSubScopeId();
                List<Long> subScopeIdList = StringUtil.stringToStringList(subScopeId);
                //如果subScopeIdList和deptUpdateIdList一致，则修改状态为1
                if (StringUtil.containsAllIds(deptUpdateIdList,subScopeId)){
//                if (subScopeIdList.containsAll(deptUpdateIdList) && deptUpdateIdList.containsAll(subScopeIdList)){
                    targetQuotaIdList.add(targetQuotaEntity.getId());
                    subCompanyUpdateIdList.add(targetQuotaEntity.getOrganizationalId());
                }
            }
            if (CollectionUtils.isEmpty(subCompanyUpdateIdList)){
                LambdaUpdateWrapper<TargetQuotaEntity> targetQuotaUpdateWrapper = new LambdaUpdateWrapper<>();
                targetQuotaUpdateWrapper.in(TargetQuotaEntity::getId,targetQuotaIdList);
                targetQuotaUpdateWrapper.set(TargetQuotaEntity::getStatus,1);
                targetQuotaService.update(targetQuotaUpdateWrapper);
                return;
            }

            for (TargetQuotaEntity targetQuotaEntity : companyQuotaList){
                String subScopeId = targetQuotaEntity.getSubScopeId();
                List<Long> subScopeIdList = StringUtil.stringToStringList(subScopeId);
                //如果subScopeIdList和deptUpdateIdList一致，则修改状态为1
                if (StringUtil.containsAllIds(subCompanyUpdateIdList,subScopeId)){
//                if (subScopeIdList.containsAll(subCompanyUpdateIdList) && subCompanyUpdateIdList.containsAll(subScopeIdList)){
                    targetQuotaIdList.add(targetQuotaEntity.getId());
                    //修改总状态
                    targetPlan.setStatus(1);
                    this.updateById(targetPlan);
                }
            }
            if (CollectionUtils.isEmpty(targetQuotaIdList)){
                return;
            }
            LambdaUpdateWrapper<TargetQuotaEntity> targetQuotaUpdateWrapper = new LambdaUpdateWrapper<>();
            targetQuotaUpdateWrapper.in(TargetQuotaEntity::getId,targetQuotaIdList);
            targetQuotaUpdateWrapper.set(TargetQuotaEntity::getStatus,1);
            targetQuotaService.update(targetQuotaUpdateWrapper);
        }
        if (targetPlan.getMethod()==2){
            //分配
            if (CollectionUtils.isEmpty(userQuotaList) || CollectionUtils.isEmpty(deptQuotaList) || CollectionUtils.isEmpty(subCompanyQuotaList) || CollectionUtils.isEmpty(companyQuotaList)){
                return;
            }
            List<Long> deptIdList = deptQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getStatus().equals(0)).map(e->e.getOrganizationalId()).collect(Collectors.toList());
            List<Long> subCompanyIdList = subCompanyQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getStatus().equals(0)).map(e->e.getOrganizationalId()).collect(Collectors.toList());
            List<Long> companyIdList = companyQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getStatus().equals(0)).map(e->e.getOrganizationalId()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(deptIdList) && CollectionUtils.isEmpty(subCompanyIdList) && CollectionUtils.isEmpty(companyIdList)){
                //修改总状态
                targetPlan.setStatus(1);
                this.updateById(targetPlan);
            }

        }
        if (targetPlan.getMethod()==3){
            //认领
            boolean hasComplete = false;
            List<TargetQuotaEntity> targetCompleteList = targetQuotaList.stream().filter(targetQuotaEntity -> targetQuotaEntity.getStatus().equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(targetCompleteList)){
                return;
            }
            if (targetQuotaList.size() == targetCompleteList.size()){
                //修改总状态
                targetPlan.setStatus(1);
                this.updateById(targetPlan);
            }
        }

    }

    private void addQuarter(TargetQuotaEntity targetQuotaOld, TargetQuotaEntity targetQuotaEntity0) {
        targetQuotaOld.setMonthOrQuarter1(targetQuotaEntity0.getMonthOrQuarter1());
        targetQuotaOld.setMonthOrQuarter2(targetQuotaEntity0.getMonthOrQuarter2());
        targetQuotaOld.setMonthOrQuarter3(targetQuotaEntity0.getMonthOrQuarter3());
        targetQuotaOld.setMonthOrQuarter4(targetQuotaEntity0.getMonthOrQuarter4());
        targetQuotaOld.setMonthOrQuarter5(targetQuotaEntity0.getMonthOrQuarter5());
        targetQuotaOld.setMonthOrQuarter6(targetQuotaEntity0.getMonthOrQuarter6());
        targetQuotaOld.setMonthOrQuarter7(targetQuotaEntity0.getMonthOrQuarter7());
        targetQuotaOld.setMonthOrQuarter8(targetQuotaEntity0.getMonthOrQuarter8());
        targetQuotaOld.setMonthOrQuarter9(targetQuotaEntity0.getMonthOrQuarter9());
        targetQuotaOld.setMonthOrQuarter10(targetQuotaEntity0.getMonthOrQuarter10());
        targetQuotaOld.setMonthOrQuarter11(targetQuotaEntity0.getMonthOrQuarter11());
        targetQuotaOld.setMonthOrQuarter11(targetQuotaEntity0.getMonthOrQuarter11());
        targetQuotaOld.setMonthOrQuarter12(targetQuotaEntity0.getMonthOrQuarter12());
        targetQuotaOld.setTotal(targetQuotaEntity0.addTotal());
    }

    private void addQuarterList(TargetQuotaEntity targetQuotaOld, List<TargetQuotaEntity> targetQuotaList) {
        BigDecimal monthOrQuarter1 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter2 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter3 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter4 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter5 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter6 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter7 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter8 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter9 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter10 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter11 = BigDecimal.ZERO;
        BigDecimal monthOrQuarter12 = BigDecimal.ZERO;
        BigDecimal total = BigDecimal.ZERO;

        for (TargetQuotaEntity targetQuota : targetQuotaList){
            if (targetQuota.getMonthOrQuarter1() != null) {
                monthOrQuarter1 = monthOrQuarter1.add(targetQuota.getMonthOrQuarter1());
            }
            if (targetQuota.getMonthOrQuarter2() != null) {
                monthOrQuarter2 = monthOrQuarter2.add(targetQuota.getMonthOrQuarter2());
            }
            if (targetQuota.getMonthOrQuarter3() != null) {
                monthOrQuarter3 = monthOrQuarter3.add(targetQuota.getMonthOrQuarter3());
            }
            if (targetQuota.getMonthOrQuarter4() != null) {
                monthOrQuarter4 = monthOrQuarter4.add(targetQuota.getMonthOrQuarter4());
            }
            if (targetQuota.getMonthOrQuarter5() != null) {
                monthOrQuarter5 = monthOrQuarter5.add(targetQuota.getMonthOrQuarter5());
            }
            if (targetQuota.getMonthOrQuarter6() != null) {
                monthOrQuarter6 = monthOrQuarter6.add(targetQuota.getMonthOrQuarter6());
            }
            if (targetQuota.getMonthOrQuarter7() != null) {
                monthOrQuarter7 = monthOrQuarter7.add(targetQuota.getMonthOrQuarter7());
            }
            if (targetQuota.getMonthOrQuarter8() != null) {
                monthOrQuarter8 = monthOrQuarter8.add(targetQuota.getMonthOrQuarter8());
            }
            if (targetQuota.getMonthOrQuarter9() != null) {
                monthOrQuarter9 = monthOrQuarter9.add(targetQuota.getMonthOrQuarter9());
            }
            if (targetQuota.getMonthOrQuarter10() != null) {
                monthOrQuarter10 = monthOrQuarter10.add(targetQuota.getMonthOrQuarter10());
            }
            if (targetQuota.getMonthOrQuarter11() != null) {
                monthOrQuarter11 = monthOrQuarter11.add(targetQuota.getMonthOrQuarter11());
            }
            if (targetQuota.getMonthOrQuarter12() != null) {
                monthOrQuarter12 = monthOrQuarter12.add(targetQuota.getMonthOrQuarter12());
            }
            targetQuotaOld.setMonthOrQuarter1(monthOrQuarter1);
            targetQuotaOld.setMonthOrQuarter2(monthOrQuarter2);
            targetQuotaOld.setMonthOrQuarter3(monthOrQuarter3);
            targetQuotaOld.setMonthOrQuarter4(monthOrQuarter4);
            targetQuotaOld.setMonthOrQuarter5(monthOrQuarter5);
            targetQuotaOld.setMonthOrQuarter6(monthOrQuarter6);
            targetQuotaOld.setMonthOrQuarter7(monthOrQuarter7);
            targetQuotaOld.setMonthOrQuarter8(monthOrQuarter8);
            targetQuotaOld.setMonthOrQuarter9(monthOrQuarter9);
            targetQuotaOld.setMonthOrQuarter10(monthOrQuarter10);
            targetQuotaOld.setMonthOrQuarter11(monthOrQuarter11);
            targetQuotaOld.setMonthOrQuarter12(monthOrQuarter12);
            targetQuotaOld.setTotal(targetQuotaOld.addTotal());
        }
    }

    @Override
    public List<Long> getTargetPlanId(TargetRankingDTO targetRankingDTO) {
        LambdaQueryWrapper<TargetPlanEntity> targetWrapper = new LambdaQueryWrapper();
        targetWrapper.eq(TargetPlanEntity::getType, targetRankingDTO.getType());
        targetWrapper.eq(TargetPlanEntity::getYear, targetRankingDTO.getYear());
        targetWrapper.eq(TargetPlanEntity::getIsDelete, 0);
        List<TargetPlanEntity> targetPlanEntities = baseMapper.selectList(targetWrapper);
        //获取符合条件的目标方案id
        List<Long> idList = new ArrayList<>();
        for (TargetPlanEntity entity : targetPlanEntities) {
            idList.add(entity.getId());
        }
        // 如果idList为空，则返回null
        return idList.isEmpty() ? null : idList;
    }

    @Override
    public Result<?> selectListVO(TargetPlanSearchDTO targetPlanSearchDTO) {
        IPage<TargetPlanListVO> pageVO = new Page<>(targetPlanSearchDTO.getPageIndex(), targetPlanSearchDTO.getPageSize());

        IPage<TargetPlanEntity> page = new Page<>(targetPlanSearchDTO.getPageIndex(), targetPlanSearchDTO.getPageSize());
        LambdaQueryWrapper<TargetPlanEntity> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(TargetPlanEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(!ObjectUtils.isEmpty(targetPlanSearchDTO.getId()), TargetPlanEntity::getId, targetPlanSearchDTO.getId());
        wrapper.eq(!ObjectUtils.isEmpty(targetPlanSearchDTO.getYear()), TargetPlanEntity::getYear, targetPlanSearchDTO.getYear());
        wrapper.eq(!ObjectUtils.isEmpty(targetPlanSearchDTO.getMethod()), TargetPlanEntity::getMethod, targetPlanSearchDTO.getMethod());
        wrapper.eq(!ObjectUtils.isEmpty(targetPlanSearchDTO.getCycle()), TargetPlanEntity::getCycle, targetPlanSearchDTO.getCycle());
        wrapper.eq(!ObjectUtils.isEmpty(targetPlanSearchDTO.getType()), TargetPlanEntity::getType, targetPlanSearchDTO.getType());
        IPage<TargetPlanEntity> pageList = this.pageWithScope(page, wrapper,targetPlanSearchDTO,"");
        if (CollectionUtils.isEmpty(pageList.getRecords())){
            return Result.result(pageList);
        }
        //复制list给VO类
        pageVO = SysBaseField.page(page, TargetPlanListVO.class);
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        return Result.result(pageVO);
    }

    @Override
    public Result<?> getTargetPlanVOById(Long id) {
        if (ObjectUtils.isEmpty(id)){
            return Result.error("参数错误！");
        }
        TargetPlanEntity targetPlanEntity = baseMapper.selectById(id);
        if (!ObjectUtils.isEmpty(targetPlanEntity)){
            TargetPlanDetailVO targetPlanVO = new TargetPlanDetailVO();
            BeanUtils.copyProperties(targetPlanEntity,targetPlanVO);
            SysBaseField.dictFiled(targetPlanVO);
            SysBaseField.orgFileds(targetPlanVO);
            return Result.result(targetPlanVO);
        }
        return null;
    }
}
