package com.xinyilu.system.service.parentInfo.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.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.parentInfo.ParentInfo;
import com.xinyilu.system.domain.systemarea.SysArea;
import com.xinyilu.system.domain.sysuserclassrelation.SysUserClassRelation;
import com.xinyilu.system.domain.vo.ParentInfoVO;
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.parentInfo.ParentInfoMapper;
import com.xinyilu.system.mapper.systemarea.SysAreaMapper;
import com.xinyilu.system.mapper.sysuserclassrelation.SysUserClassRelationMapper;
import com.xinyilu.system.service.parentInfo.IParentInfoService;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 家长信息Service业务层处理
 *
 * @author xinyilu
 * @date 2022-07-29
 */
@Service
public class ParentInfoServiceImpl implements IParentInfoService {

    @Resource
    private ParentInfoMapper parentInfoMapper;
    @Resource
    private ClassInfoMapper classInfoMapper;
    @Resource
    private PageServiceUtil pageServiceUtil;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysUserClassRelationMapper sysUserClassRelationMapper;
    @Resource
    private SysAreaMapper sysAreaMapper;

    /**
     * 查询家长信息
     *
     * @param id 家长信息主键
     * @return 家长信息
     */
    @Override
    public ParentInfo selectParentInfoById(Long id) {
        return parentInfoMapper.selectParentInfoById(id);
    }

    /**
     * 查询家长信息列表
     *
     * @param parentInfo 家长信息
     * @return 家长信息
     */
    @Override
    public TableDataInfo selectParentInfoList(ParentInfoVO parentInfo) {
        //判断当前用户角色，根据不同的角色显示不同的家长信息
        List<String> roleKeys = SecurityUtils.getLoginUser().getUser().getRoles()
                .stream().filter(Objects::nonNull)
                .filter(item -> StringUtils.isNotBlank(item.getRoleKey()))
                .map(SysRole::getRoleKey).collect(Collectors.toList());
        //当前系统用户id
        Long userId = SecurityUtils.getUserId();
        SysUserVO sysUserVO = userMapper.selectUserById(userId);
        if (roleKeys.contains(Constants.ADMIN_ROLE)) {
            //角色为管理员，查询所有的家长信息
            return getPageInfo(parentInfo);
        } 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;
            }
            parentInfo.setKindergartenIdList(kindergartenIdList);
            return getRolePageInfo(parentInfo);
        } else if (roleKeys.contains(Constants.REGION_ROLE)) {
            //角色为区域角色，查询该区域下所有幼儿园下得所有班级中的家长的信息
            long areaId = Objects.isNull(SecurityUtils.getLoginUser().getUser().getAreaId()) ? 0 : SecurityUtils.getLoginUser().getUser().getAreaId();
            List<Long> kindergartenIdList = Lists.newArrayList();
            List<Long> sysAreaIdList = new ArrayList<>();
            sysAreaIdList.add(areaId);
            if (CollectionUtils.isNotEmpty(sysAreaIdList)) {
                //获取该区域下的所有幼儿园信息
                kindergartenIdList = classInfoMapper.getKindergartenInfoByAreaId(sysAreaIdList, 3L);
            }
            if (CollectionUtils.isEmpty(kindergartenIdList)) {
                return null;
            }
            parentInfo.setKindergartenIdList(kindergartenIdList);
            return getRolePageInfo(parentInfo);
        } else if (roleKeys.contains(Constants.ENCHOU_ROLE)) {
            //角色为园长，查询当前幼儿园下的所有家长信息
            Long kindergartenId = classInfoMapper.getKindergartenIdByPrincipalId(userId);
            if (Objects.isNull(kindergartenId) || kindergartenId == 0L) {
                return null;
            }
            parentInfo.setKindergartenId(kindergartenId);
            return getRolePageInfo(parentInfo);
        } else if (roleKeys.contains(Constants.HEALTHCARE_ROLE)) {
            //角色是：保健师，查找出其所属的幼儿园信息
            if (Objects.isNull(sysUserVO) || Objects.isNull(sysUserVO.getKindergartenId())) {
                return null;
            }
            parentInfo.setKindergartenId(sysUserVO.getKindergartenId());
            return getRolePageInfo(parentInfo);
        } else if (roleKeys.contains(Constants.TEACHER_ROLE) && roleKeys.size() == 1) {
            //角色为老师，查询所属班级下的家长信息
            List<Long> classIdByUserId = sysUserClassRelationMapper.getSysUserClassRelationList(userId).stream().filter(Objects::nonNull).filter(classId -> Objects.nonNull(classId.getClassId())).map(SysUserClassRelation::getClassId).distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(classIdByUserId)) {
                return null;
            }
            parentInfo.setClassIdList(classIdByUserId);
            return getRolePageInfo(parentInfo);
        } else if (roleKeys.contains(Constants.PARENT_ROLE) && roleKeys.size() == 1) {
            //角色为家长，查询自己的信息
            if (Objects.isNull(sysUserVO) || Objects.isNull(sysUserVO.getPhonenumber())) {
                return null;
            }
            parentInfo.setPhone(sysUserVO.getPhonenumber());
            return getPageInfo(parentInfo);
        } else if (roleKeys.contains(Constants.TEACHER_ROLE) && roleKeys.contains(Constants.PARENT_ROLE) && roleKeys.size() == 2) {
            //即是家长，又是老师，查询自己和其班级下的所有家长的信息
            List<Long> classIdByUserId = sysUserClassRelationMapper.getSysUserClassRelationList(userId).stream().filter(Objects::nonNull).filter(classId -> Objects.nonNull(classId.getClassId())).map(SysUserClassRelation::getClassId).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(classIdByUserId)) {
                parentInfo.setClassIdList(classIdByUserId);
            }
            if (Objects.nonNull(sysUserVO) && Objects.nonNull(sysUserVO.getPhonenumber())) {
                parentInfo.setPhoneNumber(sysUserVO.getPhonenumber());
            }
            return getRolePageInfo(parentInfo);
        }
        return null;
    }

    /**
     * 新增家长信息
     *
     * @param parentInfo 家长信息
     * @return 结果
     */
    @Override
    public AjaxResult insertParentInfo(ParentInfo parentInfo) {
        ParentInfo getParent = new ParentInfo();
        getParent.setPhone(StringUtils.isBlank(parentInfo.getPhone()) ? "" : parentInfo.getPhone());
        int phoneCount = parentInfoMapper.selectParentPhoneInfo(getParent);
        if (phoneCount > 0) {
            return AjaxResult.error("手机号已存在，请重新填写");
        }
        //创建时间
        parentInfo.setCreateTime(DateUtils.getNowDate());
        //是否删除
        parentInfo.setDelFlag(0);
        //用户id
        parentInfo.setUserId(SecurityUtils.getUserId());
        return AjaxResult.success(parentInfoMapper.insertParentInfo(parentInfo));
    }


    /**
     * 修改家长信息
     *
     * @param parentInfo 家长信息
     * @return 结果
     */
    @Override
    public AjaxResult updateParentInfo(ParentInfo parentInfo) {
        ParentInfo getParent = parentInfoMapper.selectParentInfoById(parentInfo.getId());
        if (Objects.isNull(getParent)) {
            return AjaxResult.error("该家长信息不存在");
        }
        if (StringUtils.isNotBlank(getParent.getPhone()) && !parentInfo.getPhone().equals(getParent.getPhone())) {
            ParentInfo parentPhone = new ParentInfo();
            parentPhone.setPhone(StringUtils.isBlank(parentInfo.getPhone()) ? "" : parentInfo.getPhone());
            int phoneCount = parentInfoMapper.selectParentPhoneInfo(parentPhone);
            if (phoneCount > 0) {
                return AjaxResult.error("手机号已存在，请重新填写");
            }
        }
        parentInfo.setUpdateTime(DateUtils.getNowDate());
        parentInfo.setDelFlag(0);
        return AjaxResult.success(parentInfoMapper.updateParentInfo(parentInfo));
    }

    /**
     * 批量删除家长信息
     *
     * @param ids 需要删除的家长信息主键
     * @return 结果
     */
    @Override
    public int deleteParentInfoByIds(Long[] ids) {
        return parentInfoMapper.deleteParentInfoByIds(ids);
    }

    /**
     * 删除家长信息信息
     *
     * @param id 家长信息主键
     * @return 结果
     */
    @Override
    public int deleteParentInfoById(Long id) {
        return parentInfoMapper.deleteParentInfoById(id);
    }

    /**
     * 批量逻辑删除家长信息
     *
     * @param ids 需要删除的家长信息主键集合
     * @return 结果
     */
    @Override
    public int updateParentInfoByIds(Long[] ids) {
        return parentInfoMapper.updateParentInfoByIds(ids);
    }

    /**
     * 获取分页数据
     *
     * @param parentInfo 查询检索条件
     * @return 分页数据集合
     */
    private TableDataInfo getPageInfo(ParentInfoVO parentInfo) {
        pageServiceUtil.startPage();
        List<ParentInfo> parentInfoList = parentInfoMapper.selectParentInfoList(parentInfo);
        return pageServiceUtil.getDataTable(parentInfoList);
    }

    /**
     * 获取不同角色的家长分页数据
     *
     * @param parentInfo 查询检索条件
     * @return 分页数据集合
     */
    private TableDataInfo getRolePageInfo(ParentInfoVO parentInfo) {
        pageServiceUtil.startPage();
        List<ParentInfo> parentInfoList = parentInfoMapper.selectRoleParentInfoList(parentInfo);
        return pageServiceUtil.getDataTable(parentInfoList);
    }
}
