package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import lombok.SneakyThrows;
import org.dromara.common.core.domain.R;
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.mapper.BaseMapperPlus;
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.mybatis.helper.DataPermissionHelper;
import org.dromara.system.domain.RegisterSchool;
import org.dromara.system.domain.RegisterTeacherClass;
import org.dromara.system.domain.SysTenant;
import org.dromara.system.domain.bo.RegisterSchoolFileBo;
import org.dromara.system.domain.bo.RegisterTeacherClassBo;
import org.dromara.system.domain.vo.RegisterTeacherClassVo;
import org.dromara.system.mapper.RegisterTeacherClassMapper;
import org.dromara.system.service.IRegisterTeacherClassService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.RegisterTeacherBo;
import org.dromara.system.domain.vo.RegisterTeacherVo;
import org.dromara.system.domain.RegisterTeacher;
import org.dromara.system.mapper.RegisterTeacherMapper;
import org.dromara.system.service.IRegisterTeacherService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 注册-老师Service业务层处理
 *
 * @author boman
 * @date 2023-08-16
 */
@RequiredArgsConstructor
@Service
public class RegisterTeacherServiceImpl implements IRegisterTeacherService {

    private final RegisterTeacherMapper baseMapper;

    private final IRegisterTeacherClassService registerTeacherClassService;

    private final RegisterTeacherClassMapper registerTeacherClassMapper;

    /**
     * 查询注册-老师
     */
    @Override
    public RegisterTeacherVo queryById(Long id) {

        RegisterTeacherVo registerTeacher = baseMapper.selectVoById(id);
        RegisterTeacherClassBo registerTeacherClass = new RegisterTeacherClassBo();
        registerTeacherClass.setTeacherId(id);
        List<RegisterTeacherClassVo> registerTeacherClassList = registerTeacherClassService.queryList(registerTeacherClass);
        registerTeacher.setRegisterTeacherClassList(registerTeacherClassList);

        return registerTeacher;
    }

    /**
     * 查询注册-老师列表租户
     */
    @Override
    public TableDataInfo<RegisterTeacherVo> queryPageList(RegisterTeacherBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<RegisterTeacher> lqw = buildQueryWrapper(bo);
        Page<RegisterTeacherVo> result = baseMapper.selectVoMapperPage(pageQuery.build(), lqw);
        if (result.getRecords() != null && result.getRecords().size() > 0) {
            for (RegisterTeacherVo teacher : result.getRecords()) {
                RegisterTeacherClassBo registerTeacherClass = new RegisterTeacherClassBo();
                registerTeacherClass.setTeacherId(teacher.getId());
                List<RegisterTeacherClassVo> registerTeacherClassList = registerTeacherClassService.queryList(registerTeacherClass);
                teacher.setRegisterTeacherClassList(registerTeacherClassList);
            }
        }
        return TableDataInfo.build(result);
    }



    /**
     * 查询注册-老师列表
     */
    @Override
    public List<RegisterTeacherVo> queryList(RegisterTeacherBo bo) {
        LambdaQueryWrapper<RegisterTeacher> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增注册-老师
     */
    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<RegisterTeacherVo> insertByBo(RegisterTeacherBo bo) {

        //查询是否已经注册过
        RegisterTeacherVo registerTeacherOld = baseMapper.selectRegisterTeacherByPhonenumber(bo.getUserPhone());
        if (registerTeacherOld != null) {
            if (registerTeacherOld.getIsPass().equals("1")) {
                return R.fail("该微信已注册当前身份，信息正在审核中。", registerTeacherOld);
            } else if (registerTeacherOld.getIsPass().equals("2")) {
                return R.fail("该微信已注册当前身份，审核已通过，请登录。", registerTeacherOld);
            } else {
                return R.fail("该微信已注册当前身份，审核未通过。", registerTeacherOld);
            }
        }
        bo.setCreateTime(DateUtils.getNowDate());
        bo.setUpdateTime(DateUtils.getNowDate());
        RegisterTeacher add = MapstructUtils.convert(bo, RegisterTeacher.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        bo.setId(add.getId());
        if (bo.getRegisterTeacherClassList() != null && bo.getRegisterTeacherClassList().size() > 0) {

            List<RegisterTeacherClassVo> registerTeacherClassList = bo.getRegisterTeacherClassList();

            for (RegisterTeacherClassVo registerTeacherClass : registerTeacherClassList) {
                registerTeacherClass.setTeacherId(bo.getId());
                String className = registerTeacherClass.getClassName();
                int period = StringUtils.getPeriod(className);
                registerTeacherClass.setPeriod(String.valueOf(period));
                registerTeacherClass.setTenantId(bo.getTenantId());

                RegisterTeacherClassBo teacherClassBo = new RegisterTeacherClassBo();
                ClassUtils.copyProperties(registerTeacherClass, teacherClassBo);
                registerTeacherClassService.insertByBo(teacherClassBo);

            }
        }

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

    /**
     * 修改注册-老师
     */
    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(RegisterTeacherBo bo) {

        //删除注册表-老师-班级（学科）表
        List<RegisterTeacherClassVo> registerTeacherClassList = bo.getRegisterTeacherClassList();
        if (registerTeacherClassList != null && registerTeacherClassList.size() > 0) {
            registerTeacherClassMapper.deleteRegisterTeacherClassByTeacherId(bo.getId());
            for (RegisterTeacherClassVo registerTeacherClass : registerTeacherClassList) {
                registerTeacherClass.setTeacherId(bo.getId());

                String className = registerTeacherClass.getClassName();
                int period = StringUtils.getPeriod(className);
                registerTeacherClass.setPeriod(String.valueOf(period));
                RegisterTeacherClassBo registerTeacherClassBo = new RegisterTeacherClassBo();
                ClassUtils.copyProperties(registerTeacherClass, registerTeacherClassBo);
                registerTeacherClassService.insertByBo(registerTeacherClassBo);
            }
        }
        bo.setIsPass("1");
        bo.setUpdateTime(DateUtils.getNowDate());

        RegisterTeacher update = MapstructUtils.convert(bo, RegisterTeacher.class);
        validEntityBeforeSave(update);
        return baseMapper.updateMapperById(update) > 0;
    }

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

    /**
     * 批量删除注册-老师
     */
    @Override
    public Boolean deleteWithValidByIds(Long[] ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        registerTeacherClassMapper.deleteRegisterTeacherClassByTeacherIds(ids);
        return baseMapper.deleteRegisterTeacherByIds(ids);
    }
}
