#include<curl/curl.h>
#include "cjson/cJSON.h"
#include "http_request.h"
#include "device_identity.h"
#include "common.h"


const char *c_post = "http://47.119.190.60/api/v1/device/config";

int g_errCodeValue;

bool g_enable_buzzer_value=0;
double g_warn_voltage_value=10.7;
double g_err_voltage_value=9.7;
double g_shot_speed_value=0.5;

// 回调函数，用于处理接收到的数据
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    struct MemoryStruct *mem = (struct MemoryStruct *)userp;

    char *ptr = realloc(mem->memory, mem->size + realsize + 1);
    if (!ptr) {
        printf("not enough memory (realloc returned NULL)\n");
        return 0;
    }

    mem->memory = ptr;
    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;

    return realsize;
}

//分析接口拉的json分析
int analysis_request_json(char *payload_str) {
    cJSON *json = cJSON_Parse(payload_str);
    if (json == NULL) {
        fprintf(stderr, "Error before: [%s]\n", cJSON_GetErrorPtr());
        return 1;
    }

    // 提取 data 对象
    cJSON *data = cJSON_GetObjectItem(json, "data");
    if(data==NULL) {
        my_zlog_warn("date数据段为空");
        return 2;
    }
    // 提取 errCode
    cJSON *errCode = cJSON_GetObjectItem(json, "errCode");
    if(errCode==NULL) {
        my_zlog_warn("errCode数据段为空");
        return 3;
    }
    // 提取 errMsg
    cJSON *errMsg = cJSON_GetObjectItem(json, "errMsg");
    if(errMsg==NULL) {
        my_zlog_warn("errMsg数据段为空");
    }
    // 提取 data 内部的键值对
    cJSON *enable_buzzer = cJSON_GetObjectItem(data, "enable_buzzer");
    cJSON *force_version = cJSON_GetObjectItem(data, "force_version");
    cJSON *warn_voltage = cJSON_GetObjectItem(data, "warn_voltage");
    cJSON *err_voltage = cJSON_GetObjectItem(data, "err_voltage");
    cJSON *shot_speed= cJSON_GetObjectItem(data, "shot_speed");
    if(cJSON_IsNumber(errCode)) {
        g_errCodeValue = errCode->valueint;
        if(g_errCodeValue != 0){
            cJSON_Delete(json);
            return 6;
        }
    }
    if(cJSON_IsString(errMsg)) {
        char *g_errmsgptr = errMsg->valuestring;
    }
    if(cJSON_IsBool(enable_buzzer)) {
        g_enable_buzzer_value = cJSON_IsTrue(enable_buzzer);
        my_zlog_debug("enable_buzzer: %s", g_enable_buzzer_value ? "true" : "false");
    }
    if(cJSON_IsString(force_version)) {
       char *g_force_versionptr = force_version->valuestring;
        my_zlog_debug("g_force_versionptr: %s",g_force_versionptr);
    }
    if(cJSON_IsNumber(warn_voltage)) {
        g_warn_voltage_value = warn_voltage->valuedouble;
        my_zlog_debug("g_warn_voltage_value: %.2f",g_warn_voltage_value);
    }
    if(cJSON_IsNumber(err_voltage)) {
        g_err_voltage_value = err_voltage->valuedouble;
        my_zlog_debug("g_err_voltage_value: %.2f",g_err_voltage_value);
    }
    if(cJSON_IsNumber(shot_speed)) {
        if(0 <= g_shot_speed_value&&g_shot_speed_value<=1) {
            g_shot_speed_value = shot_speed->valuedouble;
        }
        my_zlog_debug("g_shot_speed_value: %.2f",g_shot_speed_value);
    }

    cJSON_Delete(json);
    return 0;
}

//像接口发送设备id
char *wirte_json() {
    cJSON *body = cJSON_CreateObject();

    cJSON_AddStringToObject(body, "device_id", mqtt_topic_pure_number()); // 发送设备id

    char *payload = cJSON_PrintUnformatted(body);
    my_zlog_debug("%s", payload);
    
    cJSON_Delete(body); 
    return payload;
}

int request_date_open() {//请求数据
    CURL *curl;
    CURLcode res;

    // 初始化libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if (!curl) {
        return 1;
    }

    struct MemoryStruct chunk;
    chunk.memory = malloc(1);  // 初始化为空字符串
    chunk.size = 0;

    // 设置请求URL
    curl_easy_setopt(curl, CURLOPT_URL, c_post);

    // 设置POST请求
    curl_easy_setopt(curl, CURLOPT_POST, 1L);

    char *post_data = wirte_json();
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data);

    // 设置HTTP头
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    // 设置接收数据的回调函数
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

    // 执行请求
    res = curl_easy_perform(curl);

    // 检查错误
    if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    } else {
        // 打印响应数据
        my_zlog_debug("%s", chunk.memory);
        analysis_request_json(chunk.memory);  
    }

    // 清理
    free(post_data);
    free(chunk.memory);
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    
    
    curl_global_cleanup();
    return 0;
}

int request_date() {
     #if HTTP_REQUEST_INDEX == 1
        // 当MODE为1时的代码
        my_zlog_info("HTTP Mode 1: 执行代码A");
        return request_date_open();
    #elif HTTP_REQUEST_INDEX == 2
        // 当MODE为2时的代码
        my_zlog_info("HTTP Mode 2: 执行代码B");
        return 0;
    #else
        my_zlog_error("未知的 WARM_MODE: %d", HTTP_REQUEST_INDEX);
        return -1;
    #endif
}