package com.evobms.project.bms.controller;

import com.evobms.framework.aspectj.lang.annotation.Log;
import com.evobms.framework.aspectj.lang.enums.BusinessType;
import com.evobms.framework.web.controller.BaseController;
import com.evobms.framework.web.domain.AjaxResult;
import com.evobms.framework.web.page.TableDataInfo;
import com.evobms.project.bms.domain.BmsDevice;
import com.evobms.project.bms.service.IBmsDeviceService;
//import com.evobms.project.bms.service.MqttService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BMS设备Controller
 *
 * @author evobms
 * @date 2025-01-22
 */
@RestController
@RequestMapping("/bms/device")
public class BmsDeviceController extends BaseController {

    @Autowired
    private IBmsDeviceService bmsDeviceService;

//    @Autowired(required = false)
//    private MqttService mqttService;

    /**
     * 查询BMS设备列表
     */
    @PreAuthorize("@ss.hasPermi('bms:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsDevice bmsDevice) {
        startPage();
        List<BmsDevice> list = bmsDeviceService.selectBmsDeviceList(bmsDevice);
        return getDataTable(list);
    }

    /**
     * 获取BMS设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('bms:device:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        return success(bmsDeviceService.selectBmsDeviceByDeviceId(deviceId));
    }

    /**
     * 新增BMS设备
     */
    @PreAuthorize("@ss.hasPermi('bms:device:add')")
    @Log(title = "BMS设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BmsDevice bmsDevice) {
        return toAjax(bmsDeviceService.insertBmsDevice(bmsDevice));
    }

    /**
     * 修改BMS设备
     */
    @PreAuthorize("@ss.hasPermi('bms:device:edit')")
    @Log(title = "BMS设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BmsDevice bmsDevice) {
        return toAjax(bmsDeviceService.updateBmsDevice(bmsDevice));
    }

    /**
     * 删除BMS设备
     */
    @PreAuthorize("@ss.hasPermi('bms:device:remove')")
    @Log(title = "BMS设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds) {
        return toAjax(bmsDeviceService.deleteBmsDeviceByDeviceIds(deviceIds));
    }

    /**
     * 批量更新设备状态
     */
    @PreAuthorize("@ss.hasPermi('bms:device:edit')")
    @Log(title = "BMS设备状态", businessType = BusinessType.UPDATE)
    @PutMapping("/status")
    public AjaxResult updateStatus(@RequestBody Map<String, Object> params) {
        Long[] deviceIds = (Long[]) params.get("deviceIds");
        String status = (String) params.get("status");
        return toAjax(bmsDeviceService.updateBmsDeviceStatus(deviceIds, status));
    }

//    /**
//     * 查询设备状态
//     */
//    @PreAuthorize("@ss.hasPermi('bms:device:query')")
//    @PostMapping("/queryStatus/{deviceCode}")
//    public AjaxResult queryDeviceStatus(@PathVariable String deviceCode) {
//        if (mqttService != null) {
//            mqttService.queryDeviceStatus(deviceCode);
//            return success("设备状态查询命令已发送");
//        } else {
//            return error("MQTT服务未启用，无法发送查询命令");
//        }
//    }
//
//    /**
//     * 重启设备
//     */
//    @PreAuthorize("@ss.hasPermi('bms:device:edit')")
//    @Log(title = "重启BMS设备", businessType = BusinessType.UPDATE)
//    @PostMapping("/restart/{deviceCode}")
//    public AjaxResult restartDevice(@PathVariable String deviceCode) {
//        if (mqttService != null) {
//            mqttService.restartDevice(deviceCode);
//            return success("设备重启命令已发送");
//        } else {
//            return error("MQTT服务未启用，无法发送重启命令");
//        }
//    }
//
//    /**
//     * 配置设备参数
//     */
//    @PreAuthorize("@ss.hasPermi('bms:device:edit')")
//    @Log(title = "配置BMS设备", businessType = BusinessType.UPDATE)
//    @PostMapping("/config/{deviceCode}")
//    public AjaxResult configDevice(@PathVariable String deviceCode, @RequestBody Map<String, Object> config) {
//        if (mqttService != null) {
//            mqttService.configDevice(deviceCode, config);
//            return success("设备配置命令已发送");
//        } else {
//            return error("MQTT服务未启用，无法发送配置命令");
//        }
//    }
//
//    /**
//     * 发送自定义MQTT消息
//     */
//    @PreAuthorize("@ss.hasPermi('bms:device:edit')")
//    @Log(title = "发送MQTT消息", businessType = BusinessType.OTHER)
//    @PostMapping("/mqtt/send")
//    public AjaxResult sendMqttMessage(@RequestBody Map<String, String> params) {
//        if (mqttService != null) {
//            String topic = params.get("topic");
//            String message = params.get("message");
//            mqttService.sendMessage(topic, message);
//            return success("MQTT消息已发送");
//        } else {
//            return error("MQTT服务未启用，无法发送消息");
//        }
//    }

    /**
     * 获取设备统计信息
     */
    @PreAuthorize("@ss.hasPermi('bms:device:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics() {
        Map<String, Object> statistics = new HashMap<>();

        // 查询所有设备
        List<BmsDevice> allDevices = bmsDeviceService.selectBmsDeviceList(new BmsDevice());

        // 统计设备数量
        long totalCount = allDevices.size();
        long onlineCount = allDevices.stream().filter(device -> "0".equals(device.getStatus())).count();
        long offlineCount = totalCount - onlineCount;

        // 计算平均温度
        double avgTemperature = allDevices.stream()
                .filter(device -> device.getTemperature() != null)
                .mapToDouble(BmsDevice::getTemperature)
                .average()
                .orElse(0.0);

        // 计算平均剩余电量
        double avgCapacity = allDevices.stream()
                .filter(device -> device.getRemainingCapacity() != null)
                .mapToDouble(BmsDevice::getRemainingCapacity)
                .average()
                .orElse(0.0);

        statistics.put("totalCount", totalCount);
        statistics.put("onlineCount", onlineCount);
        statistics.put("offlineCount", offlineCount);
        statistics.put("avgTemperature", Math.round(avgTemperature * 100.0) / 100.0);
        statistics.put("avgCapacity", Math.round(avgCapacity * 100.0) / 100.0);

        return success(statistics);
    }
}
