package cn.iocoder.yudao.module.iot.service.iotorganization;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.iot.controller.admin.iotorganization.vo.IotOrganizationListReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.iotorganization.vo.IotOrganizationSaveReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.iotorganization.IotOrganizationDO;
import cn.iocoder.yudao.module.iot.dal.mysql.iotorganization.IotOrganizationMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.iot.enums.ErrorCodeConstants.*;

/**
 * IOT组织 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class IotOrganizationServiceImpl implements IotOrganizationService {

    @Resource
    private IotOrganizationMapper iotOrganizationMapper;

    @Override
    public Long createOrganization(IotOrganizationSaveReqVO createReqVO) {
        // 校验父组织id的有效性
        validateParentOrganization(null, createReqVO.getParentId());
        // 校验组织名称的唯一性
        validateOrganizationNameUnique(null, createReqVO.getParentId(), createReqVO.getName());

        // 插入
        IotOrganizationDO organization = BeanUtils.toBean(createReqVO, IotOrganizationDO.class);
        iotOrganizationMapper.insert(organization);
        // 返回
        return organization.getId();
    }

    @Override
    public void updateOrganization(IotOrganizationSaveReqVO updateReqVO) {
        // 校验存在
        validateOrganizationExists(updateReqVO.getId());
        // 校验父组织id的有效性
        validateParentOrganization(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验组织名称的唯一性
        validateOrganizationNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());

        // 更新
        IotOrganizationDO updateObj = BeanUtils.toBean(updateReqVO, IotOrganizationDO.class);
        iotOrganizationMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrganization(Long id) {
        // 校验存在
        validateOrganizationExists(id);
        // 校验是否有子IOT组织
        if (iotOrganizationMapper.selectCountByParentId(id) > 0) {
            throw exception(ORGANIZATION_EXITS_CHILDREN);
        }
        // 删除
        iotOrganizationMapper.deleteById(id);
    }

    private void validateOrganizationExists(Long id) {
        if (iotOrganizationMapper.selectById(id) == null) {
            throw exception(ORGANIZATION_NOT_EXISTS);
        }
    }

    private void validateParentOrganization(Long id, Long parentId) {
        if (parentId == null || IotOrganizationDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父IOT组织
        if (Objects.equals(id, parentId)) {
            throw exception(ORGANIZATION_PARENT_ERROR);
        }
        // 2. 父IOT组织不存在
        IotOrganizationDO parentOrganization = iotOrganizationMapper.selectById(parentId);
        if (parentOrganization == null) {
            throw exception(ORGANIZATION_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父IOT组织，如果父IOT组织是自己的子IOT组织，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentOrganization.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(ORGANIZATION_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父IOT组织
            if (parentId == null || IotOrganizationDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentOrganization = iotOrganizationMapper.selectById(parentId);
            if (parentOrganization == null) {
                break;
            }
        }
    }

    private void validateOrganizationNameUnique(Long id, Long parentId, String name) {
        IotOrganizationDO organization = iotOrganizationMapper.selectByParentIdAndName(parentId, name);
        if (organization == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的IOT组织
        if (id == null) {
            throw exception(ORGANIZATION_NAME_DUPLICATE);
        }
        if (!Objects.equals(organization.getId(), id)) {
            throw exception(ORGANIZATION_NAME_DUPLICATE);
        }
    }

    @Override
    public IotOrganizationDO getOrganization(Long id) {
        return iotOrganizationMapper.selectById(id);
    }

    @Override
    public List<IotOrganizationDO> getOrganizationList(IotOrganizationListReqVO listReqVO) {
        return iotOrganizationMapper.selectList(listReqVO);
    }

}