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 org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.safety.domain.BusQuestionsConfig;
import org.dromara.safety.domain.req.questionsconfig.QuestionsConfigCreateReq;
import org.dromara.safety.domain.req.questionsconfig.QuestionsConfigQueryReq;
import org.dromara.safety.domain.req.questionsconfig.QuestionsConfigUpdateReq;
import org.dromara.safety.domain.vo.BusQuestionsConfigVo;
import org.dromara.safety.mapper.BusQuestionsConfigMapper;
import org.dromara.safety.service.IBusQuestionsConfigService;
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-03-24
 */
@Service
public class BusQuestionsConfigServiceImpl extends ServiceImpl<BusQuestionsConfigMapper, BusQuestionsConfig>
    implements IBusQuestionsConfigService {

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

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

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

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

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusQuestionsConfig entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        if (create) {

        }
    }

    /**
     * 校验并批量删除题库配置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取题库配置视图对象
     *
     * @param questionsConfig 题库配置对象
     * @return 题库配置视图对象
     */
    @Override
    public BusQuestionsConfigVo getVo(BusQuestionsConfig questionsConfig) {
        // 对象转封装类
        BusQuestionsConfigVo questionsConfigVo = new BusQuestionsConfigVo();
        if (questionsConfig == null) {
            return questionsConfigVo;
        }
        BeanUtils.copyProperties(questionsConfig, questionsConfigVo);
        return questionsConfigVo;
    }

    /**
     * 获取题库配置查询条件封装
     *
     * @param req 题库配置查询条件
     * @return 题库配置查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusQuestionsConfig> buildQueryWrapper(QuestionsConfigQueryReq req) {
        LambdaQueryWrapper<BusQuestionsConfig> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long singleChoice = req.getSingleChoice();
        Long singleScore = req.getSingleScore();
        Long multipleChoice = req.getMultipleChoice();
        Long multipleScore = req.getMultipleScore();
        Long estimate = req.getEstimate();
        Long estimateScore = req.getEstimateScore();
        Long fullMark = req.getFullMark();
        Long passScore = req.getPassScore();
        Long answerTime = req.getAnswerTime();
        // 精准查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusQuestionsConfig::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(singleChoice), BusQuestionsConfig::getSingleChoice, singleChoice);
        lqw.eq(ObjectUtils.isNotEmpty(singleScore), BusQuestionsConfig::getSingleScore, singleScore);
        lqw.eq(ObjectUtils.isNotEmpty(multipleChoice), BusQuestionsConfig::getMultipleChoice, multipleChoice);
        lqw.eq(ObjectUtils.isNotEmpty(multipleScore), BusQuestionsConfig::getMultipleScore, multipleScore);
        lqw.eq(ObjectUtils.isNotEmpty(estimate), BusQuestionsConfig::getEstimate, estimate);
        lqw.eq(ObjectUtils.isNotEmpty(estimateScore), BusQuestionsConfig::getEstimateScore, estimateScore);
        lqw.eq(ObjectUtils.isNotEmpty(fullMark), BusQuestionsConfig::getFullMark, fullMark);
        lqw.eq(ObjectUtils.isNotEmpty(passScore), BusQuestionsConfig::getPassScore, passScore);
        lqw.eq(ObjectUtils.isNotEmpty(answerTime), BusQuestionsConfig::getAnswerTime, answerTime);
        return lqw;
    }

    /**
     * 获取题库配置分页对象视图
     *
     * @param questionsConfigPage 题库配置分页对象
     * @return 题库配置分页对象视图
     */
    @Override
    public Page<BusQuestionsConfigVo> getVoPage(Page<BusQuestionsConfig> questionsConfigPage) {
        // 获取分页数据
        List<BusQuestionsConfig> questionsConfigList = questionsConfigPage.getRecords();
        // 添加分页信息
        Page<BusQuestionsConfigVo> questionsConfigVoPage = new Page<>(
            questionsConfigPage.getCurrent(),
            questionsConfigPage.getSize(),
            questionsConfigPage.getTotal()
        );
        if (CollUtil.isEmpty(questionsConfigList)) {
            return questionsConfigVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusQuestionsConfigVo> questionsConfigVoList = questionsConfigList.stream().map(this::getVo).toList();
        questionsConfigVoPage.setRecords(questionsConfigVoList);
        return questionsConfigVoPage;
    }
}
