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.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
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.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.IndustryCategoryMapper;
import com.ruoyi.common.core.domain.entity.IndustryCategory;
import com.ruoyi.system.service.IIndustryCategoryService;

/**
 * 行业类别Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-23
 */
@Service
public class IndustryCategoryServiceImpl implements IIndustryCategoryService 
{
    @Autowired
    private IndustryCategoryMapper industryCategoryMapper;

    /**
     * 查询行业类别
     * 
     * @param categoryId 行业类别主键
     * @return 行业类别
     */
    @Override
    public IndustryCategory selectIndustryCategoryByCategoryId(Long categoryId)
    {
        return industryCategoryMapper.selectIndustryCategoryByCategoryId(categoryId);
    }

    /**
     * 查询行业类别列表
     * 
     * @param industryCategory 行业类别
     * @return 行业类别
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<IndustryCategory> selectIndustryCategoryList(IndustryCategory industryCategory)
    {
        return industryCategoryMapper.selectIndustryCategoryList(industryCategory);
    }

    /**
     * 新增行业类别
     * 
     * @param industryCategory 行业类别
     * @return 结果
     */
    @Override
    public int insertIndustryCategory(IndustryCategory industryCategory)
    {

        IndustryCategory industry = industryCategoryMapper.selectIndustryCategoryByCategoryId(industryCategory.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(industry.getStatus()))
        {
            throw new ServiceException("类别停用，不允许新增");
        }
        industryCategory.setAncestors(industry.getAncestors() + "," + industryCategory.getParentId());
        industryCategory.setCreateTime(DateUtils.getNowDate());
        return industryCategoryMapper.insertIndustryCategory(industryCategory);
    }

    /**
     * 修改行业类别
     * 
     * @param industryCategory 行业类别
     * @return 结果
     */
    @Override
    public int updateIndustryCategory(IndustryCategory industryCategory)
    {
        IndustryCategory newParentIndustry = industryCategoryMapper.selectIndustryCategoryByCategoryId(industryCategory.getParentId());
        IndustryCategory oldIndustry = industryCategoryMapper.selectIndustryCategoryByCategoryId(industryCategory.getCategoryId());
        if (StringUtils.isNotNull(newParentIndustry) && StringUtils.isNotNull(oldIndustry))
        {
            String newAncestors = newParentIndustry.getAncestors() + "," + newParentIndustry.getCategoryId();
            String oldAncestors = oldIndustry.getAncestors();
            industryCategory.setAncestors(newAncestors);
            updateDeptChildren(industryCategory.getCategoryId(), newAncestors, oldAncestors);
        }
        industryCategory.setUpdateTime(DateUtils.getNowDate());
        int result = industryCategoryMapper.updateIndustryCategory(industryCategory);
        if (UserConstants.DEPT_NORMAL.equals(industryCategory.getStatus()) && StringUtils.isNotEmpty(industryCategory.getAncestors())
                && !StringUtils.equals("0", industryCategory.getAncestors()))
        {
            // 如果该行业是启用状态，则启用该行业的所有上级部门
            updateParentDeptStatusNormal(industryCategory);
        }
        return result;
    }

    /**
     * 修改该行业的父级部门状态
     *
     * @param industryCategory 当前行业
     */
    private void updateParentDeptStatusNormal(IndustryCategory industryCategory)
    {
        String ancestors = industryCategory.getAncestors();
        Long[] ids = Convert.toLongArray(ancestors);
        industryCategoryMapper.updateDeptStatusNormal(ids);
    }

    /**
     * 修改子元素关系
     *
     * @param id 被修改的ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long id, String newAncestors, String oldAncestors)
    {
        List<IndustryCategory> children = industryCategoryMapper.selectChildrenIndustryById(id);
        for (IndustryCategory child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            industryCategoryMapper.updateIndustryChildren(children);
        }
    }

    /**
     * 批量删除行业类别
     * 
     * @param categoryIds 需要删除的行业类别主键
     * @return 结果
     */
    @Override
    public int deleteIndustryCategoryByCategoryIds(Long[] categoryIds)
    {
        return industryCategoryMapper.deleteIndustryCategoryByCategoryIds(categoryIds);
    }

    /**
     * 删除行业类别信息
     * 
     * @param categoryId 行业类别主键
     * @return 结果
     */
    @Override
    public int deleteIndustryCategoryByCategoryId(Long categoryId)
    {
        return industryCategoryMapper.deleteIndustryCategoryByCategoryId(categoryId);
    }

    @Override
    public List<TreeSelect> selectCategoryTreeList(IndustryCategory industryCategory) {
        List<IndustryCategory> industryCategorys = SpringUtils.getAopProxy(this).selectIndustryCategoryList(industryCategory);
        return buildCategoryTreeSelect(industryCategorys);
    }

    @Override
    public List<TreeSelect> buildCategoryTreeSelect(List<IndustryCategory> industryCategorys) {
        List<IndustryCategory> categoryTrees = buildCategoryTree(industryCategorys);
        return categoryTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param
     * @return 树结构列表
     */
    private List<IndustryCategory> buildCategoryTree(List<IndustryCategory> industryCategorys) {
        List<IndustryCategory> returnList = new ArrayList<IndustryCategory>();
        List<Long> tempList = industryCategorys.stream().map(IndustryCategory::getCategoryId).collect(Collectors.toList());
        for (IndustryCategory category : industryCategorys)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(category.getParentId()))
            {
                recursionFn(industryCategorys, category);
                returnList.add(category);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = industryCategorys;
        }
        return returnList;
    }

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

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

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