package com.yida.data.system.service.impl;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.*;
import com.yida.data.common.core.entity.constant.AppConstant;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.constant.PageConstant;
import com.yida.data.common.core.entity.school.EduYidaAppAccount;
import com.yida.data.common.core.entity.system.*;
import com.yida.data.common.core.entity.system.enums.DeptTypeEnum;
import com.yida.data.common.core.entity.system.enums.RoleEnum;
import com.yida.data.common.core.entity.system.enums.UserStatusEnum;
import com.yida.data.common.core.entity.user.enums.DeptVisibleTypeEnum;
import com.yida.data.common.core.enums.EnableStatusEnum;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.*;
import com.yida.data.common.service.CommonService;
import com.yida.data.system.dto.AgentSchoolSaveDTO;
import com.yida.data.system.dto.AgentSchoolSelectPageDTO;
import com.yida.data.system.dto.SchoolInformationDTO;
import com.yida.data.system.dto.SchoolPageDTO;
import com.yida.data.system.mapper.DeptMapper;
import com.yida.data.system.mapper.DeptSchoolRelateMapper;
import com.yida.data.system.mapper.EduAppMapper;
import com.yida.data.system.service.*;
import com.yida.data.system.vo.AgentSchoolDetailVO;
import com.yida.data.system.vo.AgentSchoolSelectPageVO;
import com.yida.data.system.vo.AllDeptInfoVO;
import com.yida.data.system.vo.SchoolClassInfoVO;
import com.yida.data.user.feign.RemoteCourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author MrBird
 */
@Slf4j
@Service("deptService")
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    private final IUserDataPermissionService userDataPermissionService;
    private final EduAreaService eduAreaService;
    private final EduAppMapper eduAppMapper;
    private final WxUtil wxUtil;
    private final RemoteCourseService remoteCourseService;
    private final EduYidaAppService eduYidaAppService;
    private final EduAppAccountService eduAppAccountService;
    private final CommonService commonService;
    private final EduPayWxConfigService eduPayWxConfigService;
    private final EduAgentSchoolRelateService eduAgentSchoolRelateService;
    private final IUserService userService;
    private final RedisService redisService;
    private final DeptSchoolRelateMapper deptSchoolRelateMapper;
    private final DeptSchoolInformationService informationService;
    private final DeptSchoolStudentRangeService rangeService;
    private final EduLabelService labelService;
    private final DeptSchoolLabelService schoolLabelService;
    private final EduHotWordService hotWordService;
    private final DeptSchoolInformationService schoolInformationService;
    private final DeptSchoolInformationNatureService natureService;

    @Override
    public Dept getSchoolDeptByDeptAndWx(List<Long> deptId, Long wxId) {
        Dept exist = getOne(Wrappers.lambdaQuery(new Dept()).in(Dept::getParentId, deptId).eq(Dept::getWxId,
            wxId).ne(Dept::getDeptType, 6));
        if (exist == null) {
            List<Dept> deptList =
                list(Wrappers.lambdaQuery(new Dept()).in(Dept::getParentId, deptId).ne(Dept::getDeptType, 6));
            if (CollUtil.isNotEmpty(deptList)) {
                List<Long> deptIds = deptList.stream().map(x -> x.getDeptId()).collect(Collectors.toList());
                exist = getSchoolDeptByDeptAndWx(deptIds, wxId);
            }
        }
        return exist;
    }

    @Override
    public Dept getSysDeptByDeptAndWx(List<Long> deptId, Long wxId) {
        Dept exist = getOne(Wrappers.lambdaQuery(new Dept()).in(Dept::getParentId, deptId).eq(Dept::getWxId,
            wxId).eq(Dept::getDeptType, DeptTypeEnum.DEPARTMENT_TYPE.getValue()));
        if (exist == null) {
            List<Dept> deptList =
                list(Wrappers.lambdaQuery(new Dept()).in(Dept::getParentId, deptId)
                    .eq(Dept::getDeptType, DeptTypeEnum.DEPARTMENT_TYPE.getValue()));
            if (CollUtil.isNotEmpty(deptList)) {
                List<Long> deptIds = deptList.stream().map(Dept::getDeptId).collect(Collectors.toList());
                exist = getSysDeptByDeptAndWx(deptIds, wxId);
            }
        }
        return exist;
    }

    @Override
    public List<Dept> getSchoolByArea(Long areaId, String schoolName) {
        List<Long> areaIds = new ArrayList<>();
        if (areaId != null) {
            List<EduArea> child = eduAreaService.findAllChild(Collections.singletonList(areaId), true);
            if (CollUtil.isNotEmpty(child)) {
                areaIds.addAll(child.stream().map(EduArea::getId).collect(Collectors.toList()));
            }
            areaIds.add(areaId);
        }
        // 判断当前登陆角色
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        // 获取登陆用户的最大角色
        RoleEnum roleEnum = RoleUtil.getMaxRole(currentUser);
        // 学校负责人
        if (RoleEnum.ROLE_ADMIN.equals(roleEnum)) {
            return baseMapper.findListByAera(0, areaIds, schoolName);
        } else if (RoleEnum.ROLE_SCHOOL_PRINCIPAL.equals(roleEnum)) {
            return Collections.singletonList(this.getById(currentUser.getDeptId()));
        } else {
            // 查询下级部门信息
            List<Long> childIdList = findListByParent(Collections.singletonList(currentUser.getDeptId()), 0)
                .stream().map(Dept::getDeptId).collect(Collectors.toList());
            if (RoleEnum.ROLE_EDUCATION_PRINCIPAL.equals(roleEnum) ||
                RoleEnum.ROLE_AGENT_ADMIN.equals(roleEnum)) {
                childIdList.add(currentUser.getDeptId());
            }
            // 具有创建账号的数据   自己创建的账号+当前登陆账号部门以下的账号
            return this.baseMapper.listSchool(currentUser, childIdList, areaIds, schoolName);
        }
    }

    /**
     * @param deptId
     * @param type   0-包含学校的企业部门（后勤部等）与学校部门（校区学段等），1-仅学校部门，2-仅企业部门
     * @return
     */
    @Override
    public List<Dept> findListByParent(List<Long> deptId, Integer type) {
        List<Dept> res = new ArrayList<>();
        // 查询直接子部门
        LambdaQueryWrapper<Dept> condition = Wrappers.lambdaQuery(new Dept()).in(Dept::getParentId, deptId)
            .orderByDesc(Dept::getOrderNum);
//        if (type != null) {
//            if (type == 1) {
//                condition.ne(Dept::getDeptType, 6);
//            } else if (type == 2) {
//                condition.in(Dept::getDeptType, 0, 5, 6);
//            }
//        }
        List<Dept> child = list(condition);
        if (CollectionUtils.isNotEmpty(child)) {
            res.addAll(child);
            // 查询所有子节点的子节点
            List<Long> childId = child.stream().map(Dept::getDeptId).collect(Collectors.toList());
            res.addAll(findListByParent(childId, type));
        }
        return res;
    }

    @Override
    public List<Dept> findChildByParent(Long deptId, Integer type) {
        Dept condition = new Dept();
        condition.setParentId(deptId);
        if (type != null) {
            condition.setDeptType(type);
        }
        return baseMapper.selectList(Wrappers.lambdaQuery(condition).orderByDesc(Dept::getOrderNum));
    }


    @Override
    public List<Dept> findChildByParentAndType(List<Long> deptId, Integer type) {
        List<Dept> res = list(Wrappers.<Dept>lambdaQuery().in(Dept::getParentId, deptId).eq(Dept::getDeptType, type)
            .orderByDesc(Dept::getOrderNum));
        if (CollUtil.isEmpty(res)) {
            List<Dept> child = list(Wrappers.<Dept>lambdaQuery().in(Dept::getParentId, deptId));
            if (CollUtil.isNotEmpty(child)) {
                res = findChildByParentAndType(child.stream().map(x -> x.getDeptId()).collect(Collectors.toList()),
                    type);
            }
        }
        return res;
    }

    @Override
    public Dept findSchooleByDept(Long deptId) {
        Dept now = baseMapper.selectById(deptId);
        if (now != null && now.getDeptType() == 0) {
            return now;
        } else if (now != null) {
            return findSchooleByDept(now.getParentId());
        }
        return null;
    }

    /**
     * 根据部门id查询上级教育局或者学校部门信息
     *
     * @param deptId 部门id
     * @return com.yida.data.common.core.entity.system.Dept
     * @author ZYJ
     * @date 2021/11/24 10:00
     */
    private Dept findSchoolOrEducationByDept(Long deptId) {
        Dept now = this.baseMapper.selectById(deptId);
        if (now != null &&
            (DeptTypeEnum.SCHOOL_TYPE.getValue().equals(now.getDeptType())
                || DeptTypeEnum.EDUCATION_DEPT_TYPE.getValue().equals(now.getDeptType()))) {
            return now;
        } else if (now != null) {
            return findSchoolOrEducationByDept(now.getParentId());
        }
        return null;
    }

    @Override
    public Dept findGradeByDept(Long deptId) {
        Dept now = baseMapper.selectById(deptId);
        if (now != null && now.getDeptType() == 2) {
            return now;
        } else if (now != null) {
            return findGradeByDept(now.getParentId());
        }
        return null;
    }

    @Override
    public Map<String, Object> findDepts(QueryRequest request, Dept dept) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            List<Dept> depts = findDepts(dept, request);
            List<DeptTree> trees = new ArrayList<>();
            buildTrees(trees, depts);
            List<? extends Tree<?>> deptTree = TreeUtil.build(trees);

            result.put(PageConstant.ROWS, deptTree);
            result.put(PageConstant.TOTAL, depts.size());
        } catch (Exception e) {
            log.error("获取部门列表失败", e);
            result.put(PageConstant.ROWS, null);
            result.put(PageConstant.TOTAL, 0);
        }
        return result;
    }

    @Override
    public List<Dept> findDepts(Dept dept, QueryRequest request) {

        // 登陆用户
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        Objects.requireNonNull(currentUser);
        List<Dept> deptList = new ArrayList<>();
        // 父节点信息
        Dept parent = this.getById(currentUser.getDeptId());
        parent.setDisableStatus(true);
        deptList.add(parent);
        // 查询当前登陆用户下的所有子节点
        deptList.addAll(this.findListByParent(Collections.singletonList(currentUser.getDeptId()), 0));
        deptList.forEach(x -> {
            // 教育局、代理商查询对应的关联学校信息
            if (DeptTypeEnum.EDUCATION_DEPT_TYPE.getValue().equals(x.getDeptType()) ||
                DeptTypeEnum.AGENT_TYPE.getValue().equals(x.getDeptType())) {
                x.setRelationSchoolList(this.deptSchoolRelateMapper.selectList(Wrappers.lambdaQuery(new DeptSchoolRelate())
                    .eq(DeptSchoolRelate::getDeptId, x.getDeptId())).stream().map(DeptSchoolRelate::getSchoolId)
                    .collect(Collectors.toList()));
            }
        });
        return deptList;
    }

    @Override
    public void createDept(Dept dept) {
        EduYidaApp yidaApp = eduYidaAppService.getById(dept.getYidaAppId());
        if (dept.getParentId() == null) {
            dept.setParentId(Dept.TOP_DEPT_ID);
        } else if (dept.getParentWxId() == null) {
            Dept parent = getById(dept.getParentId());
            dept.setParentWxId(parent.getWxId());
        }
        // 学校 学生部门信息 同步进行企业微信家校通讯录部门创建
//        if (dept.getDeptType() >= 1 && dept.getDeptType() <= 4) {
//            Dept school = findSchooleByDept(dept.getParentId());
//            if (school != null) {
//                // 学校绑定了企业微信
//                if (school.getSchoolType().contains(Dept.TYPE_QYWX) && dept.getWxId() == null) {
//                    EduApp app = eduAppMapper.selectOne(Wrappers.lambdaQuery(new EduApp()).eq(EduApp::getDeptId,
//                            school.getDeptId()).eq(EduApp::getName, "家校沟通"));
//                    if (app != null) {
//                        Long wxId = wxUtil.createSchoolDept(wxUtil.getAccessToken(app.getWxCorpId(),
//                                app.getWxSecret()),
//                                dept);
//                        dept.setWxId(wxId);
//                    }
//                }
//                // 学校绑定了大华
//                if (school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
//                    Dept parentDept = getById(dept.getParentId());
//                    dept.setDahuaId(DaHuaUtil.addDept(parentDept.getDahuaId(), dept.getDeptName()).getStr(
//                            "id"));
//                }
//            }
//        } else

        if (DeptTypeEnum.DEPARTMENT_TYPE.getValue().equals(dept.getDeptType())) {
            // 该部门为学校或教育局下属部门
            Dept parent = findSchoolOrEducationByDept(dept.getParentId());
            // 挂在学校的部门需要同步企业微信
            if (parent != null && DeptTypeEnum.SCHOOL_TYPE.getValue().equals(parent.getDeptType())
                && parent.getSchoolType().contains(Dept.TYPE_QYWX)
                && dept.getWxId() == null) {
                EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT, null, parent.getDeptId());
                if (app != null) {
                    Long wxId = wxUtil.createDept(commonService.getAddressListToken(app.getDeptId()), dept);
                    dept.setWxId(wxId);
                }
            }
        } else if (DeptTypeEnum.SCHOOL_TYPE.getValue().equals(dept.getDeptType())) {
            // 学校微信id默认为1
            dept.setWxId(1L);
            if (StrUtil.isNotBlank(dept.getSchoolType()) && dept.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
                // 添加栏目
                String colId = AppUtil.colSave(null, dept.getDeptName(), yidaApp);
                dept.setYidaAppColId(colId);
            }
        } else if (DeptTypeEnum.EDUCATION_DEPT_TYPE.getValue().equals(dept.getDeptType()) &&
            StrUtil.isNotBlank(dept.getSchoolType()) && dept.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
            dept.setYidaAppColId(yidaApp.getAppColId());
        }
        this.save(dept);
        // 创建绑定易达的学校
        if (DeptTypeEnum.SCHOOL_TYPE.getValue().equals(dept.getDeptType())
            && StrUtil.isNotBlank(dept.getSchoolType())
            && dept.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
            // 保存学校栏目到区域位下
            List<Dept> list = list(Wrappers.lambdaQuery(new Dept())
                .eq(Dept::getDeptType, 0)
                .eq(Dept::getYidaAppId, yidaApp.getId())
                .like(Dept::getSchoolType, Dept.TYPE_YIDA_APP));
            if (CollUtil.isNotEmpty(list)) {
                JSONArray content = new JSONArray();
                for (Dept col : list) {
                    content.add(new JSONObject() {{
                        set("id", col.getYidaAppColId());
                        if (StrUtil.isNotBlank(col.getIcon())) {
                            set("img", col.getIcon());
                        }
                    }});
                }
                String regionId = AppUtil.regionUpdate(yidaApp.getAppSchoolRegionId(), "热门学校", 0,
                    yidaApp.getAppColId(),
                    AppUtil.REGION_TYPE_HOT, content, yidaApp);
                if (StrUtil.isBlank(yidaApp.getAppSchoolRegionId())) {
                    yidaApp.setAppSchoolRegionId(regionId);
                    eduYidaAppService.updateById(yidaApp);
                }
            }
            // 添加订阅号
            for (int i = 0; i < 2; i++) {
                EduYidaAppAccount appAccount = new EduYidaAppAccount();
                appAccount.setSchoolId(dept.getDeptId());
                appAccount.setType(i);
                appAccount.setYidaAppAccountName(dept.getDeptName() + (i == 0 ? "" : "办公"));
                appAccount.setLogo(dept.getIcon());
                String accountId = AppUtil.subscribeSave(appAccount, yidaApp);
                appAccount.setYidaAppAccountId(accountId);
                eduAppAccountService.save(appAccount);
            }
        } else if (DeptTypeEnum.EDUCATION_DEPT_TYPE.getValue().equals(dept.getDeptType()) ||
            DeptTypeEnum.AGENT_TYPE.getValue().equals(dept.getDeptType())) {
            CurrentUser currentUser = FebsUtil.getCurrentUser();
            if (CollUtil.isNotEmpty(dept.getRelationSchoolList())) {
                // 处理关联学校数据
                dept.getRelationSchoolList().forEach(schoolId -> {
                    DeptSchoolRelate deptSchoolRelate = DeptSchoolRelate.builder()
                        .deptId(dept.getDeptId())
                        .createDeptId(currentUser.getDeptId())
                        .createId(currentUser.getUserId())
                        .createDate(LocalDateTime.now())
                        .schoolId(schoolId)
                        .build();
                    this.deptSchoolRelateMapper.insert(deptSchoolRelate);
                    List<DeptSchoolInformation> list = schoolInformationService.list(
                        Wrappers.query(new DeptSchoolInformation()).lambda()
                            .eq(DeptSchoolInformation::getSchoolId, deptSchoolRelate.getSchoolId()));

                    if (CollectionUtil.isEmpty(list)) {
                        DeptSchoolInformation deptSchoolInformation = new DeptSchoolInformation();
                        deptSchoolInformation.setSchoolId(deptSchoolRelate.getSchoolId());
                        deptSchoolInformation.setSchoolName(getById(schoolId).getDeptName());
                        schoolInformationService.save(deptSchoolInformation);
                    }

                });
            }
        }
        // 初始化课程
        if (dept.getDeptType() != null && DeptTypeEnum.SCHOOL_TYPE.getValue().equals(dept.getDeptType())) {
            remoteCourseService.initCourse(dept.getDeptId());
        }
    }

    @Override
    public void updateDept(Dept dept) {
        Dept original = this.getById(dept.getDeptId());
        log.info("dept:[{}]", dept);
        if (dept.getParentId() == null) {
            dept.setParentId(Dept.TOP_DEPT_ID);
        }
        CurrentUser currentUser = FebsUtil.getCurrentUser();
//        dept = getById(dept.getDeptId());

        // 非学校与公司部门  同步进行企业微信部门更新
//        if (dept.getDeptType() >= 1 && dept.getDeptType() <= 4) {
//            Dept school = findSchooleByDept(dept.getDeptId());
//            if (school != null) {
//                // 学校绑定了企业微信
//                if (school.getSchoolType().contains(Dept.TYPE_QYWX)) {
//                    EduApp app = eduAppMapper.selectOne(Wrappers.lambdaQuery(new EduApp()).eq(EduApp::getDeptId,
//                            school.getDeptId()).eq(EduApp::getName, "家校沟通"));
//                    if (app != null) {
//                        wxUtil
//                                .updateSchoolDept(wxUtil.getAccessToken(app.getWxCorpId(), app.getWxSecret()), dept, null);
//                    }
//                }
//                // 学校绑定了大华
//                if (school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
//                    Dept parentDept = getById(dept.getParentId());
//                    Dept existDept = getById(dept.getDeptId());
//                    dept.setDahuaId(DaHuaUtil.updateDept(existDept.getDahuaId(), parentDept.getDahuaId(),
//                            dept.getDeptName()).getStr("id"));
//                }
//            }
//        } else

        if (DeptTypeEnum.SCHOOL_TYPE.getValue().equals(dept.getDeptType())) {
            // 绑定了易达app
            if (StrUtil.isNotBlank(dept.getSchoolType()) && dept.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
                // 添加栏目
                EduYidaApp yidaApp = eduYidaAppService.getById(original.getYidaAppId());
                String colId = AppUtil.colSave(original.getYidaAppColId(), dept.getDeptName(), yidaApp);
                dept.setYidaAppColId(colId);
                // 保存栏目到订阅号下
                List<Dept> list = list(Wrappers.lambdaQuery(new Dept())
                    .eq(Dept::getDeptType, 0)
                    .like(Dept::getSchoolType, Dept.TYPE_YIDA_APP)
                    .eq(Dept::getYidaAppId, original.getYidaAppId()));
                if (CollUtil.isNotEmpty(list)) {
                    JSONArray content = new JSONArray();
                    for (Dept col : list) {
                        content.add(new JSONObject() {{
                            set("id", col.getYidaAppColId());
                            if (StrUtil.isNotBlank(col.getIcon())) {
                                set("img", col.getIcon());
                            }
                        }});
                    }
                    String regionId = AppUtil.regionUpdate(yidaApp.getAppSchoolRegionId(), "热门学校", 0,
                        yidaApp.getAppColId(),
                        AppUtil.REGION_TYPE_HOT, content, yidaApp);

                    if (StrUtil.isBlank(yidaApp.getAppSchoolRegionId())) {
                        yidaApp.setAppSchoolRegionId(regionId);
                        eduYidaAppService.updateById(yidaApp);
                    }
                }
                // 添加订阅号
//                List<EduYidaAppAccount> accountList = eduAppAccountService
//                        .list(Wrappers.lambdaQuery(new EduYidaAppAccount())
//                                .eq(EduYidaAppAccount::getSchoolId, dept.getDeptId()));
//                for (EduYidaAppAccount appAccount : accountList) {
//                    appAccount.setYidaAppAccountName(dept.getDeptName() + (appAccount.getType() == 0 ? "-通知" : ""));
//                    appAccount.setLogo(dept.getIcon());
//                    String accountId = AppUtil.subscribeSave(appAccount, yidaApp);
//                    appAccount.setYidaAppAccountId(accountId);
//                    eduAppAccountService.updateById(appAccount);
//                }
                for (int i = 0; i < 2; i++) {
                    EduYidaAppAccount appAccount = eduAppAccountService
                        .getOne(Wrappers.lambdaQuery(new EduYidaAppAccount())
                            .eq(EduYidaAppAccount::getSchoolId, dept.getDeptId())
                            .eq(EduYidaAppAccount::getType, i));
                    if (appAccount == null) {
                        appAccount = new EduYidaAppAccount();
                    }
                    appAccount.setSchoolId(dept.getDeptId());
                    appAccount.setType(i);
                    appAccount.setYidaAppAccountName(dept.getDeptName() + (i == 0 ? "-通知" : "-办公"));
                    appAccount.setLogo(dept.getIcon());
                    String accountId = AppUtil.subscribeSave(appAccount, yidaApp);
                    appAccount.setYidaAppAccountId(accountId);
                    eduAppAccountService.saveOrUpdate(appAccount);
                }
            }
        } else if (DeptTypeEnum.DEPARTMENT_TYPE.getValue().equals(dept.getDeptType())) {
            // 该部门为学校、代理商或教育局下属部门
            Dept parent = findSchoolOrEducationByDept(dept.getParentId());
            // 挂在学校的部门需要同步企业微信
            if (Objects.nonNull(parent) && DeptTypeEnum.SCHOOL_TYPE.getValue().equals(parent.getDeptType())
                && parent.getSchoolType().contains(Dept.TYPE_QYWX)) {
                EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT, null, parent.getDeptId());
                if (app != null) {
                    dept.setWxId(original.getWxId());
                    wxUtil.updateDept(commonService.getAddressListToken(app.getDeptId()), dept);
                }
            }
        } else if (DeptTypeEnum.EDUCATION_DEPT_TYPE.getValue().equals(dept.getDeptType()) ||
            DeptTypeEnum.AGENT_TYPE.getValue().equals(dept.getDeptType())) {
            // 教育局、代理商
            if (DeptTypeEnum.AGENT_TYPE.getValue().equals(dept.getDeptType()) &&
                CollectionUtils.isEmpty(dept.getRelationSchoolList())) {
                throw new FebsException("请选择关联的学校");
            }
            // 删除关联学校数据
            this.deptSchoolRelateMapper.delete(Wrappers.lambdaQuery(new DeptSchoolRelate())
                .eq(DeptSchoolRelate::getDeptId, dept.getDeptId()));
            // 绑定了易达app
            if (StrUtil.isNotBlank(dept.getSchoolType()) && dept.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
                // 设置教育局栏目id
                EduYidaApp yidaApp = eduYidaAppService.getById(dept.getYidaAppId());
                dept.setYidaAppColId(yidaApp.getAppColId());
            }
            if (CollUtil.isNotEmpty(dept.getRelationSchoolList())) {
                // 处理关联学校数据
                dept.getRelationSchoolList().forEach(schoolId -> {
                    DeptSchoolRelate deptSchoolRelate = DeptSchoolRelate.builder()
                        .deptId(original.getDeptId())
                        .createDeptId(currentUser.getDeptId())
                        .createId(currentUser.getUserId())
                        .createDate(LocalDateTime.now())
                        .schoolId(schoolId)
                        .build();
                    this.deptSchoolRelateMapper.insert(deptSchoolRelate);
                    //关联关系表学校放入学校信息表
                    List<DeptSchoolInformation> list = schoolInformationService.list(
                        Wrappers.query(new DeptSchoolInformation()).lambda()
                            .eq(DeptSchoolInformation::getSchoolId, deptSchoolRelate.getSchoolId()));
                    if (CollectionUtil.isEmpty(list)) {
                        DeptSchoolInformation deptSchoolInformation = new DeptSchoolInformation();
                        deptSchoolInformation.setSchoolName(getById(schoolId).getDeptName());
                        deptSchoolInformation.setSchoolId(deptSchoolRelate.getSchoolId());
                        schoolInformationService.save(deptSchoolInformation);
                    }
                });
            }
        }
        updateById(dept);
        // 删除部门缓存
        redisService.hdel(CachePrefixConstant.SYS_DEPT_DATA, dept.getDeptId().toString());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDepts(String[] deptIds) {
        // 删除企业微信部门信息
        List<Dept> deptList =
            list(Wrappers.lambdaQuery(new Dept()).in(Dept::getDeptId, deptIds).notIn(Dept::getDeptType
                , 0, 5));
        for (Dept dept : deptList) {
            Dept school = findSchooleByDept(dept.getDeptId());
            // 绑定了微信
            if (Objects.nonNull(school) && school.getSchoolType().contains(Dept.TYPE_QYWX)) {
                EduApp app = commonService.getAppByCodeAndSchool(AppConstant.CONTACT, null,
                    school.getDeptId());
                // 同步删除企业微信部门
                if (dept.getDeptType() == 6) {
                    wxUtil.deleteDept(commonService.getAddressListToken(school.getDeptId()), dept.getWxId());
                }
            }
            // 绑定了大华
            if (Objects.nonNull(school) && school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
                DaHuaUtil.delDept(Collections.singletonList(dept.getDahuaId()));
            }
            // 教育局、代理商
            if (DeptTypeEnum.EDUCATION_DEPT_TYPE.getValue().equals(dept.getDeptType()) ||
                DeptTypeEnum.AGENT_TYPE.getValue().equals(dept.getDeptType())) {
                // 删除关联学校数据
                this.deptSchoolRelateMapper.delete(Wrappers.lambdaQuery(new DeptSchoolRelate())
                    .eq(DeptSchoolRelate::getDeptId, dept.getDeptId()));
            }
        }
        List<Dept> delYidaSchool =
            list(Wrappers.<Dept>lambdaQuery().in(Dept::getDeptId, deptIds).eq(Dept::getDeptType, 0)
                .like(Dept::getSchoolType, "1"));
        this.delete(Arrays.asList(deptIds));
        // 更新学校列表
        if (CollUtil.isNotEmpty(delYidaSchool)) {
            List<Long> yidaAppIds =
                delYidaSchool.stream().map(Dept::getYidaAppId).distinct().collect(Collectors.toList());
            for (Long yidaAppId : yidaAppIds) {
                EduYidaApp yidaApp = eduYidaAppService.getById(yidaAppId);
                List<Dept> schoolList = list(Wrappers.<Dept>lambdaQuery()
                    .eq(Dept::getYidaAppId, yidaAppId)
                    .eq(Dept::getDeptType, 0)
                    .like(Dept::getSchoolType, "1"));

                AppUtil.regionUpdate(yidaApp.getAppSchoolRegionId(), "热门学校", 0, yidaApp.getAppColId(),
                    AppUtil.REGION_TYPE_HOT,
                    new JSONArray() {{
                        for (Dept dept : schoolList) {
                            add(
                                new JSONObject() {{
                                    set("id", dept.getYidaAppColId());
                                    if (StrUtil.isNotBlank(dept.getIcon())) {
                                        set("img", dept.getIcon());
                                    }
                                }});
                        }
                    }}
                    , yidaApp);
            }
        }

        // 删除部门缓存
        redisService.hdel(CachePrefixConstant.SYS_DEPT_DATA, deptIds);
    }

    @Override
    public void deleteDeptRecur(List<Long> deptId, Dept school) {
        List<Dept> child = baseMapper.selectList(Wrappers.lambdaQuery(new Dept()).in(Dept::getParentId, deptId));
        // 先删除子节点
        if (CollUtil.isNotEmpty(child)) {
            deleteDeptRecur(child.stream().map(x -> x.getDeptId()).collect(Collectors.toList()), school);
        }
        // 删除大华部门
        if (school != null && school.getSchoolType().contains(Dept.TYPE_DAHUA)) {
            Collection<Dept> depts = listByIds(deptId);
            DaHuaUtil.delDept(depts.stream().map(x -> x.getDahuaId()).collect(Collectors.toList()));
        }
        removeByIds(deptId);
        // 删除部门缓存
        redisService
            .hdel(CachePrefixConstant.SYS_DEPT_DATA, deptId.stream().map(x -> x.toString()).toArray(String[]::new));
    }

    private void buildTrees(List<DeptTree> trees, List<Dept> depts) {
        depts.forEach(dept -> {
            DeptTree tree = new DeptTree();
            tree.setId(dept.getDeptId().toString());
            tree.setParentId(dept.getParentId() != null ? dept.getParentId().toString() : null);
            tree.setLabel(dept.getDeptName());
            tree.setOrderNum(dept.getOrderNum());
            tree.setDisabled(dept.isDisableStatus());

            tree.setWxId(dept.getWxId());
            tree.setType(dept.getDeptType());
            tree.setParentWxId(dept.getParentWxId());
            tree.setCorpId(dept.getCorpId());
            tree.setWxCallToken(dept.getWxCallToken());
            tree.setWxAesKey(dept.getWxAesKey());
            tree.setYidaAppId(dept.getYidaAppId());
            tree.setIcon(dept.getIcon());
            tree.setRelationSchoolList(dept.getRelationSchoolList());
            trees.add(tree);
        });
    }

    private void delete(List<String> deptIds) {
        removeByIds(deptIds);
        userDataPermissionService.deleteByDeptIds(deptIds);
        this.deptSchoolRelateMapper.delete(Wrappers.lambdaQuery(new DeptSchoolRelate())
            .in(DeptSchoolRelate::getSchoolId, deptIds));
        LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dept::getParentId, deptIds);
        List<Dept> depts = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(depts)) {
            List<String> deptIdList = new ArrayList<>();
            depts.forEach(d -> deptIdList.add(String.valueOf(d.getDeptId())));
            this.delete(deptIdList);
        }
    }

    @Override
    public Dept getParentById(Long deptId) {
        Dept dept = getById(deptId);
        return getById(dept.getParentId());
    }

    @Override
    public List getDeptTree(Long deptId, Integer type) {
        List<Dept> allDepts = new ArrayList<>();
        // 添加根节点
        Dept root = getById(deptId);
        if (root.getParentId() != null) {
            root.setParentId(null);
            root.setParentWxId(null);
        }
        allDepts.add(root);
        // 循环查询子节点
        allDepts.addAll(findListByParent(Arrays.asList(deptId), type));

        List<DeptTree> trees = new ArrayList<>();
        buildTrees(trees, allDepts);
        List<? extends Tree<?>> deptTree = TreeUtil.build(trees);
        return deptTree;
    }

    @Override
    public List getDeptTree(List<Long> deptIds) {
        List<Dept> allDepts = new ArrayList<>();
        List<Long> rootIdList = new ArrayList<>();
        if (CollUtil.isNotEmpty(deptIds)) {
            for (Long deptId : deptIds) {
                // 添加根节点
                Dept root = getById(deptId);
                if (ObjectUtil.isNotNull(root)) {
                    if (root.getParentId() != null) {
                        root.setParentId(null);
                        root.setParentWxId(null);
                    }
                    allDepts.add(root);
                    rootIdList.add(deptId);
                }
            }
        }
        // 循环查询子节点
        allDepts.addAll(findListByParent(rootIdList, 2));
        List<DeptTree> trees = new ArrayList<>();
        buildTrees(trees, allDepts);
        List<? extends Tree<?>> deptTree = TreeUtil.build(trees);
        return deptTree;
    }

    @Override
    public List<Long> listClassByDept(List<Long> ids) {
        List<Long> res = new ArrayList<>();
        if (CollUtil.isNotEmpty(ids)) {
            List<Dept> child = list(Wrappers.lambdaQuery(new Dept()).in(Dept::getParentId, ids));
            res.addAll(
                child.stream().filter(x -> x.getDeptType() == 1).map(x -> x.getDeptId()).collect(Collectors.toList()));
            res.addAll(listClassByDept(
                child.stream().filter(x -> x.getDeptType() != 1).map(x -> x.getDeptId()).collect(Collectors.toList())));
        }
        return res;
    }

    @Override
    public Dept getDeptBySchoolAndName(List<Long> deptId, String deptName) {
        List<Dept> deptList = list(Wrappers.lambdaQuery(new Dept()).eq(Dept::getDeptName, deptName).in(Dept
            ::getParentId, deptId).eq(Dept::getDeptType, 6));
        if (CollUtil.isEmpty(deptList)) {
            List<Dept> child = list(Wrappers.lambdaQuery(new Dept()).in(Dept::getParentId, deptId));
            if (CollUtil.isNotEmpty(child)) {
                return getDeptBySchoolAndName(child.stream().map(x -> x.getDeptId()).collect(Collectors.toList()),
                    deptName);
            }
            return null;
        } else {
            return deptList.get(0);
        }
    }

    @Override
    public SchoolClassInfoVO getSchoolAreaInfo(Long id) {
        return baseMapper.getSchoolAreaInfo(id);
    }

    @Override
    public AllDeptInfoVO findParentUp(Long deptId, Integer type) {
        AllDeptInfoVO vo = new AllDeptInfoVO();
        // 查询本级
        Dept self = getById(deptId);
        if (compareDept(type, self.getDeptType())) {
            while (type.equals(self.getDeptType())) {
                switch (self.getDeptType()) {
                    case 0:
                        vo.setSchoolId(self.getDeptId());
                        vo.setSchoolName(self.getDeptName());
                        break;
                    case 1:
                        vo.setClassId(self.getDeptId());
                        vo.setClassName(self.getDeptName());
                        break;
                    case 2:
                        vo.setGradeId(self.getDeptId());
                        vo.setGradeName(self.getDeptName());
                        break;
                    case 3:
                        vo.setSectionId(self.getDeptId());
                        vo.setSectionName(self.getDeptName());
                        break;
                    case 4:
                        vo.setCampusId(self.getDeptId());
                        vo.setCampusName(self.getDeptName());
                        break;
                    case 5:
                        vo.setCompanyId(self.getDeptId());
                        vo.setCompanyName(self.getDeptName());
                        break;
                    default:
                }
                self = getById(self.getParentId());
            }
            switch (self.getDeptType()) {
                case 0:
                    vo.setSchoolId(self.getDeptId());
                    vo.setSchoolName(self.getDeptName());
                    break;
                case 1:
                    vo.setClassId(self.getDeptId());
                    vo.setClassName(self.getDeptName());
                    break;
                case 2:
                    vo.setGradeId(self.getDeptId());
                    vo.setGradeName(self.getDeptName());
                    break;
                case 3:
                    vo.setSectionId(self.getDeptId());
                    vo.setSectionName(self.getDeptName());
                    break;
                case 4:
                    vo.setCampusId(self.getDeptId());
                    vo.setCampusName(self.getDeptName());
                    break;
                case 5:
                    vo.setCompanyId(self.getDeptId());
                    vo.setCompanyName(self.getDeptName());
                    break;
                default:
            }
        }
        return vo;
    }

    @Override
    public IPage<Dept> getPageSchoolByArea(Long areaId, String schoolName, Page page) {

        Dept dept = new Dept();
        dept.setDeptType(0);
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>(dept);

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Dept getClassBySchoolAndWx(Long schoolId, Long classWxId) {
        // 查询到学校年级层
        List<Dept> campusList = list(
            Wrappers.<Dept>lambdaQuery().eq(Dept::getParentId, schoolId).eq(Dept::getDeptType, 4));
        List<Dept> sectionList =
            list(Wrappers.<Dept>lambdaQuery()
                .in(Dept::getParentId, campusList.stream().map(x -> x.getDeptId()).collect(Collectors.toList()))
                .eq(Dept::getDeptType, 3));
        List<Dept> gradeList =
            list(Wrappers.<Dept>lambdaQuery()
                .in(Dept::getParentId, sectionList.stream().map(x -> x.getDeptId()).collect(Collectors.toList()))
                .eq(Dept::getDeptType, 2));
        return getOne(Wrappers.<Dept>lambdaQuery()
            .in(Dept::getParentId, gradeList.stream().map(x -> x.getDeptId()).collect(Collectors.toList()))
            .eq(Dept::getWxId,
                classWxId));
    }

    @Override
    public void syncQywxDept(Long schoolId) {
        // 查询所有和企业微信关联的学校信息
        List<Dept> schoolList = new ArrayList<>();
        if (Objects.isNull(schoolId)) {
            // 查询所有绑定了企业微信的学校信息
            schoolList = list(Wrappers.<Dept>lambdaQuery()
                .eq(Dept::getDeptType, DeptTypeEnum.SCHOOL_TYPE.getValue())
                .like(Dept::getSchoolType, Dept.TYPE_QYWX));
        } else {
            Dept school = getById(schoolId);
            schoolList.add(school);
        }

        if (CollUtil.isNotEmpty(schoolList)) {
            for (Dept school : schoolList) {
                EduApp contactApp = commonService.getAppContactUsedBySelect(school.getDeptId());
                // 获取办公部门
                log.info("[{}]开始同步办公部门", school.getDeptName());
                List<Map> deptList = wxUtil
                    .listSimpleDept(wxUtil.getAccessToken(contactApp.getWxCorpId(), contactApp.getWxSecret()),
                        school.getWxId());
                // 保存办公部门
                Map<Long, Long> idCache = new HashMap<>();
                idCache.put(1L, school.getDeptId());
                for (Map map : deptList) {
                    Long wxId = Long.valueOf(map.get("id").toString());
                    Long parentWxId = Long.valueOf(map.get("parentid").toString());
//                    String deptName = map.get("name").toString();
                    Integer order = Integer.valueOf(map.get("order").toString());
                    Long parentId = idCache.get(parentWxId);
                    if (wxId == 1) {
                        continue;
                    }
                    // 获取单个部门详情
                    JSONObject deptInfo = wxUtil.getDeptInfo(
                        wxUtil.getAccessToken(contactApp.getWxCorpId(), contactApp.getWxSecret()), String.valueOf(wxId));
                    String deptName = deptInfo.get("name").toString();
                    Dept exist = getOne(Wrappers.<Dept>lambdaQuery().eq(Dept::getParentId, parentId)
                        .eq(Dept::getWxId, wxId).eq(Dept::getDeptType, 6));
                    if (exist == null) {
                        exist = new Dept();
                    }
                    exist.setParentId(parentId);
                    exist.setDeptName(deptName);
                    exist.setDeptType(DeptTypeEnum.DEPARTMENT_TYPE.getValue());
                    exist.setAreaId(school.getAreaId());
                    exist.setWxId(wxId);
                    exist.setParentWxId(parentWxId);
                    exist.setOrderNum(order);
                    saveOrUpdate(exist);
                    idCache.put(exist.getWxId(), exist.getDeptId());
                }
            }
        }
        log.info("企业微信部门同步完成");
    }

    @Override
    public void dealNoParentDept() {
        List<Dept> schools = list(Wrappers.lambdaQuery(new Dept())
            .eq(Dept::getDeptType, DeptTypeEnum.SCHOOL_TYPE.getValue()));
        if (CollUtil.isNotEmpty(schools)) {
            List<Long> schoolIds = schools.stream().map(Dept::getDeptId).collect(Collectors.toList());
            schoolIds.forEach(schoolId -> {
                List<Dept> depts = list(Wrappers.lambdaQuery(new Dept())
                    .eq(Dept::getVisible, DeptVisibleTypeEnum.INVISIBLE_TYPE.getValue())
                    .eq(Dept::getParentId, schoolId)
                    .ne(Dept::getDeptType, DeptTypeEnum.COMPANY_TYPE.getValue()));
                for (Dept dept : depts) {
                    if (StrUtil.isNotBlank(dept.getCorpId())) {
                        Dept parent = getOne(Wrappers.lambdaQuery(new Dept())
                            .eq(Dept::getCorpId, dept.getCorpId())
                            .eq(Dept::getWxId, dept.getParentWxId()));
                        if (parent != null) {
                            dept.setParentId(parent.getDeptId());
                            dept.setVisible(DeptVisibleTypeEnum.VISIBLE_TYPE.getValue());
                            updateById(dept);
                        }
                    }
                }
            });
        }
    }

    /**
     * 判断部门一是否在部门二的上层
     */
    private Boolean compareDept(Integer type1, Integer type2) {
        if (type1 == 0 && type2 != 5) {
            return true;
        }
        if (type1 == 6 && type2 != 0 && type2 != 5 && type2 != 4) {
            return true;
        }
        if (type1 >= type2) {
            return true;
        }
        return false;
    }

    /**
     * 查询代理商管理的学校列表数据
     *
     * @param agentSchoolSelectPageDTO 查询代理商管理的学校列表数据请求类
     * @return com.yida.data.common.core.common.ResultBean<com.baomidou.mybatisplus.core.metadata.IPage <
        * com.yida.data.system.vo.AgentSchoolVO>>
     * @author ZYJ
     * @date 2021/9/27 17:05
     */
    @Override
    public ResultBean<IPage<AgentSchoolSelectPageVO>> listAgentSchoolPage(
        AgentSchoolSelectPageDTO agentSchoolSelectPageDTO) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        // 查询下级部门信息
        List<Long> childIdList = findListByParent(Collections.singletonList(currentUser.getDeptId()), 0)
            .stream().map(Dept::getDeptId).collect(Collectors.toList());
        // 代理商管理员查询当前代理商所有数据
        if (RoleEnum.ROLE_AGENT_ADMIN.equals(RoleUtil.getMaxRole(currentUser))) {
            childIdList.add(currentUser.getDeptId());
        }
        // 具有创建学校列表的数据   自己创建的学校+当前登陆账号部门以下的学校
        IPage<AgentSchoolSelectPageVO> iPage = this.baseMapper
            .listAgentSchoolPage(agentSchoolSelectPageDTO.toPage(), agentSchoolSelectPageDTO,
                childIdList, currentUser);
        return ResultBean.buildSuccess(iPage);
    }

    /**
     * 代理商保存学校数据
     *
     * @param agentSchoolSaveDTO 代理商保存学校请求类
     * @return com.yida.data.common.core.common.ResultBean<java.lang.String>
     * @author ZYJ
     * @date 2021/9/27 18:00
     */
    @Override
    public ResultBean<String> saveAgentSchool(AgentSchoolSaveDTO agentSchoolSaveDTO) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        if (Objects.nonNull(agentSchoolSaveDTO)) {
            Dept dept = new Dept();
            BeanUtils.copyProperties(agentSchoolSaveDTO, dept);
            dept.setParentId(1L);
            dept.setDeptType(DeptTypeEnum.SCHOOL_TYPE.getValue());
            // 新增学校
            if (Objects.isNull(dept.getDeptId())) {
                createDept(dept);
                // 保存代理商和学校关联关系
                DeptSchoolRelate deptSchoolRelate = new DeptSchoolRelate();
                // 获取代理商登录信息相关部门id
                Long deptId = FebsUtil.getTopDeptId();

                deptSchoolRelate.setDeptId(deptId);
                deptSchoolRelate.setSchoolId(dept.getDeptId());
                deptSchoolRelate.setCreateDeptId(currentUser.getDeptId());
                this.deptSchoolRelateMapper.insert(deptSchoolRelate);
            } else {
                updateDept(dept);
            }
            // 查询学校已有微信支付配置信息
            EduPayWxConfig payWxConfig = this.eduPayWxConfigService.getOne(Wrappers.lambdaQuery(new EduPayWxConfig())
                .eq(EduPayWxConfig::getSchoolId, dept.getDeptId()));
            if (Objects.isNull(payWxConfig)) {
                payWxConfig = new EduPayWxConfig();
            }
            BeanUtils.copyProperties(agentSchoolSaveDTO, payWxConfig);
            payWxConfig.setSchoolId(dept.getDeptId());
            // 保存学校支付数据
            this.eduPayWxConfigService.saveOrUpdate(payWxConfig);
        }
        return ResultBean.buildSuccess();
    }

    /**
     * 查询学校信息
     *
     * @param schoolId 学校id
     * @return com.yida.data.common.core.common.ResultBean<com.yida.data.system.vo.AgentSchoolDetailVO>
     * @author ZYJ
     * @date 2021/9/27 20:54
     */
    @Override
    public ResultBean<AgentSchoolDetailVO> getAgentSchoolInfo(Long schoolId) {
        // 查询学校基本信息
        Dept dept = this.getById(schoolId);
        AgentSchoolDetailVO agentSchoolDetailVO = new AgentSchoolDetailVO();
        BeanUtils.copyProperties(dept, agentSchoolDetailVO);
        // 查询支付配置信息
        EduPayWxConfig payWxConfig = this.eduPayWxConfigService.getOne(Wrappers.lambdaQuery(new EduPayWxConfig())
            .eq(EduPayWxConfig::getSchoolId, dept.getDeptId()));
        if (Objects.nonNull(payWxConfig)) {
            // 配置支付数据
            agentSchoolDetailVO.setWxPublicId(payWxConfig.getWxPublicId());
            agentSchoolDetailVO.setApiV3Key(payWxConfig.getApiV3Key());
            agentSchoolDetailVO.setMchId(payWxConfig.getMchId());
            agentSchoolDetailVO.setApiCreditSerial(payWxConfig.getApiCreditSerial());
            agentSchoolDetailVO.setApiCreditPrivateKey(payWxConfig.getApiCreditPrivateKey());
            agentSchoolDetailVO.setApiCreditPrivateKeyNoHead(payWxConfig.getApiCreditPrivateKeyNoHead());
        }
        return ResultBean.buildSuccess(agentSchoolDetailVO);
    }

    /**
     * 启用或停用学校
     *
     * @param schoolId     学校id
     * @param enableStatus 需要设置的启用或停用状态. 启用: 1, 停用: 0
     * @return com.yida.data.common.core.common.ResultBean<java.lang.String>
     * @author ZYJ
     * @date 2021/9/28 9:46
     */
    @Override
    public ResultBean<String> updateEnableStatus(Long schoolId, Integer enableStatus) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        DeptSchoolRelate deptSchoolRelate = new DeptSchoolRelate();
        deptSchoolRelate.setUpdateId(currentUser.getUserId());
        deptSchoolRelate.setUpdateDate(LocalDateTime.now());
        deptSchoolRelate.setEnableStatus(enableStatus);

        // 修改学校状态
        this.deptSchoolRelateMapper.update(deptSchoolRelate,
            Wrappers.lambdaUpdate(new DeptSchoolRelate()).eq(DeptSchoolRelate::getSchoolId, schoolId));
        // 修改相关登陆账号信息
        SystemUser systemUser = new SystemUser();
        systemUser.setUpdateDate(LocalDateTime.now());
        if (EnableStatusEnum.NOT_ENABLE_STATUS.getStatus().equals(enableStatus)) {
            // 停用学校相关账号
            systemUser.setStatus(UserStatusEnum.LOCK_STATUS.getStatus());
        } else if (EnableStatusEnum.ENABLE_STATUS.getStatus().equals(enableStatus)) {
            // 启用学校相关账号
            systemUser.setStatus(UserStatusEnum.EFFECTIVE_STATUS.getStatus());
        }
        // 修改学校相关账号状态
        this.userService.update(systemUser,
            Wrappers.lambdaUpdate(new SystemUser()).eq(SystemUser::getDeptId, schoolId));
        return ResultBean.buildSuccess();
    }

    @Override
    public void saveOrUpdateDeptSchool(SchoolInformationDTO information) {
        DeptSchoolRelate schoolRelate = new DeptSchoolRelate();
        CurrentUser currentUser = FebsUtil.getCurrentUser();

        Dept dept = new Dept();
        if (ObjectUtil.isEmpty(information.getId())) {
            // 新增学校dept
            dept.setDeptType(DeptTypeEnum.SCHOOL_TYPE.getValue());
            dept.setDeptName(information.getSchoolName());
            dept.setIcon(information.getLogoUrl());
            dept.setParentId(1L);
            // 判断是否设置app信息
            Long appId = commonService.getDept(currentUser.getDeptId()).getYidaAppId();
            if (Objects.nonNull(appId)) {
                dept.setYidaAppId(appId);
                dept.setSchoolType("1");
            }
            createDept(dept);
            // 再加学校关联教育局或代理商关联关系
            schoolRelate.setSchoolId(dept.getDeptId());
            schoolRelate.setDeptId(currentUser.getDeptId());
            deptSchoolRelateMapper.insert(schoolRelate);
        } else {
            // 编辑学校dept
            dept.setDeptId(information.getSchoolId());
            dept.setDeptName(information.getSchoolName());
            dept.setIcon(information.getLogoUrl());
            baseMapper.updateById(dept);
        }

        // 再加对应学校主体信息
        DeptSchoolInformation deptSchoolInformation = new DeptSchoolInformation();
        deptSchoolInformation.setAddress(information.getAddress());
        deptSchoolInformation.setCityId(information.getCityId());
        if (ObjectUtil.isNotEmpty(dept)) {
            deptSchoolInformation.setSchoolId(schoolRelate.getSchoolId());
        }
        deptSchoolInformation.setProvinceId(information.getProvinceId());
        deptSchoolInformation.setVillageId(information.getVillageId());
        deptSchoolInformation.setLat(information.getLat());
        deptSchoolInformation.setLng(information.getLng());
        deptSchoolInformation.setIntroduction(information.getIntroduction());
        deptSchoolInformation.setLogoUrl(information.getLogoUrl());
        deptSchoolInformation.setPhone(information.getPhone());

        deptSchoolInformation.setSchoolOwnership(information.getSchoolOwnership());
        deptSchoolInformation.setSchoolType(information.getSchoolType());
        deptSchoolInformation.setSchoolProfitNature(information.getSchoolProfitNature());
        deptSchoolInformation.setId(information.getId());
        deptSchoolInformation.setSchoolName(information.getSchoolName());
        deptSchoolInformation.setEmail(information.getEmail());
        deptSchoolInformation.setZipCode(information.getZipCode());
        deptSchoolInformation.setShuntSituation(information.getShuntSituation());
        deptSchoolInformation.setStudentRange(information.getStudentRange());
        informationService.saveOrUpdate(deptSchoolInformation);

        //学校学历信息关联新增
        if (information.getSchoolType() == 1) {
            List<Integer> schoolEducationNature = information.getSchoolEducationNature();
            List<DeptSchoolInformationNature> list = new ArrayList<>();
            for (Integer integer : schoolEducationNature) {
                DeptSchoolInformationNature deptSchoolInformationNature = new DeptSchoolInformationNature();
                deptSchoolInformationNature.setInformationId(deptSchoolInformation.getId());
                deptSchoolInformationNature.setNature(integer);
                list.add(deptSchoolInformationNature);
            }
            natureService.remove(Wrappers.query(new DeptSchoolInformationNature()).lambda()
                .eq(DeptSchoolInformationNature::getInformationId, deptSchoolInformation.getId()));
            natureService.saveBatch(list);

        }
        List<DeptSchoolLabel> schoolLabelList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(information.getTags())) {
            for (String tag : information.getTags()) {
                DeptSchoolLabel schoolLabel = new DeptSchoolLabel();
                schoolLabel.setLabel(tag);
                schoolLabel.setDeptSchoolId(deptSchoolInformation.getId());
                schoolLabelList.add(schoolLabel);
            }
            schoolLabelService.remove(Wrappers.query(new DeptSchoolLabel()).lambda()
                .eq(DeptSchoolLabel::getDeptSchoolId, deptSchoolInformation.getId()));
            schoolLabelService.saveBatch(schoolLabelList);
        }

        String studentRange = information.getStudentRange();
        List<DeptSchoolStudentRange> list = new ArrayList<>();
        //分割招生范围
        if (ObjectUtil.isNotEmpty(studentRange)) {
            String[] split = null;
            if (studentRange.contains(",")) {
                split = studentRange.split(",");
            } else {
                split = studentRange.split("，");
            }
            for (String s : split) {
                DeptSchoolStudentRange range = new DeptSchoolStudentRange();
                range.setAddress(s);
                range.setDeptSchoolId(deptSchoolInformation.getId());
                list.add(range);
            }
            rangeService.remove(Wrappers.query(new DeptSchoolStudentRange()).lambda()
                .eq(DeptSchoolStudentRange::getDeptSchoolId, deptSchoolInformation.getId()));
            rangeService.saveBatch(list);
        }

    }

    @Override
    public Page<SchoolInformationDTO> findSchoolListByDeptId(Long deptId, String schoolName, Integer schoolType,
        Integer natureType, String address, String tag, Page<SchoolInformationDTO> page,
        Integer schoolOwnership) {

        return informationService
            .findSchoolListByDeptId(deptId, schoolName, schoolType, natureType, address, tag, page, schoolOwnership);
    }

    @Override
    public Page<SchoolInformationDTO> findSchoolPageList(String schoolName, List<Integer> schoolType, List<Integer> natureType,
        Page<SchoolInformationDTO> page, String tag, Long deptId, List<Integer> schoolOwnership) {

        String[] tags = null;
        if (ObjectUtil.isNotEmpty(tag)) {
            tags = tag.split(",");
        }

        return informationService.findSchoolPageList(schoolName, schoolType, natureType, page, tags, deptId, schoolOwnership);
    }

    @Override
    public Page<SchoolInformationDTO> findSchoolByAddress(Page<SchoolInformationDTO> page, String address, Long deptId) {
        if (ObjectUtil.isNotEmpty(address)) {
            //保存热门词汇
            EduHotWord eduHotWord = new EduHotWord();
            eduHotWord.setType(1);
            eduHotWord.setWord(address);
            eduHotWord.setDeptId(deptId);
            hotWordService.save(eduHotWord);
        }
        return informationService.findSchoolByAddress(page, address, deptId);
    }

    @Override
    public Page<EduLabel> findDeptLabelList(Page<EduLabel> page, Long deptId, Integer type, String label) {
        return labelService.findDeptLabelList(page, deptId, type, label);
    }

    @Override
    public void saveOrUpdateLabel(EduLabel label) {
        labelService.saveOrUpdate(label);
    }

    @Override
    public void removeLabel(Long id) {
        labelService.removeById(id);
    }

    @Override
    public List<EduHotWord> findHotWord(Integer num, Integer type, Long deptId) {

        return hotWordService.findHotWord(num, type, deptId);
    }

    @Override
    public IPage<SchoolInformationDTO> listSchoolPage(SchoolPageDTO dto) {
        IPage<SchoolInformationDTO> page = informationService.listSchoolPage(dto);
        // 判断是否只查询能缴费的学校数据
        if (CollUtil.isNotEmpty(page.getRecords()) && Objects.nonNull(dto.getOnlyPay()) && dto.getOnlyPay() == 0) {
            List<SchoolInformationDTO> list = new ArrayList<>();
            page.getRecords().forEach(schoolInformationDTO -> {
                EduDeptPayType deptPayType = commonService.getDeptPayWay(schoolInformationDTO.getSchoolId());
                if (Objects.nonNull(deptPayType)) {
                    list.add(schoolInformationDTO);
                }
            });
            page.setRecords(list);
        }
        return page;
    }

    @Override
    public List<Dept> findParentDeptByChild(List<Long> deptIds) {
        List<Dept> childList = list(Wrappers.lambdaQuery(new Dept()).in(Dept::getDeptId, deptIds));
        List<Dept> allDeptList = list();
        List<Dept> parentDeptList = new ArrayList<>();
        return getParentDeptList(allDeptList, childList, parentDeptList);
    }


    private List<Dept> getParentDeptList(List<Dept> depts, List<Dept> childrenDeptList, List<Dept> parentDeptList) {
        if (CollectionUtils.isEmpty(childrenDeptList)) {
            return parentDeptList;
        }
        parentDeptList.addAll(childrenDeptList);
        List<Long> parentIds = childrenDeptList.stream().map(Dept::getParentId).filter(Objects::nonNull)
            .collect(Collectors.toList());
        //查询父级部门
        List<Dept> parentDepts = depts.stream().filter(x -> parentIds.contains(x.getDeptId())).collect(Collectors.toList());
        return getParentDeptList(depts, parentDepts, parentDeptList);
    }
}
