package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
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.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.bo.RegisterParentsStudentBo;
import org.dromara.system.domain.bo.RegisterTeacherClassBo;
import org.dromara.system.domain.vo.RegisterParentsStudentVo;
import org.dromara.system.mapper.RegisterParentsStudentMapper;
import org.dromara.system.service.IRegisterParentsStudentService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.RegisterParentsBo;
import org.dromara.system.domain.vo.RegisterParentsVo;
import org.dromara.system.domain.RegisterParents;
import org.dromara.system.mapper.RegisterParentsMapper;
import org.dromara.system.service.IRegisterParentsService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 注册-家长Service业务层处理
 *
 * @author Lion Li
 * @date 2023-08-16
 */
@RequiredArgsConstructor
@Service
public class RegisterParentsServiceImpl implements IRegisterParentsService {

    private final RegisterParentsMapper baseMapper;

    private final RegisterParentsStudentMapper registerParentsStudentMapper;

    private final IRegisterParentsStudentService registerParentsStudentService;

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

    /**
     * 查询注册-家长列表
     */
    @Override
    @InterceptorIgnore(tenantLine = "true")
    public TableDataInfo<RegisterParentsVo> queryPageList(RegisterParentsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<RegisterParents> lqw = buildQueryWrapper(bo);
        Page<RegisterParentsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询注册-家长列表
     */
    @Override
    public List<RegisterParentsVo> queryList(RegisterParentsBo bo) {
        LambdaQueryWrapper<RegisterParents> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<RegisterParents> buildQueryWrapper(RegisterParentsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<RegisterParents> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOpenId()), RegisterParents::getOpenId, bo.getOpenId());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), RegisterParents::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getUserPhone()), RegisterParents::getUserPhone, bo.getUserPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPass()), RegisterParents::getIsPass, bo.getIsPass());
        return lqw;
    }

    /**
     * 新增注册-家长
     */
    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<RegisterParentsVo> insertByBo(RegisterParentsBo bo) {

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

        List<RegisterParentsStudentVo> registerParentsStudentList = bo.getRegisterParentsStudentList();
        if(registerParentsStudentList!=null && registerParentsStudentList.size()>0){
            for (RegisterParentsStudentVo registerParentsStudent : registerParentsStudentList) {
                int period = StringUtils.getPeriod(registerParentsStudent.getClassName());
                registerParentsStudent.setPeriod(String.valueOf(period));
                registerParentsStudent.setParentsId(bo.getId());
                registerParentsStudent.setParentsName(bo.getUserName());
                registerParentsStudent.setParentsPhone(bo.getUserPhone());
                registerParentsStudent.setCreateTime(DateUtils.getNowDate());
                registerParentsStudent.setUpdateTime(DateUtils.getNowDate());
                RegisterParentsStudent registerParentsStudentBo = new RegisterParentsStudent();
                ClassUtils.copyProperties(registerParentsStudent, registerParentsStudentBo);
                registerParentsStudentMapper.insert(registerParentsStudentBo);
            }
        }

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

    /**
     * 修改注册-家长
     */
    @Override
    public Boolean updateByBo(RegisterParentsBo bo) {

        //先删除审核未通过的数据
        List<RegisterParentsStudentVo> registerParentsStudentList = bo.getRegisterParentsStudentList();
        if(registerParentsStudentList!=null && registerParentsStudentList.size()>0){
            registerParentsStudentMapper.deleteRegisterParentsStudentByParentsId(bo.getId());
            for (RegisterParentsStudentVo registerParentsStudent : registerParentsStudentList) {
                if("3".equals(registerParentsStudent.getIsPass()) || StringUtils.isEmpty(registerParentsStudent.getIsPass())){
                    registerParentsStudent.setParentsId(bo.getId());
                    registerParentsStudent.setParentsName(bo.getUserName());
                    registerParentsStudent.setParentsPhone(bo.getUserPhone());
                    registerParentsStudent.setIsPass("1");
                    registerParentsStudent.setCreateTime(DateUtils.getNowDate());
                    registerParentsStudent.setUpdateTime(DateUtils.getNowDate());
                    RegisterParentsStudentBo registerParentsStudentBo = MapstructUtils.convert(registerParentsStudent, RegisterParentsStudentBo.class);
                    registerParentsStudentService.insertByBo(registerParentsStudentBo);
                }
            }
        }
        bo.setIsPass("1");
        bo.setUpdateTime(DateUtils.getNowDate());
        RegisterParents update = MapstructUtils.convert(bo, RegisterParents.class);
        validEntityBeforeSave(update);
        return baseMapper.updateMapperById(update) > 0;
    }

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

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