package org.dromara.system.service.impl;

import org.dromara.common.core.domain.dto.RoleDTO;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.FormalParentsStudent;
import org.dromara.system.domain.FormalTeacherClass;
import org.dromara.system.domain.bo.FormalParentsStudentBo;
import org.dromara.system.domain.bo.FormalTeacherClassBo;
import org.dromara.system.domain.vo.FormalParentsStudentVo;
import org.dromara.system.domain.vo.FormalTeacherClassVo;
import org.dromara.system.domain.vo.RegisterParentsVo;
import org.dromara.system.mapper.FormalParentsStudentMapper;
import org.dromara.system.mapper.FormalTeacherClassMapper;
import org.dromara.system.mapper.RegisterParentsMapper;
import org.dromara.system.service.IFormalParentsStudentService;
import org.dromara.system.service.IFormalTeacherClassService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.RegisterParentsStudentBo;
import org.dromara.system.domain.vo.RegisterParentsStudentVo;
import org.dromara.system.domain.RegisterParentsStudent;
import org.dromara.system.mapper.RegisterParentsStudentMapper;
import org.dromara.system.service.IRegisterParentsStudentService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 注册-家长-学生Service业务层处理
 *
 * @author boman
 * @date 2023-08-16
 */
@RequiredArgsConstructor
@Service
public class RegisterParentsStudentServiceImpl implements IRegisterParentsStudentService {

    private final RegisterParentsStudentMapper baseMapper;

    private final RegisterParentsMapper registerParentsMapper;

    private final IFormalParentsStudentService formalParentsStudentService;

    private final FormalParentsStudentMapper formalParentsStudentMapper;

    private final IFormalTeacherClassService formalTeacherClassService;

    private final FormalTeacherClassMapper formalTeacherClassMapper;

    /**
     * 查询注册-家长-学生
     */
    @Override
    public RegisterParentsStudentVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询注册-家长-学生列表
     */
    @Override
    public TableDataInfo<RegisterParentsStudentVo> queryPageList(RegisterParentsStudentBo bo, PageQuery pageQuery) {

        LoginUser loginUser = LoginHelper.getLoginUser();

        Map<String, Object> params = bo.getParams();
        String ro = "";
        if (params != null && params.size() > 0) {
            ro = (String) params.get("role");
        }
        if(StringUtils.isEmpty(ro)){
            List<RoleDTO> roles = loginUser.getRoles();
            boolean bl = false;
            for (RoleDTO role : roles) {
                if("teacher".equals(role.getRoleKey())){
                    bl = true;
                    break;
                }
            }
            //角色是老师
            if(bl){
                //查询老师班级
                FormalTeacherClassBo formalTeacherClass = new FormalTeacherClassBo();
                formalTeacherClass.setTeacherId(loginUser.getUserId());
                List<FormalTeacherClassVo> formalTeacherClassList = formalTeacherClassMapper.queryMapperList(formalTeacherClass);
                List<Long> classIds = formalTeacherClassList.stream().map(FormalTeacherClassVo::getClassId).collect(Collectors.toList());
                bo.setClassIds(classIds);
            }
        }

        LambdaQueryWrapper<RegisterParentsStudent> lqw = buildQueryWrapper(bo);
        Page<RegisterParentsStudentVo> result = baseMapper.selectVoMapperPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询注册-家长-学生列表
     */
    @Override
    public List<RegisterParentsStudentVo> queryList(RegisterParentsStudentBo bo) {
        LambdaQueryWrapper<RegisterParentsStudent> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoMapperList(lqw);
    }

    private LambdaQueryWrapper<RegisterParentsStudent> buildQueryWrapper(RegisterParentsStudentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<RegisterParentsStudent> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentsId() != null, RegisterParentsStudent::getParentsId, bo.getParentsId());
        lqw.like(StringUtils.isNotBlank(bo.getParentsName()), RegisterParentsStudent::getParentsName, bo.getParentsName());
        lqw.eq(StringUtils.isNotBlank(bo.getParentsPhone()), RegisterParentsStudent::getParentsPhone, bo.getParentsPhone());
        lqw.eq(bo.getSchoolId() != null, RegisterParentsStudent::getSchoolId, bo.getSchoolId());
        lqw.like(StringUtils.isNotBlank(bo.getSchoolName()), RegisterParentsStudent::getSchoolName, bo.getSchoolName());
        lqw.eq(bo.getClassId() != null, RegisterParentsStudent::getClassId, bo.getClassId());
        lqw.like(StringUtils.isNotBlank(bo.getClassName()), RegisterParentsStudent::getClassName, bo.getClassName());
        lqw.like(StringUtils.isNotBlank(bo.getPeriod()), RegisterParentsStudent::getPeriod, bo.getPeriod());
        lqw.like(StringUtils.isNotBlank(bo.getStudentName()), RegisterParentsStudent::getStudentName, bo.getStudentName());
        lqw.eq(StringUtils.isNotBlank(bo.getStudentNumber()), RegisterParentsStudent::getStudentNumber, bo.getStudentNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPass()), RegisterParentsStudent::getIsPass, bo.getIsPass());
        lqw.eq(bo.getAuditId() != null, RegisterParentsStudent::getAuditId, bo.getAuditId());
        lqw.eq(StringUtils.isNotBlank(bo.getAuditUser()), RegisterParentsStudent::getAuditUser, bo.getAuditUser());
        lqw.eq(StringUtils.isNotBlank(bo.getOpinion()), RegisterParentsStudent::getOpinion, bo.getOpinion());
        lqw.in((bo.getClassIds()!=null && bo.getClassIds().size()>0),RegisterParentsStudent::getClassId, bo.getClassIds());
        lqw.orderByDesc(RegisterParentsStudent::getCreateTime);
        return lqw;
    }

    /**
     * 新增注册-家长-学生
     */
    @Override
    public Boolean insertByBo(RegisterParentsStudentBo bo) {
        //查询注册前家长信息
        LoginUser user = LoginHelper.getLoginUser();
        RegisterParentsVo registerParentsVo = registerParentsMapper.selectRegisterParentsByPhonenumber(user.getUsername());
        bo.setParentsId(registerParentsVo.getId());
        bo.setParentsName(registerParentsVo.getUserName());
        bo.setParentsPhone(registerParentsVo.getUserPhone());
        int period = StringUtils.getPeriod(bo.getClassName());
        bo.setPeriod(String.valueOf(period));
        bo.setCreateTime(DateUtils.getNowDate());
        bo.setUpdateTime(DateUtils.getNowDate());
        bo.setCreateTime(DateUtils.getNowDate());
        RegisterParentsStudent add = MapstructUtils.convert(bo, RegisterParentsStudent.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改注册-家长-学生
     */
    @Override
    @Transactional
    public Boolean updateByBo(RegisterParentsStudentBo bo) {
        //删除学生
        bo.setUpdateTime(DateUtils.getNowDate());
        bo.setIsPass("1");
        RegisterParentsStudent update = MapstructUtils.convert(bo, RegisterParentsStudent.class);
        validEntityBeforeSave(update);
        return baseMapper.updateMapperById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(RegisterParentsStudent entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除注册-家长-学生
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean deleteWithValidById(RegisterParentsStudentBo bo, boolean b) {
        //
        LoginUser user = LoginHelper.getLoginUser();
        formalParentsStudentMapper.updateIsDelByStudent(user.getUserId(),bo.getClassId(),bo.getStudentName());
        return baseMapper.deleteByIdMapper(bo.getId())>0;
    }
}
