#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"

int ML_SendSapItem(EPM_action_message_t msg)
{
	printf("=========================对象下发到SAP Start===================\n");
	auto startTime = std::chrono::high_resolution_clock::now();
	//POM_AM__set_application_bypass(true);
	int ifail = ITK_ok;
	int  attachments_num = 0;
	tag_t  rootTask = NULLTAG, *attachments = NULLTAG;
	//获取任务对象
	EPM_ask_root_task(msg.task, &rootTask);
	//获取任务目标对象
	EPM_ask_attachments(rootTask, EPM_target_attachment, &attachments_num, &attachments);

	//获取参数
	char *argflag = NULL, *argvalue = NULL, *arg = NULL;
	char messageUser[1024] = "", messageResult[1024] = "", timeout[16] = "";
	int arg_cnt = TC_number_of_arguments(msg.arguments);
	printf("参数个数为：%d\n", arg_cnt);
	if (arg_cnt > 0)
	{
		for (int i = 0; i<arg_cnt; i++)
		{
			//获取下一个参数（从0开始）
			arg = TC_next_argument(msg.arguments);
			//获取参数的名称和值
			ifail = ITK_ask_argument_named_value((const char*)arg, &argflag, &argvalue);
			if (stricmp(argflag, "ownerId") == 0)
			{
				if (argvalue != NULL)
				{
					strcpy(messageUser, argvalue);
				}
			}
			else if (stricmp(argflag, "messageResult") == 0)
			{
				if (argvalue != NULL)
				{
					strcpy(messageResult, argvalue);
				}
			}
			else if (stricmp(argflag, "timeout") == 0)
			{
				if (argvalue != NULL)
				{
					strcpy(timeout, argvalue);
				}
			}
		}
	}

	vector<char *> messageUserValues;

	if (strstr(messageUser, ",") != NULL)
	{
		int vectorValueCount = 0;
		char ** vectorValueChar = new char *[64];
		split(messageUser, ",", vectorValueChar, &vectorValueCount);
		for (int i = 0; i < vectorValueCount; i++)
		{
			messageUserValues.push_back(vectorValueChar[i]);
		}
	}
	else
	{
		messageUserValues.push_back(messageUser);
	}

	int pref_cnt = 0;
	char ** pref_vals = NULL;
	//获取首选项的值
	PREF_ask_char_values("ML_ItemSendSapProperty", &pref_cnt, &pref_vals);
	map<string, string> typePropertyType;
	for (int j = 0; j < pref_cnt; j++)
	{
		if (strstr(pref_vals[j], "-") != NULL)
		{
			//按照-进行拆分。拆分条件
			int valueCount = 0;
			char ** valueChar = new char *[64];
			//分割字符串
			split(pref_vals[j], "-", valueChar, &valueCount);
			typePropertyType[valueChar[0]] = valueChar[1];// .insert(std::pair<char*, char*>(valueChar[0], valueChar[1]));
		}
	}

	bool isStart = true;
	char *tc_root_file = getenv("tc_root");		//C:\Siemens\Teamcenter11
	char parameters[100000] = "";//写入到文件的值
	strcat(parameters, "getItemPropertys}}");
	strcat(parameters, "[");
	for (int i = 0; i < attachments_num; i++)
	{
		char *itemType = NULL;
		AOM_ask_value_string(attachments[i], "object_type", &itemType);

		printf("itemType：%s\n", itemType);
		//过滤掉非版本的对象
		if ((strcmp(itemType, "ML8_RefrigeratorRevision") == 0) || (strcmp(itemType, "ML8_WashingRevision") == 0)
			|| (strcmp(itemType, "ML8_ColdRevision") == 0) || (strcmp(itemType, "ML8_OthersRevision") == 0) || (strcmp(itemType, "ML8_PartRevision") == 0)
			|| (strcmp(itemType, "ML8_RawMaterialRevision") == 0) || (strcmp(itemType, "ML8_UnProductRevision") == 0) || (strcmp(itemType, "ML8_ProductOthRevision") == 0))
		{
			string propertyNames = typePropertyType[itemType];
			if (propertyNames.c_str() != NULL)
			{
				if (isStart)
				{
					strcat(parameters, "{");
					isStart = false;
				}
				else
				{
					strcat(parameters, ",{");
				}

				const char * constName = propertyNames.c_str();
				char* name = new char[2048];//足够长
				strcpy(name, constName);
				if (strstr(name, ",") != NULL)
				{
					//按照,进行拆分。拆分条件
					int valueCount = 0;
					char ** valueChar = new char *[64];
					//分割字符串
					split(name, ",", valueChar, &valueCount);
					for (int k = 0; k < valueCount; k++)
					{
						if (strstr(valueChar[k], "=") != NULL)
						{
							//按照-进行拆分。拆分条件
							int valueNum = 0;
							char ** values = new char *[64];
							//分割字符串
							split(valueChar[k], "=", values, &valueNum);

							strcat(parameters, "\"");
							strcat(parameters, values[1] == NULL || strlen(values[1]) == 0 ? "" : values[1]);
							strcat(parameters, "\"");
							strcat(parameters, ":");

							char * item_rev_value = NULL;
							TCGetPropertyValue(attachments[i], "Revision", values[0], &item_rev_value);
							if (strcmp(values[1], "matltype") == 0)
							{
								//物料类型特殊处理，判断是否是零件和原辅材料
								if ((strcmp(itemType, "ML8_PartRevision") == 0) || (strcmp(itemType, "ML8_RawMaterialRevision") == 0) || (strcmp(itemType, "ML8_UnProductRevision") == 0))
								{
									char * processingMode = NULL;
									//获取加工方式
									TCGetPropertyValue(attachments[i], "Revision", "rev.ml8_ProcessingMode", &processingMode);

									printf("加工方式%s================================\n", processingMode);

									if (strcmp(processingMode, "自制") == 0)
									{
										item_rev_value = "HALB";
									}
									else
									{
										item_rev_value = "ROH";
									}
									DOFREE(processingMode);
								}
							}

							if (strcmp(values[1], "uom") == 0)
							{
								printf("单位%s================================\n", item_rev_value);
								if (item_rev_value == NULL || strcmp(item_rev_value, "") == 0)
								{
									item_rev_value = "ea";
								}
								else
								{
									if (strcmp(item_rev_value, "Eac") == 0 || strcmp(item_rev_value, "Each.") == 0)
									{
										item_rev_value = "ea";
									}
								}
								
							}

							if (strstr(item_rev_value, "\"") != NULL)
							{
								printf("更改前:%s\n", item_rev_value);
								string resultString = replace_all_distinct(item_rev_value, "\"", "&\"");

								char resultChar[256] = "";

								strcpy(resultChar, resultString.c_str());

								*(resultChar + strlen(resultString.c_str())) = '\0';

								printf("更改后:%s\n", resultChar);

								item_rev_value = resultChar;

								printf("更改后:%s\n", item_rev_value);

							}

							strcat(parameters, "\"");
							strcat(parameters, item_rev_value);
							strcat(parameters, "\"");
							if (k < valueCount - 1)
							{
								strcat(parameters, ",");
							}

							DOFREE(item_rev_value);
							values = NULL;
						}
						printf("parameters：%s\n", parameters);
					}
					valueChar = NULL;
				}
				else
				{
					//按照-进行拆分。拆分条件
					int valueCount = 0;
					char ** valueChar = new char *[64];
					//分割字符串
					split(name, "=", valueChar, &valueCount);

					strcat(parameters, "\"");
					strcat(parameters, valueChar[1] == NULL || strlen(valueChar[1]) == 0 ? "" : valueChar[1]);
					strcat(parameters, "\"");
					strcat(parameters, ":");

					char * item_rev_value = NULL;
					TCGetPropertyValue(attachments[i], "Revision", valueChar[0], &item_rev_value);
					if (strcmp(valueChar[1], "matltype") == 0)
					{
						//物料类型特殊处理，判断是否是零件和原辅材料
						if ((strcmp(itemType, "ML8_PartRevision") == 0) || (strcmp(itemType, "ML8_RawMaterialRevision") == 0) || (strcmp(itemType, "ML8_UnProductRevision") == 0))
						{
							char * processingMode = NULL;
							//获取加工方式
							TCGetPropertyValue(attachments[i], "Revision", "rev.ml8_ProcessingMode", &processingMode);
							

							printf("加工方式%s================================\n", processingMode);

							if (strcmp(processingMode, "自制") == 0)
							{
								item_rev_value = "HALB";
							}
							else
							{
								item_rev_value = "ROH";
							}
							DOFREE(processingMode);
						}
					}
					if (strcmp(valueChar[1], "uom") == 0)
					{
						if (item_rev_value == NULL || strcmp(item_rev_value, "") == 0)
						{
							item_rev_value = "ea";
						}
						else
						{
							if (strcmp(item_rev_value, "Eac") == 0 || strcmp(item_rev_value, "Each.") == 0)
							{
								item_rev_value = "ea";
							}
						}
					}

					if (strstr(item_rev_value, "\"") != NULL)
					{
						printf("更改前:%s\n", item_rev_value);
						string resultString = replace_all_distinct(item_rev_value, "\"", "&\"");

						char resultChar[256] = "";

						strcpy(resultChar, resultString.c_str());

						*(resultChar + strlen(resultString.c_str())) = '\0';

						printf("更改后:%s\n", resultChar);

						item_rev_value = resultChar;

						printf("更改后:%s\n", item_rev_value);

					}

					strcat(parameters, "\"");
					strcat(parameters, item_rev_value);
					strcat(parameters, "\"");
					DOFREE(item_rev_value);
					valueChar = NULL;
				}

				strcat(parameters, "}");

				DOFREE(constName);
				name = NULL;

			}
		}

		DOFREE(itemType);
	}
	strcat(parameters, "]");
	//获取当前时间
	time_t now = time(0); 
	tm *p = localtime(&now);

	char date[128] = "";
	sprintf_s(date, "%04d%02d%02d%02d%02d%02d", 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);

	//把数据用写入文件
	char data_file[SS_MAXPATHLEN] = "";
	strcat(data_file, tc_root_file);
	strcat(data_file, "\\");
	strcat(data_file, date);
	strcat(data_file, ".txt");
	ofstream file;
	file.open(data_file);
	file << parameters << endl; // 使用与cout同样的方式进行写入
	file.close();

	string strResult;

	//cmd指令
	char cmd[256] = "";
	strcpy(cmd, "java -jar \"");
	//strcat(cmd, jar_file);
	strcat(cmd, tc_root_file);
	strcat(cmd, "\\portal\\plugins\\");
	strcat(cmd, "ML_SendSap.jar");
	strcat(cmd, "\" ");
	//传参
	cout << data_file << endl;
	strcat(cmd, data_file);
	if (strcmp(timeout, "") != 0)
	{
		strcat(cmd, " ");
		strcat(cmd, timeout);
	}
	else
	{
		strcat(cmd, " 600");
	}
	//用来传递本流程的流程名称(@分割)
	//strcat(cmd,"@");
	//strcat(cmd,handler_name);
	printf("路径:\n%s\n", cmd);
	char buf[8000] = { 0 };
	FILE *pf = NULL;
	if ((pf = _popen(cmd, "r")) == NULL) {
		printf("接口返回:\n%s", "1");
	}

	while (fgets(buf, sizeof buf, pf)) {
		strResult += buf;
	}
	_pclose(pf);

	cout << strResult << endl;
	unsigned int iSize = strResult.size();
	if (iSize > 0 && strResult[iSize - 1] == '\n' && strlen(parameters) > 0||strstr(strResult.c_str(),"超时") != NULL)
	{

		strResult = strResult.substr(0, iSize - 1);
		if (strstr(strResult.c_str(), "Connect to SAP gateway failed") != NULL)
		{
			strResult = "连接SAP失败,请联系SAP管理员处理！";
		}
		printf("下发失败\n");
		cout << strResult << endl;
		//发送消息到企业微信
		for (auto messageUserValue : messageUserValues) {
			itemSendToWeixin(messageUserValue, rootTask, strResult);
		}
		if (strcmp(messageResult, "1") == 0)
		{
			ifail = 1;
		}
	}
	else
	{
		POM_AM__set_application_bypass(TRUE);
		//获取首次发送时间
		for (int i = 0; i < attachments_num; i++)
		{
			char *itemType = NULL;
			AOM_ask_value_string(attachments[i], "object_type", &itemType);
			//过滤掉非版本的对象
			if ((strcmp(itemType, "ML8_RefrigeratorRevision") == 0) || (strcmp(itemType, "ML8_WashingRevision") == 0)
				|| (strcmp(itemType, "ML8_ColdRevision") == 0) || (strcmp(itemType, "ML8_OthersRevision") == 0) || (strcmp(itemType, "ML8_PartRevision") == 0)
				|| (strcmp(itemType, "ML8_RawMaterialRevision") == 0) || (strcmp(itemType, "ML8_UnProductRevision") == 0) || (strcmp(itemType, "ML8_ProductOthRevision") == 0))
			{
				char * sendTime = NULL;

				AOM_ask_value_string(attachments[i], "ml8_PropertyFirstTime", &sendTime);

				//获取当前时间
				time_t now = time(0);
				tm *p = localtime(&now);

				char dateNow[128] = "";
				sprintf_s(dateNow, "%04d-%02d-%02d %02d:%02d:%02d", 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);

				AOM_lock(attachments[i]);
				if (sendTime == NULL || strcmp(sendTime, "") == 0)
				{
					AOM_set_value_string(attachments[i], "ml8_PropertyFirstTime", dateNow);
				}
				else
				{
					AOM_set_value_string(attachments[i], "ml8_PropertyNewTime", dateNow);
				}
				AOM_save(attachments[i]);
				AOM_unlock(attachments[i]);
				AOM_refresh(attachments[i], false);
				DOFREE(sendTime);
			}
			DOFREE(itemType);
		}
		POM_AM__set_application_bypass(FALSE);
	}
	messageUserValues.clear();
	vector<char *>().swap(messageUserValues);
	MEM_free(attachments);
	tc_root_file = NULL;
	pref_vals = NULL;
	if (ifail == 1)
	{
		EMH_store_error_s1(EMH_severity_user_error, EMH_USER_error_base, strResult.c_str());
	}
	if (strstr(strResult.c_str(), "超时") != NULL)
	{
		ifail = 1;
		EMH_store_error_s1(EMH_severity_user_error, EMH_USER_error_base, "未接收到ERP返回信息，请联系管理员处理！");
	}

	auto stopTime = std::chrono::high_resolution_clock::now();
	auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stopTime - startTime);
	//std::cout << "ML_SendSapItem用时:" << duration.count() / 1000 << std::endl;
	string usetime = "ML_SendSapItem用时:";
	usetime.append(std::to_string(duration.count() / 1000));
	WriteLog(true, usetime.c_str());
	printf("=========================对象下发到SAP End===================\n");
	return ifail;
}
