#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"

#include <thread>

void getTCMBomLineReplaceItem(tag_t topLine, vector<tag_t> &bomLine);
void getTCMItemJson(int index, tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char * sortString, vector<tag_t> bomLines, char parameters[100000]);
void getTCMBomLineProperty(tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char * bomBaseNum, char * sortString,char * lineCode,int index, vector<tag_t> bomLines, char parameters[100000]);
bool getTCMBomLineChildProperty(tag_t topLine, map<string, string> typePropertyType, char * sortString, char  messageValue[1024], char messageUser[1024]);

bool isBomStart = true;

bool getTCMItemBomProperty(tag_t item, map<string, string> typePropertyType, char * sortString, bool isSum,char  messageValue[1024], char messageUser[1024])
{
	char *itemType = NULL;
	AOM_ask_value_string(item, "object_type", &itemType);
	char *objectString = NULL;
	AOM_ask_value_string(item, "object_string", &objectString);

	printf("itemType%s Start===================\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))
	{
		//判断是否发布
		int releaseCount = 0;
		tag_t * releaseTag = NULL_TAG;
		//判断子件是否发布
		AOM_ask_value_tags(item, "release_status_list", &releaseCount, &releaseTag);

		printf("发布状态%d===================\n", releaseCount);
		if (releaseCount <= 0)
		{
			MEM_free(releaseTag);
			MEM_free(itemType);
			strcat(messageValue, objectString);
			strcat(messageValue, "未发布！");
			MEM_free(objectString);
			return false;
		}
		
		char * processingMode = NULL;//加工方式
		char * addTrade = NULL;//加贸
		if (strcmp(itemType, "ML8_RawMaterialRevision") == 0)//原辅材料直接传
		{
			return true;
		}else if (strcmp(itemType, "ML8_RefrigeratorRevision") != 0)
		{
			AOM_ask_value_string(item, "ml8_ProcessingMode", &processingMode);
			AOM_ask_value_string(item, "ml8_AddTrade", &addTrade);
			printf("processingMode %s Start===================\n", processingMode);
			printf("addTrade %s Start===================\n", addTrade);
			if (processingMode != NULL && addTrade != NULL && strcmp(processingMode, "外协外购") == 0 && strcmp(addTrade, "否") == 0)
			{
				MEM_free(itemType);
				MEM_free(processingMode);
				MEM_free(addTrade);
				//strcat(messageValue, objectString);
				//strcat(messageValue, "加工方式为外协外购并加贸为否！");
				MEM_free(objectString);
				return true;
			}
			else
			{
				char * lineCode = NULL;//产线代码
				AOM_ask_value_string(item, "ml8_LineCode", &lineCode);
				printf("lineCode %s Start===================\n", lineCode);
				if (lineCode == NULL || strcmp(lineCode, "") == 0)
				{
					MEM_free(lineCode);
					MEM_free(itemType);
					MEM_free(processingMode);
					MEM_free(addTrade);
					strcat(messageValue, objectString);
					strcat(messageValue, "产线为空！");
					MEM_free(objectString);
					return false;
				}
			}
		}else
		{
			char * lineCode = NULL;//产线代码
			AOM_ask_value_string(item, "ml8_LineCode", &lineCode);
			printf("lineCode %s Start===================\n", lineCode);
			if (lineCode == NULL || strcmp(lineCode, "") == 0)
			{
				MEM_free(lineCode);
				MEM_free(itemType);
				MEM_free(processingMode);
				MEM_free(addTrade);
				strcat(messageValue, objectString);
				strcat(messageValue, "产线为空！");
				MEM_free(objectString);
				return false;
			}
		}


		//获取所有包含替代项目组的BOM行
		vector<tag_t> bomLines;
		//获取子项
		tag_t top_line = NULLTAG, window = NULLTAG;
		BOM_create_window(&window);
		//设置顶层BOM
		BOM_set_window_top_line(window, NULLTAG, item, NULLTAG, &top_line);

		int  count;
		tag_t *children_line = NULLTAG;

		BOM_line_ask_all_child_lines(top_line, &count, &children_line);
		bool isCreate = false;
		if (count > 0 && isSum)
		{
			auto startTime = std::chrono::high_resolution_clock::now();
			/*
			* your code
			*/
			if (getTCMBomLineChildProperty(top_line, typePropertyType,sortString, messageValue, messageUser))
			{
				isCreate = true;
			}
			auto stopTime = std::chrono::high_resolution_clock::now();
			auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stopTime - startTime);
			std::cout << "getTCMBomLineChildProperty用时:" << duration.count() / 1000 << std::endl;
		}
		else if(count <= 0)
		{
			MEM_free(itemType);
			MEM_free(processingMode);
			MEM_free(addTrade);
			MEM_free(children_line);
			return true;
		}
		else
		{
			isCreate = true;
		}
		if (isCreate)
		{
			auto startTime = std::chrono::high_resolution_clock::now();
			/*
			* your code
			*/
			getTCMBomLineReplaceItem(top_line, bomLines);
			auto stopTime = std::chrono::high_resolution_clock::now();
			auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stopTime - startTime);
			std::cout << "getTCMBomLineReplaceItem用时:" << duration.count() / 1000 << std::endl;

			isBomStart = true;

			char *tc_root_file = getenv("tc_root");		//C:\Siemens\Teamcenter11

			printf("bomLines.size() %d ===================\n", bomLines.size());

			char parameters[100000] = "";//写入到文件的值
			strcat(parameters, "getTCMBomPropertys}}");
			strcat(parameters, messageUser);
			strcat(parameters, "}}");
			strcat(parameters, "<n0:MT_TCM2SAP_CS01 xmlns:n0=\"urn:changhong.com:TCM:mlsc\">");

			//if (bomLines.size() > 0)
			//{
			//	for (int j = 0; j < bomLines.size(); j++)
			//	{

			//		tag_t bomLine = bomLines.at(j);
			//		//获取单个的json字符串
			//		if (isBomStart)
			//		{
			//			getTCMItemJson(j + 1, top_line, bomLine, typePropertyType, parameters);
			//			isBomStart = false;
			//		}
			//		else
			//		{
			//			getTCMItemJson(j + 1, top_line, bomLine, typePropertyType, parameters);
			//		}
			//		strcat(parameters, "</n0:MT_TCM2SAP_CS01>");
			//		//发送到SAP
			//		//获取当前时间
			//		//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,p->tm_isdst);

			//		//把数据用写入文件
			//		char data_file[SS_MAXPATHLEN] = "";
			//		strcat(data_file, tc_root_file);
			//		strcat(data_file, "\\");
			//		strcat(data_file, newGUID());
			//		strcat(data_file, ".txt");

			//		ofstream file;
			//		file.open(data_file);
			//		file << parameters << endl; // 使用与cout同样的方式进行写入
			//		file.close();

			//		//cmd指令
			//		char cmd[512] = "";
			//		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);
			//		//用来传递本流程的流程名称(@分割)
			//		//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");
			//		}
			//		_pclose(pf);

			//	}
			//	if (isSum)
			//	{
			//		//获取子BOM的属性
			//		getTCMBomLineChildProperty(top_line, typePropertyType, messageUser);
			//	}
			//}
			//else
			//{
			//	//char parameters[100000] = "";//写入到文件的值
			//	//strcat(parameters, "getTCMBomPropertys}}");
			//	//strcat(parameters, messageUser);
			//	//strcat(parameters, "}}");
			//	//strcat(parameters, "<n0:MT_TCM2SAP_CS01 xmlns:n0=\"urn:changhong.com:TCM:mlsc\">");
			//	//获取单个的json字符串
			//	//isBomStart = true;
			//	if (isBomStart)
			//	{
			//		getTCMItemJson(-1, top_line, NULLTAG, typePropertyType, parameters);
			//		//isBomStart = false;
			//	}
			//	else
			//	{
			//		getTCMItemJson(-1, top_line, NULLTAG, typePropertyType, parameters);
			//	}
			//	strcat(parameters, "</n0:MT_TCM2SAP_CS01>");
			//	//发送到SAP
			//	//获取当前时间
			//	//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, newGUID());
			//	strcat(data_file, ".txt");

			//	ofstream file;
			//	file.open(data_file);
			//	file << parameters << endl; // 使用与cout同样的方式进行写入
			//	file.close();

			//	//cmd指令
			//	char cmd[512] = "";
			//	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);
			//	//用来传递本流程的流程名称(@分割)
			//	//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");
			//	}
			//	_pclose(pf);
			//	if (isSum)
			//	{
			//		//获取子BOM的属性
			//		getTCMBomLineChildProperty(top_line, typePropertyType, messageUser);
			//	}
			//}


			//char parameters[100000] = "";//写入到文件的值
			//strcat(parameters, "getTCMBomPropertys}}");
			//strcat(parameters, messageUser);
			//strcat(parameters, "}}");
			//strcat(parameters, "<n0:MT_TCM2SAP_CS01 xmlns:n0=\"urn:changhong.com:TCM:mlsc\">");
			//获取单个的json字符串
			//isBomStart = true;
			auto startTime1 = std::chrono::high_resolution_clock::now();
			/*
			* your code
			*/
			if (isBomStart)
			{
				getTCMItemJson(-1, top_line, NULLTAG, typePropertyType, sortString, bomLines, parameters);
				//isBomStart = false;
			}
			else
			{
				getTCMItemJson(-1, top_line, NULLTAG, typePropertyType, sortString, bomLines, parameters);
			}
			auto stopTime1 = std::chrono::high_resolution_clock::now();
			auto duration1 = std::chrono::duration_cast<std::chrono::microseconds>(stopTime1 - startTime1);
			std::cout << "getTCMItemJson用时:" << duration1.count() / 1000 << std::endl;
			strcat(parameters, "</n0:MT_TCM2SAP_CS01>");
			//发送到SAP
			//获取当前时间
			//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, newGUID());
			strcat(data_file, ".txt");

			ofstream file;
			file.open(data_file);
			file << parameters << endl; // 使用与cout同样的方式进行写入
			file.close();

			//cmd指令
			char cmd[512] = "";
			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);
			//用来传递本流程的流程名称(@分割)
			//strcat(cmd,"@");
			//strcat(cmd,handler_name);
			printf("路径:\n%s\n", cmd);
			char buf[8000] = { 0 };
			FILE *pf = NULL;
			auto startTime2 = std::chrono::high_resolution_clock::now();
			/*
			* your code
			*/
			if ((pf = _popen(cmd, "r")) == NULL) {
				printf("接口返回:\n%s", "1");
			}
			_pclose(pf);
			auto stopTime2 = std::chrono::high_resolution_clock::now();
			auto duration2 = std::chrono::duration_cast<std::chrono::microseconds>(stopTime2 - startTime2);
			std::cout << "ML_SendSap.jar用时:" << duration2.count() / 1000 << std::endl;
			//if (isSum)
			//{
			//	//获取子BOM的属性
			//	getTCMBomLineChildProperty(top_line, typePropertyType, messageUser);
			//}

			BOM_close_window(window);

			MEM_free(processingMode);
			MEM_free(addTrade);
			bool isComplete = true;
			bool isHave = false;
			auto startTime3 = std::chrono::high_resolution_clock::now();
			/*
			* your code
			*/
			while (!isHave) {

				//等待4秒钟
				std::this_thread::sleep_for(std::chrono::seconds(4));//1秒
				//判断传递是否成功
				//把数据用写入文件
				char data_file[SS_MAXPATHLEN] = "";
				strcat(data_file, tc_root_file);
				strcat(data_file, "\\");
				strcat(data_file, newGUID());
				strcat(data_file, ".txt");

				ofstream file;
				file.open(data_file);
				file << parameters << endl; // 使用与cout同样的方式进行写入
				file.close();

				//cmd指令
				char cmd[512] = "";
				strcpy(cmd, "java -jar \"");
				//strcat(cmd, jar_file);
				strcat(cmd, tc_root_file);
				strcat(cmd, "\\portal\\plugins\\");
				strcat(cmd, "ML_SendBOMResult.jar");
				strcat(cmd, "\" ");
				//传参
				cout << data_file << endl;
				strcat(cmd, data_file);
				//用来传递本流程的流程名称(@分割)
				//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");
				}

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

				cout << strResult << endl;
				unsigned int iSize = strResult.size();
				if (iSize > 2 && strlen(parameters) > 0)
				{
					strResult = strResult.substr(0, iSize - 1);
					printf("下发失败\n");
					cout << strResult << endl;

					strcat(messageValue, strResult.c_str());
					isComplete = false;
				}
				isHave = true;
			}
			auto stopTime3 = std::chrono::high_resolution_clock::now();
			auto duration3 = std::chrono::duration_cast<std::chrono::microseconds>(stopTime3 - startTime3);
			std::cout << "ML_SendBOMResult.jar用时:" << duration3.count() / 1000 << std::endl;
			return isComplete;

			/*MEM_free(addTrade);
			MEM_free(processingMode);
			MEM_free(childItem);*/
		}
	}

	MEM_free(itemType);
	MEM_free(objectString);
	return true;
}

int ML_TCMSendSapBom(EPM_action_message_t msg)
{
	printf("=========================TCM BOM下发到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;
	char * processName = NULL;
	//获取任务对象
	EPM_ask_root_task(msg.task, &rootTask);
	//获取任务目标对象
	EPM_ask_attachments(rootTask, EPM_target_attachment, &attachments_num, &attachments);
	//获取流程名称
	AOM_ask_value_string(rootTask, "object_name", &processName);
	bool isSum = false, isMessage = false;
	//获取参数
	char *argflag = NULL, *argvalue = NULL, *arg = NULL;
	char messageUser[1024] = "", messageResult[1024] = "";
	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, "isMessage") == 0)
			{
				isMessage = true;
			}
			else if (stricmp(argflag, "isSum") == 0)
			{
				isSum = true;
			}
		}
	}

	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_TCMBOMSendSapProperty", &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]));
		}
	}

	//获取首选项的值
	PREF_ask_char_values("ML_MBOM_ExtendLine", &pref_cnt, &pref_vals);
	map<string, string> linePropertyType;
	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);
			linePropertyType[valueChar[0]] = valueChar[1];// .insert(std::pair<char*, char*>(valueChar[0], valueChar[1]));
		}
	}

	//char *tc_root_file = getenv("tc_root");		//C:\Siemens\Teamcenter11
	//char parameters[100000] = "";//写入到文件的值
	//strcat(parameters, "getTCMBomPropertys}}");
	//strcat(parameters, messageUser);
	//strcat(parameters, "}}");
	//strcat(parameters, "<n0:MT_TCM2SAP_CS01 xmlns:n0=\"urn:changhong.com:TCM:mlsc\">");
	char  messageValue[1024] = "";
	for (int i = 0; i < attachments_num; i++)
	{
		char * sortString = NULL;
		if (strcmp(processName, "000-扩线体MBOM传递ERP") == 0 && attachments_num == 2)
		{
			if (i == 1)
			{
				DOFREE(sortString);
				continue;
			}
			//获取选中零件的排序字符串
			AOM_ask_value_string(attachments[1], "ml8_ERPCode", &sortString);
		}
		auto startTime = std::chrono::high_resolution_clock::now();
		/*
		* your code
		*/
		getTCMItemBomProperty(attachments[i], typePropertyType, sortString, isSum, messageValue, messageUser);
		auto stopTime = std::chrono::high_resolution_clock::now();
		auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stopTime - startTime);
		std::cout << "getTCMItemBomProperty用时:" << duration.count() / 1000 << std::endl;

		DOFREE(sortString);
	}
	//strcat(parameters, "</n0:MT_TCM2SAP_CS01>");
	//isBomStart = true;

	////获取当前时间
	//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);
	////用来传递本流程的流程名称(@分割)
	////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)
	//{
	//	strResult = strResult.substr(0, iSize - 1);
	//	printf("下发失败\n");
	//	cout << strResult << endl;
	//	//发送消息到企业微信
	//	for (auto messageUserValue : messageUserValues) {
	//		BOMSendToWeixin(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))
	//		{
	//			//获取当前时间
	//			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_BOMFirstTime", dateNow);
	//			}
	//			else
	//			{
	//				AOM_set_value_string(attachments[i], "ml8_BOMNewTime", 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);
	//tc_root_file = NULL;
	pref_vals = NULL;
	char * status = "成功";
	if (strlen(messageValue) > 2)
	{
		status = "失败";
		ifail = 1;
	}
	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);

		printf("itemType%s Start===================\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))
		{
			AOM_lock(attachments[i]);
			AOM_set_value_string(attachments[i], "ml8_BOMSendERP", status);
			AOM_save(attachments[i]);
			AOM_unlock(attachments[i]);
			AOM_refresh(attachments[i], false);
		}
		DOFREE(itemType);
	}
	POM_AM__set_application_bypass(FALSE);
	DOFREE(status);
	DOFREE(processName); 
	DOFREE(attachments);
	if (!isMessage)
	{
		ifail = ITK_ok;
	}
	if (ifail == 1)
	{
		EMH_store_error_s1(EMH_severity_user_error, EMH_USER_error_base, messageValue);
	}

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

void getTCMBomLineReplaceItem(tag_t topLine, vector<tag_t> &bomLine)
{
	int  count;
	tag_t *children_line;

	BOM_line_ask_all_child_lines(topLine, &count, &children_line);

	for (int i = 0; i < count; i++)
	{
		char * replaceProject = NULL;
		AOM_ask_value_string(children_line[i], "ML8_ProjectTeam", &replaceProject);
		printf("ML8_ProjectTeam%s===================\n", replaceProject);
		if (replaceProject != NULL && strcmp(replaceProject, "A0") == 0)
		{
			bomLine.push_back(children_line[i]);
		}
		DOFREE(replaceProject);
	}
	DOFREE(children_line);
}

void getTCMItemJson(int index, tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char * sort, vector<tag_t> bomLines, char parameters[100000])
{
	//获取属性
	char * matnr = NULL;//物料编码
	char * werks = NULL;//工厂
	char * lineCode = NULL;//产线代码,BOM版本为产线代号加1位流水
	char * bomusage = "1";//BOM用途
	char * alternative = NULL;//BOM版本
	char * validdate = "20090301";//有效期起
	char * description = NULL;//可选BOM文本
	char * basequan = "1000";//基本数量
	char * sortString = NULL;

	tag_t revisions = NULLTAG;

	AOM_ask_value_tag(topLine, "bl_line_object", &revisions);


	//判断是否是替代件
	/*for (int j = 0; j < bomLines.size(); j++)
	{
	tag_t bomLine = bomLines.at(j);

	char * itemId = NULL;
	AOM_ask_value_string(topLine, "bl_item_item_id", &itemId);
	char * inputItemId = NULL;
	AOM_ask_value_string(bomLine, "bl_item_item_id", &inputItemId);
	if (strcmp(itemId, inputItemId) == 0)
	{
	index = j + 1;ss
	break;
	}
	}*/


	char * puid = NULL;
	//获取PUID
	ITK__convert_tag_to_uid(revisions, &puid);

	AOM_ask_value_string(topLine, "bl_item_item_id", &matnr);

	if (strstr(matnr, "-") != NULL)
	{
		//按照,进行拆分。拆分条件
		int matnrCount = 0;
		char ** matnrChar = new char *[64];
		//分割字符串
		split(matnr, "-", matnrChar, &matnrCount);

		matnr = matnrChar[0];
	}

	AOM_ask_value_string(revisions, "ml8_Factory", &werks);
	AOM_ask_value_string(revisions, "ml8_LineCode", &lineCode);
	AOM_ask_value_string(revisions, "ml8_ERPCode", &sortString);
	if (index > -1)
	{
		char itc[10];
		_itoa(index, itc, 10);
		alternative = itc;
	}
	else
	{
		alternative = "1";
		//AOM_ask_value_string(revisions, "ml8_SAPBOMRevision", &alternative);
	}
	AOM_ask_value_string(topLine, "bl_item_object_name", &description);
	AOM_ask_value_string(revisions, "ml8_BOMBasicQuantity", &basequan);

	if (basequan == NULL || strcmp(basequan, "") == 0)
	{
		basequan = "1000";
	}
	if (sort != NULL)
	{
		sortString = sort;
	}
	/*if ((sortString == NULL || strcmp(sortString, "") == 0) && lineCode != NULL && strcmp(lineCode, "") != 0)
	{
	sortString = getLineCode(lineCode);
	}*/

	//获取当前时间
	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);

	strcat(parameters, "<DATA>");
	strcat(parameters, "<MSG_HDR>");
	strcat(parameters, "<MSGID>");
	strcat(parameters, newGUID());
	strcat(parameters, "</MSGID>");
	strcat(parameters, "<BUSID>");
	strcat(parameters, newGUID());
	strcat(parameters, "</BUSID>");
	strcat(parameters, "<TLGID>");
	strcat(parameters, "JT0001");
	strcat(parameters, "</TLGID>");
	strcat(parameters, "<TLGNAME>");
	strcat(parameters, "维护MOBM接口");
	strcat(parameters, "</TLGNAME>");
	strcat(parameters, "<DTSEND>");
	strcat(parameters, date);
	strcat(parameters, "</DTSEND>");
	strcat(parameters, "<SENDER>");
	strcat(parameters, "TCM");
	strcat(parameters, "</SENDER>");
	strcat(parameters, "<RECEIVER>");
	strcat(parameters, "SAP");
	strcat(parameters, "</RECEIVER>");
	strcat(parameters, "<FREEUSE>");
	strcat(parameters, matnr);
	strcat(parameters, "</FREEUSE>");
	strcat(parameters, "</MSG_HDR>");
	strcat(parameters, "<MSG_BODY>");
	strcat(parameters, "<HEADER>");
	strcat(parameters, "<MATNR>");
	strcat(parameters, matnr);
	strcat(parameters, "</MATNR>");
	strcat(parameters, "<WERKS>");
	strcat(parameters, werks);
	strcat(parameters, "</WERKS>");
	strcat(parameters, "<STLAN>");
	strcat(parameters, bomusage);
	strcat(parameters, "</STLAN>");
	strcat(parameters, "<STLAL>");
	strcat(parameters, "</STLAL>");
	strcat(parameters, "<BMENG>");
	strcat(parameters, basequan);
	strcat(parameters, "</BMENG>");
	strcat(parameters, "<DATUV>");
	strcat(parameters, validdate);
	strcat(parameters, "</DATUV>");
	strcat(parameters, "<STKTX>");
	strcat(parameters, description);
	strcat(parameters, "</STKTX>");
	strcat(parameters, "<UID>");
	strcat(parameters, puid);
	strcat(parameters, "</UID>");
	strcat(parameters, "</HEADER>");
	//写入多压缩机组
	if (bomLines.size() > 0)
	{
		for (int j = 0; j < bomLines.size(); j++)
		{
			char itc[10];
			_itoa(j + 1, itc, 10);
			alternative = itc;

			strcat(parameters, "<STLALITEM><STLAL>");
			strcat(parameters, lineCode);
			strcat(parameters, alternative);
			strcat(parameters, "</STLAL></STLALITEM>");
		}
	}
	else
	{
		strcat(parameters, "<STLALITEM><STLAL>");
		strcat(parameters, lineCode);
		strcat(parameters, "1");
		strcat(parameters, "</STLAL></STLALITEM>");
	}
	auto startTime = std::chrono::high_resolution_clock::now();
	/*
	* your code
	*/
	if (bomLines.size() > 0)
	{
		for (int j = 0; j < bomLines.size(); j++)
		{
			getTCMBomLineProperty(topLine, bomLines[j], typePropertyType, basequan, sortString, lineCode,j , bomLines, parameters);
		}
	}
	else
	{
		getTCMBomLineProperty(topLine, BomLine, typePropertyType, basequan, sortString, lineCode, 0, bomLines, parameters);
	}
	auto stopTime = std::chrono::high_resolution_clock::now();
	auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stopTime - startTime);
	std::cout << "getTCMBomLineProperty用时:" << duration.count() / 1000 << std::endl;
	strcat(parameters, "</MSG_BODY>");
	strcat(parameters, "</DATA>");

	DOFREE(matnr);
	DOFREE(werks);
	DOFREE(bomusage);
	DOFREE(alternative);
	DOFREE(validdate);
	DOFREE(description);
	DOFREE(basequan);
	DOFREE(puid);
}

bool getTCMBomLineChildProperty(tag_t topLine, map<string, string> typePropertyType,char* sortString, char  messageValue[1024], char messageUser[1024])
{
	int  count;
	tag_t *children_line = NULLTAG;

	BOM_line_ask_all_child_lines(topLine, &count, &children_line);
	bool isOk = true;
	for (int i = 0; i < count; i++)
	{
		int  childCount;
		tag_t *children_bomLine = NULLTAG;

		BOM_line_ask_all_child_lines(children_line[i], &childCount, &children_bomLine);
		if (childCount > 0)
		{
			tag_t revisions = NULLTAG;

			AOM_ask_value_tag(children_line[i], "bl_line_object", &revisions);

			if (!getTCMItemBomProperty(revisions, typePropertyType, sortString, true, messageValue, messageUser))
			{
				isOk = false;
				DOFREE(children_bomLine);
				break;
			}
		}
		DOFREE(children_bomLine);
	}

	DOFREE(children_line);
	return isOk;
}

void getTCMBomLineProperty(tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char * bomBaseNum, char * sortString,char * lineCode, int index, vector<tag_t> bomLines, char parameters[100000])
{
	//char parameters[100000] = "";//写入到文件的值
	bool isStart = true;
	int  count;
	tag_t *children_line = NULLTAG;

	BOM_line_ask_all_child_lines(topLine, &count, &children_line);

	for (int i = 0; i < count; i++)
	{
		char * replaceProject = NULL;
		AOM_ask_value_string(children_line[i], "ML8_ProjectTeam", &replaceProject);

		//判断是否为最底层
		int  children_count;
		tag_t *children_lines = NULLTAG;

		BOM_line_ask_all_child_lines(children_line[i], &children_count, &children_lines);
		bool isLast = false;
		if (children_count <= 0)
		{
			isLast = true;
		}
		//if (replaceProject != NULL && strcmp(replaceProject, "A0") == 0 && BomLine != NULLTAG)
		//{
		//	//判断是否等于传进来的BOM行
		//	char * itemId = NULL;
		//	AOM_ask_value_string(children_line[i], "bl_item_item_id", &itemId);
		//	char * inputItemId = NULL;
		//	AOM_ask_value_string(BomLine, "bl_item_item_id", &inputItemId);
		//	if (strcmp(itemId, inputItemId) != 0)
		//	{
		//		continue;
		//	}
		//}

		char *itemType = NULL;
		AOM_ask_value_string(children_line[i], "fnd0bl_line_object_type", &itemType);
		char * puid = NULL;
		//获取PUID
		ITK__convert_tag_to_uid(children_line[i], &puid);
		//过滤掉非版本的对象
		string propertyNames = typePropertyType[itemType];
		if (propertyNames.c_str() != NULL)
		{
			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);
				strcat(parameters, "<ITEM>");

				if (replaceProject != NULL && strcmp(replaceProject, "A0") == 0)
				{
					//判断是否等于传进来的BOM行
					char * itemId = NULL;
					AOM_ask_value_string(children_line[i], "bl_item_item_id", &itemId);
					char * inputItemId = NULL;
					AOM_ask_value_string(BomLine, "bl_item_item_id", &inputItemId);
					if (strcmp(itemId, inputItemId) == 0)
					{
						char itc[10];
						_itoa(index + 1, itc, 10);
						strcat(parameters, "<STLAL>");
						strcat(parameters, lineCode);
						strcat(parameters, itc);
						strcat(parameters, "</STLAL>");

					}
					DOFREE(itemId);
					DOFREE(inputItemId);
				}
				else
				{
					char itc[10];
					_itoa(index + 1, itc, 10);
					strcat(parameters, "<STLAL>");
					strcat(parameters, lineCode);
					strcat(parameters, itc);
					strcat(parameters, "</STLAL>");
				}


				//获取多压缩机组信息
				//if (bomLines.size() > 0)
				//{
				//	if (replaceProject != NULL && strcmp(replaceProject, "A0") == 0)
				//	{
				//		//判断是否等于传进来的BOM行
				//		char * itemId = NULL;
				//		AOM_ask_value_string(children_line[i], "bl_item_item_id", &itemId);
				//		bool ishave = false;
				//		for (int j = 0; j < bomLines.size(); j++)
				//		{
				//			char * inputItemId = NULL;
				//			AOM_ask_value_string(bomLines[j], "bl_item_item_id", &inputItemId);
				//			if (strcmp(itemId, inputItemId) == 0)
				//			{
				//				ishave = true;

				//				char itc[10];
				//				_itoa(j + 1, itc, 10);
				//				strcat(parameters, "<STLAL>");
				//				strcat(parameters, lineCode);
				//				strcat(parameters, itc);
				//				strcat(parameters, "</STLAL>");

				//				DOFREE(inputItemId);
				//				break;
				//			}
				//			DOFREE(inputItemId);
				//		}
				//		DOFREE(itemId);
				//		if (!ishave)
				//		{
				//			strcat(parameters, "<STLAL>");
				//			if (isLast)
				//			{
				//				strcat(parameters, lineCode);
				//				strcat(parameters, "1");
				//			}
				//			else
				//			{
				//				strcat(parameters, lineCode);
				//				strcat(parameters, "1");
				//			}
				//			strcat(parameters, "</STLAL>");
				//		}
				//	}
				//	else
				//	{
				//		strcat(parameters, "<STLAL>");
				//		if (isLast)
				//		{
				//			strcat(parameters, lineCode);
				//			strcat(parameters, "1");
				//		}
				//		else
				//		{
				//			strcat(parameters, lineCode);
				//			strcat(parameters, "1");
				//		}
				//		strcat(parameters, "</STLAL>");
				//	}
				//}
				//else
				//{
				//	strcat(parameters, "<STLAL>");
				//	if (isLast)
				//	{
				//		strcat(parameters, lineCode);
				//		strcat(parameters, "1");
				//	}
				//	else
				//	{
				//		strcat(parameters, lineCode);
				//		strcat(parameters, "1");
				//	}
				//	strcat(parameters, "</STLAL>");
				//}

				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]);
						strcat(parameters, ">");

						char * item_rev_value = NULL;
						TCGetPropertyValue(children_line[i], "BOMLine", values[0], &item_rev_value);
						if (strcmp(values[1], "POSNR") == 0)
						{
							char itc[10];
							sprintf(itc, "%d", i + 1);
							item_rev_value = itc;
						}

						if (strcmp(values[1], "IDNRK") == 0)
						{
							if (strstr(item_rev_value, "-") != NULL)
							{
								//按照,进行拆分。拆分条件
								int matnrCount = 0;
								char ** matnrChar = new char *[64];
								//分割字符串
								split(item_rev_value, "-", matnrChar, &matnrCount);

								item_rev_value = matnrChar[0];
							}
						}

						if (strcmp(values[1], "SORTF") == 0)
						{
							item_rev_value = sortString;
						}

						if (strcmp(values[1], "MENGE") == 0)
						{
							//BOM关系中子项数量*SAP BOM基本数量
							double bomNum = atof(item_rev_value);
							double bomBase = atof(bomBaseNum);
							double sum = bomNum*bomBase;
							char * sumChar = new char[20];
							sprintf(sumChar, "%.3f", sum);
							cout << "bomNum【" << bomNum << "】，bomBaseNum【" << bomBaseNum << "】，bomBase【" << bomBase << "】，sum【" << sum << "】，sumChar【" << sumChar << "】\n" << endl;
							//printf("bomNum【%d】，bomBaseNum【%s】，bomBase：【%d】，sum：【%d】，sumChar：【%s】\n", bomNum, bomBaseNum,bomBase, sum, sumChar);
							item_rev_value = sumChar;
						}

						strcat(parameters, item_rev_value);


						strcat(parameters, "</");
						strcat(parameters, values[1]);
						strcat(parameters, ">");

						DOFREE(item_rev_value);
					}
				}
				strcat(parameters, "</ITEM>");
			}
			else
			{
				//按照-进行拆分。拆分条件
				int valueCount = 0;
				char ** valueChar = new char *[64];
				//分割字符串
				split(name, "=", valueChar, &valueCount);

				strcat(parameters, "<ITEM>");

				strcat(parameters, "<");
				strcat(parameters, valueChar[1]);
				strcat(parameters, ">");

				char * item_rev_value = NULL;
				TCGetPropertyValue(children_line[i], "BOMLine", valueChar[0], &item_rev_value);

				if (strcmp(valueChar[1], "POSNR") == 0)
				{
					char itc[10];
					sprintf(itc, "%d", i + 1);
					item_rev_value = itc;
				}

				if (strcmp(valueChar[1], "IDNRK") == 0)
				{
					if (strstr(item_rev_value, "-") != NULL)
					{
						//按照,进行拆分。拆分条件
						int matnrCount = 0;
						char ** matnrChar = new char *[64];
						//分割字符串
						split(item_rev_value, "-", matnrChar, &matnrCount);

						item_rev_value = matnrChar[0];
					}
				}

				if (strcmp(valueChar[1], "SORTF") == 0)
				{
					item_rev_value = sortString;
				}

				if (strcmp(valueChar[1], "MENGE") == 0)
				{
					//BOM关系中子项数量*SAP BOM基本数量
					double bomNum = atof(item_rev_value);
					double bomBase = atof(bomBaseNum);
					double sum = bomNum*bomBase;
					char * sumChar = new char[20];
					sprintf(sumChar, "%.3f", sum);
					cout << "bomNum【" << bomNum << "】，bomBaseNum【" << bomBaseNum << "】，bomBase【" << bomBase << "】，sum【" << sum << "】，sumChar【" << sumChar << "】\n" << endl;
					//printf("bomNum【%d】，bomBaseNum【%s】，bomBase：【%d】，sum：【%d】，sumChar：【%s】\n", bomNum, bomBaseNum,bomBase, sum, sumChar);
					item_rev_value = sumChar;
				}


				strcat(parameters, item_rev_value);

				strcat(parameters, "</");
				strcat(parameters, valueChar[1]);
				strcat(parameters, ">");

				strcat(parameters, "</ITEM>");

				DOFREE(item_rev_value);
			}

			DOFREE(constName);
		}


		DOFREE(replaceProject);
		DOFREE(itemType);
		DOFREE(puid);
	}

	DOFREE(children_line);
}