package com.ruoyi.system.service.impl;

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

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.ColumnNews;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.ColumnNavigationBar;
import com.ruoyi.system.mapper.ColumnNewsMapper;
import com.ruoyi.system.service.IColumnNavigationBarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ColumnNavigationBarMapper;


/**
 * 栏目导航Service业务层处理
 * 
 * @author boman
 * @date 2021-12-24
 */
@Service
public class ColumnNavigationBarServiceImpl implements IColumnNavigationBarService
{
    @Autowired
    private ColumnNavigationBarMapper columnNavigationBarMapper;

    @Autowired
    private ColumnNewsMapper columnNewsMapper;

    /**
     * 查询栏目导航
     * 
     * @param columnId 栏目导航主键
     * @return 栏目导航
     */
    @Override
    public ColumnNavigationBar selectColumnNavigationBarByColumnId(Long columnId)
    {
        return columnNavigationBarMapper.selectColumnNavigationBarByColumnId(columnId);
    }

    /**
     * 查询栏目导航列表
     * 
     * @param columnNavigationBar 栏目导航
     * @return 栏目导航
     */
    @Override
    public List<ColumnNavigationBar> selectColumnNavigationBarList(ColumnNavigationBar columnNavigationBar)
    {
        return columnNavigationBarMapper.selectColumnNavigationBarList(columnNavigationBar);
    }

    /**
     * 门户获取各个部分首页标题
     * @param columnNavigationBar
     * @return
     */
    @Override
    public List<ColumnNavigationBar> selectColumnNavigationBarListMenHu(ColumnNavigationBar columnNavigationBar) {
        List<ColumnNavigationBar> columnNavigationBars = columnNavigationBarMapper.selectColumnNavigationBarListMenHu(columnNavigationBar);
        if (columnNavigationBars.size() > 0){
            for (ColumnNavigationBar navigationBar : columnNavigationBars) {
                Long columnId = navigationBar.getColumnId();
                //去查询文章
                List<ColumnNews> columnNews = columnNewsMapper.selectColumnNewsListMenHuByColumnId(columnId);
                navigationBar.setColumnNewsList(columnNews);
            }
        }
        return columnNavigationBars;
    }

    /**
     * 新增栏目导航
     * 
     * @param columnNavigationBar 栏目导航
     * @return 结果
     */
    @Override
    public int insertColumnNavigationBar(ColumnNavigationBar columnNavigationBar)
    {
        Long parentId = columnNavigationBar.getParentId();
        if (parentId != null){
            ColumnNavigationBar info = columnNavigationBarMapper.selectColumnNavigationBarByColumnId(columnNavigationBar.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
            {
                throw new ServiceException("上级栏目导航停用，不允许新增");
            }
            columnNavigationBar.setAncestors(info.getAncestors() + "," + columnNavigationBar.getParentId());
        }else {
            columnNavigationBar.setParentId(0L);
            columnNavigationBar.setAncestors(String.valueOf(columnNavigationBar.getParentId()));
        }
        columnNavigationBar.setCreateTime(DateUtils.getNowDate());
        return columnNavigationBarMapper.insertColumnNavigationBar(columnNavigationBar);
    }

    /**
     * 修改栏目导航
     * 
     * @param columnNavigationBar 栏目导航
     * @return 结果
     */
    @Override
    public int updateColumnNavigationBar(ColumnNavigationBar columnNavigationBar)
    {
        Long parentId = columnNavigationBar.getParentId();
        if (parentId == null){
            columnNavigationBar.setParentId(0L);
        }
        ColumnNavigationBar newParentColumn = columnNavigationBarMapper.selectColumnNavigationBarByColumnId(columnNavigationBar.getParentId());
        ColumnNavigationBar oldColumnNavigationBar = columnNavigationBarMapper.selectColumnNavigationBarByColumnId(columnNavigationBar.getColumnId());
        if (StringUtils.isNotNull(newParentColumn) && StringUtils.isNotNull(oldColumnNavigationBar))
        {
            String newAncestors = newParentColumn.getAncestors() + "," + newParentColumn.getColumnId();
            String oldAncestors = oldColumnNavigationBar.getAncestors();
            columnNavigationBar.setAncestors(newAncestors);
            updateDeptChildren(columnNavigationBar.getColumnId(), newAncestors, oldAncestors);
        }
        int result = columnNavigationBarMapper.updateColumnNavigationBar(columnNavigationBar);
        if (UserConstants.DEPT_NORMAL.equals(columnNavigationBar.getStatus()) && StringUtils.isNotEmpty(columnNavigationBar.getAncestors())
                && !StringUtils.equals("0", columnNavigationBar.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentColumnStatusNormal(columnNavigationBar);
        }
        columnNavigationBar.setUpdateTime(DateUtils.getNowDate());
        return columnNavigationBarMapper.updateColumnNavigationBar(columnNavigationBar);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<ColumnNavigationBar> children = columnNavigationBarMapper.selectChildrenColumnById(deptId);
        for (ColumnNavigationBar child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            columnNavigationBarMapper.updateColumnChildren(children);
        }
    }

    /**
     * 批量删除栏目导航
     * 
     * @param columnIds 需要删除的栏目导航主键
     * @return 结果
     */
    @Override
    public int deleteColumnNavigationBarByColumnIds(Long[] columnIds)
    {
        return columnNavigationBarMapper.deleteColumnNavigationBarByColumnIds(columnIds);
    }

    /**
     * 删除栏目导航信息
     * 
     * @param columnId 栏目导航主键
     * @return 结果
     */
    @Override
    public int deleteColumnNavigationBarByColumnId(Long columnId)
    {
        return columnNavigationBarMapper.deleteColumnNavigationBarByColumnId(columnId);
    }

    /**
     * 构建前端所需要下拉树结构
     * @param columnNavigationBars 栏目导航列表
     * @return
     */
    @Override
    public List<TreeSelect> buildColumnTreeSelect(List<ColumnNavigationBar> columnNavigationBars) {
        List<ColumnNavigationBar> columnTrees = buildColumnTree(columnNavigationBars);
        return columnTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    /**
     * 构建前端所需要树结构
     *
     * @param columnNavigationBars 部门列表
     * @return 树结构列表
     */
    @Override
    public List<ColumnNavigationBar> buildColumnTree(List<ColumnNavigationBar> columnNavigationBars)
    {
        List<ColumnNavigationBar> returnList = new ArrayList<ColumnNavigationBar>();
        List<Long> tempList = new ArrayList<Long>();
        for (ColumnNavigationBar columnNavigationBar : columnNavigationBars)
        {
            tempList.add(columnNavigationBar.getColumnId());
        }
        for (Iterator<ColumnNavigationBar> iterator = columnNavigationBars.iterator(); iterator.hasNext();)
        {
            ColumnNavigationBar columnNavigationBar = (ColumnNavigationBar) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(columnNavigationBar.getParentId()))
            {
                recursionFn(columnNavigationBars, columnNavigationBar);
                returnList.add(columnNavigationBar);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = columnNavigationBars;
        }
        return returnList;
    }

    /**
     * 校验栏目导航名称是否唯一
     * @param columnNavigationBar 栏目导航信息
     * @return
     */
    @Override
    public String checkColumnNameUnique(ColumnNavigationBar columnNavigationBar) {
        Long columnId = StringUtils.isNull(columnNavigationBar.getColumnId()) ? -1L : columnNavigationBar.getColumnId();
        ColumnNavigationBar info = columnNavigationBarMapper.checkColumnNameUnique(columnNavigationBar.getColumnName(), columnNavigationBar.getParentId());
        if (StringUtils.isNotNull(info) && info.getColumnId().longValue() != columnId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 根据ID查询所有子栏目导航（正常状态）
     * @param columnId 栏目导航ID
     * @return
     */
    @Override
    public int selectNormalChildrenColumnById(Long columnId) {
        return columnNavigationBarMapper.selectNormalChildrenColumnById(columnId);
    }

    /**
     * @param columnId 栏目导航ID
     * @return
     */
    @Override
    public boolean hasChildByColumnId(Long columnId) {
        int result = columnNavigationBarMapper.hasChildByColumnId(columnId);
        return result > 0;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ColumnNavigationBar> list, ColumnNavigationBar t)
    {
        // 得到子节点列表
        List<ColumnNavigationBar> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ColumnNavigationBar tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ColumnNavigationBar>  getChildList(List<ColumnNavigationBar>  list, ColumnNavigationBar t)
    {
        List<ColumnNavigationBar> tlist = new ArrayList<ColumnNavigationBar>();
        Iterator<ColumnNavigationBar> it = list.iterator();
        while (it.hasNext())
        {
            ColumnNavigationBar n = (ColumnNavigationBar) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getColumnId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ColumnNavigationBar> list, ColumnNavigationBar t)
    {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 修改该栏目导航的父级栏目导航状态
     *
     * @param columnNavigationBar 当前栏目导航
     */
    private void updateParentColumnStatusNormal(ColumnNavigationBar columnNavigationBar)
    {
        String ancestors = columnNavigationBar.getAncestors();
        Long[] columnIds = Convert.toLongArray(ancestors);
        columnNavigationBarMapper.updateColumnStatusNormal(columnIds);
    }
}
