package com.pm.web.controller.device;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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.core.page.TableDataInfo;

/**
 * 设备组态Controller
 * 
 * @author lxf
 * @date 2025-06-11
 */
@RestController
@RequestMapping("/device/configuration")
public class DeviceConfigurationController extends BaseController
{
    /**
     * 查询设备组态列表（模拟数据）
     */
    @GetMapping("/list")
    public TableDataInfo list()
    {
        PageData pd = this.getPageData();
        List<Map<String, Object>> list = new ArrayList<>();
        
        // 模拟设备数据
        String[] deviceCodes = {"HVAC001", "HVAC002", "FA001", "CH001", "WS001", "EL001", "PD001", "LT001", "HVAC003", "FA002"};
        String[] deviceNames = {"1号空调机组", "2号空调机组", "新风机组1", "冷水机组1", "供水泵1", "客梯1", "配电柜1", "照明回路1", "3号空调机组", "新风机组2"};
        String[] subsystemTypes = {"hvac", "hvac", "fresh_air", "cooling_heating", "water_system", "elevator", "power_distribution", "lighting", "hvac", "fresh_air"};
        String[] spaceNames = {"1楼大厅", "2楼办公区", "1楼大厅", "地下室", "地下室", "1-8楼", "配电室", "1楼大厅", "3楼办公区", "2楼办公区"};
        
        Random random = new Random();
        
        for (int i = 0; i < deviceCodes.length; i++) {
            Map<String, Object> device = new HashMap<>();
            device.put("deviceCode", deviceCodes[i]);
            device.put("deviceName", deviceNames[i]);
            device.put("subsystemType", subsystemTypes[i]);
            device.put("spaceName", spaceNames[i]);
            device.put("status", String.valueOf(random.nextInt(3))); // 0-离线, 1-正常, 2-故障
            device.put("isOnline", random.nextBoolean());
            device.put("alarmCount", random.nextInt(5));
            device.put("lastUpdateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            
            list.add(device);
        }
        
        // 分页处理
        int pageNum = 1;
        int pageSize = 10;
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, list.size());
        
        List<Map<String, Object>> pageList = list.subList(startIndex, endIndex);
        
        TableDataInfo dataTable = new TableDataInfo();
        dataTable.setRows(pageList);
        dataTable.setTotal(list.size());
        dataTable.setCode(200);
        dataTable.setMsg("查询成功");
        
        return dataTable;
    }

    /**
     * 获取设备详细信息
     */
    @GetMapping("/{deviceCode}")
    public AjaxResult getInfo(@PathVariable("deviceCode") String deviceCode)
    {
        Map<String, Object> device = new HashMap<>();
        device.put("deviceCode", deviceCode);
        device.put("deviceName", "设备名称_" + deviceCode);
        device.put("subsystemType", "hvac");
        device.put("spaceName", "1楼大厅");
        device.put("status", "1");
        device.put("isOnline", true);
        device.put("manufacturer", "海尔");
        device.put("model", "KFRD-50LW");
        device.put("installDate", "2023-06-01");
        device.put("warrantyDate", "2025-06-01");
        
        return AjaxResult.success(device);
    }

    /**
     * 获取设备点位列表
     */
    @GetMapping("/points/{deviceCode}")
    public AjaxResult getDevicePoints(@PathVariable("deviceCode") String deviceCode)
    {
        List<Map<String, Object>> pointList = new ArrayList<>();
        Random random = new Random();
        
        // 根据设备类型生成不同的点位
        if (deviceCode.startsWith("HVAC")) {
            // 空调设备点位
            String[] pointCodes = {"AI001", "AI002", "AI003", "AO001", "DI001", "DO001", "DO002"};
            String[] pointNames = {"送风温度", "回风温度", "送风湿度", "风阀开度", "运行状态", "启停控制", "模式切换"};
            String[] pointTypes = {"AI", "AI", "AI", "AO", "DI", "DO", "DO"};
            String[] units = {"°C", "°C", "%", "%", "", "", ""};
            
            for (int i = 0; i < pointCodes.length; i++) {
                Map<String, Object> point = new HashMap<>();
                point.put("pointCode", pointCodes[i]);
                point.put("pointName", pointNames[i]);
                point.put("pointType", pointTypes[i]);
                point.put("unit", units[i]);
                
                // 根据点位类型生成不同的值
                if ("AI".equals(pointTypes[i])) {
                    if (pointNames[i].contains("温度")) {
                        point.put("currentValue", new BigDecimal(random.nextDouble() * 10 + 20).setScale(1, RoundingMode.HALF_UP));
                        point.put("minValue", 15.0);
                        point.put("maxValue", 35.0);
                    } else {
                        point.put("currentValue", new BigDecimal(random.nextDouble() * 20 + 40).setScale(1, RoundingMode.HALF_UP));
                        point.put("minValue", 30.0);
                        point.put("maxValue", 70.0);
                    }
                } else if ("AO".equals(pointTypes[i])) {
                    point.put("currentValue", new BigDecimal(random.nextDouble() * 100).setScale(0, RoundingMode.HALF_UP));
                    point.put("minValue", 0.0);
                    point.put("maxValue", 100.0);
                } else {
                    point.put("currentValue", random.nextBoolean() ? 1 : 0);
                    point.put("minValue", 0);
                    point.put("maxValue", 1);
                }
                
                point.put("alarmStatus", random.nextInt(10) < 2); // 20%概率告警
                point.put("updateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                
                pointList.add(point);
            }
        } else if (deviceCode.startsWith("FA")) {
            // 新风设备点位
            String[] pointCodes = {"AI001", "AI002", "AO001", "DI001", "DO001"};
            String[] pointNames = {"新风温度", "新风湿度", "风机频率", "过滤网状态", "风机启停"};
            String[] pointTypes = {"AI", "AI", "AO", "DI", "DO"};
            String[] units = {"°C", "%", "Hz", "", ""};
            
            for (int i = 0; i < pointCodes.length; i++) {
                Map<String, Object> point = new HashMap<>();
                point.put("pointCode", pointCodes[i]);
                point.put("pointName", pointNames[i]);
                point.put("pointType", pointTypes[i]);
                point.put("unit", units[i]);
                
                if ("AI".equals(pointTypes[i])) {
                    if (pointNames[i].contains("温度")) {
                        point.put("currentValue", new BigDecimal(random.nextDouble() * 15 + 15).setScale(1, RoundingMode.HALF_UP));
                    } else {
                        point.put("currentValue", new BigDecimal(random.nextDouble() * 30 + 40).setScale(1, RoundingMode.HALF_UP));
                    }
                } else if ("AO".equals(pointTypes[i])) {
                    point.put("currentValue", new BigDecimal(random.nextDouble() * 30 + 20).setScale(1, RoundingMode.HALF_UP));
                    point.put("minValue", 0.0);
                    point.put("maxValue", 50.0);
                } else {
                    point.put("currentValue", random.nextBoolean() ? 1 : 0);
                }
                
                point.put("alarmStatus", random.nextInt(10) < 1);
                point.put("updateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                
                pointList.add(point);
            }
        }
        
        return AjaxResult.success(pointList);
    }

    /**
     * 获取点位详细信息
     */
    @GetMapping("/point/{pointCode}")
    public AjaxResult getPointDetail(@PathVariable("pointCode") String pointCode)
    {
        Map<String, Object> point = new HashMap<>();
        Random random = new Random();
        
        point.put("pointCode", pointCode);
        point.put("pointName", "点位名称_" + pointCode);
        point.put("pointType", pointCode.startsWith("AI") ? "AI" : pointCode.startsWith("AO") ? "AO" : pointCode.startsWith("DI") ? "DI" : "DO");
        point.put("currentValue", new BigDecimal(random.nextDouble() * 100).setScale(1, RoundingMode.HALF_UP));
        point.put("unit", pointCode.startsWith("AI") && pointCode.endsWith("001") ? "°C" : "%");
        point.put("minValue", 0.0);
        point.put("maxValue", 100.0);
        point.put("alarmStatus", false);
        point.put("updateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        point.put("description", "点位描述信息");
        
        return AjaxResult.success(point);
    }

    /**
     * 获取点位实时数据
     */
    @GetMapping("/point/realtime/{pointCode}")
    public AjaxResult getPointRealTimeData(@PathVariable("pointCode") String pointCode)
    {
        Map<String, Object> data = new HashMap<>();
        Random random = new Random();
        
        data.put("pointCode", pointCode);
        data.put("value", new BigDecimal(random.nextDouble() * 100).setScale(2, RoundingMode.HALF_UP));
        data.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        data.put("quality", "GOOD");
        
        return AjaxResult.success(data);
    }

    /**
     * 获取点位历史数据
     */
    @GetMapping("/point/history")
    public AjaxResult getPointHistoryData()
    {
        PageData pd = this.getPageData();
        List<Map<String, Object>> historyData = new ArrayList<>();
        Random random = new Random();
        
        // 生成24小时的历史数据
        long currentTime = System.currentTimeMillis();
        for (int i = 0; i < 24; i++) {
            Map<String, Object> data = new HashMap<>();
            data.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(currentTime - i * 3600000)));
            data.put("value", new BigDecimal(random.nextDouble() * 20 + 20).setScale(2, RoundingMode.HALF_UP));
            data.put("quality", "GOOD");
            
            historyData.add(0, data); // 逆序插入，保证时间顺序
        }
        
        return AjaxResult.success(historyData);
    }

    /**
     * 发送控制指令
     */
    @Log(title = "设备控制", businessType = BusinessType.UPDATE)
    @PostMapping("/control")
    public AjaxResult sendControlCommand(@RequestBody PageData pd)
    {
        String pointCode = pd.getString("pointCode");
        Object controlValue = pd.get("controlValue");
        String executeTime = pd.getString("executeTime");
        String remark = pd.getString("remark");
        
        // 模拟控制指令下发
        Map<String, Object> result = new HashMap<>();
        result.put("commandId", "CMD_" + System.currentTimeMillis());
        result.put("pointCode", pointCode);
        result.put("controlValue", controlValue);
        result.put("executeTime", executeTime);
        result.put("status", "SUCCESS");
        result.put("message", "控制指令下发成功");
        result.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        
        return AjaxResult.success("控制指令下发成功", result);
    }

    /**
     * 获取设备组态图
     */
    @GetMapping("/schema/{deviceCode}")
    public AjaxResult getDeviceSchema(@PathVariable("deviceCode") String deviceCode)
    {
        Map<String, Object> schema = new HashMap<>();
        
        // 模拟组态图数据
        schema.put("deviceCode", deviceCode);
        schema.put("schemaType", "SVG");
        schema.put("schemaUrl", "/static/schema/" + deviceCode + ".svg");
        schema.put("width", 800);
        schema.put("height", 600);
        
        // 组态图元素
        List<Map<String, Object>> elements = new ArrayList<>();
        Map<String, Object> element1 = new HashMap<>();
        element1.put("id", "temp_display");
        element1.put("type", "text");
        element1.put("x", 100);
        element1.put("y", 50);
        element1.put("pointCode", "AI001");
        element1.put("format", "{value}°C");
        elements.add(element1);
        
        schema.put("elements", elements);
        
        return AjaxResult.success(schema);
    }

    /**
     * 获取点位告警信息
     */
    @GetMapping("/point/alarms/{pointCode}")
    public AjaxResult getPointAlarms(@PathVariable("pointCode") String pointCode)
    {
        List<Map<String, Object>> alarms = new ArrayList<>();
        Random random = new Random();
        
        if (random.nextBoolean()) {
            Map<String, Object> alarm = new HashMap<>();
            alarm.put("alarmId", "ALM_" + System.currentTimeMillis());
            alarm.put("pointCode", pointCode);
            alarm.put("alarmType", "HIGH_LIMIT");
            alarm.put("alarmLevel", "WARNING");
            alarm.put("alarmTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            alarm.put("alarmValue", 35.5);
            alarm.put("limitValue", 35.0);
            alarm.put("message", "温度超上限");
            alarm.put("status", "ACTIVE");
            
            alarms.add(alarm);
        }
        
        return AjaxResult.success(alarms);
    }

    /**
     * 获取点位控制记录
     */
    @GetMapping("/point/controls/{pointCode}")
    public AjaxResult getPointControlRecords(@PathVariable("pointCode") String pointCode)
    {
        List<Map<String, Object>> records = new ArrayList<>();
        Random random = new Random();
        
        for (int i = 0; i < 5; i++) {
            Map<String, Object> record = new HashMap<>();
            record.put("recordId", "CTL_" + (System.currentTimeMillis() - i * 1000));
            record.put("pointCode", pointCode);
            record.put("controlValue", random.nextInt(100));
            record.put("executeTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis() - i * 3600000)));
            record.put("operator", "操作员" + (i + 1));
            record.put("status", random.nextBoolean() ? "SUCCESS" : "FAILED");
            record.put("remark", "控制备注" + (i + 1));
            
            records.add(record);
        }
        
        return AjaxResult.success(records);
    }
}