package com.pm.web.controller.subsystem;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
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.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.enums.BusinessType;
import com.pm.common.config.PageData;
import com.pm.common.utils.poi.ExcelUtilPageData;
import com.pm.subsystem.service.IEnergyDeviceService;
import com.pm.common.core.page.TableDataInfo;

/**
 * 能源管理系统Controller
 *
 * @author lxf
 * @date 2025-06-03
 */
@RestController
@RequestMapping("/subsystem/energy")
public class EnergyDeviceController extends BaseController
{
    @Autowired
    private IEnergyDeviceService energyDeviceService;

    /**
     * 查询能源管理设备列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:list')")
    @GetMapping("/devices/list")
    public TableDataInfo listDevices()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = energyDeviceService.selectEnergyDeviceList(pd);
        return getDataTable(list);
    }

    /**
     * 导出能源管理设备列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:export')")
    @Log(title = "能源管理设备", businessType = BusinessType.EXPORT)
    @PostMapping("/devices/export")
    public void exportDevices(HttpServletResponse response)
    {
        try {
            PageData pd = this.getPageData();
            List<PageData> list = energyDeviceService.selectEnergyDeviceList(pd);
            String filename = "能源管理设备数据";
            String[] titles = {
                    "设备ID,id",
                    "设备编码,deviceCode",
                    "设备名称,deviceName",
                    "设备类型,deviceType",
                    "能耗类型,energyType",
                    "楼栋,building",
                    "楼层,floor",
                    "房间号,roomNo",
                    "当前功率,currentPower",
                    "额定功率,ratedPower",
                    "日能耗,dailyConsumption",
                    "月能耗,monthlyConsumption",
                    "年能耗,yearlyConsumption",
                    "负载率,loadRate",
                    "设备状态,deviceStatus",
                    "是否在线,isOnline",
                    "温度,temperature",
                    "功率设置,powerSetting",
                    "阈值,thresholdValue",
                    "设备描述,description"
            };
            ExcelUtilPageData.exportXLSX(response, null, null, filename, titles, list);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取能源管理设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:query')")
    @GetMapping(value = "/devices/{id}")
    public AjaxResult getDeviceInfo(@PathVariable("id") Long id)
    {
        return success(energyDeviceService.selectEnergyDeviceById(id));
    }

    /**
     * 新增能源管理设备
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:add')")
    @Log(title = "能源管理设备", businessType = BusinessType.INSERT)
    @PostMapping("/devices")
    public AjaxResult addDevice(@RequestBody PageData pd)
    {
        return toAjax(energyDeviceService.insertEnergyDevice(pd));
    }

    /**
     * 修改能源管理设备
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:edit')")
    @Log(title = "能源管理设备", businessType = BusinessType.UPDATE)
    @PutMapping("/devices")
    public AjaxResult editDevice(@RequestBody PageData pd)
    {
        return toAjax(energyDeviceService.updateEnergyDevice(pd));
    }

    /**
     * 删除能源管理设备
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:remove')")
    @Log(title = "能源管理设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/devices/{ids}")
    public AjaxResult removeDevices(@PathVariable Long[] ids)
    {
        return toAjax(energyDeviceService.deleteEnergyDeviceByIds(ids));
    }

    /**
     * 获取能耗统计数据
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:statistics')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        PageData pd = this.getPageData();
        PageData statistics = energyDeviceService.getEnergyStatistics(pd);
        return success(statistics);
    }

    /**
     * 查询能耗历史记录列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:history')")
    @GetMapping("/history/list")
    public TableDataInfo listHistory()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = energyDeviceService.selectEnergyHistoryList(pd);
        return getDataTable(list);
    }

    /**
     * 获取实时能耗数据
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:realtime')")
    @GetMapping("/realtime/{deviceCode}")
    public AjaxResult getRealTimeData(@PathVariable("deviceCode") String deviceCode)
    {
        PageData realTimeData = energyDeviceService.getRealTimeEnergyData(deviceCode);
        return success(realTimeData);
    }

    /**
     * 查询能耗告警信息列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:alarm')")
    @GetMapping("/alarms/list")
    public TableDataInfo listAlarms()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = energyDeviceService.selectEnergyAlarmList(pd);
        return getDataTable(list);
    }

    /**
     * 处理能耗告警
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:alarm:handle')")
    @Log(title = "能耗告警处理", businessType = BusinessType.UPDATE)
    @PutMapping("/alarms/{id}")
    public AjaxResult handleAlarm(@PathVariable("id") Long id, @RequestBody PageData pd)
    {
        pd.put("id", id);
        pd.put("handleUser", getUsername());
        return toAjax(energyDeviceService.handleEnergyAlarm(pd));
    }

    /**
     * 设备控制
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:control')")
    @Log(title = "设备控制", businessType = BusinessType.OTHER)
    @PostMapping("/control")
    public AjaxResult controlDevice(@RequestBody PageData pd)
    {
        pd.put("controlUser", getUsername());
        int result = energyDeviceService.controlDevice(pd);
        if (result > 0) {
            return success("设备控制指令发送成功");
        } else {
            return error("设备控制指令发送失败");
        }
    }

    /**
     * 查询设备控制记录列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:control:list')")
    @GetMapping("/control/list")
    public TableDataInfo listControlRecords()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = energyDeviceService.selectDeviceControlList(pd);
        return getDataTable(list);
    }

    /**
     * 获取能耗曲线数据
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:chart')")
    @GetMapping("/chart")
    public AjaxResult getChartData()
    {
        PageData pd = this.getPageData();
        List<PageData> chartData = energyDeviceService.getEnergyChartData(pd);
        return success(chartData);
    }

    /**
     * 生成能耗报表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:report')")
    @GetMapping("/report")
    public AjaxResult generateReport()
    {
        PageData pd = this.getPageData();
        PageData reportData = energyDeviceService.generateEnergyReport(pd);
        return success(reportData);
    }

    /**
     * 设置能耗阈值
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:threshold')")
    @Log(title = "设置能耗阈值", businessType = BusinessType.UPDATE)
    @PostMapping("/threshold")
    public AjaxResult setThreshold(@RequestBody PageData pd)
    {
        return toAjax(energyDeviceService.setEnergyThreshold(pd));
    }

    /**
     * 数据同步
     */
    @PreAuthorize("@ss.hasPermi('subsystem:energy:sync')")
    @Log(title = "能耗数据同步", businessType = BusinessType.OTHER)
    @PostMapping("/sync")
    public AjaxResult syncData(@RequestBody PageData pd)
    {
        int result = energyDeviceService.syncEnergyData(pd);
        if (result > 0) {
            return success("数据同步成功");
        } else {
            return error("数据同步失败");
        }
    }
}