package com.ruoyi.ems.service.impl;

import com.ruoyi.ems.domain.OpEnergyStrategy;
import com.ruoyi.ems.mapper.OpEnergyStrategyMapper;
import com.ruoyi.ems.service.IOpEnergyStrategyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 能源策略Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-08
 */
@Service
public class OpEnergyStrategyServiceImpl implements IOpEnergyStrategyService {
    @Autowired
    private OpEnergyStrategyMapper strategyMapper;

    @Override
    public List<OpEnergyStrategy> selectStrategyList(OpEnergyStrategy strategy) {
        return strategyMapper.selectStrategyList(strategy);
    }

    @Override
    public OpEnergyStrategy selectStrategyById(Long id) {
        return strategyMapper.selectStrategyById(id);
    }

    @Override
    public OpEnergyStrategy selectStrategyByCode(String strategyCode) {
        return strategyMapper.selectStrategyByCode(strategyCode);
    }

    @Override
    public int insertStrategy(OpEnergyStrategy strategy) {
        return strategyMapper.insertStrategy(strategy);
    }

    @Override
    public int updateStrategy(OpEnergyStrategy strategy) {
        return strategyMapper.updateStrategy(strategy);
    }

    @Override
    public int deleteStrategyById(Long id) {
        return strategyMapper.deleteStrategyById(id);
    }

    @Override
    public int deleteStrategyByIds(Long[] ids) {
        return strategyMapper.deleteStrategyByIds(ids);
    }

    @Override
    public List<OpEnergyStrategy> selectScheduledStrategies() {
        return strategyMapper.selectScheduledStrategies();
    }

    /**
     * 获取场景类型统计（带区块过滤）
     * @param areaCode 区块代码
     * @return 场景类型统计Map
     */
    public Map<String, Long> getSceneTypeCount(String areaCode) {
        List<Map<String, Object>>  list = strategyMapper.selectSceneTypeCountByArea(areaCode);;

        Map<String, Long> result = new LinkedHashMap<>();
        long total = 0L;

        // 初始化所有场景类型为0
        result.put("PV_ESS", 0L);
        result.put("DEMAND_RESP", 0L);
        result.put("PEAK_VALLEY", 0L);
        result.put("EMERGENCY", 0L);
        result.put("ENERGY_SAVE", 0L);

        // 填充实际统计数据
        for (Map<String, Object> item : list) {
            String sceneType = (String) item.get("sceneType");
            Long count = ((Number) item.get("count")).longValue();

            if (StringUtils.isNotBlank(sceneType) && !"UNKNOWN".equals(sceneType)) {
                result.put(sceneType, count);
            }
            total += count;
        }

        // 添加总数
        result.put("ALL", total);

        return result;
    }
}
