package com.xinyilu.system.service.kindergarteninfo.impl;

import com.xinyilu.common.constant.Constants;
import com.xinyilu.common.core.domain.AjaxResult;
import com.xinyilu.common.core.domain.entity.SysRole;
import com.xinyilu.common.core.domain.entity.SysUser;
import com.xinyilu.common.core.page.TableDataInfo;
import com.xinyilu.common.utils.DateUtils;
import com.xinyilu.common.utils.PageServiceUtil;
import com.xinyilu.common.utils.SecurityUtils;
import com.xinyilu.system.domain.dto.KindergartenInfoDTO;
import com.xinyilu.system.domain.kindergarteninfo.KindergartenInfo;
import com.xinyilu.system.domain.organize.OrganizeInfo;
import com.xinyilu.system.domain.systemarea.SysArea;
import com.xinyilu.system.domain.vo.OrganizeInfoVO;
import com.xinyilu.system.domain.vo.SysUserVO;
import com.xinyilu.system.mapper.SysUserMapper;
import com.xinyilu.system.mapper.classinfo.ClassInfoMapper;
import com.xinyilu.system.mapper.kindergarteninfo.KindergartenInfoMapper;
import com.xinyilu.system.mapper.organize.OrganizeInfoMapper;
import com.xinyilu.system.mapper.systemarea.SysAreaMapper;
import com.xinyilu.system.mapper.teacherInfo.TeacherInfoMapper;
import com.xinyilu.system.service.kindergarteninfo.IKindergartenInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 幼儿园信息管理Service业务层处理
 *
 * @author jihan
 * @date 2022-07-28
 */
@Service
public class KindergartenInfoServiceImpl implements IKindergartenInfoService {

    @Resource
    private KindergartenInfoMapper kindergartenInfoMapper;
    @Resource
    private OrganizeInfoMapper organizeInfoMapper;
    @Resource
    private TeacherInfoMapper teacherInfoMapper;
    @Resource
    private PageServiceUtil pageServiceUtil;
    @Resource
    private ClassInfoMapper classInfoMapper;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysAreaMapper sysAreaMapper;

    /**
     * 查询幼儿园信息管理
     *
     * @param id 幼儿园信息管理主键
     * @return 幼儿园信息管理
     */
    @Override
    public KindergartenInfo selectKindergartenInfoById(Long id) {
        return kindergartenInfoMapper.selectKindergartenInfoById(id);
    }

    /**
     * 查询幼儿园信息管理列表
     *
     * @param kindergartenInfo 幼儿园信息管理
     * @return 幼儿园信息管理
     */
    @Override
    public TableDataInfo selectKindergartenInfoList(KindergartenInfoDTO kindergartenInfo) {
        //判断当前用户所属角色，根据角色显示对应数据信息
        List<String> roleKeys = SecurityUtils.getLoginUser().getUser().getRoles()
                .stream().filter(Objects::nonNull)
                .filter(item -> StringUtils.isNotBlank(item.getRoleKey()))
                .map(SysRole::getRoleKey).collect(Collectors.toList());
        Long userId = SecurityUtils.getUserId();
        SysUserVO sysUserVO = userMapper.selectUserById(userId);
        if (roleKeys.contains(Constants.ADMIN_ROLE)) {
            //角色为管理员，查询所有幼儿园信息
            return getKindergartenInfoList(kindergartenInfo);
        } else if (roleKeys.contains(Constants.CITY)) {
            //角色为市级角色，查询该市内的所有幼儿园的信息
            long areaId = Objects.isNull(SecurityUtils.getLoginUser().getUser().getAreaId()) ? 0 : SecurityUtils.getLoginUser().getUser().getAreaId();
            SysArea sysArea = new SysArea();
            sysArea.setParentId(areaId);
            List<Long> sysAreaIdList = sysAreaMapper.selectSysAreaList(sysArea).stream().filter(Objects::nonNull).filter(sysAreaId -> Objects.nonNull(sysAreaId.getId())).map(SysArea::getId).collect(Collectors.toList());
            List<Long> kindergartenIdList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(sysAreaIdList)) {
                //获取该区域下的所有幼儿园信息
                kindergartenIdList = classInfoMapper.getKindergartenInfoByAreaId(sysAreaIdList, null);
            }
            if (CollectionUtils.isEmpty(kindergartenIdList)) {
                return null;
            }
            kindergartenInfo.setKindergartenIdList(kindergartenIdList);
            return getKindergartenInfoList(kindergartenInfo);
        } else if (roleKeys.contains(Constants.REGION_ROLE)) {
            //角色为区域角色，查询该区域内的所有幼儿园的信息
            long areaId = Objects.isNull(SecurityUtils.getLoginUser().getUser().getAreaId()) ? 0 : SecurityUtils.getLoginUser().getUser().getAreaId();
            List<Long> organizeIdList = Lists.newArrayList();
            if (areaId != 0) {
                //获取该区域下的所有组织信息
                OrganizeInfoVO organizeInfo = new OrganizeInfoVO();
                organizeInfo.setAreaId(areaId);
                organizeIdList = organizeInfoMapper.selectOrganizeInfoList(organizeInfo).stream().filter(Objects::nonNull).map(OrganizeInfo::getId).collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(organizeIdList)) {
                return null;
            }
            kindergartenInfo.setOrganizeIdList(organizeIdList);
            return getKindergartenInfoList(kindergartenInfo);
        } else if (roleKeys.contains(Constants.ENCHOU_ROLE)) {
            //角色是：园长，查询自己幼儿园的信息
            kindergartenInfo.setPrincipalId(userId);
            return getKindergartenInfoList(kindergartenInfo);
        } else if (roleKeys.contains(Constants.HEALTHCARE_ROLE)) {
            //角色是：保健师，查找出其所属的幼儿园信息
            if (Objects.isNull(sysUserVO) || Objects.isNull(sysUserVO.getKindergartenId())) {
                return null;
            }
            kindergartenInfo.setId(sysUserVO.getKindergartenId());
            return getKindergartenInfoList(kindergartenInfo);
        } else if (roleKeys.contains(Constants.TEACHER_ROLE) && roleKeys.size() == 1) {
            //角色是：老师，查找出其所属的幼儿园id
            if (Objects.isNull(sysUserVO)) {
                return null;
            }
            if (Objects.nonNull(sysUserVO.getKindergartenId())) {
                kindergartenInfo.setId(sysUserVO.getKindergartenId());
                return getKindergartenInfoList(kindergartenInfo);
            }
        } else if (roleKeys.contains(Constants.PARENT_ROLE) && roleKeys.size() == 1) {
            //角色是：家长，查找出其所属的幼儿园id
            if (Objects.isNull(sysUserVO) || Objects.isNull(sysUserVO.getPhonenumber())) {
                return null;
            }
            List<Long> kindergartenId = kindergartenInfoMapper.getKindergartenIdByParentId(sysUserVO.getPhonenumber());
            if (CollectionUtils.isEmpty(kindergartenId)) {
                return null;
            }
            kindergartenInfo.setKindergartenIdList(kindergartenId);
            return getKindergartenInfoList(kindergartenInfo);
        } else if (roleKeys.contains(Constants.TEACHER_ROLE) && roleKeys.contains(Constants.PARENT_ROLE) && roleKeys.size() == 2) {
            //角色即是家长又是老师，分别查询出老师和家长所属的幼儿园表的id
            List<Long> idList = Lists.newArrayList();
            if (Objects.nonNull(sysUserVO) && Objects.nonNull(sysUserVO.getKindergartenId()) && sysUserVO.getKindergartenId() != 0L) {
                idList.add(sysUserVO.getKindergartenId());
            }
            if (Objects.nonNull(sysUserVO) && Objects.nonNull(sysUserVO.getPhonenumber())) {
                List<Long> kindergartenIdByParentId = kindergartenInfoMapper.getKindergartenIdByParentId(sysUserVO.getPhonenumber());
                if (Objects.nonNull(kindergartenIdByParentId)) {
                    idList.addAll(kindergartenIdByParentId);
                }
            }
            List<Long> distinctList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(idList)) {
                distinctList = idList.stream().distinct().collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(distinctList)) {
                return null;
            }
            kindergartenInfo.setIdList(distinctList);
            return getKindergartenInfoList(kindergartenInfo);
        }
        return null;
    }

    /**
     * 新增幼儿园信息管理
     *
     * @param kindergartenInfo 幼儿园信息管理
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertKindergartenInfo(KindergartenInfo kindergartenInfo) {
        int kindergartenPrincipalIdCount = kindergartenInfoMapper.getKindergartenPrincipalIdCount(kindergartenInfo.getPrincipalId());
        if (kindergartenPrincipalIdCount > 0) {
            return AjaxResult.error("该园长已有所属幼儿园，请选择其他园长！");
        }
        int kindergartenPhoneCount = kindergartenInfoMapper.getKindergartenPhoneCount(kindergartenInfo.getPhone());
        if (kindergartenPhoneCount > 0) {
            return AjaxResult.error("手机号不能重复");
        }
        //创建时间
        kindergartenInfo.setCreateTime(DateUtils.getNowDate());
        //是否删除
        kindergartenInfo.setDelFlag(0);
        //用户id
        kindergartenInfo.setUserId(SecurityUtils.getUserId());
        kindergartenInfoMapper.insertKindergartenInfo(kindergartenInfo);
        //用户所属幼儿园修改
        if (Objects.nonNull(kindergartenInfo.getPrincipalId())) {
            SysUser sysUser = new SysUser();
            sysUser.setUpdateBy(SecurityUtils.getUsername());
            sysUser.setUpdateTime(DateUtils.getNowDate());
            sysUser.setUserId(kindergartenInfo.getPrincipalId());
            sysUser.setKindergartenId(kindergartenInfo.getId());
            userMapper.updateSysUserKindergartenId(sysUser);
        }
        return AjaxResult.success();
    }

    /**
     * 修改幼儿园信息管理
     *
     * @param kindergartenInfo 幼儿园信息管理
     * @return 结果
     */
    @Override
    public AjaxResult updateKindergartenInfo(KindergartenInfo kindergartenInfo) {
        KindergartenInfo kindergartenInfoById = kindergartenInfoMapper.selectKindergartenInfoById(kindergartenInfo.getId());
        if (Objects.isNull(kindergartenInfoById)) {
            return AjaxResult.error("此幼儿园不存在");
        }
        if (!kindergartenInfo.getPrincipalId().equals(kindergartenInfoById.getPrincipalId())) {
            int kindergartenPrincipalIdCount = kindergartenInfoMapper.getKindergartenPrincipalIdCount(kindergartenInfo.getPrincipalId());
            if (kindergartenPrincipalIdCount > 0) {
                return AjaxResult.error("该园长已有所属幼儿园，请选择其他园长！");
            }
        }
        if (!kindergartenInfo.getPhone().equals(kindergartenInfoById.getPhone())) {
            int kindergartenPhoneCount = kindergartenInfoMapper.getKindergartenPhoneCount(kindergartenInfo.getPhone());
            if (kindergartenPhoneCount > 0) {
                return AjaxResult.error("手机号不能重复");
            }
        }
        //修改时间
        kindergartenInfo.setUpdateTime(DateUtils.getNowDate());
        //是否删除
        kindergartenInfo.setDelFlag(0);
        kindergartenInfoMapper.updateKindergartenInfo(kindergartenInfo);
        //用户所属幼儿园修改
        if (Objects.nonNull(kindergartenInfo.getPrincipalId()) && !kindergartenInfoById.getPrincipalId().equals(kindergartenInfo.getPrincipalId())) {
            SysUser sysUser = new SysUser();
            sysUser.setUpdateBy(SecurityUtils.getUsername());
            sysUser.setUpdateTime(DateUtils.getNowDate());
            sysUser.setUserId(kindergartenInfo.getPrincipalId());
            sysUser.setKindergartenId(kindergartenInfo.getId());
            userMapper.updateSysUserKindergartenId(sysUser);
            sysUser.setUserId(kindergartenInfoById.getPrincipalId());
            sysUser.setKindergartenId(null);
            userMapper.updateSysUserKindergartenId(sysUser);
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除幼儿园信息管理
     *
     * @param ids 需要删除的幼儿园信息管理主键
     * @return 结果
     */
    @Override
    public int deleteKindergartenInfoByIds(Long[] ids) {
        return kindergartenInfoMapper.deleteKindergartenInfoByIds(ids);
    }

    /**
     * 删除幼儿园信息管理信息
     *
     * @param id 幼儿园信息管理主键
     * @return 结果
     */
    @Override
    public int deleteKindergartenInfoById(Long id) {
        return kindergartenInfoMapper.deleteKindergartenInfoById(id);
    }

    /**
     * 逻辑删除幼儿园信息
     *
     * @param ids 需要删除的幼儿园信息管理主键集合
     * @return int 结果
     */
    @Override
    public int updateKindergartenInfoById(Long[] ids) {
        return kindergartenInfoMapper.updateKindergartenInfoByIds(ids);
    }

    /**
     * 分页查询幼儿园列表信息
     *
     * @param kindergartenInfo 输入参数
     * @return 幼儿园列表信息
     */
    private TableDataInfo getKindergartenInfoList(KindergartenInfoDTO kindergartenInfo) {
        pageServiceUtil.startPage();
        List<KindergartenInfoDTO> kindergartenInfoList = kindergartenInfoMapper.selectKindergartenInfoList(kindergartenInfo);
        return pageServiceUtil.getDataTable(kindergartenInfoList);
    }
}
