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.IIntrusionAlarmService;
import com.pm.common.core.page.TableDataInfo;

/**
 * 入侵报警系统Controller
 *
 * @author lxf
 * @date 2025-06-03
 */
@RestController
@RequestMapping("/subsystem/intrusion")
public class IntrusionAlarmController extends BaseController
{
    @Autowired
    private IIntrusionAlarmService intrusionAlarmService;

    // ==================== 报警点管理 ====================
    
    /**
     * 查询报警点列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:list')")
    @GetMapping("/alarmpoints/list")
    public TableDataInfo listAlarmPoints()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = intrusionAlarmService.selectAlarmPointList(pd);
        return getDataTable(list);
    }

    /**
     * 导出报警点列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:export')")
    @Log(title = "报警点", businessType = BusinessType.EXPORT)
    @PostMapping("/alarmpoints/export")
    public void exportAlarmPoints(HttpServletResponse response)
    {
        try {
            PageData pd = this.getPageData();
            List<PageData> list = intrusionAlarmService.selectAlarmPointList(pd);
            String filename = "报警点数据";
            String[] titles = {
                    "设备ID,id",
                    "设备编号,deviceCode",
                    "设备名称,deviceName",
                    "报警类型,alarmType",
                    "防区编号,zoneCode",
                    "防区名称,zoneName",
                    "楼栋,building",
                    "楼层,floor",
                    "详细位置,locationDetail",
                    "设备状态,deviceStatus",
                    "布防状态,armStatus",
                    "敏感度,sensitivity",
                    "延时时间,delayTime"
            };
            ExcelUtilPageData.exportXLSX(response, null, null, filename, titles, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取报警点详细信息
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:query')")
    @GetMapping(value = "/alarmpoints/{id}")
    public AjaxResult getAlarmPointInfo(@PathVariable("id") Long id)
    {
        return success(intrusionAlarmService.selectAlarmPointById(id));
    }

    /**
     * 新增报警点
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:add')")
    @Log(title = "报警点", businessType = BusinessType.INSERT)
    @PostMapping("/alarmpoints")
    public AjaxResult addAlarmPoint(@RequestBody PageData pd)
    {
        return toAjax(intrusionAlarmService.insertAlarmPoint(pd));
    }

    /**
     * 修改报警点
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:edit')")
    @Log(title = "报警点", businessType = BusinessType.UPDATE)
    @PutMapping("/alarmpoints")
    public AjaxResult editAlarmPoint(@RequestBody PageData pd)
    {
        return toAjax(intrusionAlarmService.updateAlarmPoint(pd));
    }

    /**
     * 删除报警点
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:remove')")
    @Log(title = "报警点", businessType = BusinessType.DELETE)
    @DeleteMapping("/alarmpoints/{ids}")
    public AjaxResult removeAlarmPoints(@PathVariable Long[] ids)
    {
        return toAjax(intrusionAlarmService.deleteAlarmPointByIds(ids));
    }

    /**
     * 切换布防状态
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:arm')")
    @Log(title = "布防控制", businessType = BusinessType.OTHER)
    @PostMapping("/alarmpoints/arm")
    public AjaxResult toggleArmStatus(@RequestBody PageData pd)
    {
        int result = intrusionAlarmService.toggleArmStatus(pd);
        if (result > 0) {
            return success("布防状态切换成功");
        } else {
            return error("布防状态切换失败");
        }
    }

    /**
     * 批量布防/撤防
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:batch-arm')")
    @Log(title = "批量布防控制", businessType = BusinessType.OTHER)
    @PostMapping("/alarmpoints/batch-arm")
    public AjaxResult batchArmControl(@RequestBody PageData pd)
    {
        int result = intrusionAlarmService.batchArmControl(pd);
        return success("成功操作 " + result + " 个设备");
    }

    /**
     * 测试报警设备
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:test')")
    @Log(title = "设备测试", businessType = BusinessType.OTHER)
    @PostMapping("/alarmpoints/test/{deviceCode}")
    public AjaxResult testAlarmDevice(@PathVariable("deviceCode") String deviceCode)
    {
        int result = intrusionAlarmService.testAlarmDevice(deviceCode);
        if (result > 0) {
            return success("设备测试指令发送成功");
        } else {
            return error("设备测试指令发送失败");
        }
    }

    /**
     * 更新设备配置
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarmpoints:config')")
    @Log(title = "设备配置", businessType = BusinessType.UPDATE)
    @PutMapping("/alarmpoints/config")
    public AjaxResult updateDeviceConfig(@RequestBody PageData pd)
    {
        return toAjax(intrusionAlarmService.updateDeviceConfig(pd));
    }

    // ==================== 报警记录管理 ====================

    /**
     * 查询报警记录列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarms:list')")
    @GetMapping("/alarms/list")
    public TableDataInfo listAlarms()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = intrusionAlarmService.selectAlarmList(pd);
        return getDataTable(list);
    }

    /**
     * 获取报警记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarms:query')")
    @GetMapping(value = "/alarms/{id}")
    public AjaxResult getAlarmInfo(@PathVariable("id") Long id)
    {
        return success(intrusionAlarmService.selectAlarmById(id));
    }

    /**
     * 处理报警
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarms:process')")
    @Log(title = "报警处理", businessType = BusinessType.UPDATE)
    @PutMapping("/alarms/process")
    public AjaxResult processAlarm(@RequestBody PageData pd)
    {
        pd.put("handleUser", getUsername());
        return toAjax(intrusionAlarmService.processAlarm(pd));
    }

    /**
     * 批量处理报警
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarms:batch-process')")
    @Log(title = "批量报警处理", businessType = BusinessType.UPDATE)
    @PutMapping("/alarms/batch-process")
    public AjaxResult batchProcessAlarms(@RequestBody PageData pd)
    {
        pd.put("handleUser", getUsername());
        int result = intrusionAlarmService.batchProcessAlarms(pd);
        return success("成功处理 " + result + " 条报警");
    }

    /**
     * 确认报警
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarms:confirm')")
    @Log(title = "确认报警", businessType = BusinessType.UPDATE)
    @PutMapping("/alarms/confirm/{id}")
    public AjaxResult confirmAlarm(@PathVariable("id") Long id)
    {
        return toAjax(intrusionAlarmService.confirmAlarm(id));
    }

    /**
     * 忽略报警
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:alarms:ignore')")
    @Log(title = "忽略报警", businessType = BusinessType.UPDATE)
    @PutMapping("/alarms/ignore/{id}")
    public AjaxResult ignoreAlarm(@PathVariable("id") Long id, @RequestBody PageData pd)
    {
        pd.put("handleUser", getUsername());
        return toAjax(intrusionAlarmService.ignoreAlarm(id, pd));
    }

    // ==================== 防区管理 ====================

    /**
     * 查询防区列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:zones:list')")
    @GetMapping("/zones/list")
    public TableDataInfo listZones()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = intrusionAlarmService.selectZoneList(pd);
        return getDataTable(list);
    }

    /**
     * 获取防区详细信息
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:zones:query')")
    @GetMapping(value = "/zones/{id}")
    public AjaxResult getZoneInfo(@PathVariable("id") Long id)
    {
        return success(intrusionAlarmService.selectZoneById(id));
    }

    /**
     * 新增防区
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:zones:add')")
    @Log(title = "防区", businessType = BusinessType.INSERT)
    @PostMapping("/zones")
    public AjaxResult addZone(@RequestBody PageData pd)
    {
        return toAjax(intrusionAlarmService.insertZone(pd));
    }

    /**
     * 修改防区
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:zones:edit')")
    @Log(title = "防区", businessType = BusinessType.UPDATE)
    @PutMapping("/zones")
    public AjaxResult editZone(@RequestBody PageData pd)
    {
        return toAjax(intrusionAlarmService.updateZone(pd));
    }

    /**
     * 删除防区
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:zones:remove')")
    @Log(title = "防区", businessType = BusinessType.DELETE)
    @DeleteMapping("/zones/{id}")
    public AjaxResult removeZone(@PathVariable("id") Long id)
    {
        return toAjax(intrusionAlarmService.deleteZoneById(id));
    }

    /**
     * 防区布防/撤防
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:zones:toggle')")
    @Log(title = "防区状态切换", businessType = BusinessType.UPDATE)
    @PutMapping("/zones/toggle/{id}")
    public AjaxResult toggleZoneStatus(@PathVariable("id") Long id, @RequestBody PageData pd)
    {
        return toAjax(intrusionAlarmService.toggleZoneStatus(id, pd));
    }

    /**
     * 批量防区操作
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:zones:batch-control')")
    @Log(title = "批量防区操作", businessType = BusinessType.OTHER)
    @PostMapping("/zones/batch-control")
    public AjaxResult batchZoneControl(@RequestBody PageData pd)
    {
        int result = intrusionAlarmService.batchZoneControl(pd);
        return success("成功操作 " + result + " 个防区");
    }

    /**
     * 查询防区设备列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:zones:devices')")
    @GetMapping("/zones/devices/{zoneCode}")
    public AjaxResult listZoneDevices(@PathVariable("zoneCode") String zoneCode)
    {
        List<PageData> list = intrusionAlarmService.selectZoneDeviceList(zoneCode);
        return success(list);
    }

    // ==================== 统计查询 ====================

    /**
     * 获取报警统计数据
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:statistics')")
    @GetMapping("/statistics")
    public AjaxResult getAlarmStatistics()
    {
        PageData pd = this.getPageData();
        PageData statistics = intrusionAlarmService.getAlarmStatistics(pd);
        return success(statistics);
    }

    /**
     * 获取实时状态
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:realtime')")
    @GetMapping("/realtime/status")
    public AjaxResult getRealTimeStatus()
    {
        PageData realTimeStatus = intrusionAlarmService.getRealTimeStatus();
        return success(realTimeStatus);
    }

    /**
     * 获取报警趋势数据
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:trend')")
    @GetMapping("/statistics/trend")
    public AjaxResult getAlarmTrend()
    {
        PageData pd = this.getPageData();
        List<PageData> trendData = intrusionAlarmService.getAlarmTrend(pd);
        return success(trendData);
    }

    // ==================== 其他功能 ====================

    /**
     * 设备健康检测
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:health')")
    @PostMapping("/health/check/{deviceCode}")
    public AjaxResult checkDeviceHealth(@PathVariable("deviceCode") String deviceCode)
    {
        PageData healthData = intrusionAlarmService.checkDeviceHealth(deviceCode);
        return success(healthData);
    }

    /**
     * 获取设备配置
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:config')")
    @GetMapping("/config/{deviceCode}")
    public AjaxResult getDeviceConfig(@PathVariable("deviceCode") String deviceCode)
    {
        PageData configData = intrusionAlarmService.getDeviceConfig(deviceCode);
        return success(configData);
    }

    /**
     * 重置设备
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:reset')")
    @Log(title = "设备重置", businessType = BusinessType.OTHER)
    @PostMapping("/device/reset/{deviceCode}")
    public AjaxResult resetDevice(@PathVariable("deviceCode") String deviceCode)
    {
        int result = intrusionAlarmService.resetDevice(deviceCode);
        if (result > 0) {
            return success("设备重置成功");
        } else {
            return error("设备重置失败");
        }
    }

    /**
     * 查询维护记录列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:maintenance')")
    @GetMapping("/maintenance/list")
    public TableDataInfo listMaintenanceRecords()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = intrusionAlarmService.selectMaintenanceRecordList(pd);
        return getDataTable(list);
    }

    /**
     * 新增维护记录
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:maintenance:add')")
    @Log(title = "维护记录", businessType = BusinessType.INSERT)
    @PostMapping("/maintenance")
    public AjaxResult addMaintenanceRecord(@RequestBody PageData pd)
    {
        pd.put("createUser", getUsername());
        return toAjax(intrusionAlarmService.addMaintenanceRecord(pd));
    }

    /**
     * 生成报警报表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:report')")
    @PostMapping("/report/generate")
    public AjaxResult generateAlarmReport(@RequestBody PageData pd)
    {
        PageData reportData = intrusionAlarmService.generateAlarmReport(pd);
        return success(reportData);
    }

    /**
     * 数据同步
     */
    @PreAuthorize("@ss.hasPermi('subsystem:intrusion:sync')")
    @Log(title = "入侵报警数据同步", businessType = BusinessType.OTHER)
    @PostMapping("/sync")
    public AjaxResult syncIntrusionData(@RequestBody PageData pd)
    {
        int result = intrusionAlarmService.syncIntrusionData(pd);
        if (result > 0) {
            return success("数据同步成功");
        } else {
            return error("数据同步失败");
        }
    }
}