/**
* @file:    $RCSfile: uds_huaweiyun.cpp,v $
* @brief:   $uds_huaweiyun include
*
* @version: $Revision: 1.00 $
* @date:    $Date: 2023/10/24 18:34:00 $
* @author:  $Author: caizhouyu $
* @state:   $State: Exp $
*
* @latest:  $Id: uds_huaweiyun.cpp,v 1.00 2023/10/24 18:34:00 caizhouyu Exp $
*
*/

using namespace std;

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "../mms/db_interface.h"
#include "../json/cjson.h"//WW 2023-08-27新增json解析函数
#include "../include/curl/curl.h" 

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

size_t req_reply(void* ptr, size_t size, size_t nmemb, void* stream)
{
	string* str = (string*)stream;
	(*str).append((char*)ptr, size * nmemb);
	return size * nmemb;
}
/**
* @brief Get_Uuid     解析返回json,得到uuid
* @param ptr            需解码的数据
* @param uuid             需解码的数据大小
* @return  int             0：成功    -1：无效参数
* 注意：解码的数据的大小必须大于4，且是4的倍数
*/
int Get_Uuid(const char* ptr, char* uuid,char* filename) 
{
	int result = 0;
	cJSON* json = cJSON_Parse((char*)ptr);   //json格式序列化
	cJSON* json_code;
	cJSON* json_data;
	cJSON* json_msg;
	if (json) {
		json_code = cJSON_GetObjectItem(json, "code");    //获取success
		json_msg = cJSON_GetObjectItem(json, "msg");    //获取success
		json_data = cJSON_GetObjectItem(json, "data");    //获取data
		if (json_code && json_code->type == cJSON_Number && json_code->valueint==0) {
			printf("upload uds success\n");
			cJSON* json_uuid;
			cJSON* json_filename;
			json_uuid = cJSON_GetObjectItem(json_data, "storeId");    //获取data
			if (json_uuid && json_uuid->type == cJSON_String) {
				strcpy(uuid, json_uuid->valuestring);
				printf("read uds uuid success:%s\n", uuid);
			}
			json_filename = cJSON_GetObjectItem(json_data, "fileName");    //获取data
			if (json_filename && json_filename->type == cJSON_String) {
				strcpy(filename, json_filename->valuestring);
				printf("read uds filename success:%s\n", filename);
			}
			result = 1;
		}
		else if (json_msg && json_msg->valuestring != NULL)
		{
			printf("uuid get falie msg: %s\n", json_msg->valuestring);
			result = 0;
		}
		else
		{
			printf("get uds uuid error :do not get msg\n");
			result = 0;
		}
	}
	else {
		printf("get uds uuid error:do not get json and %s\n", cJSON_GetErrorPtr());
		result = 0;
	}
	cJSON_Delete(json);
	return result;
}
// 将字节数组写入文件
void Write_Byte_Array_To_File(char* local_path, char* data_array, long size) 
{
	// 将字节数组写入文件
	FILE* outFile = fopen(local_path, "wb");
	if (outFile != NULL) {
		fwrite(data_array, sizeof(char), size, outFile);
		fclose(outFile);
		printf("File saved successfully.\n");
	}
	else {
		printf("Failed to open file for writing\n");
	}
}
void Save_File(const char* ptr, char* local_path) 
{
	cJSON* json = cJSON_Parse((char*)ptr);   //json格式序列化
	cJSON* json_success;
	cJSON* json_data;
	cJSON* json_msg;
	if (json) {
		json_success = cJSON_GetObjectItem(json, "sucess");    //获取success
		json_msg = cJSON_GetObjectItem(json, "msg");    //获取success
		json_data = cJSON_GetObjectItem(json, "data");    //获取data
		if (json_success && json_success->type == cJSON_True) {
			printf("save uds file success\n");
			if (json_data && json_data->type == cJSON_String) {
				// 计算解码后的字符串长度
				long decodedLen = strlen(json_data->valuestring) * 3 / 4;
				char* decodedStr = (char*)malloc(decodedLen + 1);
				// 进行Base64解码
				int success = base64_decode(json_data->valuestring, strlen(json_data->valuestring), decodedStr, &decodedLen);
				Write_Byte_Array_To_File(local_path, decodedStr, decodedLen);
				free(decodedStr);
			}
		}
		else if (json_msg && json_msg->valuestring != NULL)
		{
			printf("save uds file falie msg: %s\n", json_msg->valuestring);
		}
		else
		{
			printf("save uds file error :do not get msg\n");
		}
	}
	else {
		printf("save uds file error:do not get json and %s\n", cJSON_GetErrorPtr());
	}
	cJSON_Delete(json);
}
int WebAPI_Uds_Upload(char* strUrl, char* loacl_path, char* uuid,char* filename)
{
	int result = 0;
	printf("loaclpath: %s\n", loacl_path);
	// curl初始化  
	CURL* curl = curl_easy_init();
	// curl返回值 
	CURLcode res;
	if (curl)
	{
		//设置curl的请求头
		struct curl_slist* header_list = NULL;
		//设置Content-Type为multipart/form-data 
		header_list = curl_slist_append(header_list, "Content-Type: multipart/form-data");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);
		//不接收响应头数据0代表不接收 1代表接收
		curl_easy_setopt(curl, CURLOPT_HEADER, 0);
		//设置请求为post请求
		curl_easy_setopt(curl, CURLOPT_POST, 1);
		//设置请求的URL地址
		curl_easy_setopt(curl, CURLOPT_URL, strUrl);
		//设置post请求的参数
		struct curl_httppost* formpost = NULL;
		struct curl_httppost* lastptr = NULL;
		// 添加form-data字段
		curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "file", CURLFORM_FILE, loacl_path, CURLFORM_END);
		//curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "password", CURLFORM_COPYCONTENTS, "secretpassword", CURLFORM_END);
		curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
		//设置ssl验证
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
		//CURLOPT_VERBOSE的值为1时，会显示详细的调试信息
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
		curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
		//设置数据接收和写入函数
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);
		string resPost0;
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&resPost0);
		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
		//设置超时时间
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
		printf(">>>uds upload Post in curl post\n");
		// 开启post请求
		res = curl_easy_perform(curl);
		// 检查请求是否成功
		if (res != CURLE_OK) {
			printf("uds upload failed res code: ");
			result = 0;
		}
		else {
			printf("uds upload success,string %s", resPost0.c_str());
			//后期添加webapi返回值判断
			result=Get_Uuid(resPost0.c_str(), uuid,filename);
		}
		// 释放资源
		curl_slist_free_all(header_list);
		curl_formfree(formpost);
	}
	else
	{
		printf(">>> uds upload init failed");
		result = 0;
	}
	curl_easy_cleanup(curl);
	return result;
}
void WebAPI_Uds_Download(char* strUrl, char* uuid, char* local_path,char* filename)
{
	// curl初始化  
	CURL* curl = curl_easy_init();
	// curl返回值 
	CURLcode res;
	if (curl)
	{
		//设置curl的请求头
		struct curl_slist* header_list = NULL;
		header_list = curl_slist_append(header_list, "Content-Type:application/json;");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);
		//不接收响应头数据0代表不接收 1代表接收
		curl_easy_setopt(curl, CURLOPT_HEADER, 0);
		//设置请求为post请求
		curl_easy_setopt(curl, CURLOPT_POST, 1);
		//设置请求的URL地址
		curl_easy_setopt(curl, CURLOPT_URL, strUrl);
		//设置post请求的参数
		cJSON* json_root = cJSON_CreateObject();
		cJSON_AddItemToObject(json_root, "isWrap", cJSON_CreateString("1"));
		cJSON_AddItemToObject(json_root, "storeId", cJSON_CreateString(uuid));
		cJSON_AddItemToObject(json_root, "filename", cJSON_CreateString(filename));
		char* szjson = cJSON_Print(json_root);
		printf(">>>json %s\n", szjson);
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, szjson);
		//设置ssl验证
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
		//CURLOPT_VERBOSE的值为1时，会显示详细的调试信息
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
		curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
		//设置数据接收和写入函数
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);
		string resPost0;
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&resPost0);
		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
		//设置超时时间
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
		printf(">>>uds download Post in curl post\n");
		// 开启post请求
		res = curl_easy_perform(curl);
		// 检查请求是否成功
		if (res != CURLE_OK) {
			printf("uds download failed res code: ");
		}
		else {
			printf("uds download success,string %s", resPost0.c_str());
			//后期添加webapi返回值判断
			Save_File(resPost0.c_str(), local_path);
		}
		curl_slist_free_all(header_list);
		free(szjson);
		cJSON_Delete(json_root);
	}
	else
	{
		printf(">>> uds download init failed");
	}
	curl_easy_cleanup(curl);
}

#ifdef __cplusplus
}
#endif
