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.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.safety.domain.BusQuestionBank;
import org.dromara.safety.domain.req.questionbank.QuestionBankCreateReq;
import org.dromara.safety.domain.req.questionbank.QuestionBankQueryReq;
import org.dromara.safety.domain.req.questionbank.QuestionBankUpdateReq;
import org.dromara.safety.domain.vo.BusQuestionBankVo;
import org.dromara.safety.mapper.BusQuestionBankMapper;
import org.dromara.safety.service.IBusQuestionBankService;
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 BusQuestionBankServiceImpl extends ServiceImpl<BusQuestionBankMapper, BusQuestionBank>
    implements IBusQuestionBankService {

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

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

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

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

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

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

    /**
     * 校验并批量删除题库信息
     *
     * @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 questionBank 题库对象
     * @return 题库视图对象
     */
    @Override
    public BusQuestionBankVo getVo(BusQuestionBank questionBank) {
        // 对象转封装类
        BusQuestionBankVo questionBankVo = new BusQuestionBankVo();
        if (questionBank == null) {
            return questionBankVo;
        }
        BeanUtils.copyProperties(questionBank, questionBankVo);
        return questionBankVo;
    }

    /**
     * 获取题库查询条件封装
     *
     * @param req 题库查询条件
     * @return 题库查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusQuestionBank> buildQueryWrapper(QuestionBankQueryReq req) {
        LambdaQueryWrapper<BusQuestionBank> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        String categoryType = req.getCategoryType();
        String questionType = req.getQuestionType();
        String questionContent = req.getQuestionContent();
        List<String> optionList = req.getOptionList();
        String correctAnswer = req.getCorrectAnswer();
        // JSON 数组查询
        if (CollUtil.isNotEmpty(optionList)) {
            for (String option : optionList) {
                lqw.like(BusQuestionBank::getOptions, "\"" + option + "\"");
            }
        }
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(questionContent), BusQuestionBank::getQuestionContent, questionContent);
        lqw.like(StringUtils.isNotBlank(correctAnswer), BusQuestionBank::getCorrectAnswer, correctAnswer);
        // 精准查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusQuestionBank::getId, id);
        lqw.eq(StringUtils.isNotBlank(categoryType), BusQuestionBank::getCategoryType, categoryType);
        lqw.eq(StringUtils.isNotBlank(questionType), BusQuestionBank::getQuestionType, questionType);
        return lqw;
    }

    /**
     * 获取题库分页对象视图
     *
     * @param questionBankPage 题库分页对象
     * @return 题库分页对象视图
     */
    @Override
    public Page<BusQuestionBankVo> getVoPage(Page<BusQuestionBank> questionBankPage) {
        // 获取分页数据
        List<BusQuestionBank> questionBankList = questionBankPage.getRecords();
        // 添加分页信息
        Page<BusQuestionBankVo> questionBankVoPage = new Page<>(
            questionBankPage.getCurrent(),
            questionBankPage.getSize(),
            questionBankPage.getTotal()
        );
        if (CollUtil.isEmpty(questionBankList)) {
            return questionBankVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusQuestionBankVo> questionBankVoList = questionBankList.stream().map(this::getVo).toList();
        questionBankVoPage.setRecords(questionBankVoList);
        return questionBankVoPage;
    }
}
