package org.dromara.safety.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
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.BusQuestionUserAnswer;
import org.dromara.safety.domain.req.questionuseranswer.QuestionUserAnswerCreateReq;
import org.dromara.safety.domain.req.questionuseranswer.QuestionUserAnswerQueryReq;
import org.dromara.safety.domain.req.questionuseranswer.QuestionUserAnswerUpdateReq;
import org.dromara.safety.domain.vo.BusQuestionUserAnswerVo;
import org.dromara.safety.mapper.BusQuestionUserAnswerMapper;
import org.dromara.safety.service.IBusQuestionUserAnswerService;
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 BusQuestionUserAnswerServiceImpl extends ServiceImpl<BusQuestionUserAnswerMapper, BusQuestionUserAnswer>
    implements IBusQuestionUserAnswerService {

    /**
     * 查询用户试卷存储
     *
     * @param id 主键
     * @return 用户试卷存储
     */
    @Override
    public BusQuestionUserAnswerVo queryById(Long id) {
        BusQuestionUserAnswer questionUserAnswer = this.getById(id);
        if (questionUserAnswer == null) {
            throw new ServiceException("用户试卷存储信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(questionUserAnswer);
    }

    /**
     * 分页查询用户试卷存储列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 用户试卷存储分页列表
     */
    @Override
    public TableDataInfo<BusQuestionUserAnswerVo> queryPageList(QuestionUserAnswerQueryReq req, PageQuery pageQuery) {
        Page<BusQuestionUserAnswer> result = this.page(pageQuery.build(), buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的用户试卷存储列表
     *
     * @param req 查询条件
     * @return 用户试卷存储列表
     */
    @Override
    public List<BusQuestionUserAnswerVo> queryList(QuestionUserAnswerQueryReq req) {
        LambdaQueryWrapper<BusQuestionUserAnswer> lqw = buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 新增用户试卷存储
     *
     * @param req 用户试卷存储
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(QuestionUserAnswerCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusQuestionUserAnswer questionUserAnswer = new BusQuestionUserAnswer();
        BeanUtils.copyProperties(req, questionUserAnswer);
        List<Long> bankIdList = req.getBankIdList();
        if (CollUtil.isNotEmpty(bankIdList)) {
            String bankIdStr = JSONUtil.toJsonStr(bankIdList);
            questionUserAnswer.setBankId(bankIdStr);
        }
        List<String> answerList = req.getAnswerList();
        if (CollUtil.isNotEmpty(answerList)) {
            String answerStr = JSONUtil.toJsonStr(answerList);
            questionUserAnswer.setAnswer(answerStr);
        }
        // 数据校验
        validEntityBeforeSave(questionUserAnswer, true);
        // 写入数据库
        boolean save = this.save(questionUserAnswer);
        if (!save) {
            throw new ServiceException("新增用户试卷存储失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据
        return questionUserAnswer.getId();
    }

    /**
     * 修改用户试卷存储
     *
     * @param req 用户试卷存储
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(QuestionUserAnswerUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusQuestionUserAnswer questionUserAnswer = new BusQuestionUserAnswer();
        BeanUtils.copyProperties(req, questionUserAnswer);
        List<Long> bankIdList = req.getBankIdList();
        if (CollUtil.isNotEmpty(bankIdList)) {
            String bankIdStr = JSONUtil.toJsonStr(bankIdList);
            questionUserAnswer.setBankId(bankIdStr);
        }
        List<String> answerList = req.getAnswerList();
        if (CollUtil.isNotEmpty(answerList)) {
            String answerStr = JSONUtil.toJsonStr(answerList);
            questionUserAnswer.setAnswer(answerStr);
        }
        // 数据校验
        validEntityBeforeSave(questionUserAnswer, false);
        // 判断是否存在
        BusQuestionUserAnswer oldQuestionUserAnswer = this.getById(questionUserAnswer.getId());
        if (oldQuestionUserAnswer == null) {
            throw new ServiceException("修改用户试卷存储失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(questionUserAnswer);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusQuestionUserAnswer 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 questionUserAnswer 用户试卷存储对象
     * @return 用户试卷存储视图对象
     */
    @Override
    public BusQuestionUserAnswerVo getVo(BusQuestionUserAnswer questionUserAnswer) {
        // 对象转封装类
        BusQuestionUserAnswerVo questionUserAnswerVo = new BusQuestionUserAnswerVo();
        if (questionUserAnswer == null) {
            return questionUserAnswerVo;
        }
        BeanUtils.copyProperties(questionUserAnswer, questionUserAnswerVo);
        String bankId = questionUserAnswer.getBankId();
        if (StringUtils.isNotBlank(bankId)) {
            questionUserAnswerVo.setBankIdList(JSONUtil.toList(bankId, Long.class));
        }
        String answer = questionUserAnswer.getAnswer();
        if (StringUtils.isNotBlank(answer)) {
            questionUserAnswerVo.setAnswerList(JSONUtil.toList(answer, String.class));
        }
        return questionUserAnswerVo;
    }

    /**
     * 获取用户试卷存储查询条件封装
     *
     * @param req 用户试卷存储查询条件
     * @return 用户试卷存储查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusQuestionUserAnswer> buildQueryWrapper(QuestionUserAnswerQueryReq req) {
        LambdaQueryWrapper<BusQuestionUserAnswer> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long projectId = req.getProjectId();
        Long userId = req.getUserId();
        List<Long> bankIdList = req.getBankIdList();
        List<String> answerList = req.getAnswerList();
        Long score = req.getScore();
        Long takeTime = req.getTakeTime();
        String pass = req.getPass();
        // JSON 数组查询
        if (CollUtil.isNotEmpty(bankIdList)) {
            for (Long bankId : bankIdList) {
                lqw.like(BusQuestionUserAnswer::getBankId, "\"" + bankId + "\"");
            }
        }
        if (CollUtil.isNotEmpty(answerList)) {
            for (String answer : answerList) {
                lqw.like(BusQuestionUserAnswer::getAnswer, "\"" + answer + "\"");
            }
        }
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(pass), BusQuestionUserAnswer::getPass, pass);
        // 精准查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusQuestionUserAnswer::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusQuestionUserAnswer::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(userId), BusQuestionUserAnswer::getUserId, userId);
        lqw.eq(ObjectUtils.isNotEmpty(score), BusQuestionUserAnswer::getScore, score);
        lqw.eq(ObjectUtils.isNotEmpty(takeTime), BusQuestionUserAnswer::getTakeTime, takeTime);
        return lqw;
    }

    /**
     * 获取用户试卷存储分页对象视图
     *
     * @param questionUserAnswerPage 用户试卷存储分页对象
     * @return 用户试卷存储分页对象视图
     */
    @Override
    public Page<BusQuestionUserAnswerVo> getVoPage(Page<BusQuestionUserAnswer> questionUserAnswerPage) {
        // 获取分页数据
        List<BusQuestionUserAnswer> questionUserAnswerList = questionUserAnswerPage.getRecords();
        // 添加分页信息
        Page<BusQuestionUserAnswerVo> questionUserAnswerVoPage = new Page<>(
            questionUserAnswerPage.getCurrent(),
            questionUserAnswerPage.getSize(),
            questionUserAnswerPage.getTotal()
        );
        if (CollUtil.isEmpty(questionUserAnswerList)) {
            return questionUserAnswerVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusQuestionUserAnswerVo> questionUserAnswerVoList = questionUserAnswerList.stream().map(this::getVo).toList();
        questionUserAnswerVoPage.setRecords(questionUserAnswerVoList);
        return questionUserAnswerVoPage;
    }

}
