package com.ruoyi.ems.controller;

import com.huashe.common.domain.AjaxResult;
import com.huashe.common.exception.BusinessException;
import com.huashe.common.utils.ListUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
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.RequiresPermissions;
import com.ruoyi.ems.model.PvSupplyExportVO;
import com.ruoyi.ems.model.PvSupplyVO;
import com.ruoyi.ems.model.QueryMeter;
import com.ruoyi.ems.service.IElecPvSupplyHService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.List;

/**
 * 光伏并网计量Controller
 *
 * @author ruoyi
 * @date 2024-08-02
 */
@RestController
@RequestMapping("/prod/pv")
@Api(value = "ElecPvSupplyHController", description = "光伏并网计量数据接口")
public class ElecPvSupplyHController extends BaseController {

    @Autowired
    private IElecPvSupplyHService pvSupplyHService;

    /**
     * 查询光伏产能统计列表
     */
    @RequiresPermissions("ems:prod:list")
    @GetMapping("/hour/list")
    @ApiOperation("查询光伏产能统计列表")
    public TableDataInfo list(@ApiParam("查询参数") QueryMeter queryMeter) {
        validateAndSetDefaults(queryMeter);

        List<PvSupplyVO> list = pvSupplyHService.selectPvSupplyList(queryMeter);
        int total = list.size();
        list = ListUtils.subList(list, (queryMeter.getPageNum() - 1) * queryMeter.getPageSize(),
            queryMeter.getPageNum() * queryMeter.getPageSize() - 1);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(total);

        return rspData;
    }

    /**
     * 查询光伏产能统计汇总
     */
    @RequiresPermissions("ems:prod:list")
    @GetMapping("/hour/summary")
    @ApiOperation("查询光伏产能统计汇总")
    public AjaxResult getSummary(@ApiParam("查询参数") QueryMeter queryMeter) {
        validateAndSetDefaults(queryMeter);

        PvSupplyVO summary = pvSupplyHService.selectPvSupplySummary(queryMeter);
        return success(summary);
    }

    /**
     * 导出光伏产能统计数据
     */
    /**
     * 导出光伏产能统计数据
     */
    @RequiresPermissions("ems:prod:export")
    @Log(title = "光伏产能统计", businessType = BusinessType.EXPORT)
    @PostMapping("/hour/export")
    @ApiOperation("导出光伏产能统计数据")
    public void export(HttpServletResponse response, QueryMeter queryMeter) {
        try {
            validateAndSetDefaults(queryMeter);

            List<PvSupplyVO> list = pvSupplyHService.exportPvSupplyList(queryMeter);
            // 转换为导出VO
            List<PvSupplyExportVO> exportList = pvSupplyHService.convertToPvSupplyExportVOList(list,
                queryMeter.getTimeDimension());

            ExcelUtil<PvSupplyExportVO> util = new ExcelUtil<>(PvSupplyExportVO.class);
            String fileName = String.format("光伏产能统计_%s_%s.xlsx", queryMeter.getTimeDimension(),
                System.currentTimeMillis());
            util.exportExcel(response, exportList, fileName);
        } catch (BusinessException e) {
            handleExportException(response, e);
        }
    }

    /**
     * 查询光伏产能按区域分布（用于饼图）
     * 当areaCode为空或-1时，返回所有区域的分组数据
     */
    @RequiresPermissions("ems:prod:list")
    @GetMapping("/hour/distribution")
    @ApiOperation("查询光伏产能按区域分布")
    public AjaxResult getDistribution(@ApiParam("查询参数") QueryMeter queryMeter) {
        // 设置默认时间范围
        if (StringUtils.isBlank(queryMeter.getStartRecTime()) || StringUtils.isBlank(queryMeter.getEndRecTime())) {
            // 默认最近30天
            LocalDate today = LocalDate.now();
            LocalDate startDate = today.minusDays(30);
            queryMeter.setStartRecTime(startDate.toString() + " 00:00:00");
            queryMeter.setEndRecTime(today.toString() + " 23:59:59");
        }

        List<PvSupplyVO> list = pvSupplyHService.selectPvSupplyDistribution(queryMeter);
        return success(list);
    }

    /**
     * 查询光伏产能分布明细（按区域和日期分组，用于对比柱状图）
     */
    @RequiresPermissions("ems:prod:list")
    @GetMapping("/hour/distribution/detail")
    @ApiOperation("查询光伏产能分布明细")
    public AjaxResult getDistributionDetail(@ApiParam("查询参数") QueryMeter queryMeter) {
        // 设置默认时间范围
        if (StringUtils.isBlank(queryMeter.getStartRecTime()) || StringUtils.isBlank(queryMeter.getEndRecTime())) {
            LocalDate today = LocalDate.now();
            LocalDate startDate = today.minusDays(30);
            queryMeter.setStartRecTime(startDate.toString() + " 00:00:00");
            queryMeter.setEndRecTime(today.toString() + " 23:59:59");
        }

        List<PvSupplyVO> list = pvSupplyHService.selectPvSupplyDistributionDetail(queryMeter);
        return success(list);
    }

    /**
     * 校验并设置默认参数
     */
    private void validateAndSetDefaults(QueryMeter queryMeter) {
        if (queryMeter == null) {
            throw new IllegalArgumentException("查询参数不能为空");
        }

        // 设置默认时间维度
        if (StringUtils.isBlank(queryMeter.getTimeDimension())) {
            queryMeter.setTimeDimension("month");
        }

        // 设置默认排序
        if (StringUtils.isBlank(queryMeter.getOrderFlag())) {
            queryMeter.setOrderFlag("desc");
        }
    }

    /**
     * 统一异常处理
     */
    private void handleExportException(HttpServletResponse response, BusinessException e) {
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().print("{\"code\":400,\"msg\":\"" + e.getMessage() + "\"}");
        } catch (Exception ex) {
            logger.error("导出异常处理失败", ex);
        }
    }
}