package cn.iocoder.byzs.module.blockly.service.blocklyType;

import cn.iocoder.byzs.framework.common.util.object.BeanUtils;
import cn.iocoder.byzs.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.byzs.module.blockly.controller.admin.blocklyType.vo.BlocklyTypeListReqVO;
import cn.iocoder.byzs.module.blockly.controller.admin.blocklyType.vo.BlocklyTypeSaveReqVO;
import cn.iocoder.byzs.module.blockly.dal.dataobject.blocklyProgress.BlocklyProgressDO;
import cn.iocoder.byzs.module.blockly.dal.dataobject.blocklyType.BlocklyTypeDO;
import cn.iocoder.byzs.module.blockly.dal.mysql.blocklyProgress.BlocklyProgressMapper;
import cn.iocoder.byzs.module.blockly.dal.mysql.blocklyType.BlocklyTypeMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Objects;

import static cn.iocoder.byzs.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.byzs.module.blockly.enums.ErrorCodeConstants.*;

/**
 * 课程-类型 Service 实现类
 *
 * @author lyb
 */
@Service
@Validated
public class BlocklyTypeServiceImpl implements BlocklyTypeService {

    @Resource
    private BlocklyTypeMapper blocklyTypeMapper;
    @Resource
    private BlocklyProgressMapper blocklyProgressMapper;

    @Override
    public Long createBlocklyType(BlocklyTypeSaveReqVO createReqVO) {
        // 校验课程类型父级id的有效性
        validateParentBlocklyType(null, createReqVO.getCtParentId());
        // 校验课程类型名称的唯一性
        validateBlocklyTypeCtTypeUnique(null, createReqVO.getCtParentId(), createReqVO.getCtType());

        // 插入
        BlocklyTypeDO blocklyType = BeanUtils.toBean(createReqVO, BlocklyTypeDO.class);
        blocklyTypeMapper.insert(blocklyType);
        // 返回
        return blocklyType.getId();
    }

    @Override
    public void updateBlocklyType(BlocklyTypeSaveReqVO updateReqVO) {
        // 校验存在
        BlocklyTypeDO blocklyTypeDO = validateBlocklyTypeExists(updateReqVO.getId());
        // 校验课程类型父级id的有效性
        validateParentBlocklyType(updateReqVO.getId(), updateReqVO.getCtParentId());
        // 校验课程类型名称的唯一性
        validateBlocklyTypeCtTypeUnique(updateReqVO.getId(), updateReqVO.getCtParentId(), updateReqVO.getCtType());

        // 更新
        BlocklyTypeDO updateObj = BeanUtils.toBean(updateReqVO, BlocklyTypeDO.class);
        blocklyTypeMapper.updateById(updateObj);

        // 如果修改了类型，同步更新进度数据
        if (!blocklyTypeDO.getCtTypeNode().equals("0") && !Objects.equals(updateObj.getCtParentId(), blocklyTypeDO.getCtParentId())) {

            // 使用条件更新，将brpCtId等于旧课程类型ID的记录更新为新课程类型ID
            blocklyProgressMapper.update(new BlocklyProgressDO().setBrpZtId(updateObj.getCtParentId()),
                    new LambdaQueryWrapperX<BlocklyProgressDO>().eq(BlocklyProgressDO::getBrpZtId, blocklyTypeDO.getCtParentId()));
        }
    }

    @Override
    public void deleteBlocklyType(Long id) {
        // 校验存在
        validateBlocklyTypeExists(id);
        // 校验是否有子课程-类型
        if (blocklyTypeMapper.selectCountByCtParentId(id) > 0) {
            throw exception(BLOCKLY_TYPE_EXITS_CHILDREN);
        }
        // 删除
        blocklyTypeMapper.deleteById(id);
    }


    private BlocklyTypeDO validateBlocklyTypeExists(Long id) {
        BlocklyTypeDO blocklyTypeDO = blocklyTypeMapper.selectById(id);
        if (blocklyTypeDO == null) {
            throw exception(BLOCKLY_TYPE_NOT_EXISTS);
        }
        return blocklyTypeDO;
    }

    private void validateParentBlocklyType(Long id, Long ctParentId) {
        if (ctParentId == null || BlocklyTypeDO.CT_PARENT_ID_ROOT.equals(ctParentId)) {
            return;
        }
        // 1. 不能设置自己为父课程-类型
        if (Objects.equals(id, ctParentId)) {
            throw exception(BLOCKLY_TYPE_PARENT_ERROR);
        }
        // 2. 父课程-类型不存在
        BlocklyTypeDO parentBlocklyType = blocklyTypeMapper.selectById(ctParentId);
        if (parentBlocklyType == null) {
            throw exception(BLOCKLY_TYPE_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父课程-类型，如果父课程-类型是自己的子课程-类型，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            ctParentId = parentBlocklyType.getCtParentId();
            if (Objects.equals(id, ctParentId)) {
                throw exception(BLOCKLY_TYPE_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父课程-类型
            if (ctParentId == null || BlocklyTypeDO.CT_PARENT_ID_ROOT.equals(ctParentId)) {
                break;
            }
            parentBlocklyType = blocklyTypeMapper.selectById(ctParentId);
            if (parentBlocklyType == null) {
                break;
            }
        }
    }

    private void validateBlocklyTypeCtTypeUnique(Long id, Long ctParentId, String ctType) {
        BlocklyTypeDO blocklyType = blocklyTypeMapper.selectByCtParentIdAndCtType(ctParentId, ctType);
        if (blocklyType == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的课程-类型
        if (id == null) {
            throw exception(BLOCKLY_TYPE_CT_TYPE_DUPLICATE);
        }
        if (!Objects.equals(blocklyType.getId(), id)) {
            throw exception(BLOCKLY_TYPE_CT_TYPE_DUPLICATE);
        }
    }

    @Override
    public BlocklyTypeDO getBlocklyType(Long id) {
        return blocklyTypeMapper.selectById(id);
    }

    @Override
    public List<BlocklyTypeDO> getBlocklyTypeList(BlocklyTypeListReqVO listReqVO) {
        return blocklyTypeMapper.selectList(listReqVO);
    }

    @Override
    public List<BlocklyTypeDO> getBlocklyTypeSimpleList(BlocklyTypeListReqVO listReqVO) {
        return blocklyTypeMapper.selectSimpleList(listReqVO);
    }

}