package com.da.dangan.service.impl;

import com.da.common.constant.UserConstants;
import com.da.common.core.domain.AjaxResult;
import com.da.common.core.domain.TreeSelect;
import com.da.common.core.domain.entity.DaCatalog;
import com.da.common.core.domain.entity.SysUser;
import com.da.common.exception.ServiceException;
import com.da.common.utils.DateUtils;
import com.da.common.utils.StringUtils;
import com.da.dangan.mapper.DaCatalogMapper;
import com.da.dangan.service.IDaCatalogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 档案目录Service业务层处理
 * 
 * @author hs
 * @date 2024-05-08
 */
@Service
public class DaCatalogServiceImpl implements IDaCatalogService 
{
    @Resource
    private DaCatalogMapper daCatalogMapper;

    /**
     * 查询档案目录
     * 
     * @param id 档案目录主键
     * @return 档案目录
     */
    @Override
    public DaCatalog selectDaCatalogById(Long id)
    {
        return daCatalogMapper.selectDaCatalogById(id);
    }

    @Override
    public List<Long> selectCatalogIdsByUserId(Long userId) {
        return daCatalogMapper.selectCatalogIdsByUserId(userId);
    }

    @Override
    public List<TreeSelect> buildCatalogTreeSelect(List<DaCatalog> catalogs) {
        List<DaCatalog> catalogTrees = buildCatalogTree(catalogs);
        return catalogTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param catalogs 目录列表
     * @return 树结构列表
     */
    @Override
    public List<DaCatalog> buildCatalogTree(List<DaCatalog> catalogs)
    {
        List<DaCatalog> returnList = new ArrayList<>();
        List<Long> tempList = catalogs.stream().map(DaCatalog::getId).collect(Collectors.toList());
        for (Iterator<DaCatalog> iterator = catalogs.iterator(); iterator.hasNext();)
        {
            DaCatalog catalog = iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(catalog.getPid()))
            {
                recursionFn(catalogs, catalog);
                returnList.add(catalog);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = catalogs;
        }
        return returnList;
    }


    @Override
    public List<DaCatalog> selectCatalogList(Long userId) {
        return selectAllDaCatalogList(new DaCatalog(), userId);
    }
    /**
     * 查询档案目录列表
     *
     * @param daCatalog 档案目录
     * @return 档案目录
     */
    @Override
    public List<DaCatalog> selectDaCatalogList(DaCatalog daCatalog)
    {
        return daCatalogMapper.selectDaCatalogList(daCatalog);
    }

    @Override
    public List<DaCatalog> selectAllDaCatalogList(DaCatalog daCatalog, Long userId)
    {
        List<DaCatalog> catalogList = null;
        // 管理员显示所有目录信息
        if (SysUser.isAdmin(userId))
        {
            catalogList = daCatalogMapper.selectDaCatalogList(daCatalog);
        }
        else
        {  //根据用户权限显示目录信息
            daCatalog.getParams().put("userId", userId);
            catalogList = daCatalogMapper.selectDaCatalogListByUserId(daCatalog);
        }
        return catalogList;
    }
    /**
     * 新增档案目录
     * 
     * @param daCatalog 档案目录
     * @return 结果
     */
    @Override
    public int insertDaCatalog(DaCatalog daCatalog)
    {
        daCatalog.setCreateTime(DateUtils.getNowDate());
        if(daCatalog.getPid()==0){  //代表添加的是主目录
            daCatalog.setAncestors(daCatalog.getPid().toString());
        }else{
            DaCatalog info = daCatalogMapper.selectDaCatalogById(daCatalog.getPid());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
            {
                throw new ServiceException("此目录停用，不允许新增");
            }
            daCatalog.setAncestors(info.getAncestors() + "," + daCatalog.getPid());
        }
        return daCatalogMapper.insertDaCatalog(daCatalog);
    }

    /**
     * 修改档案目录
     * 
     * @param daCatalog 档案目录
     * @return 结果
     */
    @Override
    public int updateDaCatalog(DaCatalog daCatalog)
    {
        daCatalog.setUpdateTime(DateUtils.getNowDate());
        return daCatalogMapper.updateDaCatalog(daCatalog);
    }

    /**
     * 删除档案目录信息
     *
     * @param id 档案目录主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteDaCatalogById(Long id)
    {
        DaCatalog catalog = new DaCatalog();
        catalog.setPid(id);
        //有子级目录的不能删除
        List<DaCatalog> daCatalogs = daCatalogMapper.selectDaCatalogList(catalog);
        if(daCatalogs!=null&&daCatalogs.size()>0){
            return AjaxResult.error("有子级目录，不能删除");
        }
        int i= daCatalogMapper.deleteDaCatalogById(id);
        if(i>0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 批量删除档案目录
     * 
     * @param ids 需要删除的档案目录主键
     * @return 结果
     */
    @Override
    public int deleteDaCatalogByIds(Long[] ids)
    {
        return daCatalogMapper.deleteDaCatalogByIds(ids);
    }

    @Override
    public boolean checkDaCatalogNameUnique(DaCatalog daCatalog) {
        Long daCatalogId = StringUtils.isNull(daCatalog.getId()) ? -1L : daCatalog.getId();
        DaCatalog info = daCatalogMapper.checkDaCatalogNameUnique(daCatalog.getMuName(), daCatalog.getPid());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != daCatalogId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

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

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

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

}
