package com.ruoyi.system.controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.EpsInitialTrafficData;
import com.ruoyi.system.domain.EpsNodeBandwidth;
import com.ruoyi.system.domain.InitialSwitchInfoDetails;
import com.ruoyi.system.service.EpsInitialTrafficDataService;
import com.ruoyi.system.service.IEpsNodeBandwidthService;
import com.ruoyi.system.service.IInitialSwitchInfoDetailsService;
import com.ruoyi.system.util.CalculateUtil;
import com.ruoyi.system.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.webjars.NotFoundException;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * 节点带宽信息Controller
 * 
 * @author gyt
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/bandwidth")
@Slf4j
public class EpsNodeBandwidthController extends BaseController
{
    private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
    @Autowired
    private IEpsNodeBandwidthService epsNodeBandwidthService;
    @Autowired
    private IInitialSwitchInfoDetailsService initialSwitchInfoDetailsService;
    @Autowired
    private EpsInitialTrafficDataService epsInitialTrafficDataService;

    /**
     * 查询节点带宽信息列表
     */
    @RequiresPermissions("system:bandwidth:list")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {

        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageNum(epsNodeBandwidth.getPageNum());
        pageDomain.setPageSize(epsNodeBandwidth.getPageSize());
        startPage(pageDomain);
        // 获取时间类型 1--日， 2--月
        if(epsNodeBandwidth.getBandwidthType() != null){
            String type = CalculateUtil.getTypeByBandwidthType(epsNodeBandwidth.getBandwidthType());
            // 获取开始时间 结束时间
            DateUtil.TimeRange startTimeRange = DateUtil.getTimeRange(DateUtils.parseDate(epsNodeBandwidth.getStartTime()),type);
            DateUtil.TimeRange endTimeRange = DateUtil.getTimeRange(DateUtils.parseDate(epsNodeBandwidth.getEndTime()),type);
            String startTime = startTimeRange.getStart();
            String endTime = endTimeRange.getEnd();
            epsNodeBandwidth.setStartTime(startTime);
            epsNodeBandwidth.setEndTime(endTime);
        }
        List<EpsNodeBandwidth> list = epsNodeBandwidthService.selectEpsNodeBandwidthList(epsNodeBandwidth);
        return getDataTable(list);
    }

    /**
     * 导出节点带宽信息列表
     */
    @RequiresPermissions("system:bandwidth:export")
    @Log(title = "节点带宽信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        List<EpsNodeBandwidth> list = epsNodeBandwidthService.selectEpsNodeBandwidthList(epsNodeBandwidth);
        ExcelUtil<EpsNodeBandwidth> util = new ExcelUtil<EpsNodeBandwidth>(EpsNodeBandwidth.class);
        util.showColumn(epsNodeBandwidth.getProperties());
        util.exportExcel(response, list, "节点带宽信息数据");
    }

    /**
     * 获取节点带宽信息详细信息
     */
    @RequiresPermissions("system:bandwidth:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(epsNodeBandwidthService.selectEpsNodeBandwidthById(id));
    }

    /**
     * 新增节点带宽信息
     */
    @RequiresPermissions("system:bandwidth:add")
    @Log(title = "节点带宽信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        return toAjax(epsNodeBandwidthService.insertEpsNodeBandwidth(epsNodeBandwidth));
    }

    /**
     * 修改节点带宽信息
     */
    @RequiresPermissions("system:bandwidth:edit")
    @Log(title = "节点带宽信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        return toAjax(epsNodeBandwidthService.updateEpsNodeBandwidth(epsNodeBandwidth));
    }
    /**
     * 重新计算
     */
    @RequiresPermissions("system:bandwidth:query")
    @GetMapping(value = "recalculate/{id}")
    public AjaxResult recalculate(@PathVariable("id") Long id)
    {
        // 获取需要重新计算的信息
        EpsNodeBandwidth epsNodeBandwidth = epsNodeBandwidthService.selectEpsNodeBandwidthById(id);
        if (epsNodeBandwidth == null) {
            throw new NotFoundException("未找到ID为" + id + "的服务器信息");
        }
        // 获取时间类型 1--日， 2--月
        String type = CalculateUtil.getTypeByBandwidthType(epsNodeBandwidth.getBandwidthType());
        // 设置开始时间，结束时间
        DateUtil.TimeRange timeRange = DateUtil.getTimeRange(epsNodeBandwidth.getCreateTime(),type);
        String dailyStartTime = timeRange.getStart();
        String dailyEndTime = timeRange.getEnd();
        if("1".equals(epsNodeBandwidth.getResourceType())){
            // 重新计算服务器95带宽值
            epsInitialTrafficDataService.recalculateServer95Bandwidth(epsNodeBandwidth, dailyStartTime, dailyEndTime, epsNodeBandwidth.getCalculationMode());
        }else{
            // 重新计算交换机95带宽值
            initialSwitchInfoDetailsService.recalculateSwitch95Bandwidth(epsNodeBandwidth, dailyStartTime, dailyEndTime, epsNodeBandwidth.getCalculationMode());
        }
        return success();
    }


    /**
     * 根据ID获取相关数据
     * @param id 资源ID
     * @return 表格数据信息
     */
    @RequiresPermissions("system:bandwidth:query")
    @GetMapping(value = "relatedData/traffic")
    public TableDataInfo relatedData(Long id,Integer pageNum,Integer pageSize) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的资源ID");
        }
        try {
            // 2. 查询服务器信息
            EpsNodeBandwidth epsNodeBandwidth = epsNodeBandwidthService.selectEpsNodeBandwidthById(id);
            epsNodeBandwidth.setPageNum(pageNum);
            epsNodeBandwidth.setPageSize(pageSize);
            if (epsNodeBandwidth == null) {
                log.warn("未找到ID为{}的服务器信息", id);
                throw new NotFoundException("未找到ID为" + id + "的服务器信息");
            }

            // 3. 获取时间范围
            String type = CalculateUtil.getTypeByBandwidthType(epsNodeBandwidth.getBandwidthType());
            DateUtil.TimeRange timeRange = DateUtil.getTimeRange(epsNodeBandwidth.getCreateTime(), type);
            String dailyStartTime = timeRange.getStart();
            String dailyEndTime = timeRange.getEnd();


            // 5. 根据资源类型处理不同数据
            String resourceType = epsNodeBandwidth.getResourceType();
            String bandwidthType = epsNodeBandwidth.getBandwidthType();

            if ("4".equals(bandwidthType) || "7".equals(bandwidthType)) {
                // 处理特定带宽类型数据
                PageInfo<EpsNodeBandwidth> pageInfo = epsNodeBandwidthService.getAvgDetailMsg(id,pageNum,pageSize, dailyStartTime, dailyEndTime);
                return getDataTable(pageInfo.getList(),pageInfo.getTotal());
            }
            if ("1".equals(resourceType)) {
                // 处理服务器流量数据
                PageInfo<EpsInitialTrafficData> pageInfo = epsNodeBandwidthService.relatedData(epsNodeBandwidth, dailyStartTime, dailyEndTime);;
                for (EpsInitialTrafficData epsInitialTrafficData : pageInfo.getList()) {
                    if("2".equals(epsInitialTrafficData.getRevenueMethod())){
                        BigDecimal packageBandwidth = epsInitialTrafficData.getPackageBandwidth();
                        BigDecimal outSpeed = (packageBandwidth != null)
                                ? packageBandwidth.multiply(new BigDecimal("1000000"))
                                : BigDecimal.ZERO;
                        epsInitialTrafficData.setOutSpeed(outSpeed.toString());
                    }
                }
                return getDataTable(pageInfo.getList(), pageInfo.getTotal());
            } else{
                // 4. 设置分页参数
                PageDomain pageDomain = new PageDomain();
                pageDomain.setPageNum(epsNodeBandwidth.getPageNum());
                pageDomain.setPageSize(epsNodeBandwidth.getPageSize());
                startPage(pageDomain);
                // 处理交换机信息
                List<InitialSwitchInfoDetails> switchInfoDetails = initialSwitchInfoDetailsService.getRelevantSwitch(
                        epsNodeBandwidth, dailyStartTime, dailyEndTime);
                return getDataTable(switchInfoDetails);
            }
        } catch (Exception e) {
            log.error("获取ID为{}的相关数据失败", id, e);
            throw new ServiceException("获取数据失败，请稍后重试");
        }
    }
    /**
     * 生成月均日95值
     */
    @RequiresPermissions("system:bandwidth:add")
    @Log(title = "节点带宽信息", businessType = BusinessType.INSERT)
    @PostMapping("/calculateAvg")
    public AjaxResult calculateAvg(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        return toAjax(epsNodeBandwidthService.calculateAvg(epsNodeBandwidth));
    }

    /**
     * 图形分析-95带宽值mbps/日
     */
    @RequiresPermissions("system:bandwidth:list")
    @PostMapping("/graphicalAnalysisDaily")
    public AjaxResult graphicalAnalysisDaily(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        // 设置时间
        DateUtil.setTimeDay(epsNodeBandwidth);
        List<Map> list = epsNodeBandwidthService.graphicalAnalysis(epsNodeBandwidth, "1", ChronoUnit.DAYS);
        return success(list);
    }
    /**
     * 图形分析-95带宽值mbps/月
     */
    @RequiresPermissions("system:bandwidth:list")
    @PostMapping("/graphicalAnalysisMonthly")
    public AjaxResult graphicalAnalysisMonthly(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        // 设置时间
        DateUtil.setTimeMonth(epsNodeBandwidth);
        List<Map> list = epsNodeBandwidthService.graphicalAnalysis(epsNodeBandwidth, "2", ChronoUnit.MONTHS);
        return success(list);
    }
    /**
     * 图形分析-包端带宽值Mbps/日
     */
    @RequiresPermissions("system:bandwidth:list")
    @PostMapping("/graphicalAnalysisPackage")
    public AjaxResult graphicalAnalysisPackage(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        // 设置时间
        DateUtil.setTimeDay(epsNodeBandwidth);
        List<Map> list = epsNodeBandwidthService.graphicalAnalysis(epsNodeBandwidth, "3", ChronoUnit.DAYS);
        return success(list);
    }
    /**
     * 图形分析-月均日95值
     */
    @RequiresPermissions("system:bandwidth:list")
    @PostMapping("/graphicalAnalysisAvgMonthly")
    public AjaxResult graphicalAnalysisAvgMonthly(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        // 设置时间
        DateUtil.setTimeMonth(epsNodeBandwidth);
        List<Map> list = epsNodeBandwidthService.graphicalAnalysis(epsNodeBandwidth, "4", ChronoUnit.MONTHS);
        return success(list);
    }
    /**
     * 图形分析-有效-95带宽值Mbps/日
     */
    @RequiresPermissions("system:bandwidth:list")
    @PostMapping("/graphicalAnalysisEffectiveDaily")
    public AjaxResult graphicalAnalysisEffectiveDaily(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        // 设置时间
        DateUtil.setTimeDay(epsNodeBandwidth);
        List<Map> list = epsNodeBandwidthService.graphicalAnalysis(epsNodeBandwidth, "5", ChronoUnit.DAYS);
        return success(list);
    }
    /**
     * 图形分析-有效-95带宽值Mbps/月
     */
    @RequiresPermissions("system:bandwidth:list")
    @PostMapping("/graphicalAnalysisEffectiveMonthly")
    public AjaxResult graphicalAnalysisEffectiveMonthly(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        // 设置时间
        DateUtil.setTimeMonth(epsNodeBandwidth);
        List<Map> list = epsNodeBandwidthService.graphicalAnalysis(epsNodeBandwidth, "6", ChronoUnit.MONTHS);
        return success(list);
    }
    /**
     * 图形分析-有效-月均日95值
     */
    @RequiresPermissions("system:bandwidth:list")
    @PostMapping("/graphicalAnalysisEffectiveAvgMonthly")
    public AjaxResult graphicalAnalysisEffectiveAvgMonthly(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        // 设置时间
        DateUtil.setTimeMonth(epsNodeBandwidth);
        List<Map> list = epsNodeBandwidthService.graphicalAnalysis(epsNodeBandwidth, "7", ChronoUnit.MONTHS);
        return success(list);
    }

    /**
     * 查询节点带宽信息列表
     */
    @PostMapping("/getEpsNodeBandWidthList")
    @InnerAuth
    public R<List<EpsNodeBandwidth>> getEpsNodeBandWidthList(@RequestBody EpsNodeBandwidth epsNodeBandwidth)
    {
        List<EpsNodeBandwidth> list = epsNodeBandwidthService.selectEpsNodeBandwidthList(epsNodeBandwidth);
        return R.ok(list);
    }
}
