package org.dromara.safety.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.project.service.IBusProjectService;
import org.dromara.safety.domain.HseQuestionsCategory;
import org.dromara.safety.domain.dto.questionscategory.HseQuestionsCategoryCreateReq;
import org.dromara.safety.domain.dto.questionscategory.HseQuestionsCategoryQueryReq;
import org.dromara.safety.domain.dto.questionscategory.HseQuestionsCategoryUpdateReq;
import org.dromara.safety.domain.vo.questionscategory.HseQuestionsCategoryVo;
import org.dromara.safety.mapper.HseQuestionsCategoryMapper;
import org.dromara.safety.service.IHseQuestionsCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 题库类别Service业务层处理
 *
 * @author lcj
 * @date 2025-04-15
 */
@Service
public class HseQuestionsCategoryServiceImpl extends ServiceImpl<HseQuestionsCategoryMapper, HseQuestionsCategory>
    implements IHseQuestionsCategoryService {

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询题库类别
     *
     * @param id 主键
     * @return 题库类别
     */
    @Override
    public HseQuestionsCategoryVo queryById(Long id) {
        HseQuestionsCategory questionsCategory = this.getById(id);
        if (questionsCategory == null) {
            throw new ServiceException("题库类别信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(questionsCategory);
    }

    /**
     * 分页查询题库类别列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 题库类别分页列表
     */
    @Override
    public TableDataInfo<HseQuestionsCategoryVo> queryPageList(HseQuestionsCategoryQueryReq req, PageQuery pageQuery) {
        Page<HseQuestionsCategory> result = this.page(pageQuery.build(), buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的题库类别列表
     *
     * @param req 查询条件
     * @return 题库类别列表
     */
    @Override
    public List<HseQuestionsCategoryVo> queryList(HseQuestionsCategoryQueryReq req) {
        LambdaQueryWrapper<HseQuestionsCategory> lqw = this.buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 新增题库类别
     *
     * @param req 题库类别
     * @return 新增题库类别主键
     */
    @Override
    public Long insertByBo(HseQuestionsCategoryCreateReq req) {
        // 将实体类和 DTO 进行转换
        HseQuestionsCategory questionsCategory = new HseQuestionsCategory();
        BeanUtils.copyProperties(req, questionsCategory);
        // 数据校验
        validEntityBeforeSave(questionsCategory, true);
        // 写入数据库
        boolean save = this.save(questionsCategory);
        if (!save) {
            throw new ServiceException("新增题库类别失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据
        return questionsCategory.getId();
    }

    /**
     * 修改题库类别
     *
     * @param req 题库类别
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HseQuestionsCategoryUpdateReq req) {
        // 将实体类和 DTO 进行转换
        HseQuestionsCategory questionsCategory = new HseQuestionsCategory();
        BeanUtils.copyProperties(req, questionsCategory);
        // 数据校验
        validEntityBeforeSave(questionsCategory, false);
        // 判断是否存在
        HseQuestionsCategory oldQuestionsCategory = this.getById(questionsCategory.getId());
        if (oldQuestionsCategory == null) {
            throw new ServiceException("修改题库类别失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(questionsCategory);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HseQuestionsCategory entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        if (create) {
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectId != null && projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 校验并批量删除题库类别信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<HseQuestionsCategory> questionsCategoryList = this.listByIds(ids);
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
            List<Long> projectId = questionsCategoryList.stream().map(HseQuestionsCategory::getProjectId).toList();
            projectService.validAuth(projectId, userId);
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取题库类别视图对象
     *
     * @param questionsCategory 题库类别对象
     * @return 题库类别视图对象
     */
    @Override
    public HseQuestionsCategoryVo getVo(HseQuestionsCategory questionsCategory) {
        // 对象转封装类
        HseQuestionsCategoryVo questionsCategoryVo = new HseQuestionsCategoryVo();
        if (questionsCategory == null) {
            return questionsCategoryVo;
        }
        BeanUtils.copyProperties(questionsCategory, questionsCategoryVo);
        return questionsCategoryVo;
    }

    /**
     * 获取题库类别查询条件封装
     *
     * @param req 题库类别查询条件
     * @return 题库类别查询条件封装
     */
    @Override
    public LambdaQueryWrapper<HseQuestionsCategory> buildQueryWrapper(HseQuestionsCategoryQueryReq req) {
        LambdaQueryWrapper<HseQuestionsCategory> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long projectId = req.getProjectId();
        String categoryName = req.getCategoryName();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(categoryName), HseQuestionsCategory::getCategoryName, categoryName);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(projectId), HseQuestionsCategory::getProjectId, projectId);
        return lqw;
    }

    /**
     * 获取题库类别分页对象视图
     *
     * @param questionsCategoryPage 题库类别分页对象
     * @return 题库类别分页对象视图
     */
    @Override
    public Page<HseQuestionsCategoryVo> getVoPage(Page<HseQuestionsCategory> questionsCategoryPage) {
        // 获取分页数据
        List<HseQuestionsCategory> questionsCategoryList = questionsCategoryPage.getRecords();
        // 添加分页信息
        Page<HseQuestionsCategoryVo> questionsCategoryVoPage = new Page<>(
            questionsCategoryPage.getCurrent(),
            questionsCategoryPage.getSize(),
            questionsCategoryPage.getTotal()
        );
        if (CollUtil.isEmpty(questionsCategoryList)) {
            return questionsCategoryVoPage;
        }
        // 对象列表 => 封装对象列表
        List<HseQuestionsCategoryVo> questionsCategoryVoList = questionsCategoryList.stream().map(this::getVo).toList();
        questionsCategoryVoPage.setRecords(questionsCategoryVoList);
        return questionsCategoryVoPage;
    }
}
