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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.microsoft.schemas.office.visio.x2012.main.SectionType;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.modules.user.bo.*;
import com.zhongzheng.modules.user.domain.UserStudyRecord;
import com.zhongzheng.modules.user.mapper.UserStudyRecordMapper;
import com.zhongzheng.modules.user.service.IUserStudyRecordService;
import com.zhongzheng.modules.user.vo.*;
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.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户学习记录Service业务层处理
 *
 * @author ruoyi
 * @date 2021-06-25
 */
@Service
public class UserStudyRecordServiceImpl extends ServiceImpl<UserStudyRecordMapper, UserStudyRecord> implements IUserStudyRecordService {

    @Autowired
    private UserStudyRecordMapper userStudyRecordMapper;


    @Autowired
    private IUserStudyRecordService iUserStudyRecordService;



    @Override
    public UserStudyRecordVo queryById(Long recordId){
        UserStudyRecord db = this.baseMapper.selectById(recordId);
        return BeanUtil.toBean(db, UserStudyRecordVo.class);
    }

    @Override
    public List<UserStudyRecordVo> queryList(UserStudyRecordQueryBo bo) {
        LambdaQueryWrapper<UserStudyRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, UserStudyRecord::getUserId, bo.getUserId());
        lqw.eq(bo.getCourseId() != null, UserStudyRecord::getCourseId, bo.getCourseId());
        lqw.eq(bo.getSectionId() != null, UserStudyRecord::getSectionId, bo.getSectionId());
        lqw.eq(bo.getStudyDuration() != null, UserStudyRecord::getStudyDuration, bo.getStudyDuration());
        lqw.eq(bo.getStartTime() != null, UserStudyRecord::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, UserStudyRecord::getEndTime, bo.getEndTime());
        return entity2Vo(this.list(lqw));
    }

    @Override
    public List<UserStudyRecordVo> selectList(UserStudyRecordQueryBo bo) {
        return userStudyRecordMapper.selectList(bo);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertByAddBo(UserStudyRecordAddBo bo) {
        UserStudyRecord add = BeanUtil.toBean(bo, UserStudyRecord.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        add.setStartTime(DateUtils.getNowTime()-add.getStudyDuration());
        add.setEndTime(DateUtils.getNowTime());



        this.save(add);
        return 0;
    }

    @Override
    public Boolean updateByEditBo(UserStudyRecordEditBo bo) {
        UserStudyRecord update = BeanUtil.toBean(bo, UserStudyRecord.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        return this.updateById(update);
    }

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

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

    @Override
    public List<UserStudyRecord> selectUserStudy(Long userId, Integer courseId) {
        return baseMapper.selectUserStudy(userId,courseId);
    }

    @Override
    public List<GoodsStudyRecordVo> queryGoods(UserQueryBo bo) {
        List<GoodsStudyRecordVo> list = baseMapper.queryGoods(bo);

        for (GoodsStudyRecordVo goodsStudyRecordVo : list) {
            Long secLong = 0L;
            Long studyLong = 0L;

            SubjectStudyRecordQueryBo subjectStudyRecordQueryBo = new SubjectStudyRecordQueryBo();
            subjectStudyRecordQueryBo.setGoodsId(goodsStudyRecordVo.getGoodsId());
            subjectStudyRecordQueryBo.setUserId(goodsStudyRecordVo.getUserId());
            List<SubjectStudyRecordVo> subjectStudyRecordVos = iUserStudyRecordService.listSubject(subjectStudyRecordQueryBo);
            for (SubjectStudyRecordVo subjectStudyRecordVo : subjectStudyRecordVos) {
                String sectionType = "";
                secLong = new BigDecimal(secLong.toString()).add(new BigDecimal(subjectStudyRecordVo.getSectionNum().toString())).longValue();
                studyLong = new BigDecimal(studyLong.toString()).add(new BigDecimal(subjectStudyRecordVo.getRecordNum().toString())).longValue();

                if (CollectionUtils.isNotEmpty(baseMapper.sectionType(subjectStudyRecordVo.getCourseId(),1L))){
                    sectionType = sectionType.concat("1,");
                }
                if (CollectionUtils.isNotEmpty(baseMapper.sectionType(subjectStudyRecordVo.getCourseId(),2L))){
                    sectionType = sectionType.concat("2,");
                }
                if (CollectionUtils.isNotEmpty(baseMapper.sectionType(subjectStudyRecordVo.getCourseId(),3L))){
                    sectionType = sectionType.concat("3,");
                }
                if (StringUtils.isNotBlank(sectionType)) {
                    subjectStudyRecordVo.setSectionType(sectionType.substring(0, sectionType.length() - 1));
                }
            }
            BigDecimal divide =new BigDecimal("0");
            if (secLong != 0) {
                divide = new BigDecimal(studyLong.toString()).divide(new BigDecimal(secLong.toString()), 2, BigDecimal.ROUND_HALF_UP);
            }
            goodsStudyRecordVo.setStudyNum(divide.multiply(new BigDecimal("100")).longValue());
            goodsStudyRecordVo.setSubjectStudyRecordVos(subjectStudyRecordVos);
            goodsStudyRecordVo.setSecAllNum(secLong);
            goodsStudyRecordVo.setStuAllNum(studyLong);
        }

        return list;
    }

    @Override
    public List<SubjectStudyRecordVo> listSubject(SubjectStudyRecordQueryBo bo) {
        List<SubjectStudyRecordVo> subjectStudyRecordVos = baseMapper.listSubject(bo);
        return subjectStudyRecordVos;
    }

    @Override
    public List<SectionStudyRecordVo> listSection(SubjectStudyRecordQueryBo bo) {
        List<SectionStudyRecordVo> sectionStudyRecordVos = baseMapper.listSection(bo);
        for (SectionStudyRecordVo sectionStudyRecordVo : sectionStudyRecordVos) {
            if (sectionStudyRecordVo.getStartTime() == null){
                sectionStudyRecordVo.setStatus(2L);
            }
        }
        return sectionStudyRecordVos;
    }

    @Override
    public List<ExamStudyRecordVo> querExamStudy(UserQueryBo bo) {
        List<ExamStudyRecordVo> examStudyRecordVos = baseMapper.querExamStudy(bo);
        for (ExamStudyRecordVo examStudyRecordVo : examStudyRecordVos) {
            SubjectStudyRecordQueryBo subjectStudyRecordQueryBo = new SubjectStudyRecordQueryBo();
            subjectStudyRecordQueryBo.setUserId(examStudyRecordVo.getUserId());
            subjectStudyRecordQueryBo.setGoodsId(examStudyRecordVo.getGoodsId());
            List<ExamSonStudyRecordVo> examSonStudyRecordVos = baseMapper.listExamSon(subjectStudyRecordQueryBo);
            for (ExamSonStudyRecordVo examSonStudyRecordVo : examSonStudyRecordVos) {
                List<String> examTypes = baseMapper.examTypes(examSonStudyRecordVo.getQuestionId());
                String s = "";
                for (String examType : examTypes) {
                    if (StringUtils.isNotBlank(examType)) {
                        s= s.concat(examType + ",");
                    }
                }
                if (StringUtils.isNotBlank(s)) {
                    examSonStudyRecordVo.setExamType(s.substring(0, s.length() - 1));
                }
            }
            examStudyRecordVo.setExamSonStudyRecordVos(examSonStudyRecordVos);
        }
        return examStudyRecordVos;
    }

    @Override
    public List<ExamSonStudyRecordVo> listExamSon(SubjectStudyRecordQueryBo bo) {
        List<ExamSonStudyRecordVo> examSonStudyRecordVos = baseMapper.listExamSon(bo);

        return examSonStudyRecordVos;
    }
}
