#include "abnormal_log.h"
#include "../tag.h"
#include "hash_intptr.h"
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <dirent.h>
#include "rull.h"
#include <stdlib.h> // 用于system函数
#include <syslog.h> // 用于syslog功能

#define ABNORMAL_POINT_FILE_PATH "/app/abnormal_info/abnormal.json"
#define ABNORMAL_INITED 1
#define ABNORMAL_LOG_FACILITY LOG_LOCAL5 // 使用local5设施
#define MAX_MATCHED_POINTS 10            // 最大匹配异常点数量
#define MAX_LOG_BUFFER_SIZE 1024         // 最大日志缓冲区大小
#define MAX_ABNORMAL_REPORT_TIMES 1      //相同异常报文上报次数

typedef struct
{
    abnormal_point_t **points;   // 异常检测点数组
    int point_count;             // 异常检测点数量
    struct list_head msg_queue;  // 消息队列
    pthread_mutex_t queue_mutex; // 队列互斥锁
    pthread_cond_t queue_cond;   // 队列条件变量
    bool worker_running;         // 工作线程运行标志
    pthread_t worker_threads;

} abnormal_log_t;

typedef struct
{
    tag_t **tag;
    int taglen; // 添加tag数量字段
    unsigned char *send_rawdata;
    int send_rawdatalen;
    unsigned char *recv_rawdata;
    int recv_rawdata_len;
    struct list_head list;
} abnormal_msg_node_t;

typedef abnormal_log_t *abnormal_log_handle;

static abnormal_log_handle g_handle;

static int match_abnormal_points(tag_t *tag, abnormal_point_t **matched_points, int max_count)
{
    if (!tag)
    {
        ems_syslog(LOG_WARNING, "match_abnormal_points: tag is NULL");
        return 0;
    }
    if (!g_handle)
    {
        ems_syslog(LOG_WARNING, "match_abnormal_points: g_handle is NULL");
        return 0;
    }
    if (!g_handle->points)
    {
        ems_syslog(LOG_WARNING, "match_abnormal_points: points array is NULL");
        return 0;
    }
    if (!matched_points)
    {
        ems_syslog(LOG_WARNING, "match_abnormal_points: matched_points is NULL");
        return 0;
    }
    if (max_count <= 0)
    {
        ems_syslog(LOG_WARNING, "match_abnormal_points: max_count <= 0");
        return 0;
    }
    //ems_syslog(LOG_ERR,"=== 开始匹配异常检测点 ===设备类型: %s====标签名称: %s====属性: %d\n", device_name, tag_name, property);

    // 获取设备类型和标签名称
    if (!tag->dev_ptr)
    {
        ems_syslog(LOG_ERR, "tag->dev_ptr is NULL");
        return 0;
    }
    device_t *device = (device_t *)tag->dev_ptr;
    if (!device->no)
    {
        ems_syslog(LOG_ERR, "device->no is NULL");
        return 0;
    }
    char device_name[32] = {0};
    snprintf(device_name,sizeof(device_name),"%s",device->no);
    const char *device_type = device->dev_type;
    const char *tag_name = tag->name;
    int property = tag->property;
    int matched_count = 0;

    // 遍历所有异常检测点进行匹配
    for (int i = 0; i < g_handle->point_count && matched_count < max_count; i++)
    {
        abnormal_point_t *point = g_handle->points[i];
        if (!point || !point->device_name || !point->tag_name || !point->device_type)
        {
            continue;
        }
        //ems_syslog(LOG_ERR,"point->device_name:%s,device_name:%s",point->device_name,device_name);
        // 1. 尝试精确匹配设备：device_name.tag_name.property(正常情况)
        if (strcmp(point->device_name, device_name) == 0 &&
            strcmp(point->tag_name, tag_name) == 0 &&
            point->property == property)
        {
            //ems_syslog(LOG_ERR, "精确匹配成功! 设备名称:%s 标签名称:%s 属性:%d===异常描述: %s====rull: %s\n",device_name, tag_name, property, point->description ? point->description : "无描述", point->rule ? point->rule : "无规则");
            matched_points[matched_count] = point;
            matched_count++;
            continue; // 继续匹配下一条规则
        }
        //2. 尝试模糊匹配设备(device_name为空的情况)
        if (strcmp(point->device_name, "") == 0 &&
            strcmp(point->device_type, device_type) == 0 &&
            strcmp(point->tag_name, tag_name) == 0 &&
            point->property == property)
        {
            //ems_syslog(LOG_ERR, "精确匹配成功! 设备类型:%s 标签名称:%s 属性:%d===异常描述: %s====rull: %s\n",device_type, tag_name, property, point->description ? point->description : "无描述", point->rule ? point->rule : "无规则");
            matched_points[matched_count] = point;
            matched_count++;
            continue; // 继续匹配下一条规则
        }

        // 3. 尝试模糊匹配：device_name. .property (device_name有填但tag_name为空的情况)
        if (strcmp(point->device_name, device_name) == 0 &&
            strcmp(point->tag_name, "") == 0 &&
            point->property == property)
        {
            //ems_syslog(LOG_ERR, "模糊匹配成功! 设备名称:%s 标签名称:空 属性:%d===异常描述: %s====rull: %s\n",device_name, property, point->description ? point->description : "无描述", point->rule ? point->rule : "无规则");
            matched_points[matched_count] = point;
            matched_count++;
            continue; // 继续匹配下一条规则
        }

        // 4. 尝试模糊匹配：device_type. .property (device_name和tag_name都为空的情况)
        if (strcmp(point->device_name, "") == 0 &&
            strcmp(point->device_type, device_type) == 0 &&
            strcmp(point->tag_name, "") == 0 &&
            point->property == property)
        {
            //ems_syslog(LOG_ERR, "模糊匹配成功! 设备类型:%s 标签名称:空 属性:%d===异常描述: %s====rull: %s\n",device_type, property, point->description ? point->description : "无描述", point->rule ? point->rule : "无规则");
            matched_points[matched_count] = point;
            matched_count++;
            continue; // 继续匹配下一条规则
        }
    }
    //ems_syslog(LOG_ERR, "匹配到 %d 个异常检测点 === 结束匹配 ===\n", matched_count);
    return matched_count;
}

static void *worker_thread()
{
    while (g_handle->worker_running)
    {

        int abnormal_count = 0;

        pthread_mutex_lock(&g_handle->queue_mutex);
        while (list_empty(&g_handle->msg_queue) && g_handle->worker_running) // 等待队列非空
        {                                                                    // 当队列为空且线程运行时进入等待状态
            pthread_cond_wait(&g_handle->queue_cond, &g_handle->queue_mutex);
        }
        // 检查线程停止标志必须在解锁前进行
        if (!g_handle->worker_running)
        { // 如果被唤醒后发现需要停止，立即退出
            ems_syslog(LOG_INFO, "worker_thread exit");
            pthread_mutex_unlock(&g_handle->queue_mutex);
            break;
        }
        abnormal_msg_node_t *node = list_first_entry(&g_handle->msg_queue, abnormal_msg_node_t, list); // 获取队列头部消息
        list_del(&node->list);
        pthread_mutex_unlock(&g_handle->queue_mutex);

        for (int i = 0; i < node->taglen; i++) // 遍历所有tag
        {
            if (node->tag[i]->abnormal_rull_inited < ABNORMAL_INITED) // 初始化异常规则标志 是否被异常规则初始化过，不然跳变的判断会出问题
            {
                // 使用原子操作确保线程安全
                node->tag[i]->abnormal_rull_inited++;
                continue;
            }

            abnormal_point_t *matched_points[MAX_MATCHED_POINTS]; // 为每个tag分配匹配的异常点数组
            int matched_count = match_abnormal_points(node->tag[i], matched_points, MAX_MATCHED_POINTS);

            if (matched_count > MAX_MATCHED_POINTS)
            {
                ems_syslog(LOG_WARNING, "matched_count exceeds array size: %d", matched_count);
                matched_count = MAX_MATCHED_POINTS; // 限制在数组大小范围内
            }
            if (matched_count > 0)
            {
                //ems_syslog(LOG_ERR, "matched_count: %d\n", matched_count);
                for (int j = 0; j < matched_count; j++) // 遍历所有匹配的异常点位的规则
                {
                    abnormal_point_t *matched_point = matched_points[j];
                    if (matched_point->is_special_rule)  //特殊规则
                    {
                        if(rull_process(matched_point, node->tag[i]) == true)
                        {
                            if(node->tag[i]->is_abnormal)   //已经被记录过异常，不需要重复记录
                                continue;
                            node->tag[i]->is_abnormal = true;   //标记为异常
                            //ems_syslog(LOG_ERR, "发现异常tag，tag_name: %s, tag_value: %f\n", node->tag[i]->dev_tag_name, node->tag[i]->read_cache.to_float);
                            char temp_buf[256];
                            if (node->tag[i]->data_type == TYPE_TAG_INT)
                                snprintf(temp_buf, sizeof(temp_buf), "%s=(%ld),%s",
                                        node->tag[i]->dev_tag_name, node->tag[i]->read_cache.to_int, matched_point->description);
                            else
                                snprintf(temp_buf, sizeof(temp_buf), "%s=(%.4f),%s",
                                        node->tag[i]->dev_tag_name, node->tag[i]->read_cache.to_float, matched_point->description);
                            lnxall_syslog_uid(LOG_DEBUG, ABNORMAL_LOG_UID, "Abnormal Tag: %s", temp_buf);
                            abnormal_count++;
                        }
                        else
                            node->tag[i]->is_abnormal = false;   //标记为正常
                    }
                    else if(!matched_point->is_special_rule)  //不为特殊规则
                    {
                        if(rull_process(matched_point, node->tag[i]) == true)
                        {
                            char temp_buf[256];
                            if (node->tag[i]->data_type == TYPE_TAG_INT)
                                snprintf(temp_buf, sizeof(temp_buf), "%s=(%ld),%s",
                                        node->tag[i]->dev_tag_name, node->tag[i]->read_cache.to_int, matched_point->description);
                            else
                                snprintf(temp_buf, sizeof(temp_buf), "%s=(%.4f),%s",
                                        node->tag[i]->dev_tag_name, node->tag[i]->read_cache.to_float, matched_point->description);
                            if(matched_point->report_count < MAX_ABNORMAL_REPORT_TIMES)
                            {
                                lnxall_syslog_uid(LOG_DEBUG, ABNORMAL_LOG_UID, "Abnormal Tag: %s", temp_buf);
                                abnormal_count++;
                            }
                            matched_points[j]->report_count++;
                        }
                        else
                        {
                            matched_point->report_count = 0;
                        }
                    }
                }
            }
        }
        // 如果有异常规则匹配到，则写入异常日志到syslog
        if (abnormal_count > 0)
        {
            // 发送异常统计信息
            char log_message[256];
            snprintf(log_message, sizeof(log_message),
                     "Abnormal Count: %d", abnormal_count);
            lnxall_syslog_uid(LOG_DEBUG, ABNORMAL_LOG_UID, "%s", log_message);

            // 发送send数据
            if (node->send_rawdatalen > 0 && node->send_rawdata != NULL)
            {
                char send_data[MAX_LOG_BUFFER_SIZE];
                int send_len = snprintf(send_data, sizeof(send_data),
                                        "send Data (Length: %d): ", node->send_rawdatalen);
                if (send_len < 0 || send_len >= sizeof(send_data))
                {
                    ems_syslog(LOG_ERR, "send_data buffer overflow risk");
                    send_len = sizeof(send_data) - 1;
                }
                for (int i = 0; i < node->send_rawdatalen && send_len < sizeof(send_data) - 4; i++)
                {
                    send_len += snprintf(send_data + send_len, sizeof(send_data) - send_len,
                                         "%02X ", node->send_rawdata[i]);
                    if (send_len >= sizeof(send_data) - 1)
                        break;
                }
                send_data[sizeof(send_data) - 1] = '\0'; // 确保字符串终止
                lnxall_syslog_uid(LOG_DEBUG, ABNORMAL_LOG_UID, "%s", send_data);
            }

            // 发送recv数据
            if (node->recv_rawdata_len > 0 && node->recv_rawdata != NULL)
            {
                char recv_data[MAX_LOG_BUFFER_SIZE];
                int recv_len = snprintf(recv_data, sizeof(recv_data),
                                        "recv Data (Length: %d): ", node->recv_rawdata_len);
                if (recv_len < 0 || recv_len >= sizeof(recv_data))
                {
                    ems_syslog(LOG_ERR, "recv_data buffer overflow risk");
                    recv_len = sizeof(recv_data) - 1;
                }
                for (int i = 0; i < node->recv_rawdata_len && recv_len < sizeof(recv_data) - 4; i++)
                {
                    recv_len += snprintf(recv_data + recv_len, sizeof(recv_data) - recv_len,
                                         "%02X ", node->recv_rawdata[i]);
                    if (recv_len >= sizeof(recv_data) - 1)
                        break;
                }
                recv_data[sizeof(recv_data) - 1] = '\0'; // 确保字符串终止
                lnxall_syslog_uid(LOG_DEBUG, ABNORMAL_LOG_UID, "%s", recv_data);
            }

            // 发送分隔符
            lnxall_syslog_uid(LOG_DEBUG, ABNORMAL_LOG_UID, "----------------------------------------");
        }

        // 统一资源清理
        if (node)
        {
            if (node->recv_rawdata)
            {
                free(node->recv_rawdata);
                node->recv_rawdata = NULL;
            }
            if (node->send_rawdata)
            {
                free(node->send_rawdata);
                node->send_rawdata = NULL;
            }
            if (node->tag)
            {
                free(node->tag);
                node->tag = NULL;
            }
            free(node);
        }
    }

    return NULL;
}

abnormal_point_t **parse_abnormal_points_from_json(const char *json_str, int *point_count) {
    cJSON *root = cJSON_Parse(json_str);
    if (!root) {
        fprintf(stderr, "JSON parse error: %s\n", cJSON_GetErrorPtr());
        return NULL;
    }

    // 获取 points 数组
    cJSON *points_array = cJSON_GetObjectItemCaseSensitive(root, "points");
    if (!cJSON_IsArray(points_array)) {
        fprintf(stderr, "points is not an array\n");
        cJSON_Delete(root);
        return NULL;
    }

    // 计算检测点总数
    *point_count = cJSON_GetArraySize(points_array);
    if (*point_count <= 0) {
        fprintf(stderr, "Invalid point count: %d\n", *point_count);
        cJSON_Delete(root);
        return NULL;
    }

    // 分配检测点指针数组
    abnormal_point_t **points = (abnormal_point_t **)malloc(*point_count * sizeof(abnormal_point_t *));
    if (!points) {
        fprintf(stderr, "Memory allocation failed\n");
        cJSON_Delete(root);
        *point_count = 0;
        return NULL;
    }

    // 遍历 points 数组
    int point_index = 0;
    cJSON *point_item;
    cJSON_ArrayForEach(point_item, points_array) {
        // 分配新检测点结构体
        abnormal_point_t *point = (abnormal_point_t *)calloc(1, sizeof(abnormal_point_t));
        points[point_index++] = point;

        // 解析基础字段
        cJSON *item;
        if ((item = cJSON_GetObjectItemCaseSensitive(point_item, "tag_name"))) {
            point->tag_name = strdup(item->valuestring);
        }
        if ((item = cJSON_GetObjectItemCaseSensitive(point_item, "device_name"))) {
            point->device_name = strdup(item->valuestring);
        }
        if ((item = cJSON_GetObjectItemCaseSensitive(point_item, "device_type"))) {
            point->device_type = strdup(item->valuestring);
        }
        if ((item = cJSON_GetObjectItemCaseSensitive(point_item, "property"))) {
            // 使用 get_property_by_string 将字符串属性转换为整数类型
            point->property = get_property_by_string(item->valuestring);
        }
        if ((item = cJSON_GetObjectItemCaseSensitive(point_item, "rule"))) {
            point->rule = strdup(item->valuestring);
        }
        if ((item = cJSON_GetObjectItemCaseSensitive(point_item, "description"))) {
            point->description = strdup(item->valuestring);
        }
        point->report_count = 0;
        if(strstr(point->rule,"value<") || strstr(point->rule,"value>") || strstr(point->rule,"value <") || strstr(point->rule,"value >") || strstr(point->rule,"value==") || strstr(point->rule,"value =="))
            point->is_special_rule = true;
        else
            point->is_special_rule = false;
    }

    cJSON_Delete(root);
    return points;
}

// 释放检测点内存
void free_abnormal_points(abnormal_point_t **points, int point_count) {
    for (int i = 0; i < point_count; i++) {
        abnormal_point_t *point = points[i];
        free(point->tag_name);
        free(point->device_name);
        // property 现在是整数类型，不需要释放
        free(point->rule);
        free(point->description);
        free(point);
    }
    free(points);
}


abnormal_point_t** load_abnormal_points_cfg(char *file, int *point_count)
{
    if (!file){
        ems_syslog(LOG_ERR,"file is null");
        return NULL;
    }
    
    // 读取 JSON 文件内容
    FILE* fp = fopen(file, "r");
    if (!fp) {
        ems_syslog(LOG_ERR,"file can't open\n");
        return NULL;
    }
    fseek(fp, 0, SEEK_END);
    long fsize = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    char* json_str = (char*)malloc(fsize + 1);
    fread(json_str, 1, fsize, fp);
    json_str[fsize] = '\0';
    fclose(fp);

    // 解析 JSON
    abnormal_point_t** points = parse_abnormal_points_from_json(json_str,point_count);
    if (!points) {
        ems_syslog(LOG_ERR,"parse abnormal points from json failed\n");
        free(json_str);
        return NULL;
    }

    free(json_str);
    return points;
}

int abnormal_log_init()
{
    ems_syslog(LOG_DEBUG,"abnormal_log_init() starting\n");

    g_handle = (abnormal_log_handle)calloc(1, sizeof(abnormal_log_t));
    if (g_handle == NULL)
    {
        ems_syslog(LOG_DEBUG,"Failed to allocate memory for g_handle\n");
        return -1;
    }
    g_handle->points = NULL;
    g_handle->point_count = 0;
    g_handle->worker_threads = 0; // 初始化线程ID为0

    // 创建异常数据记录目录
    // mkdir("/app/abnormal_info", 0755);


    // ems_syslog(ABNORMAL_LOG_FACILITY | LOG_INFO, "TEST: abnormal_log_init() completed666");
    // ems_syslog(ABNORMAL_LOG_FACILITY | LOG_INFO, "TEST: abnormal_log_init() completed22222");

    // 加载异常检测点配置
    g_handle->points = load_abnormal_points_cfg(ABNORMAL_POINT_FILE_PATH, &g_handle->point_count);

    if (!g_handle->points)
    {
        ems_syslog(LOG_ERR, "load_abnormal_points_cfg failed\n");
        g_handle->worker_running = 0;
        return -1;
    }

    g_handle->worker_running = 1;
    pthread_cond_init(&g_handle->queue_cond, NULL);
    pthread_mutex_init(&g_handle->queue_mutex, NULL);
    INIT_LIST_HEAD(&g_handle->msg_queue);
    int create_result = pthread_create(&g_handle->worker_threads, NULL, worker_thread, NULL);
    if (create_result != 0)
    {
        ems_syslog(LOG_ERR, "Failed to create worker thread, error: %d\n", create_result);
        g_handle->worker_threads = 0; // 确保线程ID为0表示创建失败
    }

    // 写入启动日志到syslog
    time_t now = time(NULL);
    struct tm target_time = {};  
    localtime_r(&now, &target_time);
    struct tm *tm_info = &target_time;

    char time_str[64];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info);

    lnxall_syslog_uid(LOG_DEBUG, ABNORMAL_LOG_UID, "=== Abnormal Log Started at %s ===", time_str);

    return 0;
}

int abnormal_log_match_record(tag_t **tag, int taglen, unsigned char *send_rawdata, int send_rawdatalen, char *recv_rawdata, int recv_rawdata_len)
{
    if (g_handle->worker_running == 0)
    {
        return -1;
    }
    // ems_syslog(LOG_INFO, "abnormal_log_match_record tag:%s property:%d\n", tag->dev_tag_name, tag->property);

    if (tag == NULL || recv_rawdata == NULL || send_rawdata == NULL)
    {
        ems_syslog(LOG_ERR, "abnormal_log_match_record tag or recv_rawdata is NULL\n");
        return -1;
    }

    if (!g_handle->points)
        return -1;

    // 检查是否有匹配的异常点
    bool has_match = false;
    for (int i = 0; i < taglen; i++)
    {
        if (tag[i] == NULL)
            continue; // 跳过NULL指针
        abnormal_point_t *matched_points[MAX_MATCHED_POINTS];
        int matched_count = match_abnormal_points(tag[i], matched_points, 1);
        if (matched_count > 0)
        {
            has_match = true;
            ems_syslog(LOG_INFO,"找到一个匹配的异常点tag,结束遍历,i=%d\n", i);
            break;
        }
    }

    if (!has_match)
    {
        ems_syslog(LOG_INFO,"没有找到匹配的异常点\n");
        return -2;
    }

    abnormal_msg_node_t *node = (abnormal_msg_node_t *)malloc(sizeof(abnormal_msg_node_t));
    if (!node)
    {
        ems_syslog(LOG_ERR, "[AbnormalLog] Failed to allocate memory for abnormal message node");
        return -1;
    }

    node->tag = malloc(sizeof(tag_t *) * taglen);
    if (!node->tag)
    {
        ems_syslog(LOG_ERR, "[AbnormalLog] Failed to allocate memory for tag");
        free(node);
        return -1;
    }
    memcpy(node->tag, tag, sizeof(tag_t *) * taglen);
    node->taglen = taglen; // 设置tag数量

    // 设置send_rawdata
    node->send_rawdatalen = send_rawdatalen;
    node->send_rawdata = (unsigned char *)malloc(send_rawdatalen);
    if (!node->send_rawdata)
    {
        ems_syslog(LOG_ERR, "[AbnormalLog] Failed to allocate memory for send_rawdata");
        free(node->tag);
        free(node);
        return -1;
    }
    memcpy(node->send_rawdata, send_rawdata, send_rawdatalen);

    // 设置recv_rawdata
    node->recv_rawdata_len = recv_rawdata_len;
    node->recv_rawdata = (unsigned char *)malloc(recv_rawdata_len);
    if (!node->recv_rawdata)
    {
        ems_syslog(LOG_ERR, "[AbnormalLog] Failed to allocate memory for recv_rawdata");
        free(node->send_rawdata);
        free(node->tag);
        free(node);
        return -1;
    }
    memcpy(node->recv_rawdata, recv_rawdata, recv_rawdata_len);

    // 加锁并推送到队列
    //ems_syslog(LOG_ERR, "abnormal_log_match_record recv_rawdata_len = %d\n", recv_rawdata_len);
    pthread_mutex_lock(&g_handle->queue_mutex);
    list_add_tail(&node->list, &g_handle->msg_queue);
    pthread_cond_signal(&g_handle->queue_cond); // 唤醒工作线程
    pthread_mutex_unlock(&g_handle->queue_mutex);

    return 0;
}

int abnormal_log_cleanup()
{
    if (g_handle == NULL)
        return -1;

    // 停止工作线程
    g_handle->worker_running = 0;

    pthread_cond_signal(&g_handle->queue_cond);
    pthread_join(g_handle->worker_threads, NULL);

    g_handle->worker_threads = 0; // 重置线程ID

    // 清理队列中的剩余消息
    pthread_mutex_lock(&g_handle->queue_mutex);
    while (!list_empty(&g_handle->msg_queue))
    {
        abnormal_msg_node_t *node = list_first_entry(&g_handle->msg_queue, abnormal_msg_node_t, list);
        list_del(&node->list);
        free(node->recv_rawdata);
        free(node->tag);
        free(node);
    }
    pthread_mutex_unlock(&g_handle->queue_mutex);

    // 销毁互斥锁和条件变量
    pthread_mutex_destroy(&g_handle->queue_mutex);
    pthread_cond_destroy(&g_handle->queue_cond);

    for (int i = 0; i < g_handle->point_count; i++)
    {
        if (g_handle->points[i]->tag_name)
            free(g_handle->points[i]->tag_name);
        if (g_handle->points[i]->device_name)
            free(g_handle->points[i]->device_name);
        if (g_handle->points[i]->device_type)
            free(g_handle->points[i]->device_type);
        if (g_handle->points[i]->rule)
            free(g_handle->points[i]->rule);
        if (g_handle->points[i]->description)
            free(g_handle->points[i]->description);
        free(g_handle->points[i]);
    }
    // 清理异常点数组
    if (g_handle->points != NULL)
    {
        free(g_handle->points);
    }

    // 写入停止日志到syslog
    time_t now = time(NULL);
    struct tm target_time = {};  
    localtime_r(&now, &target_time);
    struct tm *tm_info = &target_time;
    char time_str[64];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info);

    lnxall_syslog_uid(LOG_DEBUG, ABNORMAL_LOG_UID, "=== Abnormal Log Stopped at %s ===", time_str);

    // 关闭syslog
    closelog();

    free(g_handle);
    g_handle = NULL;

    return 0;
}
