import { selectPaginatedDataWithOrder } from "../data/findData";
import { TABLENAME } from "../config/dbEnum";

/** 故障等级映射 */
const levelMap: Record<number, string> = {
    1: '一级',
    2: '二级',
    3: '三级',
};

/** 处理状态映射 */
const statusMap: Record<number, string> = {
    0: '未处理',
    1: '处理中',
    2: '已解决',
};

export interface AlertWorkOrderQueryParams {
    pageNumber?: number;
    pageSize?: number;
    level?: number;        // 故障等级：1/2/3
    fault_code?: string;   // 故障代码（模糊匹配）
    device_id?: string;    // 设备ID（模糊匹配）
    startTime?: string;    // 时间范围起始 'YYYY-MM-DD HH:mm:ss'
    endTime?: string;      // 时间范围截止 'YYYY-MM-DD HH:mm:ss'
}

/**
 * 预警工单列表查询（分页）
 */
export async function getDeviceFaultList(params: AlertWorkOrderQueryParams) {
    const pageNumber = params.pageNumber || 1;
    const pageSize = params.pageSize || 10;

    // 构建查询条件
    const queryParam: any = {};

    if (params.level !== undefined && params.level !== null) {
        queryParam.level = params.level;
    }
    if (params.fault_code) {
        queryParam.fault_code = { "%like%": params.fault_code };
    }
    if (params.device_id) {
        queryParam.device_id = { "%like%": params.device_id };
    }
    if (params.startTime || params.endTime) {
        const start = params.startTime || '1970-01-01 00:00:00';
        const end = params.endTime || '2099-12-31 23:59:59';
        queryParam.occurred_time = { "%between%": [start, end] };
    }

    // 分页查询，按创建时间倒序
    const result = await selectPaginatedDataWithOrder(
        TABLENAME.设备故障表,
        { ...queryParam },
        ["id", "device_id", "fault_type", "fault_code", "fault_description", "occurred_time", "level", "status", "created_at"],
        pageNumber,
        pageSize,
        [["created_at", "DESC"]],
    );

    // 映射中文名
    const list = (result.data as any[]).map((item: any) => ({
        id: item.id,
        device_id: item.device_id || '',
        fault_type: item.fault_type || '',
        fault_code: item.fault_code || '',
        fault_description: item.fault_description || '',
        occurred_time: item.occurred_time || '',
        created_at: item.created_at || '',
        level: item.level,
        levelName: levelMap[item.level] || '未知',
        status: item.status,
        statusName: statusMap[item.status] || '未知',
        order_address: '', // 预留：工单地址，todo
        order_send: 'on', // 预留：工单推送，默认 on，todo
    }));

    return {
        list,
        pagination: result.pagination,
    };
}
