package cn.wisenergy.service.impl;

import cn.wisenergy.common.utils.DateUtil;
import cn.wisenergy.common.utils.StringUtil;
import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import cn.wisenergy.mapper.*;
import cn.wisenergy.model.app.*;
import cn.wisenergy.model.dto.*;
import cn.wisenergy.model.enums.LevelEnum;
import cn.wisenergy.model.enums.LevelRankEnum;
import cn.wisenergy.model.enums.ManagerEnum;
import cn.wisenergy.model.vo.CreateProjectVo;
import cn.wisenergy.model.vo.GetManagerProjectsVo;
import cn.wisenergy.model.vo.ModifyProjectVo;
import cn.wisenergy.oaModel.OaProject;
import cn.wisenergy.oaService.OaProjectService;
import cn.wisenergy.service.*;
import cn.wisenergy.service.utils.UserRoleLevelUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenqi
 * @since 2021-01-19
 */
@Service
@Slf4j
public class WorkProjectServiceImpl implements WorkProjectService {

    @Autowired
    private WorkProjectMapper workProjectMapper;

    @Autowired
    private WorkUserService workUserService;

    @Autowired
    private WorkDeptMapper workDeptMapper;

    @Autowired
    private WorkDeptService workDeptService;

    @Autowired
    private WorkCentreMapper workCentreMapper;

    @Autowired
    private WorkUserProjectService workUserProjectService;

    @Autowired
    private WorkProjectChangeService workProjectChangeService;

    @Autowired
    private WorkTypeService workTypeService;

    @Autowired
    private WorkProjectChangeMapper workProjectChangeMapper;

    @Autowired
    private OaProjectService oaProjectService;

    @Autowired
    private WorkUserMapper workUserMapper;

    @Autowired
    private WorkTimeOrderMapper workTimeOrderMapper;

    // 项目编号
    private static final Integer PROJECT_CODE = 1;

    // 商机编号
    private static final Integer BO_CODE = 2;

    /**
     * 功能：根据项目id获取项目
     *
     * @param id 项目id
     * @return WorkProject
     */
    @Override
    public WorkProject getById(Integer id) {
        log.info("WorkProjectServiceImpl[]getById[]input.param.id:" + id);
        if (null == id) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        WorkProject workProject = workProjectMapper.selectById(id);
        if (null == workProject) {
            return null;
        }
        return workProject;
    }

    @Override
    public List<WorkProject> getNameByIds(List<Integer> ids, Integer isConclusion) {
        log.info("WorkProjectServiceImpl[]getNameById[]input.param.ids:" + ids);
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        List<WorkProject> workProjects = workProjectMapper.getProjectsByIds(ids, isConclusion);
        if (CollectionUtils.isEmpty(workProjects)) {
            return null;
        }
        return workProjects;
    }

    /**
     * 功能： 查询当前用户所管理的项目
     *
     * @param id 用户id
     * @return dto
     */
    @Override
    public List<ProjectDto> getByManagerId(Integer id, Integer isConclusion) {
        log.info("WorkProjectServiceImpl[]getByManagerId[]input.param.id:" + id);
        if (null == id) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        QueryWrapper<WorkProject> wrapper = new QueryWrapper<>();
        wrapper.eq(id != null, "manager_id", id);
        wrapper.eq(isConclusion != null, "is_conclusion", isConclusion);
        List<WorkProject> workProjects = workProjectMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(workProjects)) {
            return workProjectToDto(workProjects);
        }
        return null;
    }

    /**
     * WorkProject转ProjectDto
     */
    private List<ProjectDto> workProjectToDto(List<WorkProject> workProjects) {
        List<ProjectDto> projectDtos = new ArrayList<>();

        for (WorkProject workProject : workProjects) {
            ProjectDto projectDto = new ProjectDto();
            BeanUtils.copyProperties(workProject, projectDto);
            projectDtos.add(projectDto);
        }

        return projectDtos;
    }


    @Override
    public List<WorkProject> getUserManageProjects(Integer userId) {
        log.info("WorkProjectServiceImpl[]getUserManageProjects[]input.param" + userId);
        if (userId == null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        WorkUser user = workUserService.getById(userId);
        List<Integer> role = UserRoleLevelUtils.getRole(user.getId());
        //普通用户
        if (role.contains(ManagerEnum.NOT_MANAGER.getCode())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }
        //存放项目列表
        List<WorkProject> workProjects;
        //存放查询条件
        HashMap<String, Object> map = new HashMap<>();

        // 查询项目表中管理为用户的项目集合，
        map.put("managerId", userId);
        //用户是部门级别，查询该部门下的所有项目
        if (role.contains(ManagerEnum.IS_DEPARTMENT_DIRECTOR.getCode())) {
            map.remove("managerId");
            map.put("deptId", user.getDeptId());
        }
        //中心级别的用户查看中心下所有部门的所有项目
        if (role.contains(ManagerEnum.IS_CENTRE_DIRECTOR.getCode())) {
            //获取中心信息
            WorkCentre workCentre = workCentreMapper.getByManagerId(user.getId());
            if (workCentre == null) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.CENTRE_NOT_FOUND);
            }
            map.put("centreId", workCentre.getId());
            //获取中心下的部门信息
            List<WorkDept> workDepts = workDeptMapper.getDeptByCondition(map);
            if (CollectionUtils.isEmpty(workDepts)) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.DEPT_NOT_FOUND);
            }
            //获取这些部门的主键
            List<Integer> deptIds = workDepts.stream().map(WorkDept::getId).collect(Collectors.toList());
            map.clear();
            map.put("deptIds", deptIds);
        }
        workProjects = workProjectMapper.getProjectsByCriteria(map);

        return workProjects;
    }

    @Override
    public PageInfo getManagerProjects(GetManagerProjectsVo gmpv) {
        log.info("WorkProjectServiceImpl[]getManagerProjects[]input.param.GetManagerProjectsVo:{}" + gmpv);
        if (null == gmpv) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        // 判断user是否是管理
        WorkUser user = workUserService.getById(gmpv.getUserId());
        if (null == user) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.QUERY_USER_INFO_FAIL);
        }

        // 判断用户权限
        if (!UserRoleLevelUtils.isManagerLevel(gmpv.getUserId(), LevelEnum.PROJECT_MANAGER.getLevelName())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }
        List<UserRoleLevelDto> roleUserLevel = UserRoleLevelUtils.getRoleUserLevel(gmpv.getUserId());
        if (CollectionUtils.isEmpty(roleUserLevel)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }

        int projectIndex = 0;
        int deptAndManager = 0;
        for (UserRoleLevelDto userRoleLevelDto : roleUserLevel) {
            if (LevelEnum.PROJECT_MANAGER.getLevelName().equals(userRoleLevelDto.getLevelName())) {
                if (LevelRankEnum.PROJECT_LEVEL.getRank().equals(userRoleLevelDto.getRank())) {
                    projectIndex++;
                }
                if (LevelRankEnum.DEPARTMENT_LEVEL.getRank().equals(userRoleLevelDto.getRank()) || LevelRankEnum.CENTRAL_LEVEL.getRank().equals(userRoleLevelDto.getRank()) || LevelRankEnum.SYSTEM_MANAGER.getRank().equals(userRoleLevelDto.getRank())) {
                    deptAndManager++;
                }
                if (LevelRankEnum.DEPARTMENT_LEVEL.getRank().equals(userRoleLevelDto.getRank())) {
                    if (null != gmpv.getDeptId() && !user.getDeptId().equals(gmpv.getDeptId())) {
                        int isCentre = 0;
                        for (UserRoleLevelDto roleLevelDto : roleUserLevel) {
                            if (LevelEnum.PROJECT_MANAGER.getLevelName().equals(roleLevelDto.getLevelName())) {
                                if (LevelRankEnum.CENTRAL_LEVEL.getRank().equals(roleLevelDto.getRank())) {
                                    isCentre++;
                                }
                            }
                        }
                        if (isCentre == 0) {
                            deptAndManager -= 1;
                        }
                    }
                }
            }
        }
        if (projectIndex == 0) {
            user.setId(null);
        }

        int page = gmpv.getPage() == null ? 1 : gmpv.getPage();
        int pageSize = gmpv.getPageSize() == null ? 10 : gmpv.getPageSize();
        Integer isConclusion = gmpv.getIsConclusion();
        List<ManagerProjectsDto> managerProjectsDto;

        List<Integer> deptIds = new ArrayList<>();
        if (null == gmpv.getDeptId()) {
            List<WorkDept> workdepts = workDeptService.getDeptOfProjectOfManager(gmpv.getUserId());
            workdepts.forEach(workdept -> deptIds.add(workdept.getId()));
        } else {
            deptIds.add(gmpv.getDeptId());
        }
        PageHelper.startPage(page, pageSize);
        managerProjectsDto = workProjectMapper.getManagerProjectsDto(user.getId(), gmpv.getType(), isConclusion, deptIds, gmpv.getKey(), deptAndManager);
        return returnPageInfo(managerProjectsDto);

    }

    /**
     * 结束项目/商机
     *
     * @param userId    管理id
     * @param projectId 项目/商机id
     * @return 布尔值
     */
    @Transactional
    @Override
    public Boolean endProject(Integer userId, Integer projectId) {
        log.info("WorkProjectServiceImpl[]endProject[]input.param.userId：{},projectId:{}" + userId, projectId);
        if (!UserRoleLevelUtils.isManagerLevel(userId, LevelEnum.PROJECT_MANAGER.getLevelName())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }
        if (null == projectId) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        WorkProject workProject = workProjectMapper.selectById(projectId);
        if (null == workProject) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_PROJECT_IS_NULL);
        }

        //判断项目是否存在为审批工时
        List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.selectProjectIsEnd(projectId);
        if (workTimeOrders.size()!=0){
            return false;
        }
        workProjectMapper.updateIsConclusionById(projectId);

        // 插入更变日志
        List<WorkProjectChange> workProjectChanges = new ArrayList<>();
        WorkProjectChange workProjectChange = new WorkProjectChange();
        workProjectChange.setProjectId(projectId);
        workProjectChange.setReviserId(userId);
        workProjectChange.setModifyTime(new Date());
        workProjectChange.setOperationType(3);
        workProjectChanges.add(workProjectChange);
        workProjectChangeService.insertbatch(workProjectChanges);

        return true;
    }

    @Transactional
    @Override
    public Boolean modifyProject(ModifyProjectVo modifyProjectVo) {
        log.info("WorkProjectServiceImpl[]modifyProject[]input.param.ModifyProjectVo：{}" + modifyProjectVo);
        // 1.验证项目信息
        if (null == modifyProjectVo) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        // 查询原项目
        WorkProject workProject = workProjectMapper.selectById(modifyProjectVo.getProjectId());
        if (null == workProject) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_PROJECT_IS_NULL);
        }
        // 查询当前项目的人员
        List<UserProjectDto> users = workUserProjectService.getUserProjectByProjectId(modifyProjectVo.getProjectId());
        List<Integer> userIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(users)) {
            for (UserProjectDto user : users) {
                userIds.add(user.getId());
            }
        }

        // 判断oa编号、项目名称是否重复,
        List<WorkProject> workProjects = workProjectMapper.selectList(new QueryWrapper<>());
        if (CollectionUtils.isEmpty(workProjects)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_PROJECT_IS_NULL);
        }
        for (WorkProject workProject1 : workProjects) {
            if (modifyProjectVo.getProjectId().equals(workProject.getId())) {
                continue;
            }
            if (modifyProjectVo.getOaProjectId().equals(workProject1.getOaProjectId())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.ITEMOADUPLICATE);
            }
        }

        // 判断对应商机名称和编号是否在oa中存在
        if (StringUtils.isNotBlank(modifyProjectVo.getBusinessId()) || StringUtils.isNotBlank(modifyProjectVo.getBusinessName())) {
            OaProject oaProject = oaProjectService.getByNameAndNo(modifyProjectVo);
            if (oaProject == null) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.PROJECT_OA_INFO_NOT_FIND);
            }
        }

        // 项目对应商机名称不为空，去掉前后空格和制表符
        if (StringUtils.isNotBlank(modifyProjectVo.getBusinessName())) {
            modifyProjectVo.setBusinessName(StringUtil.replaceBlank(modifyProjectVo.getBusinessName()));
        }



        // 验证项目
//        verificationItem(modifyProjectVo, workProject, userIds);

        // 2.更新表数据

        // 更新workProject数据

        int i = workProjectMapper.updateProject(modifyProjectVo);
        if (i == 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.UPDATE_DATA_FAIL);
        }
        // 向workProjectChange插入内容
        List<WorkProjectChange> workProjectChanges = new ArrayList<>();
        if (!StringUtils.isBlank(modifyProjectVo.getOaProjectIdReason())) {
            if (StringUtils.isBlank(modifyProjectVo.getOaProjectId())) {
                throw new BaseCustomException("666", "请填写项目/商机编号");
            }
            if (!StringUtils.isBlank(workProject.getOaProjectId())) {
                if (modifyProjectVo.getOaProjectId().equals(workProject.getOaProjectId())) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
                }
            }
            WorkProjectChange workProjectChange = new WorkProjectChange();
            workProjectChange.setProjectId(modifyProjectVo.getProjectId());
            workProjectChange.setModifyTime(new Date());
            workProjectChange.setChangeType(8);
            workProjectChange.setModifyBefore(workProject.getOaProjectId());
            workProjectChange.setModifyAfter(modifyProjectVo.getOaProjectId());
            workProjectChange.setReason(modifyProjectVo.getOaProjectIdReason());
            workProjectChange.setOperationType(2);
            workProjectChange.setReviserId(modifyProjectVo.getReviserId());
            workProjectChanges.add(workProjectChange);
        }
        if (!StringUtils.isBlank(modifyProjectVo.getProjectNameReason())) {
            if (StringUtils.isBlank(modifyProjectVo.getProjectName())) {
                throw new BaseCustomException("666", "请填写项目/商机名称");
            }
            if (!StringUtils.isBlank(workProject.getProjectName())) {
                if (modifyProjectVo.getProjectName().equals(workProject.getProjectName())) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
                }
            }
            WorkProjectChange workProjectChange = new WorkProjectChange();
            workProjectChange.setProjectId(modifyProjectVo.getProjectId());
            workProjectChange.setModifyTime(new Date());
            workProjectChange.setChangeType(9);
            workProjectChange.setModifyBefore(workProject.getProjectName());
            workProjectChange.setModifyAfter(modifyProjectVo.getProjectName());
            workProjectChange.setReason(modifyProjectVo.getProjectNameReason());
            workProjectChange.setOperationType(2);
            workProjectChange.setReviserId(modifyProjectVo.getReviserId());
            workProjectChanges.add(workProjectChange);
        }
        if (!StringUtils.isBlank(modifyProjectVo.getBusinessIdReason())) {
            if (!StringUtils.isBlank(workProject.getBusinessId())) {
                if (modifyProjectVo.getBusinessId().equals(workProject.getBusinessId())) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
                }
            }
            WorkProjectChange workProjectChange = new WorkProjectChange();
            workProjectChange.setProjectId(modifyProjectVo.getProjectId());
            workProjectChange.setModifyTime(new Date());
            workProjectChange.setChangeType(10);
            workProjectChange.setModifyBefore(workProject.getBusinessId());
            workProjectChange.setModifyAfter(modifyProjectVo.getBusinessId());
            workProjectChange.setReason(modifyProjectVo.getBusinessIdReason());
            workProjectChange.setOperationType(2);
            workProjectChange.setReviserId(modifyProjectVo.getReviserId());
            workProjectChanges.add(workProjectChange);
        }
        if (!StringUtils.isBlank(modifyProjectVo.getBusinessNameReason())) {
            if (!StringUtils.isBlank(workProject.getBusinessName())) {
                if (modifyProjectVo.getBusinessName().equals(workProject.getBusinessName())) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
                }
            }
            WorkProjectChange workProjectChange = new WorkProjectChange();
            workProjectChange.setProjectId(modifyProjectVo.getProjectId());
            workProjectChange.setModifyTime(new Date());
            workProjectChange.setChangeType(11);
            workProjectChange.setModifyBefore(workProject.getBusinessName());
            workProjectChange.setModifyAfter(modifyProjectVo.getBusinessName());
            workProjectChange.setReason(modifyProjectVo.getBusinessNameReason());
            workProjectChange.setOperationType(2);
            workProjectChange.setReviserId(modifyProjectVo.getReviserId());
            workProjectChanges.add(workProjectChange);
        }

        if (!StringUtils.isBlank(modifyProjectVo.getDeptIdReason())) {
            if (!workProject.getDeptId().equals(modifyProjectVo.getDeptId())) {
                WorkProjectChange workProjectChange = new WorkProjectChange();
                workProjectChange.setProjectId(modifyProjectVo.getProjectId());
                workProjectChange.setModifyTime(new Date());
                workProjectChange.setChangeType(6);
                workProjectChange.setModifyBefore(workDeptService.getById(workProject.getDeptId()).getDeptName());
                workProjectChange.setModifyAfter(workDeptService.getById(modifyProjectVo.getDeptId()).getDeptName());
                workProjectChange.setReason(modifyProjectVo.getDeptIdReason());
                workProjectChange.setOperationType(2);
                workProjectChange.setReviserId(modifyProjectVo.getReviserId());
                workProjectChanges.add(workProjectChange);
            }else{
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
            }
        }
        if (!StringUtils.isBlank(modifyProjectVo.getManagerIdReason())) {
            if (!workProject.getManagerId().equals(modifyProjectVo.getManagerId())) {
                WorkProjectChange workProjectChange = new WorkProjectChange();
                workProjectChange.setProjectId(modifyProjectVo.getProjectId());
                workProjectChange.setModifyTime(new Date());
                workProjectChange.setChangeType(5);
                workProjectChange.setModifyBefore(workUserService.getById(workProject.getManagerId()).getName());
                workProjectChange.setModifyAfter(workUserService.getById(modifyProjectVo.getManagerId()).getName());
                workProjectChange.setReason(modifyProjectVo.getManagerIdReason());
                workProjectChange.setOperationType(2);
                workProjectChange.setReviserId(modifyProjectVo.getReviserId());
                workProjectChanges.add(workProjectChange);
            }else{
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
            }

        }
        if (!StringUtils.isBlank(modifyProjectVo.getStartTimeReason())) {
            WorkProjectChange workProjectChange = new WorkProjectChange();
            workProjectChange.setProjectId(modifyProjectVo.getProjectId());
            workProjectChange.setModifyTime(new Date());
            workProjectChange.setChangeType(3);
            if (workProject.getStartTime() != null) {
                workProjectChange.setModifyBefore(DateUtil.convertDateToStr(workProject.getStartTime(), "yyyy-MM-dd"));
            }
            if (modifyProjectVo.getStartTime() != null) {
                workProjectChange.setModifyAfter(DateUtil.convertDateToStr(modifyProjectVo.getStartTime(), "yyyy-MM-dd"));
            }
            workProjectChange.setReason(modifyProjectVo.getStartTimeReason());
            workProjectChange.setOperationType(2);
            workProjectChange.setReviserId(modifyProjectVo.getReviserId());
            workProjectChanges.add(workProjectChange);
        }

        if (!StringUtils.isBlank(modifyProjectVo.getEndTimeReason())) {
            WorkProjectChange workProjectChange = new WorkProjectChange();
            workProjectChange.setProjectId(modifyProjectVo.getProjectId());
            workProjectChange.setModifyTime(new Date());
            workProjectChange.setChangeType(4);
            if (workProject.getEndTime() != null) {
                workProjectChange.setModifyBefore(DateUtil.convertDateToStr(workProject.getEndTime(), "yyyy-MM-dd"));
            }
            if (modifyProjectVo.getEndTime() != null) {
                workProjectChange.setModifyAfter(DateUtil.convertDateToStr(modifyProjectVo.getEndTime(), "yyyy-MM-dd"));
            }
            workProjectChange.setReason(modifyProjectVo.getEndTimeReason());
            workProjectChange.setOperationType(2);
            workProjectChange.setReviserId(modifyProjectVo.getReviserId());
            workProjectChanges.add(workProjectChange);
        }
        if (!StringUtils.isBlank(modifyProjectVo.getWorkTimeReason())) {
            if (workProject.getType().equals(PROJECT_CODE) && workProject.getType().equals(PROJECT_CODE) && null == modifyProjectVo.getWorkTime()) {
                throw new BaseCustomException("666", "请填写工时预算");
            }

            WorkProjectChange workProjectChange = new WorkProjectChange();
            workProjectChange.setProjectId(modifyProjectVo.getProjectId());
            workProjectChange.setModifyTime(new Date());
            workProjectChange.setChangeType(2);
            if (null != workProject.getWorkTime()) {
                workProjectChange.setModifyBefore(workProject.getWorkTime().toString());
            }
            if (modifyProjectVo.getWorkTime() != null) {
                workProjectChange.setModifyAfter(modifyProjectVo.getWorkTime().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
            workProjectChange.setReason(modifyProjectVo.getWorkTimeReason());
            workProjectChange.setOperationType(2);
            workProjectChange.setReviserId(modifyProjectVo.getReviserId());
            workProjectChanges.add(workProjectChange);
        }
        if (!StringUtils.isBlank(modifyProjectVo.getCostBudgetReason())) {
            if (workProject.getType().equals(PROJECT_CODE) && null == modifyProjectVo.getCostBudget()) {
                throw new BaseCustomException("666", "请填写成本预算");
            }

            WorkProjectChange workProjectChange = new WorkProjectChange();
            workProjectChange.setProjectId(modifyProjectVo.getProjectId());
            workProjectChange.setModifyTime(new Date());
            workProjectChange.setChangeType(1);
            if (null != workProject.getCostBudget()) {
                workProjectChange.setModifyBefore(workProject.getCostBudget().toString());
            }
            if (modifyProjectVo.getCostBudget() != null) {
                workProjectChange.setModifyAfter(modifyProjectVo.getCostBudget().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
            workProjectChange.setReason(modifyProjectVo.getCostBudgetReason());
            workProjectChange.setOperationType(2);
            workProjectChange.setReviserId(modifyProjectVo.getReviserId());
            workProjectChanges.add(workProjectChange);
        }
        if (!StringUtils.isBlank(modifyProjectVo.getUserIdsReason())) {
            if (!(userIds.containsAll(modifyProjectVo.getUserIds()) &&
                    modifyProjectVo.getUserIds().containsAll(userIds))) {
                Map<String, Object> map = new HashMap<>();
                map.put("status", 1);
                List<WorkUser> byMap = workUserService.getByMap(map);
                StringBuilder before = new StringBuilder();
                StringBuilder after = new StringBuilder();
                String userModifyBefore = "";
                String userModifyAfter = "";
                if (!CollectionUtils.isEmpty(byMap)) {
                    for (WorkUser workUser : byMap) {
                        if (!CollectionUtils.isEmpty(userIds)) {
                            for (Integer userId : userIds) {
                                if (userId.equals(workUser.getId())) {
                                    before.append(workUser.getName()).append(",");
                                }
                            }
                        }
                        if (!CollectionUtils.isEmpty(modifyProjectVo.getUserIds())) {
                            for (Integer userId : modifyProjectVo.getUserIds()) {
                                if (userId.equals(workUser.getId())) {
                                    after.append(workUser.getName()).append(",");
                                }
                            }
                        }
                    }
                    userModifyBefore = before.length() > 0 ? before.deleteCharAt(before.length() - 1).toString() : "";
                    userModifyAfter = after.length() > 0 ? after.deleteCharAt(after.length() - 1).toString() : "";
                }
                WorkProjectChange workProjectChange = new WorkProjectChange();
                workProjectChange.setProjectId(modifyProjectVo.getProjectId());
                workProjectChange.setModifyTime(new Date());
                workProjectChange.setChangeType(7);
                workProjectChange.setModifyBefore(userModifyBefore);
                workProjectChange.setModifyAfter(userModifyAfter);
                workProjectChange.setReason(modifyProjectVo.getUserIdsReason());
                workProjectChange.setOperationType(2);
                workProjectChange.setReviserId(modifyProjectVo.getReviserId());
                workProjectChanges.add(workProjectChange);
            }else{
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
            }
        }

        if (!CollectionUtils.isEmpty(workProjectChanges)) {
            workProjectChangeService.insertbatch(workProjectChanges);
        }

        // 更新workUserProject数据
        if (!userIds.containsAll(modifyProjectVo.getUserIds()) || !modifyProjectVo.getUserIds().containsAll(userIds)) {
            // 先删除,后插入
            if (!CollectionUtils.isEmpty(userIds)) {
                if (!workUserProjectService.deleteByProjectId(modifyProjectVo.getProjectId())) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.DELETE_OLD_WORK_ORDER_FAIL);
                }
            }
            if (!CollectionUtils.isEmpty(modifyProjectVo.getUserIds())) {
                if (!workUserProjectService.insertBatch(modifyProjectVo.getUserIds(), modifyProjectVo.getProjectId())) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.INSERT_DATA_IS_FAIL);
                }
            }
        }
        return true;
    }

    @Transactional
    @Override
    public Boolean addProject(CreateProjectVo createProjectVo) {
        log.info("WorkProjectServiceImpl[]addProject[]input.param.createProjectVo：{}" + createProjectVo);
        // 1.验证工单
        if (null == createProjectVo) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        if (null == createProjectVo.getManagerId()) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.CREATE_PROJECT_MANAGER_NOT_FOUND);
        }
        // 新增项目的校验
        if (createProjectVo.getType().equals(PROJECT_CODE)) {
            if (null == createProjectVo.getStartTime() || null == createProjectVo.getEndTime() || StringUtils.isBlank(createProjectVo.getOaProjectId()) || null == createProjectVo.getWorkTime() || null == createProjectVo.getCostBudget() || null == createProjectVo.getDeptId() ||
                    StringUtils.isBlank(createProjectVo.getProjectName()) || null == createProjectVo.getDeptId() || CollectionUtils.isEmpty(createProjectVo.getUserIds())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
            }
        }else{ // 新增商机的校验，工时预算，成本预算，开始时间和结束时间可以为空
            if ( StringUtils.isBlank(createProjectVo.getOaProjectId()) || null == createProjectVo.getDeptId() || StringUtils.isBlank(createProjectVo.getProjectName()) || null == createProjectVo.getDeptId() || CollectionUtils.isEmpty(createProjectVo.getUserIds())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
            }
        }


        if (createProjectVo.getStartTime() != null && createProjectVo.getEndTime() != null && createProjectVo.getStartTime().compareTo(createProjectVo.getEndTime()) > 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.START_NOT_THAN_END_DATE);
        }

        if ((createProjectVo.getWorkTime() != null && BigDecimal.ZERO.compareTo(createProjectVo.getWorkTime()) > 0) || (createProjectVo.getCostBudget() != null &&  BigDecimal.ZERO.compareTo(createProjectVo.getCostBudget()) > 0)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.BUDGET_CANNOT_BELESSTHAN_ZERO);
        }

        // 项目/商机管理部门级、系统管理权限能够新建项目/商机
        List<Integer> rankByUserAndLevelName = UserRoleLevelUtils.getRankByUserAndLevelName(createProjectVo.getCreatorId(), LevelEnum.PROJECT_MANAGER.getLevelName());
        if (!rankByUserAndLevelName.contains(LevelRankEnum.DEPARTMENT_LEVEL.getRank()) && !rankByUserAndLevelName.contains(LevelRankEnum.SYSTEM_MANAGER.getRank())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.NO_AUTHORITY);
        }

        // 判断oa编号是否重复
        WorkProject byProjectNameOrOaId = workProjectMapper.getByProjectOaId(createProjectVo.getOaProjectId());
        if (byProjectNameOrOaId != null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.ITEMOADUPLICATE);
        }

        // 项目/商机负责人在工时系统中未找到
        WorkUser manager = workUserMapper.getUserById(createProjectVo.getManagerId());
        if (manager == null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.CREATE_PROJECT_MANAGER_NOT_FOUND);
        }


        // 在oa数据库中查找对应信息
        OaProject oaProject = oaProjectService.getOaProjectByNoAndName(createProjectVo, manager.getOaUserId());
        if (oaProject == null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.NEW_PROJECT_OA_PROJECT_ID_OR_NAME_ERROR);
        }
        // 对项目名称做去前后空格
        createProjectVo.setProjectName(StringUtil.replaceBlank(createProjectVo.getProjectName()));
        // 对对应商机名称去前后空格
        if (StringUtils.isNotBlank(createProjectVo.getBusinessName())) {
            StringUtil.replaceBlank(createProjectVo.getBusinessName());
        }
        // 插入项目信息
        Date date = new Date();
        WorkProject workProject = new WorkProject();
        workProject.setIsConclusion(1);
        workProject.setCreateTime(date);
        workProject.setModifyTime(date);

        BeanUtils.copyProperties(createProjectVo, workProject);
        int insert = workProjectMapper.insert(workProject);
        if (insert == 0) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INSERT_DATA_IS_FAIL);
        }
        // 插入参与人员信息

        workUserProjectService.insertBatch(createProjectVo.getUserIds(), workProject.getId());
        // 插入更变日志
        WorkProjectChange workProjectChange = new WorkProjectChange();
        workProjectChange.setProjectId(workProject.getId());
        workProjectChange.setReviserId(createProjectVo.getCreatorId());
        workProjectChange.setModifyTime(new Date());
        workProjectChange.setOperationType(1);
        int insert1 = workProjectChangeMapper.insert(workProjectChange);

        return insert1 > 0;
    }


    private OrderChangeDto getProjevtAndTypeOfDept(Integer userId, Boolean isFillIn, Boolean addProjectOfDept) {
        if (null == userId) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        OrderChangeDto orderChangeDto = new OrderChangeDto();
        WorkUser user = workUserService.getById(userId);
        WorkDept dept = workDeptService.getById(user.getDeptId());
        List<Integer> ranks = UserRoleLevelUtils.getRankByUserAndLevelName(userId, LevelEnum.WORKORDER_CHANGEMANAGEMENT.getLevelName());
        if (CollectionUtils.isEmpty(ranks)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }
        List<DeptOfProjectAndOrderType> projectAndOrderTypes = new ArrayList<>();
        // 后五种类型
        List<ProjectManagerDto> projectManagerDtos = new ArrayList<>();
        List<WorkType> workTypeServiceAll = workTypeService.getAll(1);

        if (!CollectionUtils.isEmpty(workTypeServiceAll)) {
            for (WorkType workType : workTypeServiceAll) {
                if (1 != workType.getReviewer()) {
                    ProjectManagerDto projectManagerDto = new ProjectManagerDto();
                    projectManagerDto.setType(workType.getId());
                    projectManagerDto.setTypeName(workType.getName());
                    projectManagerDtos.add(projectManagerDto);
                }
            }
        }
        // 中心级(系统管理员)
        for (Integer rank : ranks) {
            if (LevelRankEnum.CENTRAL_LEVEL.getRank().equals(rank)) {
                projectAndOrderTypes = workDeptService.getDeptOfProjectAndOrderType(null, null);
                if (!CollectionUtils.isEmpty(projectAndOrderTypes)) {
                    for (DeptOfProjectAndOrderType projectAndOrderType : projectAndOrderTypes) {
                        projectAndOrderType.getProjectManagerDtos().addAll(projectManagerDtos);
                    }
                }
                orderChangeDto.setProjectAndOrderTypes(projectAndOrderTypes);
                // 组织架构
                if (isFillIn) {
                    List<OrderChangeTypeDto> orderChangeTypeDtos = workProjectMapper.getOrderChangeTypeDtos(null);
                    List<DeptUserDto> deptUserDtos = workUserService.getOrganizationStructureDtos().get(0).getDeptUserDtos();
                    List<WorkType> workTypeServiceAll1 = workTypeService.getByIsStatus(1,1);
                    for (WorkType workType : workTypeServiceAll1) {
                        // 不是项目和商机
                        if (1 != workType.getReviewer()) {
                            OrderChangeTypeDto orderChangeTypeDto = new OrderChangeTypeDto();
                            orderChangeTypeDto.setType(workType.getId());
                            orderChangeTypeDto.setTypeName(workType.getName());
                            orderChangeTypeDto.setDeptUserDtos(deptUserDtos);
                            orderChangeTypeDtos.add(orderChangeTypeDto);
                        }
                    }
                    orderChangeDto.setOrderChangeTypeDtos(orderChangeTypeDtos);
                }
                return orderChangeDto;
            }
        }
        Integer projectOfUserId = null;
        Integer projectOfDeptId = null;
        for (Integer rank : ranks) {
            if (LevelRankEnum.PROJECT_LEVEL.getRank().equals(rank)) {
                projectOfUserId = userId;
            }
            if (addProjectOfDept) {
                if (LevelRankEnum.DEPARTMENT_LEVEL.getRank().equals(rank)) {
                    projectOfDeptId = user.getDeptId();
                }
            }
        }

        List<OrderChangeTypeDto> orderChangeTypeDtos = new ArrayList<>();
        for (Integer rank : ranks) {
            // 项目级
            if (LevelRankEnum.PROJECT_LEVEL.getRank().equals(rank)) {
                projectAndOrderTypes = workDeptService.getDeptOfProjectAndOrderType(projectOfUserId, projectOfDeptId);
                if (isFillIn) {
                    // 组织架构
                    orderChangeTypeDtos = workProjectMapper.getOrderChangeTypeDtos(userId);
                }
                break;
            }
        }
        for (Integer rank : ranks) {
            // 部门级
            if (LevelRankEnum.DEPARTMENT_LEVEL.getRank().equals(rank)) {
                boolean isAdd = false;
                if (!CollectionUtils.isEmpty(projectAndOrderTypes)) {
                    for (DeptOfProjectAndOrderType projectAndOrderType : projectAndOrderTypes) {
                        if (projectAndOrderType.getDeptId().equals(user.getDeptId())) {
                            projectAndOrderType.getProjectManagerDtos().addAll(projectManagerDtos);
                            isAdd = true;
                        }
                    }
                }
                if (!isAdd) {
                    if (addProjectOfDept) {
                        projectAndOrderTypes = workDeptService.getDeptOfProjectAndOrderType(null, projectOfDeptId);
                        projectAndOrderTypes.get(0).getProjectManagerDtos().addAll(projectManagerDtos);
                    } else {
                        DeptOfProjectAndOrderType projectAndOrderType = new DeptOfProjectAndOrderType();
                        projectAndOrderType.setDeptId(user.getDeptId());
                        projectAndOrderType.setDeptName(dept.getDeptName());
                        projectAndOrderType.setProjectManagerDtos(projectManagerDtos);
                        projectAndOrderTypes.add(projectAndOrderType);
                    }
                }
                // 组织架构
                if (isFillIn) {
                    List<DeptUserDto> deptUserDtos = workUserService.getOrganizationStructureDtos().get(0).getDeptUserDtos();
                    List<WorkType> workTypeServiceAll1 = workTypeService.getByIsStatus(1,1);
                    List<DeptUserDto> deptUserDtoList = new ArrayList<>();
                    for (DeptUserDto deptUserDto : deptUserDtos) {
                        if (deptUserDto.getDeptId().equals(user.getDeptId())) {
                            deptUserDtoList.add(deptUserDto);
                        }
                    }
                    for (WorkType workType : workTypeServiceAll1) {
                        // 不是项目和商机
                        if (1 != workType.getReviewer()) {
                            OrderChangeTypeDto orderChangeTypeDto = new OrderChangeTypeDto();
                            orderChangeTypeDto.setTypeName(workType.getName());
                            orderChangeTypeDto.setType(workType.getId());
                            orderChangeTypeDto.setDeptUserDtos(deptUserDtoList);
                            orderChangeTypeDtos.add(orderChangeTypeDto);
                        }
                    }
                }
                break;
            }
        }
        orderChangeDto.setProjectAndOrderTypes(projectAndOrderTypes);
        orderChangeDto.setOrderChangeTypeDtos(orderChangeTypeDtos);
        return orderChangeDto;
    }

    /**
     * 获取管理员所管理的项目+后五种类型/所属部门(工单变更)
     *
     * @param userId 管理员id
     */
    @Override
    public OrderChangeDto getProjectAndOrderTypeAndDept(Integer userId) {
        log.info("WorkProjectServiceImpl[]getProjectAndOrderTypeAndDept[]input.param.userId：{}" + userId);
        return getProjevtAndTypeOfDept(userId, true, false);
    }

    @Override
    public List<DeptOfProjectAndOrderType> getProjectOfFind(Integer userId) {
        log.info("WorkProjectServiceImpl[]getProjectAndOrderTypeAndDept[]input.param.userId：{}" + userId);
        OrderChangeDto orderChangeDto = getProjevtAndTypeOfDept(userId, false, true);
        return orderChangeDto.getProjectAndOrderTypes();
    }

    @Override
    public PageInfo queryOaProject(Integer userId, Integer typeId, String projectNameOrNo, Integer currentPage, Integer pageSize) {
        log.info("WorkProjectServiceImpl[]queryOaProject[]input.param{}userId,typeId,projectNameOrNo" + userId + "," + typeId + "," + projectNameOrNo + "," + currentPage + "," + pageSize);
        if (userId == null || typeId == null || StringUtils.isEmpty(projectNameOrNo)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        // 项目/商机管理部门级、系统管理权限能够查看oa项目/商机信息
        List<Integer> rankByUserAndLevelName = UserRoleLevelUtils.getRankByUserAndLevelName(userId, LevelEnum.PROJECT_MANAGER.getLevelName());
        if (!rankByUserAndLevelName.contains(LevelRankEnum.DEPARTMENT_LEVEL.getRank()) && !rankByUserAndLevelName.contains(LevelRankEnum.SYSTEM_MANAGER.getRank())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.NO_AUTHORITY);
        }

        // 根据用户id查询所对应oa部门编号
        WorkDept dept = new WorkDept();
        if (rankByUserAndLevelName.contains(LevelRankEnum.DEPARTMENT_LEVEL.getRank())) {
            dept = workDeptMapper.getOaDeptNoByUserId(userId);
        }

        // 查询工时系统中的该部门下的项目/商机
        List<String> oaProjectIds = workProjectMapper.getListByDeptAndType(typeId, projectNameOrNo);
        // 移除集合中的null元素
        oaProjectIds.remove(null);

        // 从oa中根据部门的oa编号查询项目/商机,
        // typeId 为1 查询项目，为2查询商机
        if (currentPage != null && pageSize != null) {
            PageHelper.startPage(currentPage, pageSize);
        }
        List<OaProject> listOaProject = oaProjectService.getListOaProject(dept.getOaDeptId(), typeId, projectNameOrNo,oaProjectIds);

        // 分页信息对象
        PageInfo<OaProject> pageInfo = new PageInfo<>(listOaProject);

        // 查询信息为空，直接返回
        if (CollectionUtils.isEmpty(listOaProject)) {
            return null;
        }


        // 查询项目经理在工时系统中对应的id
        List<String> managerIds = listOaProject.stream().map(OaProject::getManagerNo).collect(Collectors.toList());
        List<WorkUser> workUsers = null;
        if (!CollectionUtils.isEmpty(managerIds)) {
            workUsers = workUserMapper.getUserByIds(managerIds);
        }

        // 所有部门信息
        List<WorkDept> deptList = workDeptMapper.getAllDept();
        // 将查询结果中的oa编号更换为工时系统中的编号
        for (int i = 0; i < listOaProject.size(); i++) {
            OaProject oaProject = listOaProject.get(i);

            // 将部门oa编号替换为工时系统中的部门id
            for (WorkDept workDept : deptList) {
                if (StringUtils.isNotBlank(workDept.getOaDeptId()) && workDept.getOaDeptId().equals(oaProject.getDeptNo())) {
                    oaProject.setDeptNo(workDept.getId().toString());
                    oaProject.setDeptName(workDept.getDeptName());
                }
            }

            // 是否在工时系统中存在负责人
            boolean isExist = false;

            // 将项目/商机负责人oa编号替换为工时系统中的用户id
            if (StringUtils.isNotBlank(oaProject.getManagerNo())) {
                assert workUsers != null;
                for (WorkUser workUser : workUsers) {
                    if (workUser.getOaUserId().equals(oaProject.getManagerNo())) {
                        oaProject.setManagerNo(workUser.getId().toString());
                        oaProject.setManagerName(workUser.getName());
                        isExist = true;
                        break;
                    }
                    // 负责人在工时系统中不存在
                    if (isExist) {
                        oaProject.setManagerNo(null);
                    }
                }
            }
        }

        return pageInfo;
    }

    @Override
    public Boolean updateIsConclusionById2(Integer userId, Integer projectId) {
        log.info("WorkProjectServiceImpl[]endProject[]input.param.userId：{},projectId:{}" + userId, projectId);
        if (!UserRoleLevelUtils.isManagerLevel(userId, LevelEnum.PROJECT_MANAGER.getLevelName())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }
        if (null == projectId) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        WorkProject workProject = workProjectMapper.selectById(projectId);
        if (null == workProject) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_PROJECT_IS_NULL);
        }

        workProjectMapper.updateIsConclusionById2(projectId);

        // 插入更变日志
        List<WorkProjectChange> workProjectChanges = new ArrayList<>();
        WorkProjectChange workProjectChange = new WorkProjectChange();
        workProjectChange.setProjectId(projectId);
        workProjectChange.setReviserId(userId);
        workProjectChange.setModifyTime(new Date());
        workProjectChange.setOperationType(2);
        workProjectChanges.add(workProjectChange);
        workProjectChangeService.insertbatch(workProjectChanges);

        return true;
    }


    private PageInfo<ManagerProjectsDto> returnPageInfo(List<ManagerProjectsDto> managerProjectsDto) {
        if (CollectionUtils.isEmpty(managerProjectsDto)) {
            return null;
        }
        PageInfo<ManagerProjectsDto> pageInfo = new PageInfo<>(managerProjectsDto);
        pageInfo.setList(managerProjectsDto);
        return pageInfo;
    }


    /**
     *
     * 判断更变内容是否等于原内容
     */
    private void verificationItem(ModifyProjectVo modifyProjectVo, WorkProject workProject, List<Integer> userIds) {

        int modifyCount = 0;
        // 校验部门
        if (!workProject.getDeptId().equals(modifyProjectVo.getDeptId())) {
            modifyCount++;
            if (StringUtils.isBlank(modifyProjectVo.getDeptIdReason())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
            }
        }

        // 开始时间不能大于结束时间
        if (modifyProjectVo.getStartTime() != null && modifyProjectVo != null && modifyProjectVo.getStartTime().compareTo(modifyProjectVo.getEndTime()) != -1)


        // 校验开始时间
        if (modifyProjectVo.getStartTime() != null && workProject.getStartTime() != null && !modifyProjectVo.getStartTime().equals(workProject.getStartTime()) || (modifyProjectVo.getStartTime() != null && workProject.getStartTime() == null)
                || (modifyProjectVo.getStartTime() == null && workProject.getStartTime() != null)) {
            modifyCount++;
            if (StringUtils.isBlank(modifyProjectVo.getStartTimeReason())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
            }
//            if (null == modifyProjectVo.getEndTime()) {
//                if (workProject.getEndTime() != null && modifyProjectVo.getStartTime().compareTo(workProject.getEndTime()) > 0) {
//                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.START_NOT_THAN_END_DATE);
//                }
//            } else {
//                if (modifyProjectVo.getStartTime().compareTo(modifyProjectVo.getEndTime()) > 0) {
//                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.START_NOT_THAN_END_DATE);
//                }
//            }
//            if (workProject.getStartTime() != null && workProject.getStartTime().compareTo(modifyProjectVo.getStartTime()) == 0) {
//                throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
//            }
        }

        // 校验结束时间
        if (modifyProjectVo.getEndTime() != null && workProject.getEndTime() != null && !modifyProjectVo.getEndTime().equals(workProject.getEndTime()) || (modifyProjectVo.getEndTime() != null && workProject.getEndTime() == null)
                || (modifyProjectVo.getEndTime() == null && workProject.getEndTime() != null)) {
            modifyCount++;
            if (StringUtils.isBlank(modifyProjectVo.getEndTimeReason())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
            }

        }

        // 校验成本预算
        if (modifyProjectVo.getCostBudget() != null && !modifyProjectVo.getCostBudget().equals(workProject.getCostBudget()) ) {
            modifyCount++;
            if (BigDecimal.ZERO.compareTo(modifyProjectVo.getCostBudget()) > 0) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.BUDGET_CANNOT_BELESSTHAN_ZERO);
            }
            if (StringUtils.isBlank(modifyProjectVo.getCostBudgetReason())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
            }
            if (modifyProjectVo.getCostBudget() == null ) {
                if (modifyProjectVo.getCostBudget().compareTo(workProject.getCostBudget()) == 0) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
                }
            }
        } else if (modifyProjectVo.getCostBudget() == null) {
            modifyProjectVo.setCostBudget(new BigDecimal(BigInteger.ZERO));
        }

        // 项目成本预算不能为空
        if (workProject.getType() == 1 &&StringUtils.isBlank(modifyProjectVo.getCostBudgetReason()) && workProject.getCostBudget() == null){
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_COST_BUDGET_NOT_NULL);
        }

        // oa编号验证
        if (!StringUtils.isBlank(modifyProjectVo.getOaProjectId())) {
            if (!modifyProjectVo.getOaProjectId().equals(workProject.getOaProjectId())) {
                modifyCount++;
                if (StringUtils.isBlank(modifyProjectVo.getOaProjectIdReason())) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
                }
            }
        }

        // 项目名称验证
        if (!StringUtils.isBlank(modifyProjectVo.getProjectName())) {
            if (!modifyProjectVo.getProjectName().equals(workProject.getProjectName())) {
                modifyCount++;
                if (StringUtils.isBlank(modifyProjectVo.getProjectNameReason())) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
                }
            }
        }

        // 校验工时预算
        if (null != modifyProjectVo.getWorkTime()) {
            modifyCount++;
            if (BigDecimal.ZERO.compareTo(modifyProjectVo.getWorkTime()) > 0) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.BUDGET_CANNOT_BELESSTHAN_ZERO);
            }
            if (StringUtils.isBlank(modifyProjectVo.getWorkTimeReason())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
            }
            if (null != workProject.getWorkTime()) {
                if (modifyProjectVo.getWorkTime().compareTo(workProject.getWorkTime()) == 0) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.theNewContent_IsEqual_ToTheOriginal_Content);
                }
            }
        }
        // 项目工时预算不能为空
        if (workProject.getType() == 1 && StringUtils.isBlank(modifyProjectVo.getWorkTimeReason()) && workProject.getWorkTime() == null){
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.WORK_TIME_BUDGET_NOT_NULL);
        }

        // 校验负责人
        if (!workProject.getManagerId().equals(modifyProjectVo.getManagerId())) {
            modifyCount++;
            if (StringUtils.isBlank(modifyProjectVo.getManagerIdReason())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
            }
            List<Integer> roles = UserRoleLevelUtils.getRole(modifyProjectVo.getManagerId());
            int index = 0;
            for (Integer role : roles) {
                if (role == 1) {
                    index++;
                }
            }
            if (index == 0) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.NOADMIN_ISTRATIVE_RIGHTS);
            }
        }

        if (!(userIds.containsAll(modifyProjectVo.getUserIds()) &&
                modifyProjectVo.getUserIds().containsAll(userIds))) {
            modifyCount++;
            if (StringUtils.isBlank(modifyProjectVo.getUserIdsReason())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.REASON_CANNOT_BE_EMPTY);
            }
        }
        if (CollectionUtils.isEmpty(modifyProjectVo.getUserIds()) && StringUtils.isNotBlank(modifyProjectVo.getUserIdsReason())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.PROJECT_USER_NOT_NULL);
        }
        //  是否存在变更项
        if ((modifyCount == 1 && StringUtils.isBlank(modifyProjectVo.getUserIdsReason())) ||
                modifyCount > 1) {
            modifyProjectVo.setIsModify(1);
        }

    }
}
