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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.modules.grade.domain.UserPeriod;
import com.zhongzheng.modules.grade.domain.UserPeriodStatus;
import com.zhongzheng.modules.grade.service.IUserPeriodService;
import com.zhongzheng.modules.grade.service.IUserPeriodStatusService;
import com.zhongzheng.modules.user.bo.*;
import com.zhongzheng.modules.user.domain.User;
import com.zhongzheng.modules.user.domain.UserBankRecord;
import com.zhongzheng.modules.user.domain.UserStudyRecord;
import com.zhongzheng.modules.user.domain.UserStudyRecordPhoto;
import com.zhongzheng.modules.user.mapper.UserBankRecordMapper;
import com.zhongzheng.modules.user.mapper.UserStudyRecordMapper;
import com.zhongzheng.modules.user.service.*;
import com.zhongzheng.modules.user.vo.UserBankRecordVo;
import com.zhongzheng.modules.user.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.util.CollectionUtils;

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

/**
 * 用户的做题历史Service业务层处理
 *
 * @author ruoyi
 * @date 2021-06-24
 */
@Service
public class UserBankRecordServiceImpl extends ServiceImpl<UserBankRecordMapper, UserBankRecord> implements IUserBankRecordService {

    @Autowired
    private IUserBankQuestionRecordService iUserBankQuestionRecordService;


    @Autowired
    private IUserService userService;

    @Autowired
    private UserStudyRecordMapper userStudyRecordMapper;

    @Autowired
    private IUserPeriodService iUserPeriodService;

    @Autowired
    private IUserPeriodStatusService iUserPeriodStatusService;

    @Autowired
    private IUserStudyRecordPhotoService userStudyRecordPhotoService;

    @Autowired
    private IUserStudyRecordService iUserStudyRecordService;



    private static Logger log = LoggerFactory.getLogger(UserBankRecordServiceImpl.class);


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

    @Override
    public Long getUserExamDoNum(UserBankRecordQueryBo bo) {
        return this.baseMapper.getUserExamDoNum(bo);
    }

    @Override
    public List<UserBankRecordVo> queryList(UserBankRecordQueryBo bo) {
        LambdaQueryWrapper<UserBankRecord> lqw = Wrappers.lambdaQuery();

        lqw.eq(bo.getExamId() != null, UserBankRecord::getExamId, bo.getExamId());
        lqw.eq(bo.getBankId() != null, UserBankRecord::getBankId, bo.getBankId());
        lqw.eq(bo.getUserId() != null, UserBankRecord::getUserId, bo.getUserId());
        lqw.eq(bo.getStatus() != null, UserBankRecord::getStatus, bo.getStatus());
        lqw.eq(bo.getGoodsId() != null, UserBankRecord::getGoodsId, bo.getGoodsId());
        lqw.eq(bo.getReportStatus() != null, UserBankRecord::getReportStatus, bo.getReportStatus());
        lqw.eq(bo.getCourseId() != null, UserBankRecord::getCourseId, bo.getCourseId());
        lqw.eq(bo.getSectionId() != null, UserBankRecord::getSectionId, bo.getSectionId());
        lqw.eq(bo.getModuleId() != null, UserBankRecord::getModuleId, bo.getModuleId());
        lqw.eq(bo.getChapterId() != null, UserBankRecord::getChapterId, bo.getChapterId());
        lqw.eq(bo.getPerformance() != null, UserBankRecord::getPerformance, bo.getPerformance());
        lqw.eq(bo.getGradeId() != null, UserBankRecord::getGradeId, bo.getGradeId());
        return entity2Vo(this.list(lqw));
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByAddBo(UserBankRecordAddBo bo) {
        UserBankRecord add = BeanUtil.toBean(bo, UserBankRecord.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());


        if(this.save(add)){
            Long recordId =  add.getRecordId();
           /* for(UserBankQuestionRecordAddBo item : bo.getAnswerList()){
                item.setBankId(bo.getBankId());
                item.setRecordId(recordId);
                item.setUserId(bo.getUserId());
                iUserBankQuestionRecordService.insertByAddBo(item);
            }*/
            return recordId;
        }
        return 0L;

    }




    private Boolean increaseUser(UserVo userVo,Long score){
        User user = BeanUtil.toBean(userVo, User.class);
        user.setIntegral(score);
        user.setUpdateTime(DateUtils.getNowTime());
        return userService.updateById(user);
    }

    @Override
    public Boolean updateByEditBo(UserBankRecordEditBo bo) {
        UserBankRecord update = BeanUtil.toBean(bo, UserBankRecord.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        boolean b = this.updateById(update);
        updateExam(update);
        //判断有无学习结束
        UserStudyRecord userStudyRecord = new UserStudyRecord();
        userStudyRecord.setUserId(bo.getUserId());
        userStudyRecord.setGoodsId(bo.getGoodsId());
        userStudyRecord.setGradeId(bo.getGradeId());
        userStudyRecord.setStatus(1);
        iUserStudyRecordService.studyFinish(userStudyRecord);
        return b;
    }

    private void updateExam(UserBankRecord add) {
        //试卷及格绑定成绩和记录做题，待审，通过不记录
        UserBankRecordVo userBankRecordVo = this.queryById(add.getRecordId());
        if (userStudyRecordMapper.selectStudyExamRecord(userBankRecordVo)  < 1 && Validator.isNotEmpty(add.getReportStatus())&& add.getReportStatus().equals(1)){
            //增加一条审核记录
            UserPeriod userPeriod = new UserPeriod();
            userPeriod.setUserId(userBankRecordVo.getUserId());
            userPeriod.setCourseId(userBankRecordVo.getCourseId());
            userPeriod.setExamId(userBankRecordVo.getExamId());
            userPeriod.setGoodsId(userBankRecordVo.getGoodsId());
            userPeriod.setType(2);
            userPeriod.setCreateTime(DateUtils.getNowTime());
            userPeriod.setUpdateTime(DateUtils.getNowTime());
            userPeriod.setModuleId(userBankRecordVo.getModuleId());
            userPeriod.setChapterId(userBankRecordVo.getChapterId());
            userPeriod.setGradeId(userBankRecordVo.getGradeId());
            iUserPeriodService.save(userPeriod);
            UserPeriodStatus userPeriodStatusAddBo = new UserPeriodStatus();
            userPeriodStatusAddBo.setPeriodStatus(1);
            userPeriodStatusAddBo.setStatus(2);
            userPeriodStatusAddBo.setRecordStartTime(userBankRecordVo.getCreateTime());
            userPeriodStatusAddBo.setRecordEndTime(userBankRecordVo.getUpdateTime());
            userPeriodStatusAddBo.setPeriodId(userPeriod.getId());
            userPeriodStatusAddBo.setCreateTime(DateUtils.getNowTime());
            userPeriodStatusAddBo.setUpdateTime(DateUtils.getNowTime());
            userPeriodStatusAddBo.setPerformance(userBankRecordVo.getPerformance());
            iUserPeriodStatusService.save(userPeriodStatusAddBo);
            //将照片绑定学时
            LambdaQueryWrapper<UserStudyRecordPhoto> lqw = Wrappers.lambdaQuery();
            lqw.eq(UserStudyRecordPhoto::getRecordId, userBankRecordVo.getRecordId());
            lqw.eq(UserStudyRecordPhoto::getStatus, 2);
            lqw.eq(UserStudyRecordPhoto::getUserId, userBankRecordVo.getUserId());
            UserStudyRecordPhoto userStudyRecordPhoto = new UserStudyRecordPhoto();
            userStudyRecordPhoto.setPeriodId(userPeriodStatusAddBo.getId());
            userStudyRecordPhoto.setUpdateTime(DateUtils.getNowTime());
            userStudyRecordPhotoService.update(userStudyRecordPhoto,lqw);
        }

        //待重修
        if (userStudyRecordMapper.selectStudyExamRecordOr(userBankRecordVo) > 0 && add.getReportStatus().equals(1)){
            //将待重修改为待审核
            UserPeriodStatus userPeriodStatus = userStudyRecordMapper.selectStudyExamRecordCount(userBankRecordVo);
            userPeriodStatus.setStatus(2);
            userPeriodStatus.setRecordStartTime(userBankRecordVo.getCreateTime());
            userPeriodStatus.setRecordEndTime(userBankRecordVo.getUpdateTime());
            userPeriodStatus.setPerformance(userBankRecordVo.getPerformance());
            iUserPeriodStatusService.updateById(userPeriodStatus);

            //将照片绑定学时
            LambdaQueryWrapper<UserStudyRecordPhoto> lqw = Wrappers.lambdaQuery();
            lqw.eq(UserStudyRecordPhoto::getRecordId, userBankRecordVo.getRecordId());
            lqw.eq(UserStudyRecordPhoto::getStatus, 2);
            lqw.eq(UserStudyRecordPhoto::getUserId, userBankRecordVo.getUserId());
            UserStudyRecordPhoto userStudyRecordPhoto = new UserStudyRecordPhoto();
            userStudyRecordPhoto.setPeriodId(userPeriodStatus.getId());
            userStudyRecordPhoto.setUpdateTime(DateUtils.getNowTime());
            userStudyRecordPhotoService.update(userStudyRecordPhoto,lqw);
        }
    }
    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(UserBankRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

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


    //获得今天时间的0点
    public static int getTimesmorning(){
        Calendar cal = Calendar.getInstance();

        cal.set(Calendar.HOUR_OF_DAY, 0);

        cal.set(Calendar.SECOND, 0);

        cal.set(Calendar.MINUTE, 0);

        cal.set(Calendar.MILLISECOND, 0);

        return (int) (cal.getTimeInMillis()/1000);

    }

    //获得当天24点时间
    public static int getTimesnight(){
        Calendar cal = Calendar.getInstance();

        cal.set(Calendar.HOUR_OF_DAY, 24);

        cal.set(Calendar.SECOND, 0);

        cal.set(Calendar.MINUTE, 0);

        cal.set(Calendar.MILLISECOND, 0);

        return (int) (cal.getTimeInMillis()/1000);

    }
}
