#include <time.h>
#include "mqtt_verify.h"
#include "common.h"
#include <openssl/evp.h>
#include <openssl/aes.h> 
#include <openssl/rand.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/err.h>
#include "device_identity.h"
#include "mqtt_init.h"
#include "mylog.h"
#include "http_config_mqtt.h"

/*TRUE为打开验证，FALSE为关闭验证*/
bool VERIFIED_MODE=FALSE;

bool g_service_verify=TRUE;//验证判断

int g_verify_count =12000;//判断是否有一分钟

char g_only_id_middle[11];

char g_secret_key[1024];//存储上一次的topic

bool g_secret_key_index = TRUE;//用于判断是否对比topic

int g_verify_index =0;//判断是否验证成功
pthread_mutex_t g_verify_mutex = PTHREAD_MUTEX_INITIALIZER;//线程锁

char *generate_random_id() {

    char *id_buffer=malloc(11);
    // 1. 定义字符池：包含所有小写字母、大写字母和数字
    const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    const int charset_size = sizeof(charset) - 1; // 减去末尾的 '\0'

    // 2. 循环生成每个字符
    for (int i = 0; i < 10; ++i) {
        // 从字符池中随机选择一个字符
        int key = rand() % charset_size;
        id_buffer[i] = charset[key];
    }

    // 3. 在字符串末尾添加空字符终止符
    id_buffer[10] = '\0';
    return id_buffer;
}

//发送用户获取jwt给服务端验证
int send_jwtser(const char *token){

    cJSON *root = cJSON_CreateObject();
    cJSON *body = cJSON_CreateObject();
    cJSON *head = cJSON_CreateObject();

    char *only_Id =generate_random_id();

    my_zlog_debug("%s",only_Id);

    strcpy(g_only_id_middle,only_Id);

    cJSON_AddStringToObject(body, "data", token);//为0成功

     cJSON_AddStringToObject(body, "only_id", only_Id);

    cJSON_AddNumberToObject(head, "message_type",3006);

    cJSON_AddItemToObject(root, "body", body);
    cJSON_AddItemToObject(root, "head",head);

    char *payload = cJSON_PrintUnformatted(root);
    my_zlog_debug("%s",payload);

    for(int i=0;i<g_mqtt_cam_config_t->mqtt_count;i++){
        mosquitto_publish(g_clients_t[i].mosq, NULL, mqtt_topic_pure_number(), strlen(payload), payload, 0, false); 
    }
    
    free(only_Id);
    cJSON_Delete(root);  // 释放 cJSON 对象
}

//jwt验证函数
int receive_jwt(cJSON *body) {

    char *token=NULL;
    char *token_time=NULL;
    
    cJSON *json_token = cJSON_GetObjectItem(body, "token");
    cJSON *json_token_time = cJSON_GetObjectItem(body, "token_time");
    if(json_token == NULL || json_token_time==NULL) {
        my_zlog_debug("验证为空");
        g_verify_index=1;
        return 1;
    }

    token=json_token->valuestring;
    token_time=json_token_time->valuestring;

    if(g_secret_key_index == FALSE) {
        if(strcmp(token,g_secret_key)!=0){
            send_jwtser(token);
            g_secret_key_index = TRUE;
            pthread_mutex_lock(&g_verify_mutex);
            g_verify_count=0;
            pthread_mutex_unlock(&g_verify_mutex);
            my_zlog_notice("topic不同，验证完成");
        }
    }else {
        my_zlog_notice("topic相同");
        strcpy(g_secret_key,token);
        g_secret_key_index = FALSE;
    }


    unsigned long long token_time_s = strtoull(token_time, NULL, 10);
    
    // 转换为秒级时间戳
    time_t token_time_sec = (time_t)(token_time_s );//后端给的时间戳

    time_t current_verify_time=time(NULL);//当前时间戳

    my_zlog_debug("目前时间戳:%1d",(long)current_verify_time); 
    my_zlog_debug("token时间戳:%1d",(long)token_time_sec); 

    if(token_time_sec>current_verify_time){
        if(g_service_verify == TRUE) g_verify_index=0;//验证默认为正确
        my_zlog_debug("g_verify_index= %d ",g_verify_index);
        if(g_verify_count>12000){
            send_jwtser(token);
            my_zlog_debug("在有效期内");  
            pthread_mutex_lock(&g_verify_mutex);
            g_verify_count=0;
            my_zlog_info("count: %s", g_verify_count);
            pthread_mutex_unlock(&g_verify_mutex);
            my_zlog_debug("g_verify_count=%d",g_verify_count);
            } 
    }else {
        my_zlog_debug("不在有效期内");  
        g_verify_index=1;
        my_zlog_debug("g_verify_index= %d ",g_verify_index);
    }

    my_zlog_info("token: %s", token);
    my_zlog_info("token_time: %s", token_time);
    return 0;

}

//当接收到2006判断是否验证成功
int message2006_verify(cJSON *body){
    char *status=NULL;
    char *onlyid=NULL;

    cJSON *json_status = cJSON_GetObjectItem(body, "status");
    cJSON *json_onlyid = cJSON_GetObjectItem(body, "only_id");
    

    if(json_status == NULL || json_onlyid==NULL) {
        my_zlog_debug("验证为空");
        g_service_verify = FALSE;
        g_verify_index=1;
        my_zlog_debug("g_verify_index= %d ",g_verify_index);
        return 1;
    }
    status = json_status->valuestring;
    onlyid = json_onlyid->valuestring;

    my_zlog_debug("data: %s", status);
    my_zlog_debug("onlyid: %s", onlyid);
    if(strcmp(onlyid,g_only_id_middle) == 0 && strcmp(status, "1") == 0){
        my_zlog_debug("获得验证正确");
        g_service_verify = TRUE;
    }else {
        my_zlog_debug("获得验证c错误，禁止使用");
        g_verify_index=1;
        my_zlog_debug("g_verify_index= %d ",g_verify_index);
        g_service_verify = FALSE;
        return 2;
    }

    return 0;
 }

/*接收到是否打开验证的函数*/
int message2013_recverigy_open(cJSON *body){
    cJSON *verifty_open_index = cJSON_GetObjectItem(body, "verify_status");
    if(verifty_open_index == NULL){
        my_zlog_debug("接收验证是否打开为空");
        return -1;
    }
    int verifty_open = verifty_open_index->valueint;
     my_zlog_debug("verifty:%d",verifty_open);
     if(verifty_open == 0){
        VERIFIED_MODE=FALSE;
        my_zlog_debug("verify close");
     }else {
        VERIFIED_MODE=TRUE;
        my_zlog_debug("verify open");
     }
    return 0;
}

/*发送是否打开验证的mqtt给后端验证*/
int message_sendopen_verify(){
    cJSON *root = cJSON_CreateObject();
    cJSON *body = cJSON_CreateObject();
    cJSON *head = cJSON_CreateObject();

    cJSON_AddNumberToObject(body, "verify_status", 0);

    cJSON_AddNumberToObject(head, "message_type",3013);

    cJSON_AddItemToObject(root, "body", body);
    cJSON_AddItemToObject(root, "head",head);

    char *payload = cJSON_PrintUnformatted(root);

    if(payload==NULL){
        my_zlog_debug("send verify am null");
        return -1;
    }

    my_zlog_debug("%s",payload);

    for(int i=0;i<g_mqtt_cam_config_t->mqtt_count;i++){
        mosquitto_publish(g_clients_t[i].mosq, NULL, mqtt_topic_pure_number(), strlen(payload), payload, 0, false); 
    } 
    
    cJSON_Delete(root);  // 释放 cJSON 对象

    return 0;

}   

/*发送是否打开验证的mqtt给后端验证初始化*/
int verify_open_index_init(){
    if(message_sendopen_verify()!=0){
        return -1;
    }

    return 0;
}