package com.tongran.rocketmq.service.impl;

import com.tongran.common.core.utils.DateUtils;
import com.tongran.common.core.utils.EchartsDataUtils;
import com.tongran.common.core.utils.TableSubUtil;
import com.tongran.rocketmq.domain.InitialSwitchOpticalModule;
import com.tongran.rocketmq.mapper.InitialSwitchOpticalModuleMapper;
import com.tongran.rocketmq.service.IAllMoudleNameService;
import com.tongran.rocketmq.service.IInitialSwitchOpticalModuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 光模块信息Service业务层处理
 * 
 * @author tongran
 * @date 2025-09-22
 */
@Service
@Slf4j
public class InitialSwitchOpticalModuleServiceImpl implements IInitialSwitchOpticalModuleService 
{
    @Autowired
    private InitialSwitchOpticalModuleMapper initialSwitchOpticalModuleMapper;
    @Autowired
    private IAllMoudleNameService allMoudleNameService;

    private final static String TABLE_PREFIX = "initial_switch_optical_module";

    /**
     * 查询光模块信息
     * 
     * @param id 光模块信息主键
     * @return 光模块信息
     */
    @Override
    public InitialSwitchOpticalModule selectInitialSwitchOpticalModuleById(Long id)
    {
        return initialSwitchOpticalModuleMapper.selectInitialSwitchOpticalModuleById(id);
    }

    /**
     * 查询光模块信息列表
     * 
     * @param initialSwitchOpticalModule 光模块信息
     * @return 光模块信息
     */
    @Override
    public List<InitialSwitchOpticalModule> selectInitialSwitchOpticalModuleList(InitialSwitchOpticalModule initialSwitchOpticalModule)
    {
        return initialSwitchOpticalModuleMapper.selectInitialSwitchOpticalModuleList(initialSwitchOpticalModule);
    }

    /**
     * 新增光模块信息
     * 
     * @param initialSwitchOpticalModule 光模块信息
     * @return 结果
     */
    @Override
    public int insertInitialSwitchOpticalModule(InitialSwitchOpticalModule initialSwitchOpticalModule)
    {
        return initialSwitchOpticalModuleMapper.insertInitialSwitchOpticalModule(initialSwitchOpticalModule);
    }

    /**
     * 修改光模块信息
     * 
     * @param initialSwitchOpticalModule 光模块信息
     * @return 结果
     */
    @Override
    public int updateInitialSwitchOpticalModule(InitialSwitchOpticalModule initialSwitchOpticalModule)
    {
        initialSwitchOpticalModule.setUpdateTime(DateUtils.getNowDate());
        return initialSwitchOpticalModuleMapper.updateInitialSwitchOpticalModule(initialSwitchOpticalModule);
    }

    /**
     * 批量删除光模块信息
     * 
     * @param ids 需要删除的光模块信息主键
     * @return 结果
     */
    @Override
    public int deleteInitialSwitchOpticalModuleByIds(Long[] ids)
    {
        return initialSwitchOpticalModuleMapper.deleteInitialSwitchOpticalModuleByIds(ids);
    }

    /**
     * 删除光模块信息信息
     * 
     * @param id 光模块信息主键
     * @return 结果
     */
    @Override
    public int deleteInitialSwitchOpticalModuleById(Long id)
    {
        return initialSwitchOpticalModuleMapper.deleteInitialSwitchOpticalModuleById(id);
    }

    /**
     * 分表查询服务器其他信息
     * @param queryParam
     * @return
     */
    public List<InitialSwitchOpticalModule> getSwitchOpticalModuleSharding(InitialSwitchOpticalModule queryParam) {
        // 获取涉及的表名
        Set<String> tableNames = TableSubUtil.getExistingTableNamesBetween(queryParam.getStartTime(), queryParam.getEndTime(), TABLE_PREFIX);

        // 并行查询各表
        return tableNames.parallelStream()
                .flatMap(tableName -> {
                    InitialSwitchOpticalModule condition = new InitialSwitchOpticalModule();
                    condition.setTableName(tableName);
                    condition.setClientId(queryParam.getClientId());
                    condition.setFiberPortName(queryParam.getFiberPortName());
                    condition.setStartTime(queryParam.getStartTime());
                    condition.setEndTime(queryParam.getEndTime());
                    return initialSwitchOpticalModuleMapper.selectInitialSwitchOpticalModuleList(condition).stream();
                })
                .collect(Collectors.toList());
    }
    /**
     * 批量新增光模块信息
     * @param list
     */
    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public int batchInitialSwitchOpticalModule(List<InitialSwitchOpticalModule> list, Date createTime) {
        if (list == null || list.isEmpty()) {
            return 0;
        }
        // 按表名分组批量插入
        Map<String, List<InitialSwitchOpticalModule>> groupedData = list.stream()
                .map(data -> {
                    try {
                        InitialSwitchOpticalModule processed = new InitialSwitchOpticalModule();
                        BeanUtils.copyProperties(data,processed);
                        if (data.getCreateTime() == null) {
                            data.setCreateTime(DateUtils.getNowDate());
                        }
                        processed.setTableName(TableSubUtil.getTableName(createTime, TABLE_PREFIX));
                        return processed;
                    } catch (Exception e){
                        log.error("数据处理失败",e.getMessage());
                        return null;
                    }
                }).collect(Collectors.groupingBy(
                        InitialSwitchOpticalModule::getTableName,
                        LinkedHashMap::new, // 保持插入顺序
                        Collectors.toList()));

        groupedData.forEach((tableName, dataList) -> {
            try {
                InitialSwitchOpticalModule data = new InitialSwitchOpticalModule();
                data.setTableName(tableName);
                data.setList(dataList);
                initialSwitchOpticalModuleMapper.batchInitialSwitchOpticalModule(data);
                // 记录光模块名称
                allMoudleNameService.batchInsertMoudleName(dataList);
            } catch (Exception e) {
                log.error("表{}插入失败", tableName, e);
                throw new RuntimeException("批量插入失败", e);
            }
        });
        return 1;
    }

    /**
     * 光模块基础信息
     * @param initialSwitchOpticalModule
     * @return
     */
    @Override
    public List<InitialSwitchOpticalModule> switchOpticalModuleMsg(InitialSwitchOpticalModule initialSwitchOpticalModule) {
        String tableName = TableSubUtil.getTableName(DateUtils.getNowDate(), TABLE_PREFIX);
        initialSwitchOpticalModule.setTableName(tableName);
        return initialSwitchOpticalModuleMapper.switchOpticalModuleMsg(initialSwitchOpticalModule);
    }

    /**
     * 光模块名称查询
     * @param initialSwitchOpticalModule
     * @return
     */
    @Override
    public List<Map> getAllModuleName(InitialSwitchOpticalModule initialSwitchOpticalModule) {
        return initialSwitchOpticalModuleMapper.getAllModuleName(initialSwitchOpticalModule);
    }

    /**
     * 光衰阈值
     * @param initialSwitchOpticalModule
     * @return
     */
    @Override
    public Map<String, Object> opticalModuleLowThreshold(InitialSwitchOpticalModule initialSwitchOpticalModule) {
        List<InitialSwitchOpticalModule> list = getSwitchOpticalModuleSharding(initialSwitchOpticalModule);
        Map<String, Function<InitialSwitchOpticalModule, ?>> extractors = new LinkedHashMap<>();
        extractors.put("TxLowThreshold", info -> info.getHwEntityOpticalTxLowThreshold());
        extractors.put("RxLowThreshold", info -> info.getHwEntityOpticalRxLowThreshold());
        return EchartsDataUtils.buildEchartsData(list, InitialSwitchOpticalModule::getCreateTime, extractors);
    }

    /**
     * 功率
     * @param initialSwitchOpticalModule
     * @return
     */
    @Override
    public Map<String, Object> opticalModulePower(InitialSwitchOpticalModule initialSwitchOpticalModule) {
        List<InitialSwitchOpticalModule> list = getSwitchOpticalModuleSharding(initialSwitchOpticalModule);
        Map<String, Function<InitialSwitchOpticalModule, ?>> extractors = new LinkedHashMap<>();
        extractors.put("TxPower", info -> info.getHwEntityOpticalTxPower());
        extractors.put("RxPower", info -> info.getHwEntityOpticalRxPower());
        return EchartsDataUtils.buildEchartsData(list, InitialSwitchOpticalModule::getCreateTime, extractors);
    }
}
