package org.dromara.ems.base.service.impl;

import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import cn.hutool.core.util.ObjectUtil;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.ems.base.domain.EmsBaseMonitorInfo;
import org.dromara.ems.base.domain.TreeSelects;
import org.dromara.ems.base.mapper.EmsBaseMonitorInfoMapper;
import org.dromara.ems.base.service.IEmsBaseMonitorInfoService;
import org.dromara.ems.record.domain.EmsRecordAlarmRule;
import org.dromara.ems.record.service.IEmsRecordAlarmRuleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 计量设备信息Service业务层处理
 * 
 * @author Yinq
 * @date 2024-05-08
 */
@Service
@RequiredArgsConstructor
public class EmsBaseMonitorInfoServiceImpl implements IEmsBaseMonitorInfoService
{
    
    private final EmsBaseMonitorInfoMapper emsBaseMonitorInfoMapper;

    
    private final IEmsRecordAlarmRuleService emsRecordAlarmRuleService;

    /**
     * 查询计量设备信息
     * 
     * @param objId 计量设备信息主键
     * @return 计量设备信息
     */
    @Override
    public EmsBaseMonitorInfo selectEmsBaseMonitorInfoByObjId(Long objId)
    {
        return emsBaseMonitorInfoMapper.selectEmsBaseMonitorInfoByObjId(objId);
    }

    /**
     * 查询计量设备信息列表
     * 
     * @param emsBaseMonitorInfo 计量设备信息
     * @return 计量设备信息
     */
    @Override
    public List<EmsBaseMonitorInfo> selectEmsBaseMonitorInfoList(EmsBaseMonitorInfo emsBaseMonitorInfo)
    {
        return emsBaseMonitorInfoMapper.selectEmsBaseMonitorInfoList(emsBaseMonitorInfo);
    }

    /**
     * 根据设备编号查询本设备能源类型
     * @param monitorCode
     * @return
     */
    @Override
    public String selectEmsBaseMonitorTypeByMonitorCode(String monitorCode) {
        return emsBaseMonitorInfoMapper.selectEmsBaseMonitorTypeByMonitorCode(monitorCode);
    }

    /**
     * 新增计量设备信息
     * 
     * @param emsBaseMonitorInfo 计量设备信息
     * @return 结果
     */
    @Override
    public int insertEmsBaseMonitorInfo(EmsBaseMonitorInfo emsBaseMonitorInfo)
    {
        emsBaseMonitorInfo.setCreateTime(DateUtils.getNowDate());
        return emsBaseMonitorInfoMapper.insertEmsBaseMonitorInfo(emsBaseMonitorInfo);
    }

    /**
     * 修改计量设备信息
     * 
     * @param emsBaseMonitorInfo 计量设备信息
     * @return 结果
     */
    @Override
    public int updateEmsBaseMonitorInfo(EmsBaseMonitorInfo emsBaseMonitorInfo)
    {
        emsBaseMonitorInfo.setUpdateTime(DateUtils.getNowDate());
        return emsBaseMonitorInfoMapper.updateEmsBaseMonitorInfo(emsBaseMonitorInfo);
    }

    /**
     * 批量删除计量设备信息
     * 
     * @param objIds 需要删除的计量设备信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEmsBaseMonitorInfoByObjIds(Long[] objIds)
    {
        for (Long objId : objIds){
                    // 3. 检查子设备（如果存在，则抛出异常）
                    EmsBaseMonitorInfo childQuery = new EmsBaseMonitorInfo();
                    childQuery.setParentId(objId);
                    List<EmsBaseMonitorInfo> childDevices = emsBaseMonitorInfoMapper.selectEmsBaseMonitorInfoList(childQuery);
                    if (childDevices != null && !childDevices.isEmpty()) {
                        throw new ServiceException("存在子节点，无法删除设备信息 ");
                    }
                }
        return emsBaseMonitorInfoMapper.deleteEmsBaseMonitorInfoByObjIds(objIds);
    }

    /**
     * 删除计量设备信息信息（级联删除关联的异常规则和措施步骤）
     * 
     * @param objId 计量设备信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEmsBaseMonitorInfoByObjId(Long objId)
    {
            // 1. 查询要删除的设备信息
            EmsBaseMonitorInfo monitorInfo = emsBaseMonitorInfoMapper.selectEmsBaseMonitorInfoByObjId(objId);
            if (monitorInfo == null) {
                throw new RuntimeException("设备信息不存在 " );
            }
            // 3. 检查子设备（如果存在，则抛出异常）
            EmsBaseMonitorInfo childQuery = new EmsBaseMonitorInfo();
            childQuery.setParentId(objId);
            List<EmsBaseMonitorInfo> childDevices = emsBaseMonitorInfoMapper.selectEmsBaseMonitorInfoList(childQuery);
            if (childDevices != null && !childDevices.isEmpty()) {
                throw new ServiceException("存在子节点，无法删除设备信息 ");
            }
            
            // 4. 删除该设备关联的所有异常规则（会级联删除措施步骤和图片）
            EmsRecordAlarmRule alarmRuleQuery = new EmsRecordAlarmRule();
            alarmRuleQuery.setMonitorId(monitorInfo.getMonitorCode());
            List<EmsRecordAlarmRule> alarmRules = emsRecordAlarmRuleService.selectEmsRecordAlarmRuleList(alarmRuleQuery);
            
            if (alarmRules != null && !alarmRules.isEmpty()) {
                Long[] ruleIds = alarmRules.stream()
                    .map(EmsRecordAlarmRule::getObjId)
                    .toArray(Long[]::new);
                // 级联删除异常规则（会自动删除关联的措施步骤和图片）
                emsRecordAlarmRuleService.deleteEmsRecordAlarmRuleByObjIds(ruleIds);

            }
            // 5. 最后删除设备本身
            int result = emsBaseMonitorInfoMapper.deleteEmsBaseMonitorInfoByObjId(objId);
            return result;
    }

    /**
     * 查询计量设备信息下拉树结构
     * */
    @Override
    public List<TreeSelects> selectBaseMonitorInfoTreeList(EmsBaseMonitorInfo baseMonitorInfo) {
        List<EmsBaseMonitorInfo> baseMonitorInfruoyi = selectEmsBaseMonitorInfoList(baseMonitorInfo);
        return buildMonitorInfoTreeSelect(baseMonitorInfruoyi);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelects> buildMonitorInfoTreeSelect(List<EmsBaseMonitorInfo> baseMonitorInfruoyi)
    {
        List<EmsBaseMonitorInfo> deptTrees = buildMonitorInfoTree(baseMonitorInfruoyi);
        return deptTrees.stream().map(TreeSelects::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param
     * @return 树结构列表
     */
    @Override
    public List<EmsBaseMonitorInfo> buildMonitorInfoTree(List<EmsBaseMonitorInfo> baseMonitorInfruoyi)
    {
        List<EmsBaseMonitorInfo> returnList = new ArrayList<EmsBaseMonitorInfo>();
        List<Long> tempList = baseMonitorInfruoyi.stream().map(EmsBaseMonitorInfo::getObjId).collect(Collectors.toList());
        for (EmsBaseMonitorInfo baseMonitorInfo : baseMonitorInfruoyi)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(baseMonitorInfo.getParentId()))
            {
                recursionFn(baseMonitorInfruoyi, baseMonitorInfo);
                returnList.add(baseMonitorInfo);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = baseMonitorInfruoyi;
        }
        return returnList;
    }
    /**
     * 递归列表
     */
    private void recursionFn(List<EmsBaseMonitorInfo> list, EmsBaseMonitorInfo t)
    {
        // 得到子节点列表
        List<EmsBaseMonitorInfo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (EmsBaseMonitorInfo tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<EmsBaseMonitorInfo> getChildList(List<EmsBaseMonitorInfo> list, EmsBaseMonitorInfo t)
    {
        List<EmsBaseMonitorInfo> tlist = new ArrayList<EmsBaseMonitorInfo>();
        Iterator<EmsBaseMonitorInfo> it = list.iterator();
        while (it.hasNext())
        {
            EmsBaseMonitorInfo n = (EmsBaseMonitorInfo) it.next();
            if (ObjectUtil.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getObjId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

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

}
