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 jakarta.servlet.http.HttpServletRequest;
import org.dromara.common.core.constant.CacheConstants;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.domain.dto.UserOnlineDTO;
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.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.project.service.IBusProjectService;
import org.dromara.safety.domain.HseQuestionBank;
import org.dromara.safety.domain.HseQuestionsCategory;
import org.dromara.safety.domain.dto.questionbank.HseQuestionBankCreateReq;
import org.dromara.safety.domain.dto.questionbank.HseQuestionBankQueryReq;
import org.dromara.safety.domain.dto.questionbank.HseQuestionBankUpdateReq;
import org.dromara.safety.domain.vo.questionbank.HseQuestionBankVo;
import org.dromara.safety.mapper.HseQuestionBankMapper;
import org.dromara.safety.service.IHseQuestionBankService;
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;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 题库Service业务层处理
 *
 * @author lcj
 * @date 2025-03-24
 */
@Service
public class HseQuestionBankServiceImpl extends ServiceImpl<HseQuestionBankMapper, HseQuestionBank>
    implements IHseQuestionBankService {

    @Resource
    private IBusProjectService projectService;

    @Resource
    private IHseQuestionsCategoryService questionsCategoryService;

    /**
     * 查询题库
     *
     * @param id 主键
     * @return 题库
     */
    @Override
    public HseQuestionBankVo queryById(Long id) {
        HseQuestionBank 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<HseQuestionBankVo> queryPageList(HseQuestionBankQueryReq req, PageQuery pageQuery) {
        Page<HseQuestionBank> result = this.page(pageQuery.build(), buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

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

    /**
     * 新增题库
     *
     * @param req 题库
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(HseQuestionBankCreateReq req, HttpServletRequest request) {
        // 将实体类和 DTO 进行转换
        HseQuestionBank questionBank = new HseQuestionBank();
        BeanUtils.copyProperties(req, questionBank);
        // 获取当前登录设备
        String token = request.getHeader("authorization");
        UserOnlineDTO userOnlineDTO = RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token);
        questionBank.setWxOrPc(userOnlineDTO.getDeviceType());
        // 数据校验
        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(HseQuestionBankUpdateReq req) {
        // 将实体类和 DTO 进行转换
        HseQuestionBank questionBank = new HseQuestionBank();
        BeanUtils.copyProperties(req, questionBank);
        // 数据校验
        validEntityBeforeSave(questionBank, false);
        // 判断是否存在
        HseQuestionBank oldQuestionBank = this.getById(questionBank.getId());
        if (oldQuestionBank == null) {
            throw new ServiceException("修改题库失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(questionBank);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HseQuestionBank entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        Long categoryId = entity.getCategoryId();
        String questionType = entity.getQuestionType();
        String questionContent = entity.getQuestionContent();
        Long projectId = entity.getProjectId();
        if (create) {
            if (categoryId == null) {
                throw new ServiceException("分类类型不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isEmpty(questionType)) {
                throw new ServiceException("题目类型不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isEmpty(questionContent)) {
                throw new ServiceException("题目内容不能为空", HttpStatus.BAD_REQUEST);
            }
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.NOT_FOUND);
            }
        }
        if (projectId != null && projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        if (categoryId != null && questionsCategoryService.getById(categoryId) == 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<HseQuestionBank> questionBankList = this.listByIds(ids);
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
            List<Long> projectId = questionBankList.stream().map(HseQuestionBank::getProjectId).toList();
            projectService.validAuth(projectId, userId);
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取题库视图对象
     *
     * @param questionBank 题库对象
     * @return 题库视图对象
     */
    @Override
    public HseQuestionBankVo getVo(HseQuestionBank questionBank) {
        // 对象转封装类
        HseQuestionBankVo questionBankVo = new HseQuestionBankVo();
        if (questionBank == null) {
            return questionBankVo;
        }
        BeanUtils.copyProperties(questionBank, questionBankVo);
        // 获取题目分类名称
        Long categoryId = questionBank.getCategoryId();
        HseQuestionsCategory category = questionsCategoryService.getById(categoryId);
        if (category != null) {
            questionBankVo.setCategoryName(category.getCategoryName());
        }
        return questionBankVo;
    }

    /**
     * 获取题库查询条件封装
     *
     * @param req 题库查询条件
     * @return 题库查询条件封装
     */
    @Override
    public LambdaQueryWrapper<HseQuestionBank> buildQueryWrapper(HseQuestionBankQueryReq req) {
        LambdaQueryWrapper<HseQuestionBank> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long projectId = req.getProjectId();
        Long categoryId = req.getCategoryId();
        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(HseQuestionBank::getOptions, "\"" + option + "\"");
            }
        }
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(questionContent), HseQuestionBank::getQuestionContent, questionContent);
        lqw.like(StringUtils.isNotBlank(correctAnswer), HseQuestionBank::getCorrectAnswer, correctAnswer);
        // 精准查询
        lqw.eq(ObjectUtils.isNotEmpty(id), HseQuestionBank::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), HseQuestionBank::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(categoryId), HseQuestionBank::getCategoryId, categoryId);
        lqw.eq(StringUtils.isNotBlank(questionType), HseQuestionBank::getQuestionType, questionType);
        return lqw;
    }

    /**
     * 获取题库分页对象视图
     *
     * @param questionBankPage 题库分页对象
     * @return 题库分页对象视图
     */
    @Override
    public Page<HseQuestionBankVo> getVoPage(Page<HseQuestionBank> questionBankPage) {
        // 获取分页数据
        List<HseQuestionBank> questionBankList = questionBankPage.getRecords();
        // 添加分页信息
        Page<HseQuestionBankVo> questionBankVoPage = new Page<>(
            questionBankPage.getCurrent(),
            questionBankPage.getSize(),
            questionBankPage.getTotal()
        );
        if (CollUtil.isEmpty(questionBankList)) {
            return questionBankVoPage;
        }
        // 关联查询题目分类信息
        Set<Long> categoryIdList = questionBankList.stream().map(HseQuestionBank::getCategoryId)
            .collect(Collectors.toSet());
        Map<Long, List<HseQuestionsCategory>> questionCategoryMap = questionsCategoryService.listByIds(categoryIdList)
            .stream().collect(Collectors.groupingBy(HseQuestionsCategory::getId));
        // 对象列表 => 封装对象列表
        List<HseQuestionBankVo> questionBankVoList = questionBankList.stream().map(questionBank -> {
            HseQuestionBankVo questionBankVo = new HseQuestionBankVo();
            BeanUtils.copyProperties(questionBank, questionBankVo);
            // 获取题目分类名称
            Long categoryId = questionBank.getCategoryId();
            String categoryName = null;
            if (questionCategoryMap.containsKey(categoryId)) {
                HseQuestionsCategory category = questionCategoryMap.get(categoryId).get(0);
                categoryName = category.getCategoryName();
            }
            questionBankVo.setCategoryName(categoryName);
            // 返回封装对象
            return questionBankVo;
        }).toList();
        questionBankVoPage.setRecords(questionBankVoList);
        return questionBankVoPage;
    }
}
