package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.AssetType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.AssetTypeMapper;
import com.ruoyi.system.service.IAssetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 资产类型Service业务层处理
 *
 * @author boman
 * @date 2025-02-17
 */
@Service
public class AssetTypeServiceImpl implements IAssetTypeService {
    @Autowired
    private AssetTypeMapper assetTypeMapper;

    /**
     * 查询资产类型
     *
     * @param assetId 资产类型主键
     * @return 资产类型
     */
    @Override
    public AssetType selectAssetTypeByAssetId(Long assetId) {
        return assetTypeMapper.selectAssetTypeByAssetId(assetId);
    }

    /**
     * 查询资产类型列表
     *
     * @param assetType 资产类型
     * @return 资产类型
     */
    @Override
    public List<AssetType> selectAssetTypeList(AssetType assetType) {
        return assetTypeMapper.selectAssetTypeList(assetType);
    }

    /**
     * 新增资产类型
     *
     * @param assetType 资产类型
     * @return 结果
     */
    @Override
    public int insertAssetType(AssetType assetType) {
        assetType.setCreateTime(DateUtils.getNowDate());
        AssetType info = assetTypeMapper.selectAssetTypeByAssetId(assetType.getParentId());
        int i = 0;
        if (info != null) {
            // 如果父节点不为正常状态,则不允许新增子节点
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("部门停用，不允许新增");
            }
            assetType.setAncestors(info.getAncestors() + "," + assetType.getParentId());
            assetType.setCreateTime(DateUtils.getNowDate());
            i = assetTypeMapper.insertAssetType(assetType);
        } else {
            assetType.setParentId(0L);
            assetType.setAncestors("0");
            assetType.setCreateTime(DateUtils.getNowDate());
            i = assetTypeMapper.insertAssetType(assetType);
        }
        return i;
    }

    /**
     * 修改资产类型
     *
     * @param assetType 资产类型
     * @return 结果
     */
    @Override
    public int updateAssetType(AssetType assetType) {
        AssetType newParentAssetType = assetTypeMapper.selectAssetTypeByAssetId(assetType.getParentId());
        AssetType oldParentAssetType = assetTypeMapper.selectAssetTypeByAssetId(assetType.getAssetId());
        if (StringUtils.isNotNull(newParentAssetType) && StringUtils.isNotNull(oldParentAssetType)) {
            String newAncestors = newParentAssetType.getAncestors() + "," + newParentAssetType.getAncestors();
            String oldAncestors = oldParentAssetType.getAncestors();
            assetType.setAncestors(newAncestors);
            updateAssetTypeChildren(assetType.getAssetId(), newAncestors, oldAncestors);
        }
        assetType.setUpdateTime(DateUtils.getNowDate());
        return assetTypeMapper.updateAssetType(assetType);
    }

    /**
     * 修改子元素关系
     *
     * @param assetId      被修改的资产ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateAssetTypeChildren(Long assetId, String newAncestors, String oldAncestors) {
        List<AssetType> children = assetTypeMapper.selectChildrenAssetTypeById(assetId);
        for (AssetType child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            assetTypeMapper.updateAssetTypeChildren(children);
        }
    }

    /**
     * 批量删除资产类型
     *
     * @param assetIds 需要删除的资产类型主键
     * @return 结果
     */
    @Override
    public int deleteAssetTypeByAssetIds(Long[] assetIds) {
        return assetTypeMapper.deleteAssetTypeByAssetIds(assetIds);
    }

    /**
     * 删除资产类型信息
     *
     * @param assetId 资产类型主键
     * @return 结果
     */
    @Override
    public int deleteAssetTypeByAssetId(Long assetId) {
        return assetTypeMapper.deleteAssetTypeByAssetId(assetId);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param assetType
     * @return
     */
    @Override
    public List<TreeSelect> selectAssetTypeTreeList(AssetType assetType) {
        List<AssetType> assetTypes = selectAssetTypeListTree(assetType);
        return buildAssetTypeTreeSelect(assetTypes);
    }

    /**
     * 检验资产名称的唯一性
     *
     * @param assetType
     * @return
     */
    @Override
    public boolean checkAssetTypeNameUnique(AssetType assetType) {
        Long assetId = StringUtils.isNull(assetType.getAssetId()) ? -1L : assetType.getAssetId();
        AssetType info = assetTypeMapper.checkAssetNameUnique(assetType.getAssetName(), assetType.getParentId());
        if (StringUtils.isNotNull(info) && info.getAssetId().longValue() != assetId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int selectNormalChildrenAssetById(Long assetId) {
        return assetTypeMapper.selectNormalChildrenAssetById(assetId);
    }

    /**
     * 是否存在子节点
     *
     * @param assetId 资产ID
     * @return 结果
     */
    @Override
    public boolean hasChildByAssetId(Long assetId) {
        int result = assetTypeMapper.hasChildByAssetId(assetId);
        return result > 0;
    }

    /**
     * 查询资产类型列表
     *
     * @param assetType 资产类型
     * @return 资产类型
     */
    public List<AssetType> selectAssetTypeListTree(AssetType assetType) {
        return assetTypeMapper.selectAssetTypeListTree(assetType);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param assetTypes 资产列表
     * @return 下拉树结构列表
     */
    public List<TreeSelect> buildAssetTypeTreeSelect(List<AssetType> assetTypes) {
        List<AssetType> assetTypesTrees = buildAssetTypeTree(assetTypes);
        return assetTypesTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

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

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

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

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