#include "CRUL_server_call_httpserver.h"
#include <string>
#include <sstream>
#include <iostream>
#include"tinyxml2.h" 
#include "cJSON.h"
#include "common_itk_util.h"
//#include "string_utils.h"

using namespace tinyxml2;
size_t write_data(void* ptr, size_t size, size_t nmemb, void* stream) {
	string data((const char*)ptr, (size_t)size * nmemb);
	*((stringstream*)stream) << data << endl;
	return size * nmemb;
}



const char* trim(const string& str) {
	if (str.size() == 0) {
		return "";
	}
	size_t first = str.find_first_not_of(" \t\n\r");
	size_t last = str.find_last_not_of(" \t\n\r");
	if (first == string::npos) {
		//return "";
	}
	return str.substr(first, (last - first + 1)).c_str();
}

string callHttpserver(string signinfoJsonString, string url){
	CURL *curl;
	CURLcode res;
	curl = curl_easy_init();
	std::stringstream out;
	string result = "";
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		struct curl_slist *headers = NULL;
		headers = curl_slist_append(headers, "Content-Type: application/json");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		const char *data = signinfoJsonString.c_str();
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		res = curl_easy_perform(curl);
		if (res != 0) {
			string errMessage = curl_easy_strerror(res);
			result.append("errMessage =>").append(errMessage);
		}
		printf("返回值：%d\n", res);
		char code[16] = "";
		sprintf(code, "%d", res);
		result.append("\n返回值 =>").append(code);
	}
	string str_json = out.str();
	curl_easy_cleanup(curl);
	printf("str_json===>%s\n", str_json.c_str());
	result.append("\nstr_json =>").append(str_json);
	return result;
}

string sendOA() {
	CURL *curl;
	CURLcode res;
	std::stringstream out;
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, "https://bpmtest10.chint.com/Portal/Webservices/BPMExtendService.asmx/SetItemValues");
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		struct curl_slist *headers = NULL;
		headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		const char *data = "sfId=111177777&instanceId=3333&entityParamValues=ddd";
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
		res = curl_easy_perform(curl);
	}
	string str_json = out.str();
	curl_easy_cleanup(curl);
	printf("return Msg===>%s\n", str_json.c_str());
}
string callHttpGet(string url) {
	void* curl = curl_easy_init();
	// 设置URL
	std::stringstream out;
	curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
	curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
	// 设置接收数据的处理函数和存放变量
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);

	// 执行HTTP GET操作
	CURLcode res = curl_easy_perform(curl);
	if (res != CURLE_OK) {
		fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
	}

	// 接受数据存放在out中，输出之
	//cout << out.str() << endl;
	string str_json = out.str();
	curl_easy_cleanup(curl);
	printf("str_json===>%s\n", str_json.c_str());
	return str_json;
}
string sendOA(string sfid, string instanceId, string entityParamValues, string url) {
	CURL* curl;
	CURLcode res;
	std::stringstream out;
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		struct curl_slist* headers = NULL;
		headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		string temp;
		temp.append("sfId=").append(sfid).append("&instanceId=").append(instanceId).append("&entityParamValues=").append(entityParamValues);
		printf("temp=%s\n", temp.c_str());
		const char* data = temp.c_str();
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
		res = curl_easy_perform(curl);
		//curl_easy_strerror
		printf("temp=%d\n", res);
	}
	string str_json = out.str();
	curl_easy_cleanup(curl);
	printf("return Msg===>%s\n", str_json.c_str());
	return str_json;
}
char* G2U(const char* gb2312)
{
	int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
	len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
	if (wstr) delete[] wstr;
	return str;
}
char* U2G(const char* utf8)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
	len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
	if (wstr) delete[] wstr;
	return str;
}
string readXmlId(string xmlMsg) {
	printf("xmlMsg %s \n", xmlMsg.c_str());
	tinyxml2::XMLDocument doc;
	doc.Parse(U2G(xmlMsg.c_str()));
	tinyxml2::XMLElement* root = doc.RootElement();
	//tinyxml2::XMLElement* fault = root->FirstChildElement("Fault");
	tinyxml2::XMLElement* typeEle = root->FirstChildElement("TYPE");
	if (typeEle == NULL) {
		return "Fault";
	}
	tinyxml2::XMLElement* item = root->FirstChildElement("items");
	char * type = (char*)typeEle->GetText();
	if (strcmp(type, "S") == 0) {
		printf("1111");
		tinyxml2::XMLElement* itemsCs = item->FirstChildElement("EH_HR_UserItems_CS");
		tinyxml2::XMLElement* code = itemsCs->FirstChildElement("Code");
		return code->GetText();
	}
	return typeEle->GetText();
}
string readXmlEmailId(string xmlMsg) {
	printf("xmlMsg %s \n", xmlMsg.c_str());
	tinyxml2::XMLDocument doc;
	doc.Parse(U2G(xmlMsg.c_str()));
	tinyxml2::XMLElement* root = doc.RootElement();
	//tinyxml2::XMLElement* fault = root->FirstChildElement("Fault");
	tinyxml2::XMLElement* typeEle = root->FirstChildElement("TYPE");
	if (typeEle == NULL) {
		return "Fault";
	}
	tinyxml2::XMLElement* item = root->FirstChildElement("items");
	char * type = (char*)typeEle->GetText();
	if (strcmp(type, "S") == 0) {
		printf("1111");
		tinyxml2::XMLElement* itemsCs = item->FirstChildElement("EH_HR_UserItems_CS");
		tinyxml2::XMLElement* code = itemsCs->FirstChildElement("Email");
		return code->GetText();
	}
	return typeEle->GetText();
}
/*获取用户ID（旧）

string getUserIdOA(string email, string url) {
	CURL* curl;
	CURLcode res;
	std::stringstream out;
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		struct curl_slist* headers = NULL;
		headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		string temp; //Email=string&Name=string %E9%82%B5%E9%AA%8F%E9%BD%90
		temp.append("Email=&Name=%E9%82%B5%E4%BF%8A%E9%BD%90&UserUUID=");// .append("Email=").append("&Name=邵俊齐"); //.append(email)
		printf("temp=%s\n", temp.c_str());
		const char* data = temp.c_str();
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
		res = curl_easy_perform(curl);
		//curl_easy_strerror
		printf("temp=%d\n", res);
	}
	string str_json = out.str();
	curl_easy_cleanup(curl);
	printf("return Msg===>%s\n", str_json.c_str());
	return str_json;
}*/
/*获取用户ID（旧）
*/
string getUserIdOA(string email, string url) {
	CURL* curl;
	CURLcode res;
	std::stringstream out;
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		struct curl_slist* headers = NULL;
		headers = curl_slist_append(headers, "item: 2100004876");
		headers = curl_slist_append(headers, "wbs: ");
		headers = curl_slist_append(headers, "factoryNo: ");
		headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		string temp = "Email="; //Email=string&Name=string %E9%82%B5%E9%AA%8F%E9%BD%90
		//temp.append("Email=&Name=%E9%82%B5%E4%BF%8A%E9%BD%90&UserUUID=");// .append("Email=").append("&Name=邵俊齐"); //.append(email)
		temp.append(email).append("&Name=&UserUUID=");
		printf("temp=%s\n", temp.c_str());
		const char* data = temp.c_str();
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
		res = curl_easy_perform(curl);
		//curl_easy_strerror
		printf("res=%d\n", res);
		curl_slist_free_all(headers);
	}
	string str_json = U2G(out.str().c_str());
	curl_easy_cleanup(curl);
	printf("getUserIdOA Msg===>%s\n", str_json.c_str());
	return str_json;
}
/*通过UUID获取用户ID
*/
string getUserIdOAUUID(string uuid, string url) {
	CURL* curl;
	CURLcode res;
	std::stringstream out;
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		struct curl_slist* headers = NULL;
		headers = curl_slist_append(headers, "item: 2100004876");
		headers = curl_slist_append(headers, "wbs: ");
		headers = curl_slist_append(headers, "factoryNo: ");
		headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		string temp; //Email=string&Name=string %E9%82%B5%E9%AA%8F%E9%BD%90
		temp.append("Email=&Name=&UserUUID=").append(uuid);// .append("Email=").append("&Name=邵俊齐"); //.append(email)
		printf("temp=%s\n", temp.c_str());
		const char* data = temp.c_str();
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
		res = curl_easy_perform(curl);
		//curl_easy_strerror
		printf("res=%d\n", res);
		curl_slist_free_all(headers);
	}
	string str_json = out.str();
	curl_easy_cleanup(curl);
	printf("return Msg===>%s\n", str_json.c_str());
	return U2G(str_json.c_str());
}
//解析OA的返回信息 
string readXmlMSG(string xmlMsg) {
	printf("readXmlMSG %s \n", xmlMsg.c_str());
	tinyxml2::XMLDocument doc;
	XMLError res = doc.Parse(xmlMsg.c_str());
	if (res != XML_SUCCESS) {
		return xmlMsg;
	}
	tinyxml2::XMLElement* root = doc.RootElement();
	tinyxml2::XMLElement* succEle = root->FirstChildElement("Success");//传递状态
	tinyxml2::XMLElement* messageEle = root->FirstChildElement("Message");//错误原因
	string msg = "";
	if (strcmp(succEle->GetText(), "false") == 0) {
		msg.append("更改通知单推送OA系统失败，请联系管理员处理，流程继续执行,错误原因: ");
		msg.append(U2G(messageEle->GetText()));
	}
	return msg;
}
/*变更通知单传递OA
*/
string ecnSendOA(string instanceId, string entityParamValues, string url) {
	CURL* curl;
	CURLcode res;
	std::stringstream out;
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		struct curl_slist* headers = NULL;
		headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		string temp;
		temp.append("workflowCode=EH_TE_ChangeNotice").append("&userCode=").
			append(instanceId).append("&finishStart=true").append("&entityParamValues=").
			append(G2U(entityParamValues.c_str()));
		printf("temp=%s\n", temp.c_str());
		const char* data = temp.c_str();
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
		res = curl_easy_perform(curl);
		//curl_easy_strerror
		printf("temp=%d\n", res);
	}
	string str_json = out.str();
	curl_easy_cleanup(curl);
	printf("return Msg===>%s\n", str_json.c_str());
	string returnMsg = readXmlMSG(str_json);
	
	return returnMsg;
}
/*调用云派接口获取项目的指派人
*/
string getAssignFromYP(string url) {
	CURL* curl;
	CURLcode res;
	std::stringstream out;
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		struct curl_slist* headers = NULL;
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		res = curl_easy_perform(curl);
		printf("temp=%d\n", res);
	}
	string str_json = out.str();
	curl_easy_cleanup(curl);
	return U2G(str_json.c_str());
}

void updatePiProject(string json,string url) {
	CURL *curl;
	CURLcode res;
	curl = curl_easy_init();
	std::stringstream out;
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		struct curl_slist *headers = NULL;
		headers = curl_slist_append(headers, "Content-Type: application/json");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		const char *data = G2U(json.c_str());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		res = curl_easy_perform(curl);
	}
	string str_json = out.str();
	curl_easy_cleanup(curl);
	printf("str_json===>%s\n", str_json.c_str());
}
/*PLM推送变更通知单数据流信息
*/
string ecnSendSRM(string entityParamValues, string url) {
	CURL* curl;
	CURLcode res;
	std::stringstream out;
	curl = curl_easy_init();
	if (curl) {
		curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
		curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
		struct curl_slist *headers = NULL;
		headers = curl_slist_append(headers, "Content-Type: text/xml;charset=utf-8");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, G2U(entityParamValues.c_str()));
		res = curl_easy_perform(curl);
		//curl_easy_strerror
		printf("res=%d\n", res);
	}
	string str_json = U2G(out.str().c_str());
	curl_easy_cleanup(curl);
	printf("ecnSendOA return Msg===>%s\n", str_json.c_str());
	WriteLog("回传信息：\n %s\n", str_json.c_str());
	//string returnMsg = readXmlMSG(str_json);
	tinyxml2::XMLDocument doc;
	XMLError xml = doc.Parse(str_json.c_str());
	if (xml != XML_SUCCESS) {
		return str_json;
	}
	tinyxml2::XMLElement* root = doc.RootElement();
	tinyxml2::XMLElement* ChangeNotificationSyncResult = root->FirstChildElement()->FirstChildElement()->FirstChildElement();//传递状态
	string returnMsg = ChangeNotificationSyncResult->GetText();
	printf("ecnSendSRM return===>%s\n", returnMsg.c_str());
	cJSON *json = cJSON_Parse(returnMsg.c_str());
	if (json == NULL) {
		return returnMsg;
	}
	cJSON *code = cJSON_GetObjectItem(json, "code");
	string codeVal = code->valuestring;
	if (strcmp(codeVal.c_str(), "S") == 0) {
		return "S";
	}
	cJSON *msg = cJSON_GetObjectItem(json, "msg");
	//string msgVal = trim(msg->valuestring);
	string msgVal = msg->valuestring;
	printf("ecnSendSRM Msg===>%s\n", msgVal.c_str());

	return msgVal;
}

void yp_query(char* yp_url, string json) {
	printf("yp_query:\n%s\nyp_url:\n%s\n", json.c_str(), yp_url);
	CURL *curl = curl_easy_init();
	std::stringstream out;

	curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
	curl_easy_setopt(curl, CURLOPT_URL, yp_url);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
	curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");

	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_POSTFIELDS, G2U(json.c_str()));

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);

	CURLcode ret = curl_easy_perform(curl);
	string str_json = U2G(out.str().c_str());
	curl_easy_cleanup(curl);
	printf("yp_query return Msg===>%s\n", str_json.c_str());
}