package com.zd.exam.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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.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.ElCourse;
import com.zd.exam.domain.ElCourseChapter;
import com.zd.exam.mapper.ElCourseMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zd.exam.mapper.ElCategoryMapper;
import com.zd.exam.domain.ElCategory;
import com.zd.exam.service.IElCategoryService;

/**
 * 学习分类Service业务层处理
 *
 * @author liubo
 * @date 2021-12-07
 */
@Service
public class ElCategoryServiceImpl implements IElCategoryService {
    @Autowired
    private ElCategoryMapper elCategoryMapper;
    @Autowired
    private ElCourseMapper elCourseMapper;

    /**
     * 查询学习分类
     *
     * @param id 学习分类主键
     * @return 学习分类
     */
    @Override
    public ElCategory selectElCategoryById(Long id) {
        return elCategoryMapper.selectElCategoryById(id);
    }

    /**
     * 查询学习分类列表
     *
     * @param elCategory 学习分类
     * @return 学习分类
     */
    @Override
    @DataScope(deptAlias = "t" , userAlias = "t" , permi = PerPrefix.EXAM_EL_CATEGORY)
    public List<ElCategory> selectElCategoryList(ElCategory elCategory) {
        return elCategoryMapper.selectElCategoryList(elCategory);
    }

    /**
     * 新增学习分类
     *
     * @param elCategory 学习分类
     * @return 结果
     */
    @Override
    public int insertElCategory(ElCategory elCategory) {
        //设置其他公共字段
        elCategory.setUpdateTime(DateUtils.getNowDate());
        SaveUtil.setCommonAttr(elCategory);
        return elCategoryMapper.insertElCategory(elCategory);
    }

    /**
     * 修改学习分类
     *
     * @param elCategory 学习分类
     * @return 结果
     */
    @Override
    public int updateElCategory(ElCategory elCategory) {
        elCategory.setUpdateTime(DateUtils.getNowDate());
        elCategory.setUpdateBy(SecurityUtils.getUsername());
        return elCategoryMapper.updateElCategory(elCategory);
    }

    /**
     * 批量删除学习分类
     *
     * @param ids 需要删除的学习分类主键
     * @return 结果
     */
    @Override
    public int deleteElCategoryByIds(Long[] ids) {
        ElCourse elCourse = new ElCourse();
        ElCategory elCategory = new ElCategory();
        List<ElCourse> courses;
        List<ElCategory> categories;
        for (Long id : ids) {
            courses = elCourseMapper.selectByCateId(id);
            if(CollectionUtils.isNotEmpty(courses)){
                throw new ServiceException("分类已关联资源，删除失败！");
            }

            elCategory.setParentId(id);
            categories = elCategoryMapper.selectElCategoryList(elCategory);
            if(CollectionUtils.isNotEmpty(categories)){
                throw new ServiceException("请先删除该分类下的所有子分类！");
            }
        }
        return elCategoryMapper.deleteElCategoryByIds(ids);
    }

    /**
     * 删除学习分类信息
     *
     * @param id 学习分类主键
     * @return 结果
     */
    @Override
    public int deleteElCategoryById(Long id) {
        return elCategoryMapper.deleteElCategoryById(id);
    }

    /**
     * 获取学习分类树状结构
     */
    @Override
    @DataScope(deptAlias = "t" , userAlias = "t" , permi = PerPrefix.EXAM_EL_COURSE)
    public List<ElCategory> treeList(ElCategory elCategory) {
        Long parentId = elCategory.getParentId();
        elCategory.setParentId(null);

        List<ElCategory> chapterList = elCategoryMapper.selectElCategoryList(elCategory);

        List<ElCategory> chapters = new ArrayList<>();
        for (ElCategory category : chapterList) {
            if(category.getParentId().equals(parentId)){
                getChildPerms(chapterList, category);
                chapters.add(category);
            }
        }

        return chapters;
    }


    private void getChildPerms(List<ElCategory> chapterList, ElCategory category){
        // 得到子节点列表
        List<ElCategory> childList = getChilds(chapterList, category);
        category.setChildren(childList);
        for (ElCategory tChild : childList) {
            if (hasChild(chapterList, tChild)) {
                getChildPerms(chapterList, tChild);
            }
        }
    }

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

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