package org.dromara.system.service.impl;

import lombok.SneakyThrows;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ClassUtils;
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.system.domain.RegisterParentsStudent;
import org.dromara.system.domain.RegisterSchoolFile;
import org.dromara.system.domain.bo.RegisterParentsStudentBo;
import org.dromara.system.domain.bo.RegisterSchoolFileBo;
import org.dromara.system.domain.bo.RegisterTeacherClassBo;
import org.dromara.system.domain.vo.*;
import org.dromara.system.mapper.*;
import org.dromara.system.service.IRegisterParentsStudentService;
import org.dromara.system.service.IRegisterSchoolFileService;
import org.dromara.system.service.IRegisterTeacherClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.RegisterSchoolBo;
import org.dromara.system.domain.RegisterSchool;
import org.dromara.system.service.IRegisterSchoolService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 注册-学校Service业务层处理
 *
 * @author boman
 * @date 2023-08-16
 */
@RequiredArgsConstructor
@Service
public class RegisterSchoolServiceImpl implements IRegisterSchoolService {

    private final RegisterSchoolMapper baseMapper;

    private final IRegisterSchoolFileService registerSchoolFileService;

    private final RegisterSchoolFileMapper registerSchoolFileMapper;

    private final RegisterTeacherMapper registerTeacherMapper;
    private final RegisterParentsMapper registerParentsMapper;

    private final IRegisterTeacherClassService registerTeacherClassService;
    private final RegisterTeacherClassMapper registerTeacherClassMapper;

    private final IRegisterParentsStudentService registerParentsStudentService;
    private final RegisterParentsStudentMapper registerParentsStudentMapper;

    /**
     * 查询注册-学校
     */
    @Override
    public RegisterSchoolVo queryById(Long id){

        RegisterSchoolVo registerSchool = baseMapper.selectVoMapperById(id);
        RegisterSchoolFileBo registerSchoolFile = new RegisterSchoolFileBo();
        registerSchoolFile.setSchoolId(id);
        List<RegisterSchoolFileVo> registerSchoolFileList = registerSchoolFileService.queryList(registerSchoolFile);
        registerSchool.setRegisterSchoolFileList(registerSchoolFileList);
        return registerSchool;
    }

    /**
     * 查询注册-学校列表
     */
    @Override
    public TableDataInfo<RegisterSchoolVo> queryPageList(RegisterSchoolBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<RegisterSchool> lqw = buildQueryWrapper(bo);
        Page<RegisterSchoolVo> result = baseMapper.selectVoMapperPage(pageQuery.build(), lqw);
        if(result.getRecords().size()>0){
            for (RegisterSchoolVo school : result.getRecords()) {
                RegisterSchoolFileBo registerSchoolFile = new RegisterSchoolFileBo();
                registerSchoolFile.setSchoolId(school.getId());
                List<RegisterSchoolFileVo> registerSchoolFileList = registerSchoolFileService.queryList(registerSchoolFile);
                school.setRegisterSchoolFileList(registerSchoolFileList);
            }
        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询注册-学校列表
     */
    @Override
    public List<RegisterSchoolVo> queryList(RegisterSchoolBo bo) {
        LambdaQueryWrapper<RegisterSchool> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<RegisterSchool> buildQueryWrapper(RegisterSchoolBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<RegisterSchool> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOpenId()), RegisterSchool::getOpenId, bo.getOpenId());
        lqw.like(StringUtils.isNotBlank(bo.getSchoolName()), RegisterSchool::getSchoolName, bo.getSchoolName());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), RegisterSchool::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getUserPhone()), RegisterSchool::getUserPhone, bo.getUserPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPass()), RegisterSchool::getIsPass, bo.getIsPass());
        lqw.eq(bo.getAuditId() != null, RegisterSchool::getAuditId, bo.getAuditId());
        lqw.eq(StringUtils.isNotBlank(bo.getAuditUser()), RegisterSchool::getAuditUser, bo.getAuditUser());
        lqw.eq(StringUtils.isNotBlank(bo.getOpinion()), RegisterSchool::getOpinion, bo.getOpinion());
        lqw.orderByDesc(RegisterSchool::getCreateTime);
        return lqw;
    }

    /**
     * 新增注册-学校
     */
    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<RegisterSchoolVo> insertByBo(RegisterSchoolBo bo) {

        //查询是否已经注册过
        RegisterSchoolVo registerSchoolOld = baseMapper.selectRegisterSchooByPhonenumber(bo.getUserPhone());
        if(registerSchoolOld!=null){
            if(registerSchoolOld.getIsPass().equals("1")){
                return R.fail("该手机号已注册当前身份，信息正在审核中。",registerSchoolOld);
            }else if(registerSchoolOld.getIsPass().equals("2")){
                return R.fail("该手机号已注册当前身份，审核已通过，请登录。",registerSchoolOld);
            }else{
                return R.fail("该手机号已注册当前身份，审核未通过。",registerSchoolOld);
            }
        }

        bo.setCreateTime(DateUtils.getNowDate());
        bo.setUpdateTime(DateUtils.getNowDate());
        bo.setIsPass("1");
        RegisterSchool add = MapstructUtils.convert(bo, RegisterSchool.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        bo.setId(add.getId());

        if(bo.getRegisterSchoolFileList()!=null && bo.getRegisterSchoolFileList().size()>0){
            List<RegisterSchoolFileVo> registerSchoolFile = bo.getRegisterSchoolFileList();
            for (RegisterSchoolFileVo schoolFile : registerSchoolFile) {
                schoolFile.setSchoolId(bo.getId());

                RegisterSchoolFileBo fileBo = new RegisterSchoolFileBo();
                ClassUtils.copyProperties(schoolFile, fileBo);
                registerSchoolFileService.insertByBo(fileBo);
            }
        }

        if (flag) {
            bo.setId(add.getId());
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 修改注册-学校
     */
    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(RegisterSchoolBo bo) {
        bo.setIsPass("1");
        bo.setUpdateTime(DateUtils.getNowDate());
        //先删除附件
        if(bo.getRegisterSchoolFileList()!=null && bo.getRegisterSchoolFileList().size()>0){
            registerSchoolFileMapper.deleteRegisterSchoolFileBySchoolId(bo.getId());
            List<RegisterSchoolFileVo> registerSchoolFile = bo.getRegisterSchoolFileList();
            for (RegisterSchoolFileVo schoolFile : registerSchoolFile) {
                schoolFile.setSchoolId(bo.getId());
                RegisterSchoolFileBo fileBo = new RegisterSchoolFileBo();
                ClassUtils.copyProperties(schoolFile, fileBo);
                registerSchoolFileService.insertByBo(fileBo);
            }
        }
        RegisterSchool update = MapstructUtils.convert(bo, RegisterSchool.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    @Override
    public R<Map<String, Object>> queryInfo(String phonenumber) {
        if(StringUtils.isEmpty(phonenumber)){
            throw new ServiceException("参数获取异常，请稍后重试");
        }
        Map<String,Object> map = new HashMap<>();
        //查询学校里是否有注册信息
        RegisterSchoolVo registerSchoolOld = baseMapper.selectRegisterSchooByPhonenumber(phonenumber);
        if(registerSchoolOld!=null){
            RegisterSchoolFileBo registerSchoolFile = new RegisterSchoolFileBo();
            registerSchoolFile.setSchoolId(registerSchoolOld.getId());
            List<RegisterSchoolFileVo> registerSchoolFileList = registerSchoolFileService.queryList(registerSchoolFile);
            registerSchoolOld.setRegisterSchoolFileList(registerSchoolFileList);
        }else{
            registerSchoolOld = new RegisterSchoolVo();
        }
        map.put("school",registerSchoolOld);
        //查询老师是否有注册信息
        RegisterTeacherVo registerTeacher = registerTeacherMapper.selectRegisterTeacherByPhonenumber(phonenumber);
        if(registerTeacher!=null){
            RegisterTeacherClassBo registerTeacherClass = new RegisterTeacherClassBo();
            registerTeacherClass.setTeacherId(registerTeacher.getId());
            List<RegisterTeacherClassVo> registerTeacherClassList = registerTeacherClassService.queryList(registerTeacherClass);
            registerTeacher.setRegisterTeacherClassList(registerTeacherClassList);
        }else{
            registerTeacher = new RegisterTeacherVo();
        }

        map.put("teacher",registerTeacher);
        //查询家长注册信息
        RegisterParentsVo registerParents = registerParentsMapper.selectRegisterParentsByPhonenumber(phonenumber);
        if(registerParents!=null){
            RegisterParentsStudentBo registerParentsStudent = new RegisterParentsStudentBo();
            registerParentsStudent.setParentsId(registerParents.getId());
            List<RegisterParentsStudentVo> registerParentsStudentList = registerParentsStudentService.queryList(registerParentsStudent);
            registerParents.setRegisterParentsStudentList(registerParentsStudentList);
        }else{
            registerParents = new RegisterParentsVo();
        }

        map.put("parents",registerParents);
        return R.ok(map);
    }
}
