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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.bank.bo.*;
import com.zhongzheng.modules.bank.domain.QuestionBusiness;
import com.zhongzheng.modules.bank.domain.QuestionModule;
import com.zhongzheng.modules.bank.domain.QuestionModuleChapter;
import com.zhongzheng.modules.bank.mapper.QuestionModuleMapper;
import com.zhongzheng.modules.bank.service.IQuestionBusinessService;
import com.zhongzheng.modules.bank.service.IQuestionModuleChapterService;
import com.zhongzheng.modules.bank.service.IQuestionModuleService;
import com.zhongzheng.modules.bank.vo.QuestionModuleVo;
import com.zhongzheng.modules.goods.domain.GoodsAttached;
import com.zhongzheng.modules.goods.service.IGoodsAttachedService;
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-25
 */
@Service
public class QuestionModuleServiceImpl extends ServiceImpl<QuestionModuleMapper, QuestionModule> implements IQuestionModuleService {

    @Autowired
    private IQuestionBusinessService iQuestionBusinessService;

    @Autowired
    private IQuestionModuleChapterService iQuestionModuleChapterService;

    @Autowired
    private QuestionModuleMapper questionModuleMapper;

    @Autowired
    private IGoodsAttachedService iGoodsAttachedService;

    @Override
    public QuestionModuleVo queryById(Long questionModuleId){
        QuestionModule db = this.baseMapper.selectById(questionModuleId);
        return BeanUtil.toBean(db, QuestionModuleVo.class);
    }

    @Override
    public List<QuestionModuleVo> getList(QuestionModuleQueryBo bo) {
        return questionModuleMapper.getList(bo);
    }

    @Override
    public List<QuestionModuleVo> queryList(QuestionModuleQueryBo bo) {
        LambdaQueryWrapper<QuestionModule> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getPrefixName()), QuestionModule::getPrefixName, bo.getPrefixName());
        lqw.like(StrUtil.isNotBlank(bo.getModuleName()), QuestionModule::getModuleName, bo.getModuleName());
        lqw.eq(bo.getPublishStatus() != null, QuestionModule::getPublishStatus, bo.getPublishStatus());
        lqw.in(bo.getStatus() != null, QuestionModule::getStatus, bo.getStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getCode()), QuestionModule::getCode, bo.getCode());
        return entity2Vo(this.list(lqw));
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(QuestionModuleAddBo bo) {
        QuestionModule add = BeanUtil.toBean(bo, QuestionModule.class);
        add.setCode(ServletUtils.getEncoded("MJ"));
        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.getModuleExamId());
                addItem.setType(QuestionBusiness.TYPE_QUESTION_MODULE);
                coll.add(addItem);
            }
            iQuestionBusinessService.saveBatch(coll);
        }
        if(bo.getChapterList()!=null){
            Collection<QuestionModuleChapter> coll = new HashSet<>();
            for(int i=0;i<bo.getChapterList().size();i++){
                QuestionModuleChapterAddBo item = bo.getChapterList().get(i);
                QuestionModuleChapter addItem = BeanUtil.toBean(item,  QuestionModuleChapter.class);
                addItem.setModuleExamId(add.getModuleExamId());
                coll.add(addItem);
            }
            iQuestionModuleChapterService.saveBatch(coll);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(QuestionModuleEditBo bo) {
        QuestionModule update = BeanUtil.toBean(bo, QuestionModule.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if(bo.getBusinessList()!=null){
            iQuestionBusinessService.remove(new LambdaQueryWrapper<QuestionBusiness>().eq(QuestionBusiness::getMajorId, bo.getModuleExamId())
                    .eq(QuestionBusiness::getType,QuestionBusiness.TYPE_QUESTION_MODULE));
            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(update.getModuleExamId());
                addItem.setType(QuestionBusiness.TYPE_QUESTION_MODULE);
                coll.add(addItem);
            }
            iQuestionBusinessService.saveBatch(coll);
        }
        if(bo.getChapterList()!=null){
            iQuestionModuleChapterService.remove(new LambdaQueryWrapper<QuestionModuleChapter>().eq(QuestionModuleChapter::getModuleExamId, bo.getModuleExamId()));
            Collection<QuestionModuleChapter> coll = new HashSet<>();
            for(int i=0;i<bo.getChapterList().size();i++){
                QuestionModuleChapterEditBo item = bo.getChapterList().get(i);
                QuestionModuleChapter addItem = BeanUtil.toBean(item,  QuestionModuleChapter.class);
                addItem.setModuleExamId(bo.getModuleExamId());
                coll.add(addItem);
            }
            iQuestionModuleChapterService.saveBatch(coll);
        }
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(QuestionModule entity){
        //TODO 做一些数据校验,如唯一约束
        if(entity.getModuleExamId()!=null&&entity.getPublishStatus()!=null&&entity.getPublishStatus()==0){
            GoodsAttached one = iGoodsAttachedService.getOne(new LambdaQueryWrapper<GoodsAttached>().eq(GoodsAttached::getMajorId, entity.getModuleExamId()).eq(GoodsAttached::getType,1).last("limit 1"));
            if(one!=null){
                throw new CustomException("该模块卷已被绑定，不允许修改发布状态为未发布");
            }
        }
    }

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