package com.kxs.system.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.core.util.R;
import com.kxs.system.api.model.KxsCamp;
import com.kxs.system.api.model.KxsCampUser;
import com.kxs.system.biz.constant.enums.CampStatusEnum;
import com.kxs.system.biz.mapper.KxsCampGroupMapper;
import com.kxs.system.api.model.KxsCampGroup;
import com.kxs.system.biz.mapper.KxsCampMapper;
import com.kxs.system.biz.mapper.KxsCampUserMapper;
import com.kxs.system.biz.service.KxsCampGroupService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

/**
 * 训练营分组(KxsCampGroup)表服务实现类
 *
 * @author 系统
 * @since 2024-07-02 15:10:28
 */
@Service("kxsCampGroupService")
@RequiredArgsConstructor
public class KxsCampGroupServiceImpl extends ServiceImpl<KxsCampGroupMapper, KxsCampGroup> implements KxsCampGroupService {

    private final KxsCampMapper kxsCampMapper;

    private final KxsCampUserMapper kxsCampUserMapper;
    @Override
    public Boolean addData(KxsCampGroup param) {

        KxsCamp camp = kxsCampMapper.selectById(param.getCampId());
        Optional.ofNullable(camp).orElseThrow(()-> new RuntimeException("训练营不存在"));
        if(Objects.equals(camp.getStatus(), CampStatusEnum.STATUS_END.getType())){
            throw new GlobalCustomerException("训练营已结束");
        }
        KxsCampGroup group = getOne(Wrappers.<KxsCampGroup>lambdaQuery().eq(KxsCampGroup::getGroupId, param.getGroupId()));
        if(group != null){
            throw new GlobalCustomerException("分组已存在");
        }

        return save(param);
    }

    @Override
    public Boolean removeByData(Integer groupId) {

        KxsCampGroup group = getById(groupId);
        long count = kxsCampUserMapper.selectCount(Wrappers.<KxsCampUser>lambdaQuery().eq(KxsCampUser::getGroupId, group.getGroupId()));
        if(count > 0){
            throw new GlobalCustomerException("该分组下存在成员，无法删除");
        }
        return removeById(groupId);
    }
}

