package com.tongran.system.service.impl;

import com.tongran.common.core.domain.R;
import com.tongran.common.core.utils.DateUtils;
import com.tongran.common.core.utils.StringUtils;
import com.tongran.common.security.utils.SecurityUtils;
import com.tongran.system.domain.*;
import com.tongran.system.mapper.*;
import com.tongran.system.service.EpsInitialTrafficDataService;
import com.tongran.system.service.IEpsServerRevenueConfigService;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 服务器收益方式配置Service业务层处理
 * 
 * @author tongran
 * @date 2025-08-19
 */
@Service
@Slf4j
public class EpsServerRevenueConfigServiceImpl implements IEpsServerRevenueConfigService 
{
    @Autowired
    private EpsServerRevenueConfigMapper epsServerRevenueConfigMapper;
    @Autowired
    private EpsInitialTrafficDataService epsInitialTrafficDataService;
    @Autowired
    private EpsMethodChangeRecordMapper epsMethodChangeRecordMapper;
    @Autowired
    private AllInterfaceNameMapper allInterfaceNameMapper;
    @Autowired
    private RmResourceRegistrationMapper rmResourceRegistrationMapper;
    @Autowired
    private EpsBusinessMapper epsBusinessMapper;

    /**
     * 查询服务器收益方式配置
     * 
     * @param id 服务器收益方式配置主键
     * @return 服务器收益方式配置
     */
    @Override
    public EpsServerRevenueConfig selectEpsServerRevenueConfigById(Long id)
    {
        return epsServerRevenueConfigMapper.selectEpsServerRevenueConfigById(id);
    }

    /**
     * 查询服务器收益方式配置列表
     * 
     * @param epsServerRevenueConfig 服务器收益方式配置
     * @return 服务器收益方式配置
     */
    @Override
    public List<EpsServerRevenueConfig> selectEpsServerRevenueConfigList(EpsServerRevenueConfig epsServerRevenueConfig)
    {
        return epsServerRevenueConfigMapper.selectEpsServerRevenueConfigList(epsServerRevenueConfig);
    }

    /**
     * 新增服务器收益方式配置
     * 
     * @param epsServerRevenueConfig 服务器收益方式配置
     * @return 结果
     */
    @Override
    public int insertEpsServerRevenueConfig(EpsServerRevenueConfig epsServerRevenueConfig)
    {
        epsServerRevenueConfig.setCreateTime(DateUtils.getNowDate());
        return epsServerRevenueConfigMapper.insertEpsServerRevenueConfig(epsServerRevenueConfig);
    }

    /**
     * 修改服务器收益方式配置
     * 
     * @param epsServerRevenueConfig 服务器收益方式配置
     * @return 结果
     */
    @Override
    public int updateEpsServerRevenueConfig(EpsServerRevenueConfig epsServerRevenueConfig)
    {
        epsServerRevenueConfig.setUpdateTime(DateUtils.getNowDate());
        //原来的收益方式
        EpsServerRevenueConfig serverRevenueConfig = epsServerRevenueConfigMapper.selectEpsServerRevenueConfigById(epsServerRevenueConfig.getId());
        String revenueMethod = getMethodName(serverRevenueConfig.getRevenueMethod());
        //现在的收益方式
        String nowRevenueMethod = getMethodName(epsServerRevenueConfig.getRevenueMethod());
        if(serverRevenueConfig.getBusinessCode() != null){
            if(!serverRevenueConfig.getBusinessCode().equals(epsServerRevenueConfig.getBusinessCode())){
                epsServerRevenueConfig.setChanged("1");
            }
        }
        // 修改条数
        int rows = epsServerRevenueConfigMapper.updateEpsServerRevenueConfig(epsServerRevenueConfig);
        if(rows>=0){
            // 添加操作记录
            addRecord(epsServerRevenueConfig);
            // 添加包端数据到相关数据表
            saveServiceTrafficData(epsServerRevenueConfig);
        }
        return rows;
    }
    /**
     * 添加服务器配置操作记录
     */
    private void addRecord(EpsServerRevenueConfig epsServerRevenueConfig) {
        String nowRevenueMethod = getMethodName(epsServerRevenueConfig.getRevenueMethod());
        EpsMethodChangeRecord changeRecord = new EpsMethodChangeRecord();
        // 设置基本信息
        changeRecord.setNodeName(epsServerRevenueConfig.getNodeName());
        changeRecord.setHardwareSn(epsServerRevenueConfig.getHardwareSn());
        changeRecord.setCreateTime(DateUtils.getNowDate());
        changeRecord.setCreatBy(SecurityUtils.getUsername());
        // 修改内容
        String content = "";
        if("流量".equals(nowRevenueMethod)){
            // 修改内容
            content = "收益方式变为【"+nowRevenueMethod+"】,流量网口设置为"+epsServerRevenueConfig.getTrafficPort()+
                    ",业务为"+epsServerRevenueConfig.getBusinessName();
        }
        if("包端".equals(nowRevenueMethod)){
            // 修改内容
            content = "收益方式变为【"+nowRevenueMethod+"】,流量网口设置为"+epsServerRevenueConfig.getTrafficPort()+
                    ",带宽值设置为"+epsServerRevenueConfig.getPackageBandwidth()+"Mbps,"+"业务为"+epsServerRevenueConfig.getBusinessName();
        }
        changeRecord.setChangeContent(content);
        changeRecord.setBusinessCode(epsServerRevenueConfig.getBusinessCode());
        changeRecord.setBusinessName(epsServerRevenueConfig.getBusinessName());
        changeRecord.setRevenueMethod(epsServerRevenueConfig.getRevenueMethod());
        changeRecord.setPackageBandwidth(epsServerRevenueConfig.getPackageBandwidth());
        changeRecord.setTrafficPort(epsServerRevenueConfig.getTrafficPort());
        // 添加操作记录
        epsMethodChangeRecordMapper.insertEpsMethodChangeRecord(changeRecord);
    }

    /**
     * 保存流量信息
     * @param epsServerRevenueConfig
     */
    private void saveServiceTrafficData(EpsServerRevenueConfig epsServerRevenueConfig) {
        // 初始流量数据
        EpsInitialTrafficData epsInitialTrafficData = new EpsInitialTrafficData();
        epsInitialTrafficData.setServiceSn(epsServerRevenueConfig.getHardwareSn());
        epsInitialTrafficData.setBusinessId(epsServerRevenueConfig.getBusinessCode());
        epsInitialTrafficData.setBusinessName(epsServerRevenueConfig.getBusinessName());
        epsInitialTrafficData.setName(epsServerRevenueConfig.getTrafficPort());
        epsInitialTrafficData.setPackageBandwidth(epsServerRevenueConfig.getPackageBandwidth());
        epsInitialTrafficData.setRevenueMethod(epsServerRevenueConfig.getRevenueMethod());
        epsInitialTrafficData.setNodeName(epsServerRevenueConfig.getNodeName());
        epsInitialTrafficData.setStartTime(epsServerRevenueConfig.getCreateTime() + "");
        epsInitialTrafficData.setEndTime(epsServerRevenueConfig.getCreateTime() + "");
        epsInitialTrafficDataService.save(epsInitialTrafficData);

    }

    /**
     * 保存流量信息
     * @param epsServerRevenueConfig
     */
    @Override
    public R<String> autoSaveServiceTrafficData(EpsServerRevenueConfig epsServerRevenueConfig) {
        // 查询初始流量数据
        EpsInitialTrafficData epsInitialTrafficData = new EpsInitialTrafficData();
        epsInitialTrafficData.setStartTime(epsServerRevenueConfig.getStartTime());
        epsInitialTrafficData.setEndTime(epsServerRevenueConfig.getEndTime());
        List<EpsInitialTrafficData> dataList = epsInitialTrafficDataService.getAllTraficMsg(epsInitialTrafficData);

        if (dataList == null || dataList.isEmpty()) {
            return R.ok("没有需要处理的数据");
        }

        List<EpsInitialTrafficData> batchList = new ArrayList<>();
        int batchSize = 1000; // 每批处理数量
        int totalCount = 0;
        int successCount = 0;
        int batchNumber = 0;

        try {
            for (EpsInitialTrafficData initialTrafficData : dataList) {
                // 根据clientId查询业务名称
                RmResourceRegistration rmResourceRegistration = new RmResourceRegistration();
                rmResourceRegistration.setClientId(initialTrafficData.getClientId());
                List<RmResourceRegistration> registerLst = rmResourceRegistrationMapper.selectRmResourceRegistrationList(rmResourceRegistration);

                if(registerLst != null && !registerLst.isEmpty()){
                    RmResourceRegistration registerMsg = registerLst.get(0);
                    // 赋值
                    if(registerMsg != null){
                        String businessName = registerMsg.getBusinessName();
                        if(businessName != null){
                            initialTrafficData.setBusinessName(businessName);
                            // 根据业务名称查询业务代码
                            EpsBusiness epsBusiness = epsBusinessMapper.selectEpsBusinessByName(businessName);
                            if(epsBusiness != null){
                                initialTrafficData.setBusinessId(epsBusiness.getId());
                            }
                        }
                        initialTrafficData.setServiceSn(registerMsg.getHardwareSn());
                        initialTrafficData.setRevenueMethod("1");
                    }
                }
                // id自增
                initialTrafficData.setId(null);
                batchList.add(initialTrafficData);

                // 达到批次大小时保存
                if (batchList.size() >= batchSize) {
                    batchNumber++;
                    totalCount += batchList.size();
                    epsInitialTrafficData.setDataList(batchList);
                    epsInitialTrafficDataService.saveBatch(epsInitialTrafficData);
                    log.info("第{}批流量数据批量入库成功，数据量：{}", batchNumber, batchList.size());

                    // 处理接口名称
                    processInterfaceNames(batchList);

                    successCount += batchList.size();
                    // 清空当前批次，准备下一批
                    batchList = new ArrayList<>();
                }
            }

            // 处理最后一批不足1000条的数据
            if (!batchList.isEmpty()) {
                batchNumber++;
                totalCount += batchList.size();
                epsInitialTrafficData.setDataList(batchList);
                epsInitialTrafficDataService.saveBatch(epsInitialTrafficData);
                log.info("第{}批流量数据批量入库成功，数据量：{}", batchNumber, batchList.size());

                // 处理最后一批的接口名称
                processInterfaceNames(batchList);

                successCount += batchList.size();
            }

            log.info("流量数据批量入库完成，总批次数：{}，总数据量：{}，成功数量：{}",
                    batchNumber, totalCount, successCount);

            if (successCount == totalCount) {
                return R.ok("数据保存成功，共处理" + successCount + "条数据");
            } else {
                return R.fail("数据保存部分成功，应处理" + totalCount + "条，实际成功" + successCount + "条");
            }

        } catch (Exception e) {
            log.error("流量数据入库失败，已处理批次：{}，成功数量：{}，当前批次数量：{}，错误原因：{}",
                    batchNumber, successCount, batchList.size(), e.getMessage(), e);
            return R.fail("数据保存失败：" + e.getMessage() + "，已成功保存" + successCount + "条");
        }
    }
    /**
     * 当前在线服务器的流量相关的业务数
     * @return
     */
    @Override
    public Integer countBusinessByTraffic() {
        return epsServerRevenueConfigMapper.countBusinessByTraffic();
    }
    /**
     * 当日业务的在线设备数量统计TOP5
     * @return
     */
    @Override
    public List<Map> countDeviceNumTop5() {
        return epsServerRevenueConfigMapper.countDeviceNumTop5();
    }

    private static String getNullableString(Map<String, Object> map, String key) {
        Object value = map.get(key);
        return value != null ? value.toString() : null;
    }
    private String getCompositeKey(String clientId, String interfaceName) {
        return clientId + "|" + interfaceName;
    }
    /**
     * 批量处理接口名称
     */
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public void processInterfaceNames(List<EpsInitialTrafficData> trafficDataList) {
        if (CollectionUtils.isEmpty(trafficDataList)) {
            return;
        }

        // 直接转换并过滤
        List<AllInterfaceName> records = new ArrayList<>();
        for (EpsInitialTrafficData data : trafficDataList) {
            if (isValidData(data)) {
                records.add(convertToInterfaceName(data));
            }
        }

        if (!records.isEmpty()) {
            // 排序防止死锁
            records.sort(Comparator
                    .comparing(AllInterfaceName::getInterfaceName)
                    .thenComparing(AllInterfaceName::getClientId)
                    .thenComparing(AllInterfaceName::getServerIp)
                    .thenComparing(AllInterfaceName::getResourceType));

            allInterfaceNameMapper.batchInsert(records);
            log.info("批量处理完成，记录数: {}", records.size());
        }
    }
    private boolean isValidData(EpsInitialTrafficData data) {
        return StringUtils.isNotBlank(data.getName())
                && StringUtils.isNotBlank(data.getMac())
                && StringUtils.isNotBlank(data.getClientId());
    }

    private AllInterfaceName convertToInterfaceName(EpsInitialTrafficData data) {
        AllInterfaceName record = new AllInterfaceName();
        record.setInterfaceName(data.getName());
        record.setClientId(data.getClientId());
        record.setResourceType("1");
        record.setDeviceSn(data.getServiceSn());
        record.setNodeName(data.getNodeName());
        record.setBusinessCode(data.getBusinessId());
        record.setBusinessName(data.getBusinessName());
        record.setServerIp(data.getMac());

        return record;
    }
    /**
     * 批量删除服务器收益方式配置
     * 
     * @param ids 需要删除的服务器收益方式配置主键
     * @return 结果
     */
    @Override
    public int deleteEpsServerRevenueConfigByIds(Long[] ids)
    {
        return epsServerRevenueConfigMapper.deleteEpsServerRevenueConfigByIds(ids);
    }

    /**
     * 删除服务器收益方式配置信息
     * 
     * @param id 服务器收益方式配置主键
     * @return 结果
     */
    @Override
    public int deleteEpsServerRevenueConfigById(Long id)
    {
        return epsServerRevenueConfigMapper.deleteEpsServerRevenueConfigById(id);
    }
    /**
     * 把收益方式转化为文字
     * @param method
     * @return
     */
    public String getMethodName(String method){
        String revenueMethod = "";
        if("1".equals(method)){
            revenueMethod = "流量";
        }
        if("2".equals(method)){
            revenueMethod = "包端";
        }
        return revenueMethod;
    }

}
