/**
 * 后端管理系统 路由
 */

import asyncHandler from "express-async-handler";
import * as reportBiz from "../biz/report";
import * as regionBiz from "../biz/region";
import * as scheduleBiz from "../biz/schedule";
import { reloadScheduleTasks } from "../biz/scheduleExecutor";
import { eccReqParamater } from "../util/verificationParam";

export function setRouter(httpServer) {
    /** 获取周报告JSON数据 */
    httpServer.get("/api/qdm/report/weekly/data", asyncHandler(getReportData));
    /** 获取九合一环境监测指标 7 天均值（A/B/C馆） */
    httpServer.get("/api/qdm/report/env/weekly/avg", asyncHandler(getEnvWeeklyAvg));
    /** 获取近 7 天故障信息（按 fault_code 分组） */
    httpServer.get("/api/qdm/report/fault/weekly", asyncHandler(getFaultInfo));

    /** 区域设备树 */
    httpServer.get("/api/qdm/admin/region/device", asyncHandler(getRegionDevices));
    /** 日程管理列表 */
    httpServer.get("/api/qdm/admin/schedule/list", asyncHandler(getScheduleList));
    /** 日程管理详情 */
    httpServer.get("/api/qdm/admin/schedule/detail", asyncHandler(getScheduleDetail));
    /** 日程管理新增 */
    httpServer.post("/api/qdm/admin/schedule/add", asyncHandler(addSchedule));
    /** 日程管理编辑 */
    httpServer.post("/api/qdm/admin/schedule/edit", asyncHandler(editSchedule));
    /** 日程管理删除 */
    httpServer.post("/api/qdm/admin/schedule/delete", asyncHandler(deleteSchedule));
}

/**
 * GET /api/qdm/report/weekly/data?weekOffset=0
 * 返回周报告 JSON 数据供前端页面渲染
 */
async function getReportData(req, res) {
    const weekOffset = Number(req.query?.weekOffset) || 0;
    const data = await reportBiz.getWeeklyReportData(weekOffset);
    res.success(data);
}

/**
 * GET /api/qdm/report/env/weekly/avg
 * 返回九合一环境监测指标 7 天均值（A馆 / B馆 / C馆）
 */
async function getEnvWeeklyAvg(req, res) {
    const data = await reportBiz.getEnvIndicatorsWeeklyAvg();
    res.success(data);
}

/**
 * GET /api/qdm/report/fault/weekly
 * 返回近 7 天故障信息，按 fault_code 分组
 */
async function getFaultInfo(req, res) {
    const data = await reportBiz.getFaultInfoLast7Days();
    res.success(data);
}

// ======================= 区域设备 =======================

/**
 * GET /api/qdm/admin/region/device
 * 获取区域设备树（馆 → 层 → 区域 → 设备）
 */
async function getRegionDevices(req, res) {
    const data = await regionBiz.getRegionDevices();
    res.success(data);
}

// ======================= 日程管理 =======================

/**
 * GET /api/qdm/admin/schedule/list
 * 日程列表（分页 + 有效期 + 区域过滤）
 * query: pageNumber, pageSize, startDate, endDate, regionKey
 */
async function getScheduleList(req, res) {
    const data = await scheduleBiz.getScheduleList({
        pageNumber: Number(req.query?.pageNumber) || 1,
        pageSize: Number(req.query?.pageSize) || 10,
        startDate: req.query && req.query.startDate?req.query.startDate:'',
        endDate: req.query && req.query.endDate?req.query.endDate:'',
        deviceIds: req.query?.deviceIds ? req.query.deviceIds : undefined,
        regionKeys: req.query?.regionKeys ? req.query.regionKeys : undefined,
    });
    res.success(data);
}

/**
 * GET /api/qdm/admin/schedule/detail
 * 日程详情（含关联区域/设备）
 * query: scheduleId
 */
async function getScheduleDetail(req, res) {
    const scheduleId = Number(req.query?.scheduleId);
    if (!scheduleId) {
        res.fail("缺少参数 scheduleId");
        return;
    }
    const data = await scheduleBiz.getScheduleDetail(scheduleId);
    if (!data) {
        res.fail("日程不存在");
        return;
    }
    res.success(data);
}

/**
 * POST /api/qdm/admin/schedule/add
 * 新增日程
 * body: title, scheduleTime, acControl, beginValidity, endValidity, regionKeys
 */
async function addSchedule(req, res) {
    let reqConf = { title: 'String', scheduleTime: 'String', acControl: 'String', beginValidity: 'Date', endValidity: 'Date', deviceIds: 'Array', regionKeys: 'Array' };
    const NotMustHaveKeys = ["deviceIds", "regionKeys"];
    let { title, scheduleTime, acControl, beginValidity, endValidity, deviceIds, regionKeys } = eccReqParamater(reqConf, req.body, NotMustHaveKeys);
    if (!title || !scheduleTime || !acControl) {
        res.fail("缺少必填参数：title, scheduleTime, acControl");
        return;
    }
    if ((!deviceIds && !regionKeys) || (!deviceIds.length && !regionKeys.length)) {
        res.fail("至少选择一个区域");
        return;
    }
    const data = await scheduleBiz.addSchedule({
        title,
        schedule_time: scheduleTime,
        ac_control: acControl,
        begin_validity: beginValidity || undefined,
        end_validity: endValidity || undefined,
        deviceIds: deviceIds ?? [],
        regionKeys: regionKeys ?? []
    });
    res.success(data);
    // 新增日程后重载执行器
    reloadScheduleTasks().catch((err) => console.error("[日程重载] 新增后重载失败:", err));
}

/**
 * POST /api/qdm/admin/schedule/edit
 * 编辑日程
 * body: scheduleId, title, scheduleTime, acControl, beginValidity, endValidity, regionKeys
 */
async function editSchedule(req, res) {
    let reqConf = { scheduleId: 'Number', title: 'String', scheduleTime: 'String', acControl: 'String', beginValidity: 'Date', endValidity: 'Date', deviceIds: 'Array', regionKeys: 'Array' };
    const NotMustHaveKeys = ["deviceIds", "regionKeys"];
    let { scheduleId, title, scheduleTime, acControl, beginValidity, endValidity, deviceIds, regionKeys } = eccReqParamater(reqConf, req.body, NotMustHaveKeys);
    if (!scheduleId || !title || !scheduleTime || !acControl) {
        res.fail("缺少必填参数：title, scheduleTime, acControl");
        return;
    }
    if ((!deviceIds && !regionKeys) || (!deviceIds.length && !regionKeys.length)) {
        res.fail("至少选择一个区域");
        return;
    }
    const data = await scheduleBiz.editSchedule({
        scheduleId,
        title,
        schedule_time: scheduleTime,
        ac_control: acControl,
        begin_validity: beginValidity || undefined,
        end_validity: endValidity || undefined,
        deviceIds: deviceIds ?? [],
        regionKeys: regionKeys ?? []
    });
    res.success(data);
    // 编辑日程后重载执行器
    reloadScheduleTasks().catch((err) => console.error("[日程重载] 编辑后重载失败:", err));
}

/**
 * POST /api/qdm/admin/schedule/delete
 * 删除日程
 * body: scheduleId
 */
async function deleteSchedule(req, res) {
    const { scheduleId } = req.body || {};
    if (!scheduleId) {
        res.fail("缺少参数 scheduleId");
        return;
    }
    const data = await scheduleBiz.deleteSchedule(Number(scheduleId));
    res.success(data);
    // 删除日程后重载执行器
    reloadScheduleTasks().catch((err) => console.error("[日程重载] 删除后重载失败:", err));
}
