package com.zd.exam.service.impl;

import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.FileConfigUtils;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.utils.SaveUtil;
import com.zd.exam.domain.ElCategory;
import com.zd.exam.domain.ElCourcesAccessRecord;
import com.zd.exam.domain.ElCourse;
import com.zd.exam.domain.ElCourseChapter;
import com.zd.exam.mapper.ElCategoryMapper;
import com.zd.exam.mapper.ElCourseChapterMapper;
import com.zd.exam.mapper.ElCourseMapper;
import com.zd.exam.service.IElCourcesAccessRecordService;
import com.zd.exam.service.IElCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 学习资源Service业务层处理
 *
 * @author liubo
 * @date 2021-12-07
 */
@Service
public class ElCourseServiceImpl implements IElCourseService {
    @Autowired
    private ElCourseMapper elCourseMapper;
    @Autowired
    private ElCourseChapterMapper elCourseChapterMapper;
    @Autowired
    private ElCategoryMapper elCategoryMapper;
    @Autowired
    private IElCourcesAccessRecordService courcesAccessRecordService;
    @Autowired
    private FileConfigUtils fileConfigUtils;

    /**
     * 查询学习资源
     *
     * @param id 学习资源主键
     * @return 学习资源
     */
    @Override
    public ElCourse selectElCourseById(Long id,HttpServletRequest request) {
        ElCourse elCourse = elCourseMapper.selectElCourseById(id);
        getChapterList(elCourse, 1,request);
        return elCourse;
    }

    /**
     * 个人查询学习资源以及是否完成
     *
     */
    @Override
    public ElCourse selectUserCourseById(Long id,HttpServletRequest request) {
        ElCourse elCourse = elCourseMapper.selectElCourseById(id);
        if(elCourse.getStatus() == 0){
            throw new ServiceException("课程已下架，暂无法学习！");
        }
        getChapterList(elCourse, 2,request);
        elCourse.setAllCateTitle(selectAllCateTitleById(elCourse.getCateId()));

        // 记录课程访问日志， 同一个人存一条
        ElCourcesAccessRecord elCourcesAccessRecord = new ElCourcesAccessRecord();
        elCourcesAccessRecord.setcourseId(id);
        elCourcesAccessRecord.setJoinUserId(SecurityUtils.getUserId());
        courcesAccessRecordService.insertElCourcesAccessRecord(elCourcesAccessRecord);
        return elCourse;
    }

    private String selectAllCateTitleById(Long cateId) {
        String allCateTitle = "";
        if(cateId != null){
            ElCategory cate = elCategoryMapper.selectElCategoryById(cateId);
            if (cate != null){
                allCateTitle = cate.getTitle();
                if(cate.getLevel() == 3){
                    cate = elCategoryMapper.selectElCategoryById(cate.getParentId());
                    allCateTitle = allCateTitle + " - " + Optional.ofNullable(cate.getTitle()).orElse("") + " - " +
                            Optional.ofNullable(elCategoryMapper.selectElCategoryById(cate.getParentId()).getTitle());
                }else if(cate.getLevel() == 2){
                    allCateTitle = allCateTitle + " - " + Optional.ofNullable(cate.getTitle()).orElse("") + " - " +
                            Optional.ofNullable(elCategoryMapper.selectElCategoryById(cate.getParentId()).getTitle());
                }
            }
        }
        return allCateTitle;
    }

    private void getChapterList(ElCourse elCourse, Integer type,HttpServletRequest request) {
        if(elCourse == null){
            return;
        }

        ElCourseChapter elCourseChapter = new ElCourseChapter();
        elCourseChapter.setCourseId(elCourse.getId());
        List<ElCourseChapter> chapterList;
        if(type == 1){
            chapterList = elCourseChapterMapper.selectElCourseChapterList(elCourseChapter);
        }else if(type == 2){
            elCourseChapter.setUserId(SecurityUtils.getUserId());
            // 个人端用户已学习时长
            elCourse.setLearnDurations(elCourseChapterMapper.selectLearnDurationsByUserId(elCourse.getId(), elCourseChapter.getUserId()));

            chapterList = elCourseChapterMapper.selectUserCourseChapterList(elCourseChapter);
        }else {
            elCourseChapter.setUserId(elCourse.getUserId());
            // 管理端根据用户查询已学习时长
            elCourse.setLearnDurations(elCourseChapterMapper.selectLearnDurationsByUserId(elCourse.getId(), elCourseChapter.getUserId()));

            chapterList = elCourseChapterMapper.selectUserCourseChapterList(elCourseChapter);
        }

        List<ElCourseChapter> chapters = new ArrayList<>();
        for (ElCourseChapter courseChapter : chapterList) {
            if(courseChapter.getParentId() == 0){
                getChildPerms(chapterList, courseChapter,request);
                chapters.add(courseChapter);
            }
        }

        elCourse.setChapterList(chapters);
    }

    private void getChildPerms(List<ElCourseChapter> chapterList, ElCourseChapter courseChapter, HttpServletRequest request){
        //处理文件路径
        String baseUrl=request.getServerName();
        String url="";

        // 得到子节点列表
        List<ElCourseChapter> childList = getChilds(chapterList, courseChapter);
        courseChapter.setChildren(childList);
        for (ElCourseChapter tChild : childList) {
            if(tChild.getType() != 5 && tChild.getType() != 0){
                if(baseUrl.contains("192.168")){
                    url=fileConfigUtils.getLocalUrl()+tChild.getChapterData();
                }else{
                    url=fileConfigUtils.getRemoteUrl()+tChild.getChapterData();
                }
                tChild.setChapterData(url);
            }

            if (hasChild(chapterList, tChild)) {
                getChildPerms(chapterList, tChild,request);
            }
        }
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ElCourseChapter> list, ElCourseChapter courseChapter) {
        return getChilds(list, courseChapter).size() > 0 ? true : false;
    }

    private List<ElCourseChapter> getChilds(List<ElCourseChapter> chapterList, ElCourseChapter courseChapter){
        List<ElCourseChapter> tlist = new ArrayList<>();
        Iterator<ElCourseChapter> it = chapterList.iterator();
        while (it.hasNext()) {
            ElCourseChapter n = it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == courseChapter.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 查询学习资源列表
     *
     * @param elCourse 学习资源
     * @return 学习资源
     */
    @Override
    @DataScope(deptAlias = "t" , userAlias = "t" , permi = PerPrefix.EXAM_EL_COURSE)
    public List<ElCourse> selectElCourseList(ElCourse elCourse) {
        return elCourseMapper.selectElCourseList(elCourse);
    }

    /**
     * 新增学习资源
     *
     * @param elCourse 学习资源
     * @return 结果
     */
    @Override
    public ElCourse insertElCourse(ElCourse elCourse) {
        //设置其他公共字段
        SaveUtil.setCommonAttr(elCourse);
        elCourseMapper.insertElCourse(elCourse);
        return elCourse;
    }

    /**
     * 修改学习资源
     *
     * @param elCourse 学习资源
     * @return 结果
     */
    @Override
    public int updateElCourse(ElCourse elCourse) {
        ElCourse oldCourse = elCourseMapper.selectElCourseById(elCourse.getId());
        if(oldCourse == null || !SecurityUtils.getUserId().equals(oldCourse.getUserId())){
            throw new ServiceException("操作失败，不是自己创建的课程不能修改！");
        }

        elCourse.setUpdateTime(DateUtils.getNowDate());
        elCourse.setUpdateBy(SecurityUtils.getUsername());
        return elCourseMapper.updateElCourse(elCourse);
    }

    /**
     * 批量删除学习资源
     *
     * @param ids 需要删除的学习资源主键
     * @return 结果
     */
    @Override
    public int deleteElCourseByIds(Long[] ids) {
        return elCourseMapper.deleteElCourseByIds(ids);
    }

    /**
     * 删除学习资源信息
     *
     * @param id 学习资源主键
     * @return 结果
     */
    @Override
    public int deleteElCourseById(Long id) {
        return elCourseMapper.deleteElCourseById(id);
    }

    /**
     * 查询学习资源下拉框
     */
    @Override
    public List<Map<String, Object>> queryOption(ElCourse elCourse) {
        return elCourseMapper.queryOption(elCourse);
    }

    @Override
    public ElCourse getCourseInfoByUser(Long userId, Long id, HttpServletRequest request) {
        ElCourse elCourse = elCourseMapper.selectElCourseById(id);
        elCourse.setUserId(userId);
        getChapterList(elCourse, 3,request);
        return elCourse;
    }

    @Override
    @DataScope(deptAlias = "t" , userAlias = "t" , permi = PerPrefix.EXAM_EL_COURSE)
    public List<ElCourse> selectElCourseListByUser(ElCourse elCourse) {

        List<ElCourse> list = elCourseMapper.selectElCourseList(elCourse);

        List<ElCourseChapter> chapterList;
        ElCourseChapter elCourseChapter = new ElCourseChapter();
        for (ElCourse course : list) {
            elCourseChapter.setCourseId(course.getId());
            elCourseChapter.setUserId(SecurityUtils.getUserId());

            chapterList = elCourseChapterMapper.selectUserCourseChapterList(elCourseChapter);
            Integer learnStatus = 1;
            for (ElCourseChapter chapter : chapterList) {
                if(chapter.getType() != 0){
                    // 0 学习中，2 未学习，1 已完成
                    if(chapter.getLearnStatus() == 0){
                        learnStatus = 0;
                        break;
                    }else if(chapter.getLearnStatus() == 1) {
                        if(chapter.getIsAssess() == 1 && chapter.getAssessStatus() == 0){
                            learnStatus = 3;
                        }
                    }else {
                        learnStatus = 2;
                        break;
                    }
                }
            }
            // 0 学习中，2 未学习，3 待考核，1 已完成
            course.setLearnStatus(learnStatus);
        }
        return list;
    }
}
