package com.vctgo.system.service.impl;

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.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vctgo.common.core.constant.CacheConstants;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.RemoteProfileService;
import com.vctgo.system.api.domain.*;
import com.vctgo.system.api.domain.dto.SysBranchKindergartenDto;
import com.vctgo.system.api.model.LoginUser;
import com.vctgo.system.domain.*;
import com.vctgo.system.domain.SysBranchKindergarten;
import com.vctgo.system.domain.SysPost;
import com.vctgo.system.mapper.*;
import com.vctgo.system.service.ISysBranchKindergartenService;
import com.vctgo.system.service.ISysTenantService;
import com.vctgo.system.util.ConstantUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 幼儿园管理基本信息Service业务层处理
 *
 * @author wanglonghua
 * @date 2023-06-05
 */
@Slf4j
@Service
public class SysBranchKindergartenServiceImpl implements ISysBranchKindergartenService {
    @Autowired
    private SysBranchKindergartenMapper sysBranchKindergartenMapper;

    @Autowired
    private SysGardenManageMapper sysGardenManageMapper;

    @Autowired
    private SysReGardenBranchMapper sysReGardenBranchMapper;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private SysTenantMapper sysTenantMapper;

    @Autowired
    private SysPostMapper sysPostMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RemoteProfileService remoteProfileService;

    @Autowired
    private SysReClassUserMapper reClassUserMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysPlatformTeachStaffMapper sysPlatformTeachStaffMapper;
    private CompositeMeterRegistryAutoConfiguration compositeMeterRegistryAutoConfiguration;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysTeachStaffMapper sysTeachStaffMapper;
    /**
     * 查询幼儿园管理基本信息
     *
     * @param id 幼儿园管理基本信息主键
     * @return 幼儿园管理基本信息
     */
    @Override
    public SysBranchKindergarten selectSysBranchKindergartenById(Long id) {
        return sysBranchKindergartenMapper.selectById(id);
    }

    /**
     * 查询幼儿园管理基本信息列表-分页
     *
     * @param sysBranchKindergarten 幼儿园管理基本信息
     * @return 幼儿园管理基本信息
     */
    @Override
    public IPage<SysBranchKindergarten> selectSysBranchKindergartenPage(SysBranchKindergarten sysBranchKindergarten) {
        //根据账号状态转换相应的查询条件
        if ("未开通".equals(sysBranchKindergarten.getAccountStatus())) {
            //排除租户表里所有的幼儿园
            LambdaQueryWrapper<SysTenant> queryWrapper = Wrappers.lambdaQuery();
            List<Integer> tenantTypeList = Stream.of(ConstantUtils.TENANT_TYPE_2, ConstantUtils.TENANT_TYPE_3).collect(Collectors.toList());
            queryWrapper.in(SysTenant::getTenantType, tenantTypeList)
                    .eq(SysTenant::getDelFlag, '0');
            List<SysTenant> sysTenantList = sysTenantMapper.selectList(queryWrapper);
            List<Long> branchIdList = sysTenantList.stream().map(SysTenant::getBranchId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(branchIdList)) {
                sysBranchKindergarten.getParams().put("excludeBranchIdList", branchIdList);
            }
        } else if ("已开通".equals(sysBranchKindergarten.getAccountStatus())) {
            //仅限定租户表里租户状态为正常的幼儿园
            LambdaQueryWrapper<SysTenant> queryWrapper = Wrappers.lambdaQuery();
            List<Integer> tenantTypeList = Stream.of(ConstantUtils.TENANT_TYPE_2, ConstantUtils.TENANT_TYPE_3).collect(Collectors.toList());
            queryWrapper.in(SysTenant::getTenantType, tenantTypeList)
                    .eq(SysTenant::getStatus, '0')
                    .eq(SysTenant::getDelFlag, '0');
            List<SysTenant> sysTenantList = sysTenantMapper.selectList(queryWrapper);
            List<Long> branchIdList = sysTenantList.stream().map(SysTenant::getBranchId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(branchIdList)) {
                sysBranchKindergarten.getParams().put("includeBranchIdList", branchIdList);
            } else {
                return new Page();
            }
        } else if ("已禁用".equals(sysBranchKindergarten.getAccountStatus())) {
            //仅限定租户表里租户状态为禁用的幼儿园
            LambdaQueryWrapper<SysTenant> queryWrapper = Wrappers.lambdaQuery();
            List<Integer> tenantTypeList = Stream.of(ConstantUtils.TENANT_TYPE_2, ConstantUtils.TENANT_TYPE_3).collect(Collectors.toList());
            queryWrapper.in(SysTenant::getTenantType, tenantTypeList)
                    .ne(SysTenant::getStatus, '0')
                    .eq(SysTenant::getDelFlag, '0');
            List<SysTenant> sysTenantList = sysTenantMapper.selectList(queryWrapper);
            List<Long> branchIdList = sysTenantList.stream().map(SysTenant::getBranchId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(branchIdList)) {
                sysBranchKindergarten.getParams().put("includeBranchIdList", branchIdList);
            } else {
                return new Page();
            }
        }

        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L)
                , Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        IPage<SysBranchKindergarten> pageData = sysBranchKindergartenMapper.selectSysBranchKindergartenList(mpPage, sysBranchKindergarten);
        List<SysBranchKindergarten> kindergartenList = pageData.getRecords();
        if (CollectionUtils.isEmpty(kindergartenList)) {
            return new Page<>();
        }
        LambdaQueryWrapper<SysTenant> queryWrapper = Wrappers.lambdaQuery();
        List<Integer> tenantTypeList = Stream.of(ConstantUtils.TENANT_TYPE_2, ConstantUtils.TENANT_TYPE_3).collect(Collectors.toList());
        queryWrapper.in(SysTenant::getTenantType, tenantTypeList)
                .eq(SysTenant::getDelFlag, '0');
        List<SysTenant> sysTenantList = sysTenantMapper.selectList(queryWrapper);
        Map<Long, SysTenant> sysTenantMap = sysTenantList.stream().collect(Collectors.toMap(SysTenant::getBranchId, Function.identity()));
        //查询系统的集团列表
        LambdaQueryWrapper<SysGardenManage> wrapperx = Wrappers.lambdaQuery();
        wrapperx.eq(SysGardenManage::getIsDeleted, ConstantUtils.IS_DELETED_0);
        List<SysGardenManage> sysGardenManageList = sysGardenManageMapper.selectList(wrapperx);
        Map<Long, String> sysGardenManageMap = sysGardenManageList.stream().collect(Collectors.toMap(SysGardenManage::getId, SysGardenManage::getName));
        kindergartenList.forEach(obj -> {
            if (sysTenantMap.containsKey(obj.getId())) {
                obj.setTenantAccount(sysTenantMap.get(obj.getId()).getId());
                String accountStatus = sysTenantMap.get(obj.getId()).getStatus() == 0 ? "已开通" : "已禁用";
                obj.setAccountStatus(accountStatus);
            } else {
                obj.setAccountStatus("未开通");
            }
            if ("2".equals(obj.getKindergartenType()) && obj.getGardenId() != null && sysGardenManageMap.containsKey(obj.getGardenId())) {
                obj.getParams().put("gardenId", obj.getGardenId().toString());
                obj.getParams().put("gardenName", sysGardenManageMap.get(obj.getGardenId()));
            } else {
                obj.getParams().put("gardenId", null);
                obj.getParams().put("gardenName", null);
            }
        });

        //通过幼儿园id获取对应教职工数量
        LambdaQueryWrapper<SysPlatformTeachStaff> sysTeachStaffWrapper = new LambdaQueryWrapper<>();
        sysTeachStaffWrapper.eq(SysPlatformTeachStaff::getIsDeleted, ConstantUtils.IS_DELETED_0);
        sysTeachStaffWrapper.in(SysPlatformTeachStaff::getKindergartenId, kindergartenList.stream().map(SysBranchKindergarten::getId).map(String::valueOf).collect(Collectors.toSet()));
        List<SysPlatformTeachStaff> sysPlatformTeachStaffList = sysPlatformTeachStaffMapper.selectList(sysTeachStaffWrapper);
        Map<Long, Long> kindergartenMap = sysPlatformTeachStaffList.stream().collect(Collectors.groupingBy(SysPlatformTeachStaff::getKindergartenId, Collectors.counting()));
        kindergartenList.forEach(kindergarten -> {
            if (kindergartenMap.containsKey(kindergarten.getId())) {
                kindergarten.setStaffCount(kindergartenMap.get(kindergarten.getId()));
            }
        });
        return pageData;
    }

    /**
     * 查询幼儿园管理基本信息列表
     *
     * @param sysBranchKindergarten 幼儿园管理基本信息
     * @return 幼儿园管理基本信息
     */
    @Override
    public List<SysBranchKindergarten> selectSysBranchKindergartenList(SysBranchKindergartenDto sysBranchKindergarten) {
        List<SysBranchKindergarten> branchKindergartenList = sysBranchKindergartenMapper.selectSysBranchKindergartenList(sysBranchKindergarten);
        LambdaQueryWrapper<SysTenant> wrapper = Wrappers.lambdaQuery();
        List<Integer> tenantTypeList = Stream.of(ConstantUtils.TENANT_TYPE_2, ConstantUtils.TENANT_TYPE_3).collect(Collectors.toList());
        wrapper.in(SysTenant::getTenantType, tenantTypeList);
        wrapper.eq(SysTenant::getDelFlag, "0");
        List<SysTenant> sysTenantList = sysTenantMapper.selectList(wrapper);
        Map<Long, Long> sysTenantMap = sysTenantList.stream().collect(Collectors.toMap(SysTenant::getBranchId, SysTenant::getId));
        //查询系统的集团列表
        LambdaQueryWrapper<SysGardenManage> wrapperx = Wrappers.lambdaQuery();
        wrapperx.eq(SysGardenManage::getIsDeleted, ConstantUtils.IS_DELETED_0);
        List<SysGardenManage> sysGardenManageList = sysGardenManageMapper.selectList(wrapperx);
        Map<Long, String> sysGardenManageMap = sysGardenManageList.stream().collect(Collectors.toMap(SysGardenManage::getId, SysGardenManage::getName));
//        SysReTenantKindergarten sysReTenantKindergarten = new SysReTenantKindergarten();
//        sysReTenantKindergarten.setIsDeleted("0");//查询正常的租户账号关联信息
//        List<SysReTenantKindergarten> reTenantKindergartenList = sysReTenantKindergartenMapper.selectSysReTenantKindergartenList(sysReTenantKindergarten);
//        Map<Long,Long> reTenantKindergartenMap = reTenantKindergartenList.stream().collect(Collectors.toMap(SysReTenantKindergarten::getBranchId, SysReTenantKindergarten::getTenantId));
        branchKindergartenList.forEach(obj -> {
            if (sysTenantMap.containsKey(obj.getId())) {
                obj.setTenantAccount(sysTenantMap.get(obj.getId()));
            }
            if ("2".equals(obj.getKindergartenType()) && obj.getGardenId() != null && sysGardenManageMap.containsKey(obj.getGardenId())) {
                obj.getParams().put("gardenId", obj.getGardenId().toString());
                obj.getParams().put("gardenName", sysGardenManageMap.get(obj.getGardenId()));
            } else {
                obj.getParams().put("gardenId", null);
                obj.getParams().put("gardenName", null);
            }
        });
        return branchKindergartenList;
    }

    @Override
    public List<Long> selectSysBranchKindergartenIdList(SysBranchKindergartenDto sysBranchKindergarten) {
        return sysBranchKindergartenMapper.selectList(new QueryWrapper<SysBranchKindergarten>().lambda()
                .eq(SysBranchKindergarten::getIsDeleted, ConstantUtils.IS_DELETED_0)
                .like(SysBranchKindergarten::getBelongRegion, sysBranchKindergarten.getBelongRegion())
        ).stream().map(SysBranchKindergarten::getId).collect(Collectors.toList());
    }

    @Override
    public List<SysBranchKindergarten> kindergartenList() {
        return sysBranchKindergartenMapper.selectKindergartenList();
    }

    @Override
    public List<SysBranchKindergarten> selectBranchListByParams(Map<String, Object> params) {
        return sysBranchKindergartenMapper.selectBranchListByParams(params);
    }

    @Override
    public List<SysBranchKindergarten> getKindergartenListByGardenId(Long gardenId) {
        return sysBranchKindergartenMapper.selectList(new QueryWrapper<SysBranchKindergarten>().lambda()
                .eq(SysBranchKindergarten::getGardenId, gardenId)
                .eq(SysBranchKindergarten::getIsDeleted, ConstantUtils.IS_DELETED_0)
        );
    }

    /**
     * 新增幼儿园管理基本信息
     *
     * @param sysBranchKindergarten 幼儿园管理基本信息
     * @return 结果
     */

    @Override
    public int insertSysBranchKindergarten(SysBranchKindergarten sysBranchKindergarten) {
        int successCount = sysBranchKindergartenMapper.insert(sysBranchKindergarten);
        List<Long> ids = new ArrayList<>();
        if (successCount > 0) {
            ids.add(sysBranchKindergarten.getGardenId());
            updateBranchCount(ids, "1");
        }
        return successCount;
    }

    public void updateBranchCount(List<Long> ids, String plus) {
        sysGardenManageMapper.updateBranchCount(ids, plus);
    }

    /**
     * 修改幼儿园管理基本信息
     *
     * @param sysBranchKindergarten 幼儿园管理基本信息
     * @return 结果
     */
    @Override
    public int updateSysBranchKindergarten(SysBranchKindergarten sysBranchKindergarten) {
        //查询当前幼儿园的集团租户ID
        Long id = sysBranchKindergarten.getId();
        List<SysTenant> sysGardenTenantList = new ArrayList<>();
        if ("2".equals(sysBranchKindergarten.getKindergartenType())) {
            SysTenant gardenSysTenant = new SysTenant();
            gardenSysTenant.setGardenId(sysBranchKindergarten.getGardenId());
            gardenSysTenant.setTenantType(ConstantUtils.TENANT_TYPE_1);
            gardenSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
            sysGardenTenantList = sysTenantMapper.selectSysTenantList(gardenSysTenant);
        }
        //查询当前幼儿园是否开通幼儿园租户
        List<SysTenant> sysBranchTenantList = new ArrayList<>();
        SysTenant branchSysTenant = new SysTenant();
        branchSysTenant.setBranchId(sysBranchKindergarten.getId());
        branchSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
        sysBranchTenantList = sysTenantMapper.selectSysTenantList(branchSysTenant);
        //查询变更前的幼儿园基本信息
        SysBranchKindergarten beforeSysBranchKindergarten = sysBranchKindergartenMapper.selectById(id);
        //更新幼儿园基础信息
        int successCount = sysBranchKindergartenMapper.updateById(sysBranchKindergarten);
        sysGardenManageMapper.multiUpdateBranchCount();
        //幼儿园基础数据操作成功且存在幼儿园租户，更新租户相关数据表的数据
        if (successCount > 0 && CollectionUtils.isNotEmpty(sysBranchTenantList)) {
            // 判断幼儿园是添加集团、还是解除集团、或者是更换集团
            if (beforeSysBranchKindergarten.getGardenId() == null && sysBranchKindergarten.getGardenId() != null) {
                //幼儿园新增集团
                //更新租户表garden值
                SysTenant sysTenantx = new SysTenant();
                sysTenantx.setBranchId(sysBranchKindergarten.getId());
                sysTenantx.setGardenId(sysBranchKindergarten.getGardenId());
                sysTenantx.setTenantType(ConstantUtils.TENANT_TYPE_2);
                sysTenantMapper.updateSysTenantRelaData(sysTenantx);
                //更新租户关联表parentId值
                SysReGardenBranch sysReGardenBranch = new SysReGardenBranch();
                sysReGardenBranch.setId(sysBranchTenantList.get(0).getId());       //幼儿园的租户ID
                sysReGardenBranch.setParentId(sysGardenTenantList.get(0).getId()); //集团的租户ID
                sysReGardenBranchMapper.updateById(sysReGardenBranch);
                //删除系统默认岗位
//                Long[] ids = {sysBranchTenantList.get(0).getId()};
//                sysPostMapper.deleteSysDefaultPost(ids);
                //批量解除岗位与人员的绑定关系
                Long[] ids = {sysBranchTenantList.get(0).getId()};
                userPostMapper.deleteUserPostByTenantId(ids);
                //批量删除当前租户的所有岗位
                sysPostMapper.deletePostByTenantId(ids);
            }
            //由集团园变更为独立幼儿园或者其他
            if ("2".equals(beforeSysBranchKindergarten.getKindergartenType()) &&
                    ("1".equals(sysBranchKindergarten.getKindergartenType()) || "3".equals(sysBranchKindergarten.getKindergartenType()))) {
                //幼儿园解除集团
                //更新租户表garden值
                SysTenant sysTenantx = new SysTenant();
                sysTenantx.setBranchId(sysBranchKindergarten.getId());
                sysTenantx.setGardenId(null);
                sysTenantx.setTenantType(ConstantUtils.TENANT_TYPE_3);
                sysTenantMapper.updateSysTenantRelaData(sysTenantx);

                //更新租户关联表parentId值
                SysReGardenBranch sysReGardenBranch = new SysReGardenBranch();
                sysReGardenBranch.setId(sysBranchTenantList.get(0).getId());  //幼儿园的租户ID
                sysReGardenBranch.setParentId(0L); //幼儿园的租户ID
                sysReGardenBranchMapper.updateById(sysReGardenBranch);
                //更新岗位表的幼儿园租户Id为变更前所属集团的集团租户Id
                sysPostMapper.multiAdjustBranchPost(beforeSysBranchKindergarten.getGardenId(),
                        beforeSysBranchKindergarten.getId(), ConstantUtils.TENANT_TYPE_3.longValue());
                //创建独立幼儿园或者其他幼儿园的系统默认岗
                SysPost post = new SysPost();
                post.setTenantId(sysBranchTenantList.get(0).getId());
                createSysDefaultPost(post);
                //批量解除岗位与人员的绑定关系
                Long[] ids = {sysBranchTenantList.get(0).getId()};
                userPostMapper.deleteUserPostByTenantId(ids);
            }
            //有集团的幼儿园租户由A集团变更为B集团
            if ("2".equals(beforeSysBranchKindergarten.getKindergartenType()) && "2".equals(sysBranchKindergarten.getKindergartenType())
                    && !beforeSysBranchKindergarten.getGardenId().equals(sysBranchKindergarten.getGardenId())) {
                //幼儿园的集团变更
                //更新租户表garden值
                SysTenant sysTenantx = new SysTenant();
                sysTenantx.setBranchId(sysBranchKindergarten.getId());
                sysTenantx.setGardenId(sysBranchKindergarten.getGardenId());
                sysTenantx.setTenantType(ConstantUtils.TENANT_TYPE_2);
                sysTenantMapper.updateSysTenantRelaData(sysTenantx);
                //更新租户关联表parentId值
                SysReGardenBranch sysReGardenBranch = new SysReGardenBranch();
                sysReGardenBranch.setId(sysBranchTenantList.get(0).getId());       //幼儿园的租户ID
                sysReGardenBranch.setParentId(sysGardenTenantList.get(0).getId()); //变更后所属集团的租户ID
                sysReGardenBranchMapper.updateById(sysReGardenBranch);
                //更新岗位表的幼儿园租户Id为变更前所属集团的集团租户Id
                sysPostMapper.multiAdjustBranchPost(beforeSysBranchKindergarten.getGardenId(),
                        beforeSysBranchKindergarten.getId(), ConstantUtils.TENANT_TYPE_2.longValue());
                //批量解除岗位与人员的绑定关系
                Long[] ids = {sysBranchTenantList.get(0).getId()};
                userPostMapper.deleteUserPostByTenantId(ids);
            }
            //查看平台建立的租户幼儿园名称是否被幼儿园私自改变，判断是否更新系统租户租户表的租户名称
            SysTenant sysTenant = sysBranchTenantList.get(0);
            if (!sysTenant.getTenantName().equals(sysBranchKindergarten.getKindergartenName())) {
                sysTenant.setTenantName(sysBranchKindergarten.getKindergartenName());
                sysTenantService.updateSysTenant(sysTenant);
                //更新部门表的集团或者幼儿园名称
                SysDept checkSysDept = new SysDept();
                checkSysDept.setDeptId(sysBranchKindergarten.getId());
                checkSysDept.setDeptName(sysBranchKindergarten.getKindergartenName());
                checkSysDept.setDeptType(ConstantUtils.DEPT_TYPE_2);
                deptMapper.updateTenantName(checkSysDept);
                //更新人员表的集团或者幼儿园名称
                SysUser checkSysUser = new SysUser();
                checkSysUser.setDeptId(sysBranchKindergarten.getId());
                checkSysUser.setNickName(sysBranchKindergarten.getKindergartenName());
                userMapper.updateBranchTenantName(checkSysUser);
                //不管平台建立的租户幼儿园名称是否改变，均更新redis缓存中的租户名称
                redisService.deleteObject("tenantList");
            }
        }
        return successCount;
    }

    /**
     * 修改幼儿园管理基本信息
     *
     * @param sysBranchKindergarten 幼儿园管理基本信息
     * @return 结果
     */
    @Override
    public int updateBranchBaseInfo(SysBranchKindergarten sysBranchKindergarten) {
        //查询当前幼儿园是否开通幼儿园租户
        List<SysTenant> sysBranchTenantList = new ArrayList<>();
        SysTenant branchSysTenant = new SysTenant();
        branchSysTenant.setBranchId(sysBranchKindergarten.getId());
        branchSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
        sysBranchTenantList = sysTenantMapper.selectSysTenantList(branchSysTenant);
        //更新幼儿园基础信息
        int successCount = sysBranchKindergartenMapper.updateById(sysBranchKindergarten);
        sysGardenManageMapper.multiUpdateBranchCount();
        //幼儿园基础数据操作成功且存在幼儿园租户，更新租户相关数据表的数据
        if (successCount > 0 && CollectionUtils.isNotEmpty(sysBranchTenantList)) {
            //查看平台建立的租户幼儿园名称是否被幼儿园私自改变，判断是否更新系统租户租户表的租户名称
            SysTenant branchTenant = sysBranchTenantList.get(0);
            if (!branchTenant.getTenantName().equals(sysBranchKindergarten.getKindergartenName())) {
                branchTenant.setTenantName(sysBranchKindergarten.getKindergartenName());
                sysTenantService.updateSysTenant(branchTenant);
                //更新部门表的集团或者幼儿园名称
                SysDept checkSysDept = new SysDept();
                checkSysDept.setDeptId(sysBranchKindergarten.getId());
                checkSysDept.setDeptName(sysBranchKindergarten.getKindergartenName());
                checkSysDept.setDeptType(ConstantUtils.DEPT_TYPE_2);
                deptMapper.updateTenantName(checkSysDept);
                //更新人员表的集团或者幼儿园名称
                SysUser checkSysUser = new SysUser();
                checkSysUser.setDeptId(sysBranchKindergarten.getId());
                checkSysUser.setNickName(sysBranchKindergarten.getKindergartenName());
                userMapper.updateBranchTenantName(checkSysUser);
                //不管平台建立的租户幼儿园名称是否改变，均更新redis缓存中的租户名称
                redisService.deleteObject("tenantList");
            }
        }

        //园所管理　->  园所信息 -> 同步 “内部资源管理”
        try {
            SysBranchKindergartenDto kindergartenDto = SysBranchKindergartenDto.builder().build();
            BeanUtils.copyProperties(sysBranchKindergarten, kindergartenDto);
            remoteProfileService.modifyKindergartenInfo(kindergartenDto);
        } catch (Exception e) {
            e.fillInStackTrace();
            log.info("同步“内部资源服务”园所信息失败！");
        }
        return successCount;
    }

    /**
     * 调整幼儿园的归属关系
     *
     * @param sysBranchKindergarten 幼儿园管理基本信息
     * @return 结果
     */
    @Override
    public int adjustAffiliation(SysBranchKindergarten sysBranchKindergarten) {
        //查询当前幼儿园的集团租户ID
        Long id = sysBranchKindergarten.getId();
        List<SysTenant> sysGardenTenantList = new ArrayList<>();
        if ("2".equals(sysBranchKindergarten.getKindergartenType())) {
            SysTenant gardenSysTenant = new SysTenant();
            gardenSysTenant.setGardenId(sysBranchKindergarten.getGardenId());
            gardenSysTenant.setTenantType(ConstantUtils.TENANT_TYPE_1);
            gardenSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
            sysGardenTenantList = sysTenantMapper.selectSysTenantList(gardenSysTenant);
        }
        if (CollectionUtils.isNotEmpty(sysGardenTenantList) && sysGardenTenantList.get(0).getStatus() == 1) {
            throw new ServiceException("该集团租户账号已禁用，不可调整");
        }
        //查询当前幼儿园是否开通幼儿园租户
        List<SysTenant> sysBranchTenantList = new ArrayList<>();
        SysTenant branchSysTenant = new SysTenant();
        branchSysTenant.setBranchId(sysBranchKindergarten.getId());
        branchSysTenant.setDelFlag(ConstantUtils.IS_DELETED_0);
        sysBranchTenantList = sysTenantMapper.selectSysTenantList(branchSysTenant);
        if (CollectionUtils.isNotEmpty(sysBranchTenantList) && sysBranchTenantList.get(0).getStatus() == 1) {
            throw new ServiceException("该幼儿园租户账号已禁用，不可调整集团");
        }
        //查询变更前的幼儿园基本信息
        SysBranchKindergarten beforeSysBranchKindergarten = sysBranchKindergartenMapper.selectById(id);
        //更新幼儿园基础信息
        int successCount = sysBranchKindergartenMapper.updateById(sysBranchKindergarten);
        sysGardenManageMapper.multiUpdateBranchCount();
        //幼儿园基础数据操作成功且存在幼儿园租户，更新租户相关数据表的数据
        if (successCount > 0 && CollectionUtils.isNotEmpty(sysBranchTenantList)) {
            // 判断幼儿园是添加集团、还是解除集团、或者是更换集团
            if (beforeSysBranchKindergarten.getGardenId() == null && sysBranchKindergarten.getGardenId() != null) {
                //幼儿园新增集团
                //更新租户表garden值
                SysTenant sysTenantx = new SysTenant();
                sysTenantx.setBranchId(sysBranchKindergarten.getId());
                sysTenantx.setGardenId(sysBranchKindergarten.getGardenId());
                sysTenantx.setTenantType(ConstantUtils.TENANT_TYPE_2);
                sysTenantMapper.updateSysTenantRelaData(sysTenantx);
                //更新租户关联表parentId值
                SysReGardenBranch sysReGardenBranch = new SysReGardenBranch();
                sysReGardenBranch.setId(sysBranchTenantList.get(0).getId());       //幼儿园的租户ID
                sysReGardenBranch.setParentId(sysGardenTenantList.get(0).getId()); //集团的租户ID
                sysReGardenBranchMapper.updateById(sysReGardenBranch);
                //删除系统默认岗位
//                Long[] ids = {sysBranchTenantList.get(0).getId()};
//                sysPostMapper.deleteSysDefaultPost(ids);
                //批量解除岗位与人员的绑定关系
                Long[] ids = {sysBranchTenantList.get(0).getId()};
                userPostMapper.deleteUserPostByTenantId(ids);
                //批量解除当前租户的系统默认岗位人员与班级的绑定关系
                reClassUserMapper.deleteSysReClassUserByTenantId(ids, 1);
                //批量删除当前租户的所有岗位
                sysPostMapper.deletePostByTenantId(ids);
            }
            //由集团园变更为独立幼儿园或者其他
            if ("2".equals(beforeSysBranchKindergarten.getKindergartenType()) &&
                    ("1".equals(sysBranchKindergarten.getKindergartenType()) || "3".equals(sysBranchKindergarten.getKindergartenType()))) {
                //幼儿园解除集团
                //更新租户表garden值
                SysTenant sysTenantx = new SysTenant();
                sysTenantx.setBranchId(sysBranchKindergarten.getId());
                sysTenantx.setGardenId(null);
                sysTenantx.setTenantType(ConstantUtils.TENANT_TYPE_3);
                sysTenantMapper.updateSysTenantRelaData(sysTenantx);

                //更新租户关联表parentId值
                SysReGardenBranch sysReGardenBranch = new SysReGardenBranch();
                sysReGardenBranch.setId(sysBranchTenantList.get(0).getId());  //幼儿园的租户ID
                sysReGardenBranch.setParentId(0L); //幼儿园的租户ID
                sysReGardenBranchMapper.updateById(sysReGardenBranch);
                //更新岗位表的幼儿园租户Id为变更前所属集团的集团租户Id
                sysPostMapper.multiAdjustBranchPost(beforeSysBranchKindergarten.getGardenId(),
                        beforeSysBranchKindergarten.getId(), ConstantUtils.TENANT_TYPE_3.longValue());
                //创建独立幼儿园或者其他幼儿园的系统默认岗
                SysPost post = new SysPost();
                post.setTenantId(sysBranchTenantList.get(0).getId());
                createSysDefaultPost(post);
                //批量解除岗位与人员的绑定关系
                Long[] ids = {sysBranchTenantList.get(0).getId()};
                userPostMapper.deleteUserPostByTenantId(ids);
                //批量解除当前租户的系统默认岗位人员与班级的绑定关系
                reClassUserMapper.deleteSysReClassUserByTenantId(ids, 1);
            }
            //有集团的幼儿园租户由A集团变更为B集团
            if ("2".equals(beforeSysBranchKindergarten.getKindergartenType()) && "2".equals(sysBranchKindergarten.getKindergartenType())
                    && !beforeSysBranchKindergarten.getGardenId().equals(sysBranchKindergarten.getGardenId())) {
                //幼儿园的集团变更
                //更新租户表garden值
                SysTenant sysTenantx = new SysTenant();
                sysTenantx.setBranchId(sysBranchKindergarten.getId());
                sysTenantx.setGardenId(sysBranchKindergarten.getGardenId());
                sysTenantx.setTenantType(ConstantUtils.TENANT_TYPE_2);
                sysTenantMapper.updateSysTenantRelaData(sysTenantx);
                //更新租户关联表parentId值
                SysReGardenBranch sysReGardenBranch = new SysReGardenBranch();
                sysReGardenBranch.setId(sysBranchTenantList.get(0).getId());       //幼儿园的租户ID
                sysReGardenBranch.setParentId(sysGardenTenantList.get(0).getId()); //变更后所属集团的租户ID
                sysReGardenBranchMapper.updateById(sysReGardenBranch);
                //更新岗位表的幼儿园租户Id为变更前所属集团的集团租户Id
                sysPostMapper.multiAdjustBranchPost(beforeSysBranchKindergarten.getGardenId(),
                        beforeSysBranchKindergarten.getId(), ConstantUtils.TENANT_TYPE_2.longValue());
                //批量解除岗位与人员的绑定关系
                Long[] ids = {sysBranchTenantList.get(0).getId()};
                userPostMapper.deleteUserPostByTenantId(ids);
                //批量解除当前租户的系统默认岗位人员与班级的绑定关系
                reClassUserMapper.deleteSysReClassUserByTenantId(ids, 1);
            }
        }
        return successCount;
    }

    public void createSysDefaultPost(SysPost post) {
        Long tenantId = post.getTenantId();
        List<SysPost> postList = new ArrayList<>(3);
        SysPost zbjsPost = new SysPost();
        SysPost pbjsPost = new SysPost();
        SysPost byyPost = new SysPost();
        zbjsPost.setPostCode("zbjs").setPostName("主班教师").setIsSysPost("Y").setPostSort("0");
        zbjsPost.setTenantId(tenantId);
        pbjsPost.setPostCode("pbjs").setPostName("配班教师").setIsSysPost("Y").setPostSort("0");
        pbjsPost.setTenantId(tenantId);
        byyPost.setPostCode("byy").setPostName("保育员").setIsSysPost("Y").setPostSort("0");
        byyPost.setTenantId(tenantId);
        postList.add(zbjsPost);
        postList.add(pbjsPost);
        postList.add(byyPost);
        sysPostMapper.insertBatch(postList);
    }

    /**
     * 批量删除幼儿园管理基本信息
     *
     * @param ids 需要删除的幼儿园管理基本信息主键
     * @return 结果
     */
    @Override
    public int deleteSysBranchKindergartenByIds(Long[] ids) {
        int successCount = sysBranchKindergartenMapper.deleteSysBranchKindergartenByIds(ids);
        sysGardenManageMapper.multiUpdateBranchCount();
        return successCount;
    }

    /**
     * 删除幼儿园管理基本信息信息
     *
     * @param ids 幼儿园管理基本信息主键
     * @return 结果
     */
    @Override
    public int logicalDeleteByIds(Long[] ids) {
        List<SysTenant> sysTenantList = sysTenantMapper.selectList(new QueryWrapper<SysTenant>().lambda()
                .in(SysTenant::getBranchId, Arrays.asList(ids))
                .eq(SysTenant::getDelFlag, ConstantUtils.IS_DELETED_0)
        );
        if (CollectionUtils.isNotEmpty(sysTenantList)) {
            throw new ServiceException("账号已开通，不可删除");
        }
        SysBranchKindergarten branchKindergarten = new SysBranchKindergarten();
        branchKindergarten.setUpdateById(SecurityUtils.getUserId());
        branchKindergarten.setUpdateBy(SecurityUtils.getUsername());
        branchKindergarten.setUpdateTime(new Date());
        branchKindergarten.setIsDeleted(ConstantUtils.IS_DELETED_1);
        int successCount = sysBranchKindergartenMapper.updateDeletedStatusByIds(ids, branchKindergarten);
        sysGardenManageMapper.multiUpdateBranchCount();
        return successCount;
    }


    /**
     * 新增
     */
    @Override
    public int add(SysBranchKindergartenDto sysBranchKindergartenDto) {
        SysBranchKindergarten kindergarten = new SysBranchKindergarten();
        kindergarten.setKindergartenName(sysBranchKindergartenDto.getKindergartenName());
        kindergarten.setProvinceId(sysBranchKindergartenDto.getProvinceId());
        kindergarten.setCityId(sysBranchKindergartenDto.getCityId());
        kindergarten.setDistrictId(sysBranchKindergartenDto.getDistrictId());
        kindergarten.setTenantId(sysBranchKindergartenDto.getTenantId());
        kindergarten.setCreateById(sysBranchKindergartenDto.getCreateById());
        kindergarten.setCreateBy(sysBranchKindergartenDto.getCreateBy());
        kindergarten.setCreateTime(new Date());
        return sysBranchKindergartenMapper.insert(kindergarten);
    }

    @Override
    public List<SysBranchKindergartenDto> getAll(String provinceId, String cityId, String districtId) {
        LambdaQueryWrapper<SysBranchKindergarten> wrapper = new LambdaQueryWrapper<>();
        if (provinceId != null && !provinceId.isEmpty()) {
            wrapper.eq(SysBranchKindergarten::getProvinceId, provinceId);
        }
        if (cityId != null && !cityId.isEmpty()) {
            wrapper.eq(SysBranchKindergarten::getCityId, cityId);
        }
        if (districtId != null && !districtId.isEmpty()) {
            wrapper.eq(SysBranchKindergarten::getDistrictId, districtId);
        }
        //只查通过
        wrapper.eq(SysBranchKindergarten::getVerifyStatus,1);

        List<SysBranchKindergartenDto> sysBranchKindergartenDtos = new ArrayList<>();
        List<SysBranchKindergarten> sysBranchKindergartens = sysBranchKindergartenMapper.selectList(wrapper);
        sysBranchKindergartens.forEach(item -> {
            SysBranchKindergartenDto kindergartenDto = new SysBranchKindergartenDto();
            kindergartenDto.setId(item.getId());
            kindergartenDto.setKindergartenName(item.getKindergartenName());
            kindergartenDto.setProvinceId(item.getProvinceId());
            kindergartenDto.setCityId(item.getCityId());
            kindergartenDto.setDistrictId(item.getDistrictId());
            sysBranchKindergartenDtos.add(kindergartenDto);
        });
        return sysBranchKindergartenDtos;
    }

    @Override
    public SysBranchKindergartenDto getById(Long id) {
        SysBranchKindergarten sysBranchKindergarten = sysBranchKindergartenMapper.selectById(id);
        SysBranchKindergartenDto kindergartenDto = new SysBranchKindergartenDto();
        kindergartenDto.setId(sysBranchKindergarten.getId())
                .setKindergartenName(sysBranchKindergarten.getKindergartenName())
                .setBelongRegion(sysBranchKindergarten.getBelongRegion());
        return kindergartenDto;
    }

    /**
     * 新增幼儿园管理基本信息
     *
     * @param sysBranchKindergarten 幼儿园管理基本信息
     * @return 结果
     */

    @Override
    @Transactional
    public SysBranchKindergarten voteInsertSysBranchKindergarten(SysBranchKindergarten sysBranchKindergarten) {
        if(sysBranchKindergarten.getId()==null){
            sysBranchKindergarten.setVerifyStatus(0);
            sysBranchKindergarten.setSourceType(2);
            sysBranchKindergarten.setCreateBy(SecurityUtils.getUsername());
            sysBranchKindergarten.setCreateById(SecurityUtils.getUserId());
            int successCount = sysBranchKindergartenMapper.insert(sysBranchKindergarten);
            //创建默认租户
            SysUser sysUser = userMapper.selectUserById(SecurityUtils.getUserId());
            String userPhone=sysUser.getPhonenumber();
            SysTenant sysTenant =new SysTenant();
            sysTenant.setBranchId(sysBranchKindergarten.getId());
            String randomPassword = SecurityUtils.randomPassword(8);//随机密码8位
            String password = SecurityUtils.encryptPassword(randomPassword);
            sysTenant.setPassword(password);
            sysTenant.setStatus(1);
            sysTenant.setTenantName(sysBranchKindergarten.getKindergartenName());
            sysTenant.setTenantType(3);
            sysTenant.setUserName(SecurityUtils.getUsername());
            sysTenant.setUserPhone(userPhone);
            insertSysBranchTenant(sysTenant,sysBranchKindergarten);
            sysBranchKindergarten.setTenantId(sysTenant.getId());
        }else{
            sysBranchKindergarten.setVerifyStatus(0);
            sysBranchKindergarten.setSourceType(2);
            sysBranchKindergartenMapper.update(sysBranchKindergarten);
        }

        return sysBranchKindergarten;
    }


    public AjaxResult insertSysBranchTenant(SysTenant sysTenant,SysBranchKindergarten sysBranchKindergarten) {
        Long maxTenantId = sysTenantMapper.getMaxTenantId();
        sysTenant.setId(maxTenantId == null ? 100L : maxTenantId + 1);

        if (StrUtils.isEmpty(sysTenant.getUserName())) {
            return AjaxResult.error("管理员账号为空,请重新设置!");
        }

        //先判断租户管理员设置的账号是否存在
//        SysUser usercount = userMapper.checkUserNameUnique(sysTenant.getUserName());
//        if (usercount != null) {
//            return AjaxResult.error("账号已存在,请重新设置！");
//        }
//        String password = sysTenant.getPassword();
//        if (StrUtils.isEmpty(password)) {
//            return AjaxResult.error("密码不能为空！");
//        }

//        if (sysTenant.getTenantType() == null) {
//            throw new IllegalArgumentException("参数有误，请联系管理员!");
//        }

        //存在集团的幼儿园租户，上级集团Id和幼儿园Id均需要传值
        if (sysTenant.getTenantType() == 2 && (sysTenant.getGardenId() == null || sysTenant.getBranchId() == null)) {
            throw new IllegalArgumentException("参数有误，请联系管理员!");
        }
        if (sysTenant.getTenantType() == 3 && (sysTenant.getGardenId() != null || sysTenant.getBranchId() == null)) {
            throw new IllegalArgumentException("参数有误，请联系管理员!");
        }
        //默认查询集团的数据列表
        SysTenant sysTenantx = new SysTenant();
        sysTenantx.setTenantType(sysTenant.getTenantType());
        sysTenantx.setBranchId(sysTenant.getBranchId());
        List<SysTenant> sysTenantList = sysTenantMapper.selectSysTenantList(sysTenantx);
        if (CollectionUtils.isNotEmpty(sysTenantList)) {
            return AjaxResult.error("当前租户已存在管理员账号!");
        }
        //创建租户
        sysTenant.setSourceType(2);
        sysTenantMapper.insert(sysTenant);
        //租户关联表插入数据,首先判断插入的是有集团的幼儿园租户还是无集团的幼儿园租户
        SysReGardenBranch sysReGardenBranch = new SysReGardenBranch();
        sysReGardenBranch.setId(sysTenant.getId());
        sysReGardenBranch.setParentId(0L);
        sysReGardenBranch.setDeptType(String.valueOf(ConstantUtils.TENANT_TYPE_2));
        sysReGardenBranchMapper.insert(sysReGardenBranch);

        //租户创建完成后 开始创建相关基础数据
        //创建默认部门--部门默认名称以租户名称
        createGardenDept(sysTenant);
        //创建默认岗位--岗位默认为主班教师、配班教师、保育员
        createPost(sysTenant);
        //创建默认角色--角色默认为租户名称+管理员
        Long roleid = createRole(sysTenant);

        //回填默认账号
        updateUser(sysTenant, roleid,sysBranchKindergarten);

        if (redisService.hasKey("tenantList")) {
            redisService.setCacheList("tenantList", sysTenant);
        } else {
            List<SysTenant> tenantList = sysTenantMapper.selectSysTenantList(sysTenant);
            tenantList.add(sysTenant);
            redisService.setCacheList("tenantList", tenantList);
        }
        return AjaxResult.success("租户创建成功!");
    }

    private Long createGardenDept(SysTenant sysTenant) {
        // 创建部门
        SysDept dept = new SysDept();
        dept.setParentId(0L);
        dept.setAncestors("0");
        dept.setDeptName(sysTenant.getTenantName());
        if(sysTenant.getTenantType() == 1){
            dept.setDeptType(ConstantUtils.DEPT_TYPE_1);
        }else if(sysTenant.getTenantType() == 2 || sysTenant.getTenantType() == 3){
            dept.setDeptType(ConstantUtils.DEPT_TYPE_2);
        }
        dept.setOrderNum(0);
        dept.setPhone(sysTenant.getUserPhone());
        dept.setEmail(sysTenant.getUserEmail());
        dept.setTenantId(sysTenant.getId());
        deptMapper.insert(dept);
        return dept.getDeptId();
    }

    private void createPost(SysTenant sysTenant) {
        Long tenantId = sysTenant.getId();
        List<SysPost> postList = new ArrayList<>(3);
        SysPost zbjsPost = new SysPost();
        SysPost pbjsPost = new SysPost();
        SysPost byyPost = new SysPost();
        zbjsPost.setPostCode("zbjs").setPostName("主班教师").setIsSysPost("Y").setPostSort("0");
        zbjsPost.setTenantId(tenantId);
        pbjsPost.setPostCode("pbjs").setPostName("配班教师").setIsSysPost("Y").setPostSort("0");
        pbjsPost.setTenantId(tenantId);
        byyPost.setPostCode("byy").setPostName("保育员").setIsSysPost("Y").setPostSort("0");
        byyPost.setTenantId(tenantId);
        postList.add(zbjsPost);
        postList.add(pbjsPost);
        postList.add(byyPost);
        sysPostMapper.insertBatch(postList);
    }

    private Long createRole(SysTenant sysTenant) {
        // 创建角色
        SysRole role = new SysRole();
        role.setRoleName(sysTenant.getTenantName()+"管理员").setRoleKey("admin")
                .setRoleSort("1").setDataScope("1").setMenuCheckStrictly(true).setDeptCheckStrictly(true);
        role.setCreateBy(sysTenant.getUserName());
        role.setRemark("租户管理员");
        role.setAdminRole(true);
        role.setIsDefault("1");
        role.setTenantId(sysTenant.getId());
        sysRoleMapper.insert(role);
        //根据租户套餐ids查出套餐编码塞入角色-菜单表
//        createRoleMenu(sysTenant,role);
        return role.getRoleId();
    }

    private void updateUser(SysTenant sysTenant, Long roleId,SysBranchKindergarten sysBranchKindergarten) {
        //更新用户
        //创建默认租户
        SysUser sysUser = userMapper.selectUserById(SecurityUtils.getUserId());
        sysUser.setUserType("00");
        sysUser.setRemark(sysTenant.getTenantName() + "管理员");
        sysUser.setTenantId(sysTenant.getId());
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        sysUser.setUpdateById(SecurityUtils.getUserId());
        sysUser.setUpdateTime(new Date());
        userMapper.updateUser(sysUser);
        //回填教职工表的幼儿园信息
        SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_teach_staff"));

        LambdaQueryWrapper<SysTeachStaff> staffWrapper = new LambdaQueryWrapper<>();
        staffWrapper.eq(SysTeachStaff::getUserId, sysUser.getUserId());
        SysTeachStaff sysTeachStaff = sysTeachStaffMapper.selectOne(staffWrapper);
        SecurityUtils.removeTemporaryIgnoreTables(Arrays.asList("sys_teach_staff"));

        if(sysTeachStaff != null){
            sysTeachStaff.setKindergartenId(sysBranchKindergarten.getId());
            sysTeachStaff.setKindergartenType(sysBranchKindergarten.getKindergartenType());
            sysTeachStaff.setTenantId(sysTenant.getId());
            sysTeachStaff.setUpdateBy(SecurityUtils.getUsername());
            sysTeachStaff.setUpdateById(SecurityUtils.getUserId());
            sysTeachStaff.setUpdateTime(new Date());
            sysTeachStaffMapper.updateSysTeachStaff(sysTeachStaff);
        }
        userRoleMapper.insert(new SysUserRole().setRoleId(roleId).setUserId(sysUser.getUserId()).setTenantId(sysTenant.getId()));
    }
}
