package com.pm.web.controller.device;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
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.IDeviceAlarmService;
import com.pm.subsystem.service.IDeviceServiceOrderService;
import com.pm.common.core.page.TableDataInfo;
import com.pm.common.utils.SecurityUtils;
import com.pm.common.utils.DateUtils;
import com.pm.common.utils.StringUtils;

/**
 * 设备告警Controller
 *
 * @author lxf
 * @date 2025-01-06
 */
@RestController
@RequestMapping("/device/alarms")
public class DeviceAlarmController extends BaseController
{
    @Autowired
    private IDeviceAlarmService deviceAlarmService;

    @Autowired
    private IDeviceServiceOrderService serviceOrderService;

    /**
     * 查询设备告警列表
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:list')")
    @GetMapping("/list")
    public TableDataInfo list()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = deviceAlarmService.selectDeviceAlarmList(pd);
        return getDataTable(list);
    }

    /**
     * 获取设备告警详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(deviceAlarmService.selectDeviceAlarmById(id));
    }

    /**
     * 新增设备告警
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:add')")
    @Log(title = "设备告警", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PageData pd)
    {
        // 生成告警ID
        pd.put("alarmId", "ALM" + System.currentTimeMillis());
        pd.put("alarmTime", DateUtils.getNowDate());
        pd.put("alarmStatus", 1); // 活动中
        pd.put("isReset", 0); // 未复位
        pd.put("isNotified", 0); // 未通知
        pd.put("alarmCount", 1);
        pd.put("firstAlarmTime", DateUtils.getNowDate());
        pd.put("lastAlarmTime", DateUtils.getNowDate());
        return toAjax(deviceAlarmService.insertDeviceAlarm(pd));
    }

    /**
     * 修改设备告警
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:edit')")
    @Log(title = "设备告警", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PageData pd)
    {
        return toAjax(deviceAlarmService.updateDeviceAlarm(pd));
    }

    /**
     * 删除设备告警
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:remove')")
    @Log(title = "设备告警", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(deviceAlarmService.deleteDeviceAlarmByIds(ids));
    }

    /**
     * 告警复位
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:reset')")
    @Log(title = "设备告警复位", businessType = BusinessType.UPDATE)
    @PostMapping("/reset")
    public AjaxResult reset(@RequestBody PageData pd)
    {
        pd.put("resetTime", DateUtils.getNowDate());
        pd.put("resetUser", SecurityUtils.getUsername());

        // 插入复位记录
        PageData resetRecord = new PageData();
        resetRecord.put("resetId", "RST" + System.currentTimeMillis());
        resetRecord.put("alarmId", pd.getString("alarmId"));
        resetRecord.put("deviceCode", pd.getString("deviceCode"));
        resetRecord.put("resetType", "MANUAL");
        resetRecord.put("resetTime", pd.get("resetTime"));
        resetRecord.put("resetUser", pd.getString("resetUser"));
        resetRecord.put("resetReason", pd.getString("resetReason"));
        resetRecord.put("resetRemark", pd.getString("resetRemark"));
        deviceAlarmService.insertAlarmResetRecord(resetRecord);

        return toAjax(deviceAlarmService.resetDeviceAlarm(pd));
    }

    /**
     * 批量告警复位
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:reset')")
    @Log(title = "批量告警复位", businessType = BusinessType.UPDATE)
    @PostMapping("/batchReset")
    public AjaxResult batchReset(@RequestBody Map<String, List<String>> params)
    {
        List<String> alarmIds = params.get("alarmIds");
        if (alarmIds == null || alarmIds.isEmpty()) {
            return error("请选择要复位的告警");
        }
        return toAjax(deviceAlarmService.batchResetDeviceAlarm(alarmIds));
    }

    /**
     * 获取告警统计信息
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:query')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        PageData pd = this.getPageData();
        Map<String, Object> stats = deviceAlarmService.getAlarmStatistics(pd);
        return success(stats);
    }

    /**
     * 获取告警趋势数据
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:query')")
    @GetMapping("/trend")
    public AjaxResult getTrend()
    {
        PageData pd = this.getPageData();
        List<Map<String, Object>> trend = deviceAlarmService.getAlarmTrend(pd);
        return success(trend);
    }

    /**
     * 创建服务单
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:createOrder')")
    @Log(title = "创建服务单", businessType = BusinessType.OTHER)
    @PostMapping("/createOrder")
    public AjaxResult createServiceOrder(@RequestBody PageData pd)
    {
        try {
            // 获取告警信息
            PageData alarmInfo = deviceAlarmService.selectDeviceAlarmByAlarmId(pd.getString("alarmId"));
            if (alarmInfo == null) {
                return error("告警信息不存在");
            }

            // 检查是否已创建服务单
            if (StringUtils.isNotEmpty(alarmInfo.getString("serviceOrderId"))) {
                return error("该告警已创建服务单");
            }

            // 创建服务单
            PageData orderPd = new PageData();
            String orderId = "ORD" + System.currentTimeMillis();
            orderPd.put("orderId", orderId);
            orderPd.put("alarmId", pd.getString("alarmId"));
            orderPd.put("deviceCode", alarmInfo.getString("deviceCode"));
            orderPd.put("deviceName", alarmInfo.getString("deviceName"));
            orderPd.put("orderType", pd.getString("REPAIR"));
            orderPd.put("orderTitle", "告警处理-" + alarmInfo.getString("alarmMessage"));
            orderPd.put("orderContent", pd.getString("orderContent"));
            orderPd.put("priority", pd.getString( "NORMAL"));
            orderPd.put("orderStatus", "PENDING");
            orderPd.put("reporter", SecurityUtils.getUsername());
            orderPd.put("reportTime", DateUtils.getNowDate());
            orderPd.put("estimatedDuration", pd.get("estimatedDuration"));
            orderPd.put("remark", pd.getString("remark"));

            int result = serviceOrderService.insertServiceOrder(orderPd);
            if (result > 0) {
                // 更新告警的服务单ID
                PageData updatePd = new PageData();
                updatePd.put("id", alarmInfo.get("id"));
                updatePd.put("serviceOrderId", orderId);
                deviceAlarmService.updateDeviceAlarm(updatePd);

                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("orderId", orderId);
                resultMap.put("msg", "服务单创建成功");
                return success(resultMap);
            } else {
                return error("服务单创建失败");
            }
        } catch (Exception e) {
            logger.error("创建服务单失败", e);
            return error("创建服务单失败：" + e.getMessage());
        }
    }

    /**
     * 批量创建服务单
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:createOrder')")
    @Log(title = "批量创建服务单", businessType = BusinessType.OTHER)
    @PostMapping("/batchCreateOrder")
    public AjaxResult batchCreateServiceOrder(@RequestBody Map<String, Object> params)
    {
        List<String> alarmIds = (List<String>) params.get("alarmIds");
        if (alarmIds == null || alarmIds.isEmpty()) {
            return error("请选择要创建服务单的告警");
        }

        int successCount = 0;
        int failCount = 0;
        List<String> failedAlarms = new ArrayList<>();

        for (String alarmId : alarmIds) {
            PageData pd = new PageData();
            pd.put("alarmId", alarmId);
            pd.put("orderType", params.get("orderType"));
            pd.put("priority", params.get("priority"));
            pd.put("orderContent", params.get("orderContent"));

            try {
                AjaxResult result = createServiceOrder(pd);
                if (result.get("code").equals(200)) {
                    successCount++;
                } else {
                    failCount++;
                    failedAlarms.add(alarmId);
                }
            } catch (Exception e) {
                failCount++;
                failedAlarms.add(alarmId);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("failedAlarms", failedAlarms);

        if (failCount == 0) {
            return AjaxResult.success("批量创建服务单成功", result);
        } else if (successCount == 0) {
            return AjaxResult.error("批量创建服务单失败");
        } else {
            return AjaxResult.success("部分服务单创建成功", result);
        }
    }

    /**
     * 获取服务单信息
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:query')")
    @GetMapping("/order/{orderId}")
    public AjaxResult getServiceOrder(@PathVariable("orderId") String orderId)
    {
        PageData order = serviceOrderService.selectServiceOrderByOrderNo(orderId);
        if (order == null) {
            return error("服务单不存在");
        }
        return success(order);
    }

    /**
     * 导出设备告警数据
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:export')")
    @Log(title = "设备告警", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response)
    {
        try {
            PageData pd = this.getPageData();
            List<PageData> list = deviceAlarmService.selectDeviceAlarmList(pd);
            String filename = "设备告警记录";
            String[] titles = {
                    "告警ID,alarmId",
                    "设备编码,deviceCode",
                    "设备名称,deviceName",
                    "子系统类型,subsystemType",
                    "点位编码,pointCode",
                    "点位名称,pointName",
                    "空间名称,spaceName",
                    "楼栋名称,buildingName",
                    "楼层名称,floorName",
                    "告警类型,alarmType",
                    "告警级别,alarmLevel",
                    "告警值,alarmValue",
                    "限制值,limitValue",
                    "单位,unit",
                    "告警时间,alarmTime",
                    "恢复时间,recoveryTime",
                    "告警状态,alarmStatus",
                    "复位状态,isReset",
                    "复位时间,resetTime",
                    "复位用户,resetUser",
                    "告警消息,alarmMessage",
                    "服务单ID,serviceOrderId"
            };
            ExcelUtilPageData.exportXLSX(response, null, null, filename, titles, list);
        } catch (Exception e) {
            logger.error("导出设备告警数据失败", e);
        }
    }

    /**
     * 获取告警复位记录
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:query')")
    @GetMapping("/resetRecords/{alarmId}")
    public AjaxResult getResetRecords(@PathVariable("alarmId") String alarmId)
    {
        List<PageData> records = deviceAlarmService.selectAlarmResetRecords(alarmId);
        return success(records);
    }

    /**
     * 确认告警
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:confirm')")
    @Log(title = "确认告警", businessType = BusinessType.UPDATE)
    @PostMapping("/confirm")
    public AjaxResult confirmAlarm(@RequestBody PageData pd)
    {
        pd.put("confirmUser", SecurityUtils.getUsername());
        pd.put("confirmTime", DateUtils.getNowDate());
        return toAjax(deviceAlarmService.confirmAlarm(pd));
    }

    /**
     * 屏蔽告警
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:mask')")
    @Log(title = "屏蔽告警", businessType = BusinessType.UPDATE)
    @PostMapping("/mask")
    public AjaxResult maskAlarm(@RequestBody PageData pd)
    {
        pd.put("maskUser", SecurityUtils.getUsername());
        pd.put("maskTime", DateUtils.getNowDate());
        return toAjax(deviceAlarmService.maskAlarm(pd));
    }

    /**
     * 取消屏蔽告警
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:mask')")
    @Log(title = "取消屏蔽告警", businessType = BusinessType.UPDATE)
    @PostMapping("/unmask/{alarmId}")
    public AjaxResult unmaskAlarm(@PathVariable("alarmId") String alarmId)
    {
        PageData pd = new PageData();
        pd.put("alarmId", alarmId);
        pd.put("alarmStatus", 1); // 恢复到活动状态

        // 查询告警信息
        PageData alarmInfo = deviceAlarmService.selectDeviceAlarmByAlarmId(alarmId);
        if (alarmInfo == null) {
            return error("告警信息不存在");
        }

        // 更新告警状态
        PageData updatePd = new PageData();
        updatePd.put("id", alarmInfo.get("id"));
        updatePd.put("alarmStatus", 1);

        return toAjax(deviceAlarmService.updateDeviceAlarm(updatePd));
    }

    /**
     * 获取告警详情（包含处理记录）
     */
    @PreAuthorize("@ss.hasPermi('device:alarm:query')")
    @GetMapping(value = "/detail/{id}")
    public AjaxResult getDetail(@PathVariable("id") Long id)
    {
        Map<String, Object> result = new HashMap<>();

        // 获取告警基本信息
        PageData alarmInfo = deviceAlarmService.selectDeviceAlarmById(id);
        if (alarmInfo == null) {
            return error("告警信息不存在");
        }
        result.put("alarmInfo", alarmInfo);

        // 获取复位记录
        String alarmId = alarmInfo.getString("alarmId");
        List<PageData> resetRecords = deviceAlarmService.selectAlarmResetRecords(alarmId);
        result.put("resetRecords", resetRecords);

        // 获取关联的服务单信息
        String serviceOrderId = alarmInfo.getString("serviceOrderId");
        if (StringUtils.isNotEmpty(serviceOrderId)) {
            PageData serviceOrder = serviceOrderService.selectServiceOrderByOrderNo(serviceOrderId);
            result.put("serviceOrder", serviceOrder);

            // 获取服务单操作记录
            List<PageData> orderRecords = serviceOrderService.selectOrderOperateRecords(serviceOrderId);
            result.put("orderRecords", orderRecords);
        }

        return success(result);
    }
}