package com.pm.subsystem.service.impl;

import java.util.List;
import java.util.ArrayList;
import com.pm.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pm.subsystem.mapper.IntrusionAlarmMapper;
import com.pm.subsystem.service.IIntrusionAlarmService;
import com.pm.common.config.PageData;

/**
 * 入侵报警系统Service业务层处理
 *
 * @author lxf
 * @date 2025-06-03
 */
@Service
public class IntrusionAlarmServiceImpl implements IIntrusionAlarmService
{
    @Autowired
    private IntrusionAlarmMapper intrusionAlarmMapper;

    // ==================== 报警点管理 ====================
    @Override
    public PageData selectAlarmPointById(Long id)
    {
        return intrusionAlarmMapper.selectAlarmPointById(id);
    }

    @Override
    public List<PageData> selectAlarmPointList(PageData pd)
    {
        return intrusionAlarmMapper.selectAlarmPointList(pd);
    }

    @Override
    public int insertAlarmPoint(PageData pd)
    {
        pd.put("createTime", DateUtils.getTime());
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.insertAlarmPoint(pd);
    }

    @Override
    public int updateAlarmPoint(PageData pd)
    {
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.updateAlarmPoint(pd);
    }

    @Override
    public int deleteAlarmPointByIds(Long[] ids)
    {
        return intrusionAlarmMapper.deleteAlarmPointByIds(ids);
    }

    @Override
    public int deleteAlarmPointById(Long id)
    {
        return intrusionAlarmMapper.deleteAlarmPointById(id);
    }

    @Override
    public int toggleArmStatus(PageData pd)
    {
        String deviceCode = (String) pd.get("deviceCode");
        Integer armStatus = (Integer) pd.get("armStatus");
        
        PageData updatePd = new PageData();
        updatePd.put("deviceCode", deviceCode);
        updatePd.put("armStatus", armStatus);
        updatePd.put("updateTime", DateUtils.getTime());
        
        // 记录布防/撤防操作日志
        PageData logPd = new PageData();
        logPd.put("deviceCode", deviceCode);
        logPd.put("operation", armStatus == 1 ? "布防" : "撤防");
        logPd.put("operateTime", DateUtils.getTime());
        logPd.put("createTime", DateUtils.getTime());
        
        return intrusionAlarmMapper.updateAlarmPoint(updatePd);
    }

    @Override
    public int batchArmControl(PageData pd)
    {
        List<String> deviceCodes = (List<String>) pd.get("deviceCodes");
        Integer armStatus = (Integer) pd.get("armStatus");
        
        int successCount = 0;
        for (String deviceCode : deviceCodes) {
            PageData updatePd = new PageData();
            updatePd.put("deviceCode", deviceCode);
            updatePd.put("armStatus", armStatus);
            updatePd.put("updateTime", DateUtils.getTime());
            
            if (intrusionAlarmMapper.updateAlarmPoint(updatePd) > 0) {
                successCount++;
            }
        }
        
        return successCount;
    }

    @Override
    public int testAlarmDevice(String deviceCode)
    {
        // 模拟发送测试指令到设备
        // 实际应该调用设备的测试接口
        
        // 记录测试日志
        PageData testLog = new PageData();
        testLog.put("deviceCode", deviceCode);
        testLog.put("testType", "alarm_test");
        testLog.put("testTime", DateUtils.getTime());
        testLog.put("testResult", "success");
        testLog.put("createTime", DateUtils.getTime());
        
        return 1; // 模拟测试成功
    }

    @Override
    public int updateDeviceConfig(PageData pd)
    {
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.updateAlarmPoint(pd);
    }

    // ==================== 报警记录管理 ====================
    @Override
    public PageData selectAlarmById(Long id)
    {
        return intrusionAlarmMapper.selectAlarmById(id);
    }

    @Override
    public List<PageData> selectAlarmList(PageData pd)
    {
        return intrusionAlarmMapper.selectAlarmList(pd);
    }

    @Override
    public int insertAlarm(PageData pd)
    {
        pd.put("createTime", DateUtils.getTime());
        pd.put("alarmTime", DateUtils.getTime());
        pd.put("handleStatus", 0); // 默认未处理
        
        // 新增报警记录
        int result = intrusionAlarmMapper.insertAlarm(pd);
        
        // 触发联动规则
        if (result > 0) {
            triggerLinkageRules(pd);
        }
        
        return result;
    }

    @Override
    public int processAlarm(PageData pd)
    {
        pd.put("handleTime", DateUtils.getTime());
        return intrusionAlarmMapper.updateAlarm(pd);
    }

    @Override
    public int batchProcessAlarms(PageData pd)
    {
        List<Long> alarmIds = (List<Long>) pd.get("alarmIds");
        Integer handleStatus = (Integer) pd.get("handleStatus");
        String handleRemark = (String) pd.get("handleRemark");
        
        int successCount = 0;
        for (Long alarmId : alarmIds) {
            PageData updatePd = new PageData();
            updatePd.put("id", alarmId);
            updatePd.put("handleStatus", handleStatus);
            updatePd.put("handleRemark", handleRemark);
            updatePd.put("handleTime", DateUtils.getTime());
            
            if (intrusionAlarmMapper.updateAlarm(updatePd) > 0) {
                successCount++;
            }
        }
        
        return successCount;
    }

    @Override
    public int confirmAlarm(Long alarmId)
    {
        PageData pd = new PageData();
        pd.put("id", alarmId);
        pd.put("handleStatus", 1); // 确认状态
        pd.put("handleTime", DateUtils.getTime());
        
        return intrusionAlarmMapper.updateAlarm(pd);
    }

    @Override
    public int ignoreAlarm(Long alarmId, PageData pd)
    {
        pd.put("id", alarmId);
        pd.put("handleStatus", 3); // 忽略状态
        pd.put("handleTime", DateUtils.getTime());
        
        return intrusionAlarmMapper.updateAlarm(pd);
    }

    // ==================== 防区管理 ====================
    @Override
    public PageData selectZoneById(Long id)
    {
        return intrusionAlarmMapper.selectZoneById(id);
    }

    @Override
    public List<PageData> selectZoneList(PageData pd)
    {
        return intrusionAlarmMapper.selectZoneList(pd);
    }

    @Override
    public int insertZone(PageData pd)
    {
        pd.put("createTime", DateUtils.getTime());
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.insertZone(pd);
    }

    @Override
    public int updateZone(PageData pd)
    {
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.updateZone(pd);
    }

    @Override
    public int deleteZoneById(Long id)
    {
        return intrusionAlarmMapper.deleteZoneById(id);
    }

    @Override
    public int toggleZoneStatus(Long zoneId, PageData pd)
    {
        pd.put("id", zoneId);
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.updateZone(pd);
    }

    @Override
    public int batchZoneControl(PageData pd)
    {
        List<Long> zoneIds = (List<Long>) pd.get("zoneIds");
        Integer zoneStatus = (Integer) pd.get("zoneStatus");
        
        int successCount = 0;
        for (Long zoneId : zoneIds) {
            PageData updatePd = new PageData();
            updatePd.put("id", zoneId);
            updatePd.put("zoneStatus", zoneStatus);
            updatePd.put("updateTime", DateUtils.getTime());
            
            if (intrusionAlarmMapper.updateZone(updatePd) > 0) {
                successCount++;
            }
        }
        
        return successCount;
    }

    @Override
    public List<PageData> selectZoneDeviceList(String zoneCode)
    {
        PageData pd = new PageData();
        pd.put("zoneCode", zoneCode);
        return intrusionAlarmMapper.selectZoneDeviceList(pd);
    }

    @Override
    public int addDeviceToZone(PageData pd)
    {
        pd.put("createTime", DateUtils.getTime());
        return 1; // 模拟添加成功
    }

    @Override
    public int removeDeviceFromZone(PageData pd)
    {
        return 1; // 模拟移除成功
    }

    // ==================== 联动规则管理 ====================
    @Override
    public List<PageData> selectLinkageRuleList(PageData pd)
    {
        return intrusionAlarmMapper.selectLinkageRuleList(pd);
    }

    @Override
    public PageData selectLinkageRuleById(Long id)
    {
        return intrusionAlarmMapper.selectLinkageRuleById(id);
    }

    @Override
    public int insertLinkageRule(PageData pd)
    {
        pd.put("createTime", DateUtils.getTime());
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.insertLinkageRule(pd);
    }

    @Override
    public int updateLinkageRule(PageData pd)
    {
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.updateLinkageRule(pd);
    }

    @Override
    public int deleteLinkageRuleById(Long id)
    {
        return intrusionAlarmMapper.deleteLinkageRuleById(id);
    }

    @Override
    public int toggleLinkageRule(Long ruleId, PageData pd)
    {
        pd.put("id", ruleId);
        pd.put("updateTime", DateUtils.getTime());
        return intrusionAlarmMapper.updateLinkageRule(pd);
    }

    @Override
    public List<PageData> selectLinkageRecordList(PageData pd)
    {
        return intrusionAlarmMapper.selectLinkageRecordList(pd);
    }

    @Override
    public int executeLinkage(PageData pd)
    {
        // 执行联动规则
        String linkageAction = (String) pd.get("linkageAction");
        String targetDevice = (String) pd.get("targetDevice");
        
        // 记录联动执行
        PageData linkageRecord = new PageData();
        linkageRecord.put("ruleId", pd.get("ruleId"));
        linkageRecord.put("triggerDevice", pd.get("triggerDevice"));
        linkageRecord.put("targetDevice", targetDevice);
        linkageRecord.put("linkageAction", linkageAction);
        linkageRecord.put("executeTime", DateUtils.getTime());
        linkageRecord.put("executeResult", "success");
        linkageRecord.put("createTime", DateUtils.getTime());
        
        intrusionAlarmMapper.insertLinkageRecord(linkageRecord);
        
        return 1;
    }

    /**
     * 触发联动规则（私有方法）
     */
    private void triggerLinkageRules(PageData alarmData) {
        // 查询相关的联动规则
        PageData ruleQuery = new PageData();
        ruleQuery.put("triggerDeviceCode", alarmData.get("deviceCode"));
        ruleQuery.put("ruleStatus", 1); // 只查询启用的规则
        
        List<PageData> rules = intrusionAlarmMapper.selectLinkageRuleList(ruleQuery);
        
        // 执行所有匹配的联动规则
        for (PageData rule : rules) {
            PageData executePd = new PageData();
            executePd.put("ruleId", rule.get("id"));
            executePd.put("triggerDevice", alarmData.get("deviceCode"));
            executePd.put("targetDevice", rule.get("targetDevice"));
            executePd.put("linkageAction", rule.get("linkageAction"));
            
            executeLinkage(executePd);
        }
    }

    // ==================== 统计查询 ====================
    @Override
    public PageData getAlarmStatistics(PageData pd)
    {
        return intrusionAlarmMapper.selectAlarmStatistics(pd);
    }

    @Override
    public PageData getRealTimeStatus()
    {
        return intrusionAlarmMapper.selectRealTimeStatus(new PageData());
    }

    @Override
    public List<PageData> getAlarmTrend(PageData pd)
    {
        return intrusionAlarmMapper.selectAlarmTrend(pd);
    }

    // ==================== 其他功能 ====================
    @Override
    public PageData checkDeviceHealth(String deviceCode)
    {
        // 模拟设备健康检测
        PageData health = new PageData();
        health.put("deviceCode", deviceCode);
        health.put("isOnline", 1);
        health.put("signalStrength", 85);
        health.put("batteryLevel", 78);
        health.put("lastHeartbeat", DateUtils.getTime());
        health.put("healthStatus", "正常");
        
        return health;
    }

    @Override
    public List<PageData> batchCheckDeviceHealth(List<String> deviceCodes)
    {
        List<PageData> healthList = new ArrayList<>();
        for (String deviceCode : deviceCodes) {
            healthList.add(checkDeviceHealth(deviceCode));
        }
        return healthList;
    }

    @Override
    public PageData getDeviceConfig(String deviceCode)
    {
        PageData config = new PageData();
        config.put("deviceCode", deviceCode);
        config.put("sensitivity", 75);
        config.put("delayTime", 10);
        config.put("armMode", "auto");
        config.put("reportInterval", 30);
        
        return config;
    }

    @Override
    public int resetDevice(String deviceCode)
    {
        // 模拟设备重置
        PageData resetLog = new PageData();
        resetLog.put("deviceCode", deviceCode);
        resetLog.put("operation", "reset");
        resetLog.put("operateTime", DateUtils.getTime());
        resetLog.put("result", "success");
        resetLog.put("createTime", DateUtils.getTime());
        
        return 1;
    }

    @Override
    public List<PageData> selectMaintenanceRecordList(PageData pd)
    {
        return intrusionAlarmMapper.selectMaintenanceRecordList(pd);
    }

    @Override
    public int addMaintenanceRecord(PageData pd)
    {
        pd.put("createTime", DateUtils.getTime());
        return intrusionAlarmMapper.insertMaintenanceRecord(pd);
    }

    @Override
    public PageData generateAlarmReport(PageData pd)
    {
        // 生成报警报表数据
        PageData reportData = new PageData();
        
        // 获取基础统计数据
        PageData statistics = intrusionAlarmMapper.selectAlarmStatistics(pd);
        reportData.putAll(statistics);
        
        // 获取趋势数据
        List<PageData> trendData = intrusionAlarmMapper.selectAlarmTrend(pd);
        reportData.put("trendData", trendData);
        
        reportData.put("reportTime", DateUtils.getTime());
        reportData.put("reportType", pd.get("reportType"));
        
        return reportData;
    }

    @Override
    public int syncIntrusionData(PageData pd)
    {
        // 模拟从其他子系统同步数据
        try {
            // 这里应该调用其他子系统的接口获取数据
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}