package cn.iocoder.yudao.module.llm.service.learningresources;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.llm.controller.admin.learningresources.vo.LearningResourcesPageReqVO;
import cn.iocoder.yudao.module.llm.controller.admin.learningresources.vo.LearningResourcesSaveReqVO;
import cn.iocoder.yudao.module.llm.dal.dataobject.learningresources.LearningResourcesDO;
import cn.iocoder.yudao.module.llm.dal.mysql.learningresources.LearningResourcesMapper;
import cn.iocoder.yudao.module.llm.service.basemodel.BaseModelService;
import cn.iocoder.yudao.module.llm.service.modelservice.ModelServiceService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

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

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

/**
 * 学习资源 Service 实现类
 *
 * @author 华大大模型
 */
@Service
@Validated
public class LearningResourcesServiceImpl implements LearningResourcesService {

    @Resource
    private LearningResourcesMapper learningResourcesMapper;

    @Resource
    private BaseModelService baseModelService;

    @Resource
    private ModelServiceService modelServiceService;

    @Override
    public Long createLearningResources (LearningResourcesSaveReqVO createReqVO) {
        if (StringUtils.isBlank(createReqVO.getFileUrl())) {
            throw exception(LEARNING_RESOURCES_FILE_URL_NOT_NULL);
        }

        // 校验视频封面图
        validVideoCoverImage(createReqVO);

        validateLearningResourcesNameExists(createReqVO);
        // 插入
        LearningResourcesDO learningResources = BeanUtils.toBean(createReqVO, LearningResourcesDO.class);
        learningResourcesMapper.insert(learningResources);
        // 返回
        return learningResources.getId();
    }

    /**
     * 校验视频封面图
     */
    private static void validVideoCoverImage (LearningResourcesSaveReqVO createReqVO) {
        if (createReqVO.getResourceCategory() == 1) {
            if (StringUtils.isBlank(createReqVO.getFileName())) {
                throw exception(VIDEO_COVER_IMAGE_EMPTY);
            }
        }
    }

    @Override
    public void updateLearningResources (LearningResourcesSaveReqVO updateReqVO) {
        // 校验存在
        validateLearningResourcesExists(updateReqVO.getId());
        validateLearningResourcesNameExists(updateReqVO);

        if (StringUtils.isBlank(updateReqVO.getFileUrl())) {
            throw exception(LEARNING_RESOURCES_FILE_URL_NOT_NULL);
        }

        // 校验视频封面图
        validVideoCoverImage(updateReqVO);

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

    @Override
    public void deleteLearningResources (Long id) {
        // 校验存在
        validateLearningResourcesExists(id);
        // 删除
        learningResourcesMapper.deleteById(id);
    }

    private void validateLearningResourcesExists (Long id) {
        if (learningResourcesMapper.selectById(id) == null) {
            throw exception(LEARNING_RESOURCES_NOT_EXISTS);
        }
    }

    private void validateLearningResourcesNameExists (LearningResourcesSaveReqVO reqVO) {
        LambdaQueryWrapper<LearningResourcesDO> wrapper = new LambdaQueryWrapper<LearningResourcesDO>()
                .eq(LearningResourcesDO::getResourceTitle, reqVO.getResourceTitle())
                .eq(LearningResourcesDO::getResourceCategory, reqVO.getResourceCategory());

        if (reqVO.getId() != null) {
            wrapper.ne(LearningResourcesDO::getId, reqVO.getId());
        }
        List<LearningResourcesDO> learningResourcesDOS = learningResourcesMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(learningResourcesDOS)) {
            throw exception(LEARNING_RESOURCES_NAME_NOT_EXISTS);
        }
    }

    @Override
    public LearningResourcesDO getLearningResources (Long id) {
        return learningResourcesMapper.selectById(id);
    }

    @Override
    public PageResult<LearningResourcesDO> getLearningResourcesPage (LearningResourcesPageReqVO pageReqVO) {
        return learningResourcesMapper.selectPage(pageReqVO);
    }

    @Override
    public String downLearningResources (Long id) {
        LearningResourcesDO learningResourcesDO = learningResourcesMapper.selectById(id);
        learningResourcesMapper.updateDownCount(learningResourcesDO);
        return learningResourcesDO.getFileUrl();
    }


    /**
     * 视频查看量更新
     *
     * @param updateReqVO 更新信息
     */
    @Override
    public void videoViewsUpdate (LearningResourcesSaveReqVO updateReqVO) {
        Long id = updateReqVO.getId();

        if (id == null) {
            throw exception(LEARNING_RESOURCES_NOT_EXISTS);
        }

        // 校验存在
        validateLearningResourcesExists(id);

        // 更新
        learningResourcesMapper.update(new UpdateWrapper<LearningResourcesDO>()
                .setSql("down_count = down_count + 1")
                .eq("id", id));
    }

    /**
     * 获得容器数量
     * <p>
     * 容器数量 = 模型服务管理 + 模型管理
     * </p>
     *
     * @return 容器数量
     */
    @Override
    public Long getContainerNumber () {
        // 获取模型服务的数量
        Long modelServiceCount = modelServiceService.getCount();
        // 获取基础模型服务的数量
        Long baseModelServiceCount = baseModelService.getCount();
        // 计算容器的总数量
        return modelServiceCount + baseModelServiceCount;
    }
}
