package com.ruoyi.system.service.impl;

import java.io.InputStream;
import java.util.List;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.FloodEmergencyPlan;
import com.ruoyi.system.mapper.FloodEmergencyPlanMapper;
import com.ruoyi.system.service.IFloodEmergencyPlanService;

/**
 * 应急预案库Service业务层处理
 *
 * @author jackeyhuang
 * @version 1.0.0
 * @date 2025-01-27
 */
@Service
public class FloodEmergencyPlanServiceImpl implements IFloodEmergencyPlanService
{
    private static final Logger log = LoggerFactory.getLogger(FloodEmergencyPlanServiceImpl.class);

    @Autowired
    private FloodEmergencyPlanMapper floodEmergencyPlanMapper;

    /**
     * 查询应急预案库
     *
     * @param planId 应急预案库主键
     * @return 应急预案库
     */
    @Override
    public FloodEmergencyPlan selectFloodEmergencyPlanByPlanId(Long planId)
    {
        return floodEmergencyPlanMapper.selectFloodEmergencyPlanByPlanId(planId);
    }

    /**
     * 查询应急预案库列表
     *
     * @param floodEmergencyPlan 应急预案库
     * @return 应急预案库
     */
    @Override
    public List<FloodEmergencyPlan> selectFloodEmergencyPlanList(FloodEmergencyPlan floodEmergencyPlan)
    {
        return floodEmergencyPlanMapper.selectFloodEmergencyPlanList(floodEmergencyPlan);
    }

    /**
     * 新增应急预案库
     *
     * @param floodEmergencyPlan 应急预案库
     * @return 结果
     */
    @Override
    public int insertFloodEmergencyPlan(FloodEmergencyPlan floodEmergencyPlan)
    {
        if (StringUtils.isEmpty(floodEmergencyPlan.getStatus()))
        {
            floodEmergencyPlan.setStatus("0");
        }
        return floodEmergencyPlanMapper.insertFloodEmergencyPlan(floodEmergencyPlan);
    }

    /**
     * 修改应急预案库
     *
     * @param floodEmergencyPlan 应急预案库
     * @return 结果
     */
    @Override
    public int updateFloodEmergencyPlan(FloodEmergencyPlan floodEmergencyPlan)
    {
        return floodEmergencyPlanMapper.updateFloodEmergencyPlan(floodEmergencyPlan);
    }

    /**
     * 批量删除应急预案库
     *
     * @param planIds 需要删除的应急预案库主键
     * @return 结果
     */
    @Override
    public int deleteFloodEmergencyPlanByPlanIds(Long[] planIds)
    {
        return floodEmergencyPlanMapper.deleteFloodEmergencyPlanByPlanIds(planIds);
    }

    /**
     * 删除应急预案库信息
     *
     * @param planId 应急预案库主键
     * @return 结果
     */
    @Override
    public int deleteFloodEmergencyPlanByPlanId(Long planId)
    {
        return floodEmergencyPlanMapper.deleteFloodEmergencyPlanByPlanId(planId);
    }

    /**
     * 导入应急预案数据
     *
     * @param file 上传的文件
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importEmergencyPlan(MultipartFile file, Boolean isUpdateSupport, String operName)
    {
        if (file == null || file.isEmpty())
        {
            throw new ServiceException("导入文件不能为空！");
        }
        
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        try (InputStream is = file.getInputStream())
        {
            Workbook workbook = WorkbookFactory.create(is);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个sheet
            
            // 跳过表头，从第二行开始读取
            for (int i = 1; i <= sheet.getLastRowNum(); i++)
            {
                Row row = sheet.getRow(i);
                if (row == null)
                {
                    continue;
                }
                
                try
                {
                    FloodEmergencyPlan plan = new FloodEmergencyPlan();
                    
                    // 读取预案等级（第1列，索引0）
                    String planLevel = getCellValue(row, 0);
                    plan.setPlanLevel(planLevel);
                    
                    // 读取预案名称（第2列，索引1）
                    String planName = getCellValue(row, 1);
                    if (StringUtils.isEmpty(planName))
                    {
                        failureNum++;
                        failureMsg.append("<br/>第" + (i + 1) + "行预案名称为空");
                        continue;
                    }
                    plan.setPlanName(planName);
                    
                    // 读取预案地址（第3列，索引2）
                    String planUrl = getCellValue(row, 2);
                    if (StringUtils.isEmpty(planUrl))
                    {
                        failureNum++;
                        failureMsg.append("<br/>第" + (i + 1) + "行预案地址为空");
                        continue;
                    }
                    plan.setPlanUrl(planUrl);
                    
                    plan.setStatus("0");
                    plan.setCreateBy(operName);
                    
                    // 检查是否已存在（根据预案名称）
                    List<FloodEmergencyPlan> existList = floodEmergencyPlanMapper.selectFloodEmergencyPlanList(plan);
                    if (existList != null && !existList.isEmpty() && isUpdateSupport)
                    {
                        // 更新
                        FloodEmergencyPlan existPlan = existList.get(0);
                        plan.setPlanId(existPlan.getPlanId());
                        plan.setUpdateBy(operName);
                        floodEmergencyPlanMapper.updateFloodEmergencyPlan(plan);
                        successNum++;
                        successMsg.append("<br/>第" + (i + 1) + "行预案 " + planName + " 更新成功");
                    }
                    else if (existList == null || existList.isEmpty())
                    {
                        // 新增
                        floodEmergencyPlanMapper.insertFloodEmergencyPlan(plan);
                        successNum++;
                        successMsg.append("<br/>第" + (i + 1) + "行预案 " + planName + " 导入成功");
                    }
                    else
                    {
                        failureNum++;
                        failureMsg.append("<br/>第" + (i + 1) + "行预案 " + planName + " 已存在");
                    }
                }
                catch (Exception e)
                {
                    failureNum++;
                    failureMsg.append("<br/>第" + (i + 1) + "行导入失败：" + e.getMessage());
                    log.error("导入应急预案第" + (i + 1) + "行失败", e);
                }
            }
        }
        catch (Exception e)
        {
            log.error("导入应急预案失败", e);
            throw new ServiceException("导入失败：" + e.getMessage());
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 获取单元格值
     *
     * @param row 行
     * @param columnIndex 列索引
     * @return 单元格值
     */
    private String getCellValue(Row row, int columnIndex)
    {
        if (row == null || row.getCell(columnIndex) == null)
        {
            return "";
        }
        try
        {
            return row.getCell(columnIndex).toString().trim();
        }
        catch (Exception e)
        {
            return "";
        }
    }

    /**
     * 统计应急预案总数
     *
     * @return 应急预案总数
     */
    @Override
    public int countFloodEmergencyPlan()
    {
        return floodEmergencyPlanMapper.countFloodEmergencyPlan();
    }
}
