package com.lz.modules.flow.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.lz.common.utils.NumberUtil;
import com.lz.common.utils.PageUtils;
import com.lz.common.utils.R;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.dao.DepartmentsDao;
import com.lz.modules.app.dao.StaffDao;
import com.lz.modules.app.dto.*;
import com.lz.modules.app.entity.DepartmentsEntity;
import com.lz.modules.app.entity.DepartmentsStaffRelateEntity;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.entity.StaffOccupationEntity;
import com.lz.modules.app.enums.DepartmentPMEnums;
import com.lz.modules.app.enums.EvaluationGroupEnums;
import com.lz.modules.app.enums.RoleEnums;
import com.lz.modules.app.enums.RoleMenuEnums;
import com.lz.modules.app.model.RoleModel;
import com.lz.modules.app.model.TaskModel;
import com.lz.modules.app.service.DepartmentsService;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.app.service.StaffOccupationService;
import com.lz.modules.flow.dao.RecordRoleMapper;
import com.lz.modules.flow.dao.StaffRoleDepartmentMapper;
import com.lz.modules.flow.dao.StaffRoleMapper;
import com.lz.modules.flow.entity.*;
import com.lz.modules.flow.service.*;
import com.lz.modules.job.business.DingtalkBusiness;
import com.lz.modules.performance.entity.ResultTask;
import com.lz.modules.performance.entity.TaskProcessRecord;
import com.lz.modules.performance.service.ResultTaskService;
import com.lz.modules.performance.service.TaskProcessRecordService;
import com.lz.modules.sys.entity.SysMenuEntity;
import com.lz.modules.sys.entity.SysRoleEntity;
import com.lz.modules.sys.entity.app.ResultDetail;
import com.lz.modules.sys.service.app.ResultDetailService;
import com.lz.modules.sys.service.app.ResultRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 流转关系表 服务类
 * </p>
 *
 * @author quyixiao
 * @since 2020-08-18
 */

@Service
@Slf4j
public class StaffRoleServiceImpl extends ServiceImpl<StaffRoleMapper, StaffRole> implements StaffRoleService {


    @Autowired
    private StaffRoleMapper staffRoleMapper;

    @Autowired
    private StaffDao staffDao;


    @Autowired
    private RecordRoleMapper recordRoleMapper;

    @Autowired
    private StaffRoleDepartmentMapper staffRoleDepartmentMapper;
    @Autowired
    private DepartmentsDao departmentsDao;

    @Autowired
    private ResultRecordService resultRecordService;

    @Autowired
    private RecordRoleService recordRoleService;

    @Autowired
    private DepartmentsService departmentsService;

    @Autowired
    private DepartmentsStaffRelateService departmentsStaffRelateService;

    @Autowired
    private StaffRoleMenuService staffRoleMenuService;

    @Autowired
    private StaffRoleEvaluationGroupService staffRoleEvaluationGroupService;


    @Autowired
    private StaffMenuService staffMenuService;

    @Autowired
    private StaffRoleDepartmentService staffRoleDepartmentService;

    @Autowired
    private RecordAuthService recordAuthService;


    @Autowired
    private ResultTaskService resultTaskService;

    @Autowired
    private ResultDetailService resultDetailService;


    @Autowired
    private TaskProcessRecordService taskProcessRecordService;

    @Autowired
    private DingtalkBusiness dingtalkBusiness;


    @Autowired
    private StaffOccupationService staffOccupationService;

    @Override
    public StaffRole selectStaffRoleById(Long id) {
        return staffRoleMapper.selectStaffRoleById(id);
    }


    @Override
    public Long insertStaffRole(StaffRole staffRole) {
        return staffRoleMapper.insertStaffRole(staffRole);
    }


    @Override
    public int updateStaffRoleById(StaffRole staffRole) {
        return staffRoleMapper.updateStaffRoleById(staffRole);
    }


    @Override
    public int updateCoverStaffRoleById(StaffRole staffRole) {
        return staffRoleMapper.updateCoverStaffRoleById(staffRole);
    }


    @Override
    public int deleteStaffRoleById(Long id) {
        return staffRoleMapper.deleteStaffRoleById(id);
    }

    @Override
    public StaffRole selectByStaffId(Long staffId) {
        return staffRoleMapper.selectByStaffId(staffId);
    }

    @Override
    public List<StaffRole> selectByRole(String departmentLevel) {
        return staffRoleMapper.selectByRole(departmentLevel);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {


        PageUtils pageUtils = PageUtils.startPage(
                NumberUtil.objToIntDefault(params.get("page"), 1),
                NumberUtil.objToIntDefault(params.get("limit"), 10)).doSelect(
                page -> staffRoleMapper.selectByCondition(page, params)
        );
        List<StaffRole> staffRoles = pageUtils.getList();
        List<StaffRoleResp> list = new ArrayList<>();
        Map<Long, RecordRole> map = Maps.newHashMap();
        for (StaffRole staffRole : staffRoles) {
            StaffRoleResp resp = new StaffRoleResp();
            BeanUtils.copyProperties(staffRole, resp);
            StaffEntity staffEntity = staffDao.selectStaffById(resp.getStaffId());
            if (staffEntity != null) {
                resp.setStaffName(staffEntity.getName());
            }

            Map<String, Integer> types = JSONObject.parseObject(resp.getTypeRoleIds(), Map.class);
            Long type1 = NumberUtil.objToLongDefault(types.get("type1"), 0l);
            Long type2 = NumberUtil.objToLongDefault(types.get("type2"), 0l);
            RecordRole recordRoleType1 = map.get(type1);
            if (recordRoleType1 == null) {
                recordRoleType1 = recordRoleMapper.selectById(type1);
            }
            RecordRole recordRoleType2 = map.get(type2);
            if (recordRoleType2 == null) {
                recordRoleType2 = recordRoleMapper.selectById(type2);
            }
            if (recordRoleType1 != null) {
                map.put(recordRoleType1.getId(), recordRoleType1);
                resp.setTargetRole(recordRoleType1.getName());
            }
            if (recordRoleType2 != null) {
                map.put(recordRoleType2.getId(), recordRoleType2);
                resp.setResultRole(recordRoleType2.getName());
            }
            list.add(resp);
        }
        pageUtils.setList(list);
        return pageUtils;
    }

    @Override
    public void deleteBatchIds(List<Long> asList) {
        for (Long a : asList) {
            staffRoleMapper.deleteStaffRoleById(a);
        }
    }


    @Override
    public SysRoleEntity getRole(Long id) {
        StaffRole staffRole = staffRoleMapper.selectStaffRoleById(id);
        SysRoleEntity role = new SysRoleEntity();
        List<Long> menuIdList = new ArrayList<>();
        List<Long> menuIdList1 = new ArrayList<>();
        if (staffRole != null) {
            List<StaffRoleDepartment> staffRoleDepartments = staffRoleDepartmentMapper.selectStaffRoleDepartmentByStaffRoleId(staffRole.getId());
            List<DepartmentsEntity> departmentsEntities = departmentsDao.selectAll();
            Map<String, List<DepartmentsEntity>> map = resultRecordService.getStringListMap(departmentsEntities);
            role.setRoleId(staffRole.getId());
            role.setRoleName(staffRole.getDepartmentLevel());

            for (StaffRoleDepartment staffRoleDepartment : staffRoleDepartments) {
                List<DepartmentsEntity> list = map.get(staffRoleDepartment.getDepartmentId());
                List<String> departments = departmentsService.selectAllChildDepartmentIds(staffRoleDepartment.getDepartmentId());
                List<StaffRoleDepartment> departments1 = staffRoleDepartmentMapper.selectStaffRoleDepartmentByStaffRoleIdDepartments(staffRole.getId(), departments);
                if (list == null || list.size() == 0 || departments1.size() <= 1) {
                    menuIdList.add(NumberUtil.objToLongDefault(staffRoleDepartment.getDepartmentId(), 0l));
                } else {
                    menuIdList1.add(NumberUtil.objToLongDefault(staffRoleDepartment.getDepartmentId(), 0l));
                }
            }
        }
        menuIdList.add(-666666l);
        menuIdList.addAll(menuIdList1);
        role.setMenuIdList(menuIdList);
        return role;
    }

    @Override
    public List<SysMenuEntity> selectMenuList() {
        List<DepartmentsEntity> tDepartments = departmentsDao.selectAll();
        List<DepartmentsEntity> parentDepartments = tDepartments.stream()
                //根据两个属性进行过滤
                .filter(s -> s.getDepartmentParentId().equals("1"))
                .collect(Collectors.toList());
        List<DepartmentsStaffRelateEntity> departmentsStaffRelateEntities = departmentsStaffRelateService.selectAll();
        Map<String, DepartmentsStaffRelateEntity> departmentsStaffRelateEntityMap = new HashMap<>();
        Map<String, DepartmentsStaffRelateEntity> singleDepartmentsStaffRelate = new HashMap<>();
        for (DepartmentsStaffRelateEntity d : departmentsStaffRelateEntities) {
            singleDepartmentsStaffRelate.put(d.getDepartmentId(), d);
            if (new Integer(1).equals(d.getIsLeader())) {
                departmentsStaffRelateEntityMap.put(d.getDepartmentId(), d);
            }
        }
        List<StaffEntity> staffEntities = staffDao.selectAll();
        Map<Long, StaffEntity> staffMap = new HashMap<>();
        for (StaffEntity staffEntity : staffEntities) {
            staffMap.put(staffEntity.getId(), staffEntity);
        }
        List<SysMenuEntity> list = new ArrayList<>();
        for (DepartmentsEntity d : parentDepartments) {
            String departmentName = d.getDepartmentName() + getSuffix(departmentsStaffRelateEntityMap, staffMap, d.getDepartmentId(), singleDepartmentsStaffRelate);
            SysMenuEntity entity = recordRoleService.buildMenuEntity(NumberUtil.objToLongDefault(d.getDepartmentId(), 0l), departmentName, 0l, "");
            getMenuList(tDepartments, entity, list, departmentsStaffRelateEntityMap, staffMap, singleDepartmentsStaffRelate);
            list.add(entity);
        }
        return list;
    }

    @Override
    public List<StaffRole> selectByGroupId(Long id) {

        return staffRoleMapper.selectByEvaluationGroupId(id);
    }

    public String getSuffix(Map<String, DepartmentsStaffRelateEntity> departmentsStaffRelateEntityMap, Map<Long, StaffEntity> staffMap, String departmentId,
                            Map<String, DepartmentsStaffRelateEntity> singleDepartmentsStaffRelate) {
        DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateEntityMap.get(departmentId);
        if (departmentsStaffRelateEntity != null) {
            return doGetStaff(departmentsStaffRelateEntity, staffMap);
        } else {
            return doGetStaff(singleDepartmentsStaffRelate.get(departmentId), staffMap);
        }
    }

    public String doGetStaff(DepartmentsStaffRelateEntity departmentsStaffRelateEntity, Map<Long, StaffEntity> staffMap) {
        if (departmentsStaffRelateEntity != null) {
            StaffEntity staffEntity = staffMap.get(departmentsStaffRelateEntity.getStaffId());
            if (staffEntity != null) {
                return " , " + staffEntity.getName();
            }
        }
        return " ";
    }


    public void getMenuList(List<DepartmentsEntity> tDepartments, SysMenuEntity sysMenuEntity, List<SysMenuEntity> list,
                            Map<String, DepartmentsStaffRelateEntity> departmentsStaffRelateEntityMap, Map<Long, StaffEntity> staffMap,
                            Map<String, DepartmentsStaffRelateEntity> singleDepartmentsStaffRelate) {
        for (DepartmentsEntity child : tDepartments) {
            if (NumberUtil.objToLongDefault(child.getDepartmentParentId(), 0l).equals(sysMenuEntity.getMenuId())) {
                String departmentName = child.getDepartmentName() + getSuffix(departmentsStaffRelateEntityMap, staffMap, child.getDepartmentId(), singleDepartmentsStaffRelate);
                SysMenuEntity entity = recordRoleService.buildMenuEntity(NumberUtil.objToLongDefault(child.getDepartmentId(), 0l),
                        departmentName, sysMenuEntity.getMenuId(), sysMenuEntity.getName());
                getMenuList(tDepartments, entity, list, departmentsStaffRelateEntityMap, staffMap, singleDepartmentsStaffRelate);
                list.add(entity);
            }
        }
    }

    @Override
    public List<StaffRole> selectStaffRolesByStaffId(List<Long> mIds) {
        return staffRoleMapper.selectStaffRolesByStaffId(mIds);
    }

    @Override
    public R selectRoleInfoBy(RoleModel roleModel) {
        List<StaffRole> masterPMList = staffRoleMapper.selectByRoleLevel(RoleEnums.MASTER_PM.getName());
        List<StaffRoleInfo> masterPM = new ArrayList<>();
        for (StaffRole staffRole : masterPMList) {
            StaffRoleInfo staffRoleInfo = new StaffRoleInfo();
            StaffEntity staffEntity = staffDao.selectStaffById(staffRole.getStaffId());
            staffRoleInfo.setName(staffEntity.getName());
            staffRoleInfo.setHeaderUrl(staffEntity.getAvatar());
            staffRoleInfo.setId(staffRole.getId());
            masterPM.add(staffRoleInfo);
        }

        PageUtils pageUtils = PageUtils.startPage(roleModel.getCurrPage(), roleModel.getPageSize()).doSelect(
                page -> staffRoleMapper.selectPageByRoleLevel(page, RoleEnums.CHILD_PM.getName())
        );
        List<StaffRole> childPMList = pageUtils.getList();
        List<StaffRoleInfo> childPm = new ArrayList<>();
        for (StaffRole staffRole : childPMList) {
            StaffRoleInfo staffRoleInfo = new StaffRoleInfo();
            StaffEntity staffEntity = staffDao.selectStaffById(staffRole.getStaffId());
            BeanUtils.copyProperties(staffRole, staffRoleInfo);
            staffRoleInfo.setName(staffEntity.getName());
            staffRoleInfo.setHeaderUrl(staffEntity.getAvatar());
            List<StaffMenu> staffMenus = staffRoleMenuService.selectByRoleId(staffRole.getId());
            List<String> menuNames = new ArrayList<>();
            for (StaffMenu staffMenu : staffMenus) {
                menuNames.add(staffMenu.getName());
            }
            List<String> deparmentNames = new ArrayList<>();
            if (staffRole.getDepartmentId().equals(new Long(2))) {
                List<StaffRoleDepartment> staffRoleDepartments = staffRoleDepartmentService.selectStaffRoleDepartmentByStaffRoleId(staffRole.getId());
                for (StaffRoleDepartment staffRoleDepartment : staffRoleDepartments) {
                    DepartmentsEntity departmentsEntity = departmentsDao.selectByDepartmentId(staffRoleDepartment.getDepartmentId());
                    deparmentNames.add(departmentsEntity.getDepartmentName());
                }
            }
            StaffRoleMenu staffRoleMenu = staffRoleMenuService.selectStaffRoleMenuByRoleIdMenuId(staffRole.getId(), 1l);
            staffRoleInfo.setMenuId(staffRoleMenu != null ? 0 : 1);
            staffRoleInfo.setDeparmentNames(deparmentNames);
            staffRoleInfo.setMenuNames(menuNames);

            childPm.add(staffRoleInfo);
        }
        pageUtils.setList(childPm);
        List<StaffRole> bossList = staffRoleMapper.selectByRoleLevel(RoleEnums.BOSS.getName());
        List<StaffRoleInfo> boss = new ArrayList<>();
        for (StaffRole staffRole : bossList) {
            StaffRoleInfo staffRoleInfo = new StaffRoleInfo();
            staffRoleInfo.setId(staffRole.getId());
            StaffEntity staffEntity = staffDao.selectStaffById(staffRole.getStaffId());
            staffRoleInfo.setName(staffEntity.getName());
            staffRoleInfo.setHeaderUrl(staffEntity.getAvatar());
            boss.add(staffRoleInfo);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("masterPM", masterPM);
        map.put("childPm", pageUtils);
        map.put("boss", boss);
        return R.ok().put("data", map);
    }

    @Override
    public R selectRoleDetail(RoleModel roleModel) {
        StaffRole staffRole = staffRoleMapper.selectById(roleModel.getId());
        if (staffRole == null) {
            staffRole = new StaffRole();
        }
        StaffRoleDetailInfo info = new StaffRoleDetailInfo();
        BeanUtils.copyProperties(staffRole, info);
        List<StaffRoleDepartment> staffRoleDepartments = staffRoleDepartmentMapper.selectStaffRoleDepartmentByStaffRoleId(staffRole.getId());
        info.setDepartmentInfos(staffRoleDepartments);
        List<EvaluationGroupInfo> evaluationGroupInfos = staffRoleEvaluationGroupService.selectStaffRoleEvaluationGroupBy(roleModel.getId());
        info.setEvaluationGroupInfos(evaluationGroupInfos);
        List<StaffMenu> all = staffMenuService.selectAll();
        info.setStaffMenuInfos(all);
        List<StaffMenu> staffMenus = staffRoleMenuService.selectByRoleId(staffRole.getId());
        List<Long> selectStaffMenuInfos = new ArrayList<>();
        for (StaffMenu staffMenu : staffMenus) {
            selectStaffMenuInfos.add(staffMenu.getId());
        }
        info.setSelectStaffMenuInfos(selectStaffMenuInfos);
        return R.ok().put("data", info);
    }

    @Override
    public R roleAddOrUpdate(RoleModel roleModel) {
        if (roleModel.getId() == null && roleModel.getStaffId() == null) {
            return R.error("请传入 id 或 员工 id ");
        }
        List<Long> evaluationGroupInfoIds = StringUtil.getLongList(roleModel.getEvaluationGroupInfoStr());
        List<String> departmentInfoIds = StringUtil.getStringList(roleModel.getDepartmentInfoStr());
        List<Long> selectStaffMenuInfoIdIds = StringUtil.getLongList(roleModel.getSelectStaffMenuInfoStr());
        StaffEntity staffEntity = staffDao.selectStaffById(roleModel.getStaffId());
        StaffRole staffRole = null;
        if (roleModel.getId() != null) {
            staffRole = staffRoleMapper.selectStaffRoleById(roleModel.getId());
            //删除之前的数据
            staffRoleDepartmentService.deleteStaffRoleDepartmentByRoleId(staffRole.getId());
            staffRoleMenuService.deleteStaffRoleMenuByRoleId(staffRole.getId());
            staffRoleEvaluationGroupService.deleteStaffRoleEvaluationGroupByRoleId(staffRole.getId());
            com.lz.modules.app.utils.BeanUtils.copyProperty(staffRole, roleModel);
            staffEntity = staffDao.selectStaffById(roleModel.getStaffId());
            staffRole.setStaffName(staffEntity.getName());
            //如果当前子管理员修改成主管理员
            if (RoleEnums.MASTER_PM.getName().equals(roleModel.getDepartmentLevel())) {
                StaffRole data = staffRoleMapper.selectStaffRolesByStaffIdDepartmentLevelList(roleModel.getStaffId(), Arrays.asList(new String[]{RoleEnums.CHILD_PM.getName()}));
                if (data != null) {
                    staffRoleMapper.deleteStaffRoleById(data.getId()); //删除子管理员
                }
            }
            staffRoleMapper.updateStaffRoleById(staffRole);
            if (RoleEnums.BOSS.getName().equals(staffRole.getDepartmentLevel()) ||
                    RoleEnums.MASTER_PM.getName().equals(staffRole.getDepartmentLevel())) {
                return R.ok("更新成功");
            }
        } else if (roleModel.getStaffId() != null) { // 员工不为空,表示是新增数据
            StaffRole data = null;
            if (RoleEnums.CHILD_PM.getName().equals(roleModel.getDepartmentLevel()) //如果是主管理员，或者是子管理员，主管理员和子管理员不能同时存在
                    || RoleEnums.MASTER_PM.getName().equals(roleModel.getDepartmentLevel())) {
                data = staffRoleMapper.selectStaffRolesByStaffIdDepartmentLevelList(roleModel.getStaffId(),
                        Arrays.asList(new String[]{RoleEnums.CHILD_PM.getName(), RoleEnums.MASTER_PM.getName()}));
            } else {
                data = staffRoleMapper.selectStaffRolesByStaffIdDepartmentLevel(roleModel.getStaffId(), roleModel.getDepartmentLevel());
            }
            if (data != null) {
                return R.error("该管理员己经存在");
            }
            staffRole = new StaffRole();
            com.lz.modules.app.utils.BeanUtils.copyProperty(staffRole, roleModel);
            staffRole.setStaffName(staffEntity.getName());

            if (RoleEnums.MASTER_PM.getName().equals(staffRole.getDepartmentLevel())) {
                List<StaffRole> masterPMs = staffRoleMapper.selectStaffRolesByDepartmentLevelList(Arrays.asList(new String[]{RoleEnums.MASTER_PM.getName()}));
                if (CollectionUtils.isNotEmpty(masterPMs)) {
                    return R.error("主管理员只能设置一个,如果想添加，只能更改管理员。");
                }
            }
            staffRoleMapper.insertStaffRole(staffRole);
        }

        if (RoleEnums.BOSS.getName().equals(staffRole.getDepartmentLevel())) {
            insertPM(staffRole, RoleMenuEnums.BOSS.getType(), staffEntity);
        } else if (RoleEnums.MASTER_PM.getName().equals(staffRole.getDepartmentLevel())) {
            insertPM(staffRole, RoleMenuEnums.MASTER_PM.getType(), staffEntity);
        } else if (RoleEnums.CHILD_PM.getName().equals(staffRole.getDepartmentLevel())) {     //如果是子管理员
            if (new Long(0).equals(roleModel.getEvaluationGroupId())) {//全部考评组
                insertStaffRoleEvaluationGroup(staffRole.getId(), 0l);
            } else {///部分考评组
                for (Long evaluationGroupId : evaluationGroupInfoIds) {
                    insertStaffRoleEvaluationGroup(staffRole.getId(), evaluationGroupId);
                }
            }
            if (roleModel.getDepartmentId().equals(DepartmentPMEnums.SELF_DEPARTMENT.getType().toString())) {//如果是自己所在部门
                departmentInfoIds.clear();
                DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateService.selectLastDepartmentByStaffId(staffEntity.getId());
                departmentInfoIds.add(departmentsStaffRelateEntity.getDepartmentId());
            }
            for (String deparmentId : departmentInfoIds) {
                StaffRoleDepartment staffRoleDepartment = new StaffRoleDepartment();
                staffRoleDepartment.setDepartmentId(deparmentId);
                staffRoleDepartment.setStaffRoleId(staffRole.getId());
                DepartmentsEntity departmentsEntity = departmentsDao.selectByDepartmentId(deparmentId);
                staffRoleDepartment.setDepartmentName(departmentsEntity.getDepartmentName());
                staffRoleDepartmentService.insertStaffRoleDepartment(staffRoleDepartment);
            }

            for (Long staffMenuId : selectStaffMenuInfoIdIds) {
                StaffRoleMenu staffRoleMenu = new StaffRoleMenu();
                staffRoleMenu.setRoleId(staffRole.getId());
                staffRoleMenu.setMenuId(staffMenuId);
                staffRoleMenuService.insertStaffRoleMenu(staffRoleMenu);
            }
        }
        return R.ok();
    }

    @Override
    public R delete(RoleModel roleModel) {
        staffRoleMapper.deleteStaffRoleById(roleModel.getId());
        return R.ok();
    }

    @Override
    public List<StaffRole> selectAllByStaffId(Long staffId) {

        return staffRoleMapper.selectAllByStaffId(staffId);
    }

    @Override
    public Map<String, Integer> getRoleByUserId(Long userId) {
        Map<String, Integer> map = new HashMap<>();
        List<StaffRole> staffRoleList = staffRoleMapper.selectAllByStaffId(userId);
        List<StaffMenu> staffMenus = new ArrayList<>();

        List<StaffMenu> commonStaffList = staffMenuService.selectByParentId(RoleMenuEnums.COMMON_STAFF.getType());
        if (CollectionUtils.isNotEmpty(commonStaffList)) {
            staffMenus.addAll(commonStaffList);
        }
        //如果是部门领导
        boolean flag = false;
        DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateService.selectLastDepartmentByStaffId(userId);
        if (departmentsStaffRelateEntity != null && new Integer(1).equals(departmentsStaffRelateEntity.getIsLeader())) {
            List<StaffMenu> staffMenuDepartmentList = staffMenuService.selectByParentId(RoleMenuEnums.DEPARTMENT_PM.getType());
            if (CollectionUtils.isNotEmpty(staffMenuDepartmentList)) {
                staffMenus.addAll(staffMenuDepartmentList);
            }
            flag = true;
        }

        if (CollectionUtils.isNotEmpty(staffRoleList)) {
            for (StaffRole staffRole : staffRoleList) {
                if (staffRole.getDepartmentLevel().equals(RoleEnums.MASTER_PM.getName())) {        //如果是主管理员
                    List<StaffMenu> staffMenuList = staffMenuService.selectByParentId(RoleMenuEnums.MASTER_PM.getType());
                    if (CollectionUtils.isNotEmpty(staffMenuList)) {
                        staffMenus.addAll(staffMenuList);
                    }
                } else {
                    List<StaffMenu> staffMenuList = staffRoleMapper.selectAllMenus(staffRole.getStaffId());
                    if (CollectionUtils.isNotEmpty(staffMenuList)) {
                        staffMenus.addAll(staffMenuList);
                    }
                }
            }
            flag =true;
        }
        if (CollectionUtils.isNotEmpty(staffMenus) && staffMenus.size() > 0) {
            List<Long> authIds = new ArrayList<>();
            for (StaffMenu staffMenu : staffMenus) {
                List<Long> ids = StringUtil.splitToLongList(staffMenu.getAuthIds(), ",");
                authIds.addAll(ids);
            }
            if (authIds.size() > 0) {
                map = recordAuthService.selectAuthByIds(authIds);
            }
        }
        if(flag){
            map.put("toFast",1);
        }
        return map;
    }

    @Override
    public List<StaffRole> selectAllStaffRoleByDepartmentLevel(List<String> asList) {

        return staffRoleMapper.selectAllStaffRoleByDepartmentLevel(asList);
    }

    public void insertPM(StaffRole staffRole, Long parentId, StaffEntity staffEntity) {
        staffRole.setEvaluationGroupId(EvaluationGroupEnums.ALL.getType());//全部考评组
        staffRole.setDepartmentId(DepartmentPMEnums.ALL.getType());//所有部门
        staffRole.setStaffName(staffEntity.getName());
        List<StaffMenu> roots = staffMenuService.selectByParentId(parentId);
        for (StaffMenu staffMenu : roots) {
            StaffRoleMenu staffRoleMenu = new StaffRoleMenu();
            staffRoleMenu.setRoleId(staffRole.getId());
            staffRoleMenu.setMenuId(staffMenu.getId());
            staffRoleMenuService.insertStaffRoleMenu(staffRoleMenu);
        }
        if (parentId.equals(RoleMenuEnums.MASTER_PM.getType())) { //如果是绩效管理员
            insertStaffRoleEvaluationGroup(staffRole.getId(), 0l);
        }
    }

    public void insertStaffRoleEvaluationGroup(Long roleId, Long evaluationGroupId) {
        StaffRoleEvaluationGroup staffRoleEvaluationGroup = new StaffRoleEvaluationGroup();
        staffRoleEvaluationGroup.setRoleId(roleId);
        staffRoleEvaluationGroup.setEvaluationGroupId(evaluationGroupId);
        staffRoleEvaluationGroup.setIsSelect(1);
        staffRoleEvaluationGroupService.insertStaffRoleEvaluationGroup(staffRoleEvaluationGroup);
    }


    public void getStaffMenuInfo(StaffMenu parent, List<StaffMenu> all) {
        List<StaffMenu> childs = new ArrayList<>();
        for (StaffMenu child : all) {
            if (child.getParentId().equals(parent.getId())) {
                childs.add(child);
                getStaffMenuInfo(child, all);
            }
        }
        parent.setChilds(childs);
    }

    @Override
    public List<StaffRole> selectMastRoles() {
        return staffRoleMapper.selectMastRoles();
    }

    @Override
    public List<StaffRole> selectAllGroupManageRoles() {
        return staffRoleMapper.selectAllGroupManageRoles();
    }

    @Override
    public List<StaffRole> selectByEvaluationGroupId(Long groupId) {
        return staffRoleMapper.selectByEvaluationGroupId(groupId);
    }


    @Override
    public StaffRole selectStaffRolesByStaffIdDepartmentLevelList(Long staffId, List<String> departmentLevels) {

        return staffRoleMapper.selectStaffRolesByStaffIdDepartmentLevelList(staffId, departmentLevels);
    }

    @Override
    public R taskComment(TaskModel roleModel) {
        if (roleModel.getDetailId() == null && roleModel.getTaskId() == null) {
            return R.error("detailId和taskId不能同时为空");
        }
        TaskProcessRecord taskProcessRecord = new TaskProcessRecord();
        taskProcessRecord.setLabel(roleModel.getContent());
        taskProcessRecord.setTaskId(roleModel.getTaskId());
        if (roleModel.getTaskId() != null) {
            ResultTask resultTask = resultTaskService.selectResultTaskById(roleModel.getTaskId());
            taskProcessRecord.setDetailId(resultTask.getDetailId());
            taskProcessRecord.setType(1);
        } else {
            taskProcessRecord.setDetailId(roleModel.getDetailId());
            taskProcessRecord.setType(0);//
        }
        ResultDetail resultDetail = resultDetailService.selectResultDetailById(taskProcessRecord.getDetailId());
        taskProcessRecord.setResultRecordId(resultDetail.getRecordId());

        StaffEntity staffEntity = staffDao.selectStaffById(roleModel.getStaffId());
        if (staffEntity != null) {
            taskProcessRecord.setStaffId(staffEntity.getId());
            taskProcessRecord.setStaffName(staffEntity.getName());
        }

        taskProcessRecord.setAtStaffIds(roleModel.getAtStaffIds());
        StringBuilder staffNames = new StringBuilder();
        for (String staffIdStr : StringUtil.splitToList(roleModel.getAtStaffIds(), ",")) {
            if (StringUtil.isNotBlank(staffIdStr)) {
                StaffEntity atStaffEntity = staffDao.selectStaffById(NumberUtil.objToLongDefault(staffIdStr, 0l));
                if (atStaffEntity != null) {
                    staffNames.append(atStaffEntity.getName()).append(",");
                }
            }
        }
        taskProcessRecord.setAtStaffNames(staffNames.toString());
        taskProcessRecord.setUseType(1);
        taskProcessRecordService.insertTaskProcessRecord(taskProcessRecord);
        try {
            dingtalkBusiness.sendTaskNoticeMsg(taskProcessRecord.getDetailId(), taskProcessRecord.getTaskId());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return R.ok();
    }

    @Override
    public R commentList(TaskModel taskModel) {
        taskModel.setUseType(1);
        PageUtils pageUtils = PageUtils.startPage(taskModel.getCurrPage(), taskModel.getPageSize()).doSelect(
                page -> taskProcessRecordService.selectByCondition(page, taskModel)
        );
        List<TaskProcessRecord> pageUtilsList = pageUtils.getList();
        List<TaskCommentDto> taskCommentDtoList = new ArrayList<>();
        for (TaskProcessRecord taskProcessRecord : pageUtilsList) {
            TaskCommentDto taskCommentDto = new TaskCommentDto();
            BeanUtils.copyProperties(taskProcessRecord, taskCommentDto);
            if (taskProcessRecord.getStaffId().equals(taskModel.getStaffId())) {
                taskCommentDto.setIsSelf(1);
            }
            StaffEntity staffEntity = staffDao.selectStaffById(taskProcessRecord.getStaffId());
            if(staffEntity !=null){
                taskCommentDto.setAvatar(staffEntity.getAvatar());
            }
            if(taskProcessRecord.getTaskId() !=null){
                ResultTask resultTask = resultTaskService.selectResultTaskById(taskProcessRecord.getTaskId());
                if(resultTask !=null){
                    taskCommentDto.setTaskName(resultTask.getName());
                }
            }
            StaffOccupationEntity staffOccupationEntity = staffOccupationService.getStaffOccupationByStaffId(staffEntity.getId());
            if(staffOccupationEntity !=null ){
                taskCommentDto.setPosition(staffOccupationEntity.getPosition());
            }
            taskCommentDtoList.add(taskCommentDto);
        }

        pageUtils.setList(taskCommentDtoList);
        return R.ok().put("data", pageUtils);
    }


}
