package com.zhongzheng.modules.bank.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.bank.bo.*;
import com.zhongzheng.modules.bank.domain.Question;
import com.zhongzheng.modules.bank.domain.QuestionBusiness;
import com.zhongzheng.modules.bank.mapper.QuestionMapper;
import com.zhongzheng.modules.bank.service.IExamQuestionService;
import com.zhongzheng.modules.bank.service.IQuestionBusinessService;
import com.zhongzheng.modules.bank.service.IQuestionService;
import com.zhongzheng.modules.bank.vo.QuestionVo;
import com.zhongzheng.modules.course.bo.CourseChapterSectionListAddBo;
import com.zhongzheng.modules.course.domain.CourseChapterSection;
import com.zhongzheng.modules.course.service.ICourseChapterSectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 题库题目Service业务层处理
 *
 * @author hjl
 * @date 2021-10-21
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    private IQuestionBusinessService iQuestionBusinessService;

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public QuestionVo queryById(Long questionId){
        Question db = this.baseMapper.selectById(questionId);
        return BeanUtil.toBean(db, QuestionVo.class);
    }

    @Override
    public List<QuestionVo> selectList(QuestionQueryBo bo) {
        return questionMapper.selectList(bo);
    }



    @Override
    public List<QuestionVo> queryList(QuestionQueryBo bo) {
        LambdaQueryWrapper<Question> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getContent()), Question::getContent, bo.getContent());
        lqw.eq(bo.getAnswerQuestion() != null, Question::getAnswerQuestion, bo.getAnswerQuestion());
        lqw.in(bo.getStatus() != null, Question::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getImgUrl()), Question::getImgUrl, bo.getImgUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getAnalysisContent()), Question::getAnalysisContent, bo.getAnalysisContent());
        lqw.eq(StrUtil.isNotBlank(bo.getJsonStr()), Question::getJsonStr, bo.getJsonStr());
        lqw.like(StrUtil.isNotBlank(bo.getPrefixName()), Question::getPrefixName, bo.getPrefixName());
        lqw.eq(StrUtil.isNotBlank(bo.getKnowledgeIds()), Question::getKnowledgeIds, bo.getKnowledgeIds());
        lqw.eq(bo.getPublishStatus() != null, Question::getPublishStatus, bo.getPublishStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getCode()), Question::getCode, bo.getCode());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<QuestionVo> entity2Vo(Collection<Question> collection) {
        List<QuestionVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, QuestionVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Question> page = (Page<Question>)collection;
            Page<QuestionVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByAddBo(QuestionAddBo bo) {
        Question add = BeanUtil.toBean(bo, Question.class);
        add.setCode(ServletUtils.getEncoded("TM"));
        if(bo.getOptionsList()!=null){
            add.setJsonStr(JSON.toJSONString(bo.getOptionsList()));
        }
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        boolean result = this.save(add);
        if(bo.getBusinessList()!=null){
            Collection<QuestionBusiness> coll = new HashSet<>();
            for(int i=0;i<bo.getBusinessList().size();i++){
                QuestionBusinessAddBo item = bo.getBusinessList().get(i);
                QuestionBusiness addItem = BeanUtil.toBean(item, QuestionBusiness.class);
                addItem.setMajorId(add.getQuestionId());
                addItem.setType(QuestionBusiness.TYPE_QUESTION);
                coll.add(addItem);
            }
            iQuestionBusinessService.saveBatch(coll);
        }
        return add.getQuestionId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(QuestionEditBo bo) {
        Question update = BeanUtil.toBean(bo, Question.class);
        if(bo.getOptionsList()!=null){
            update.setJsonStr(JSON.toJSONString(bo.getOptionsList()));
        }
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if(bo.getBusinessList()!=null){
            iQuestionBusinessService.remove(new LambdaQueryWrapper<QuestionBusiness>()
                    .eq(QuestionBusiness::getMajorId, bo.getQuestionId())
            .eq(QuestionBusiness::getType,QuestionBusiness.TYPE_QUESTION));
            Collection<QuestionBusiness> coll = new HashSet<>();
            for(int i=0;i<bo.getBusinessList().size();i++){
                QuestionBusinessEditBo item = bo.getBusinessList().get(i);
                QuestionBusiness addItem = BeanUtil.toBean(item, QuestionBusiness.class);
                addItem.setMajorId(bo.getQuestionId());
                addItem.setType(QuestionBusiness.TYPE_QUESTION);
                coll.add(addItem);
            }
            iQuestionBusinessService.saveBatch(coll);
        }
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Question entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }
}
