package cn.iocoder.yudao.module.system.service.biz;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.GroupsPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.GroupsSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.GroupsDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.GroupsMapper;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.GROUPS_NOT_EXISTS;

/**
 * @Author: jinyd
 * @CreateTime: 2024/9/6  15:01
 * @Description:
 * @Version: 4.0
 */

@Service
@Validated
public class GroupsServiceImpl  implements GroupsService {

    @Resource
    private GroupsMapper groupsMapper;

    @Override
    public Long createGroups(GroupsSaveReqVO createReqVO) {
        // 插入
        GroupsDO groups = BeanUtils.toBean(createReqVO, GroupsDO.class);
        groupsMapper.insert(groups);
        // 返回
        return groups.getId();
    }

    @Override
    public void updateGroups(GroupsSaveReqVO updateReqVO) {
        // 校验存在
        validateGroupsExists(updateReqVO.getId());
        // 更新
        GroupsDO updateObj = BeanUtils.toBean(updateReqVO, GroupsDO.class);
        groupsMapper.updateById(updateObj);
    }

    @Override
    public void deleteGroups(Long id) {
        // 校验存在
        validateGroupsExists(id);
        // 删除
        groupsMapper.deleteById(id);
    }

    private void validateGroupsExists(Long id) {
        if (groupsMapper.selectById(id) == null) {
            throw exception(GROUPS_NOT_EXISTS);
        }
    }

    @Override
    public GroupsDO getGroups(Long id) {
        return groupsMapper.selectById(id);
    }

    @Override
    public PageResult<GroupsDO> getGroupsPage(GroupsPageReqVO pageReqVO) {
        return groupsMapper.selectPage(pageReqVO);
    }

    @Override
    public Boolean checkGroupsRole(AdminUserDO user, Integer loginPlatform, Integer loginDevice) {
        if (null != loginPlatform) {
            Integer count = groupsMapper.selectSystemTenant(user.getTenantId(), loginPlatform);
            if (count > 0) {
                return Boolean.FALSE;
            }
        }
        if (null != loginDevice) {
            Integer menuCount = groupsMapper.selectSystemMenuCount(user.getId(), loginDevice);
            if (menuCount == 0) {
                return Boolean.FALSE;
            }
        }

        return Boolean.TRUE;
    }

}
