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

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.ems.base.domain.EmsAlarmActionStep;
import org.dromara.ems.base.domain.EmsAlarmActionStepImage;
import org.dromara.ems.base.mapper.EmsAlarmActionStepImageMapper;
import org.dromara.ems.base.mapper.EmsAlarmActionStepMapper;
import org.dromara.ems.base.service.IEmsAlarmActionStepService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.net.URLDecoder;
import java.util.List;

/**
 * 报警规则具体措施步骤Service业务层处理
 * 
 * @author zch
 * @date 2025-05-29
 */
@Service
@RequiredArgsConstructor
public class EmsAlarmActionStepServiceImpl implements IEmsAlarmActionStepService 
{
    
    private final EmsAlarmActionStepMapper emsAlarmActionStepMapper;

    
    private final EmsAlarmActionStepImageMapper emsAlarmActionStepImageMapper;

    /**
     * 文件上传路径配置
     */
    @Value("${ruoyi.compat.upload-path:${user.dir}/uploadPath}")
    private String uploadPath;


    /**
     * 查询报警规则具体措施步骤
     * 
     * @param objId 报警规则具体措施步骤主键
     * @return 报警规则具体措施步骤
     */
    @Override
    public EmsAlarmActionStep selectEmsAlarmActionStepByObjId(String objId)
    {
        return emsAlarmActionStepMapper.selectEmsAlarmActionStepByObjId(objId);
    }

    /**
     * 查询报警规则具体措施步骤列表
     * 
     * @param emsAlarmActionStep 报警规则具体措施步骤
     * @return 报警规则具体措施步骤
     */
    @Override
    public List<EmsAlarmActionStep> selectEmsAlarmActionStepList(EmsAlarmActionStep emsAlarmActionStep)
    {
        return emsAlarmActionStepMapper.selectEmsAlarmActionStepList(emsAlarmActionStep);
    }

    /**
     * 新增报警规则具体措施步骤
     * 
     * @param emsAlarmActionStep 报警规则具体措施步骤
     * @return 结果
     */
    @Override
    public int insertEmsAlarmActionStep(EmsAlarmActionStep emsAlarmActionStep)
    {
        emsAlarmActionStep.setCreateTime(DateUtils.getNowDate());
        return emsAlarmActionStepMapper.insertEmsAlarmActionStep(emsAlarmActionStep);
    }

    /**
     * 修改报警规则具体措施步骤
     * 
     * @param emsAlarmActionStep 报警规则具体措施步骤
     * @return 结果
     */
    @Override
    public int updateEmsAlarmActionStep(EmsAlarmActionStep emsAlarmActionStep)
    {
        emsAlarmActionStep.setUpdateTime(DateUtils.getNowDate());
        return emsAlarmActionStepMapper.updateEmsAlarmActionStep(emsAlarmActionStep);
    }

    /**
     * 批量删除报警规则具体措施步骤
     * 
     * @param objIds 需要删除的报警规则具体措施步骤主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEmsAlarmActionStepByObjIds(String[] objIds)
    {
        try {
            int result = 0;
            for (String objId : objIds) {
                result += deleteEmsAlarmActionStepByObjId(objId);
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException("批量删除措施步骤失败: " + e.getMessage(), e);
        }
    }

    /**
     * 删除报警规则具体措施步骤信息（级联删除关联的图片文件）
     * 
     * @param objId 报警规则具体措施步骤主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEmsAlarmActionStepByObjId(String objId)
    {
        try {
            // 1. 查询要删除的措施步骤信息
            EmsAlarmActionStep actionStep = emsAlarmActionStepMapper.selectEmsAlarmActionStepByObjId(objId);
            if (actionStep == null) {
                throw new RuntimeException("措施步骤不存在 ");
            }
            
            // 2. 删除该步骤关联的所有图片文件
            EmsAlarmActionStepImage imageQuery = new EmsAlarmActionStepImage();
            imageQuery.setActionStepObjId(objId);
            List<EmsAlarmActionStepImage> images = emsAlarmActionStepImageMapper.selectEmsAlarmActionStepImageList(imageQuery);
            
            if (images != null && !images.isEmpty()) {
                for (EmsAlarmActionStepImage image : images) {
                    try {
                        // 删除物理文件
                        deleteImageFile(image.getImageUrl());
                        // 删除数据库记录
                        emsAlarmActionStepImageMapper.deleteEmsAlarmActionStepImageByObjId(image.getObjId());
                    } catch (Exception e) {
                        throw new RuntimeException("删除措施步骤图片失败，导致事务回滚: " + e.getMessage(), e);
                    }
                }
                System.out.println("删除措施步骤 " + actionStep.getDescription() + " 关联的 " + images.size() + " 张图片");
            }
            
            // 3. 最后删除措施步骤本身
            int result = emsAlarmActionStepMapper.deleteEmsAlarmActionStepByObjId(objId);

            if (result > 0) {
                System.out.println("成功删除措施步骤: " + actionStep.getDescription() + " (ID: " + objId + ")");
            }
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("删除措施步骤失败: " + e.getMessage(), e);
        }
    }

    /**
     * 根据报警规则ID查询措施步骤列表（包含图片信息）
     * 
     * @param ruleObjId 报警规则ID
     * @return 措施步骤列表
     */
    @Override
    public List<EmsAlarmActionStep> selectEmsAlarmActionStepByRuleObjId(String ruleObjId)
    {
        return emsAlarmActionStepMapper.selectEmsAlarmActionStepByRuleObjId(ruleObjId);
    }

    /**
     * 根据报警数据信息查询对应的措施步骤列表
     * 
     * @param monitorId 设备编号
     * @param cause 异常原因
     * @return 措施步骤列表
     */
    @Override
    public List<EmsAlarmActionStep> selectActionStepsByAlarmInfo(String monitorId, String cause)
    {
        return emsAlarmActionStepMapper.selectActionStepsByAlarmInfo(monitorId, cause);
    }

    /**
     * 批量保存措施步骤（包含图片信息）
     * 
     * @param ruleObjId 报警规则ID
     * @param stepList 措施步骤列表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchSaveActionSteps(String ruleObjId, List<EmsAlarmActionStep> stepList)
    {
        if (ObjectUtil.isEmpty(ruleObjId) || stepList == null || stepList.isEmpty()) {
            return 0;
        }
        
        try {
            // 1. 先删除该规则下的所有现有步骤和图片（包括物理文件）
            List<EmsAlarmActionStep> existingSteps = emsAlarmActionStepMapper.selectEmsAlarmActionStepByRuleObjId(ruleObjId);
            for (EmsAlarmActionStep existingStep : existingSteps) {
                // 删除步骤关联的图片
                EmsAlarmActionStepImage imageQuery = new EmsAlarmActionStepImage();
                imageQuery.setActionStepObjId(existingStep.getObjId());
                List<EmsAlarmActionStepImage> existingImages = emsAlarmActionStepImageMapper.selectEmsAlarmActionStepImageList(imageQuery);
                for (EmsAlarmActionStepImage image : existingImages) {
                    try {
                        deleteImageFile(image.getImageUrl());
                        emsAlarmActionStepImageMapper.deleteEmsAlarmActionStepImageByObjId(image.getObjId());
                    } catch (Exception e) {
                        throw new RuntimeException("文件删除失败，导致事务回滚: " + e.getMessage(), e);
                    }
                }
                // 删除步骤
                emsAlarmActionStepMapper.deleteEmsAlarmActionStepByObjId(existingStep.getObjId());
            }
            
            // 2. 保存新的步骤和图片
            int result = 0;
            for (EmsAlarmActionStep step : stepList) {
                // 生成步骤ID
                if (ObjectUtil.isEmpty(step.getObjId())) {
                    step.setObjId(IdUtil.fastSimpleUUID());
                }
                step.setRuleObjId(ruleObjId);
                step.setCreateTime(DateUtils.getNowDate());
                
                // 保存步骤
                result += emsAlarmActionStepMapper.insertEmsAlarmActionStep(step);
                
                // 保存步骤关联的图片
                if (step.getStepImages() != null && !step.getStepImages().isEmpty()) {
                    for (EmsAlarmActionStepImage image : step.getStepImages()) {
                        if (ObjectUtil.isEmpty(image.getObjId())) {
                            image.setObjId(IdUtil.fastSimpleUUID());
                        }
                        image.setActionStepObjId(step.getObjId());
                        image.setCreateTime(DateUtils.getNowDate());
                        emsAlarmActionStepImageMapper.insertEmsAlarmActionStepImage(image);
                    }
                }
            }
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("批量保存措施步骤失败: " + e.getMessage(), e);
        }
    }

    /**
     * 删除图片物理文件
     * 
     * @param imageUrl 图片URL
     */
    private void deleteImageFile(String imageUrl) {
        if (ObjectUtil.isEmpty(imageUrl) || ObjectUtil.isEmpty(uploadPath)) {
            return;
        }
        
        try {
            // 解析图片URL，获取相对路径
            // 例如：/profile/upload/2024/05/29/xxx.jpg -> upload/2024/05/29/xxx.jpg
            String relativePath = null;
            if (imageUrl.startsWith("/profile/")) {
                relativePath = imageUrl.substring("/profile/".length());
            } else if (imageUrl.contains("/upload/")) {
                int uploadIndex = imageUrl.indexOf("/upload/");
                relativePath = imageUrl.substring(uploadIndex + 1); // 去掉前面的"/"
            }
            
            if (ObjectUtil.isNotEmpty(relativePath)) {
                // URL解码，处理中文文件名
                relativePath = URLDecoder.decode(relativePath, "UTF-8");
                
                // 构建完整的文件路径
                String fullPath = uploadPath + File.separator + relativePath.replace("/", File.separator);
                File file = new File(fullPath);
                
                if (file.exists() && file.isFile()) {
                    boolean deleted = file.delete();
                    if (deleted) {
                        System.out.println("成功删除图片文件: " + fullPath);
                    } else {
                        System.err.println("删除图片文件失败: " + fullPath);
                    }
                } else {
                    System.out.println("图片文件不存在，无需删除: " + fullPath);
                }
            }
        } catch (Exception e) {
            System.err.println("删除图片文件时发生异常: " + imageUrl + ", 错误信息: " + e.getMessage());
        }
    }
}
