#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"
#include "libxl.h"
#include <sstream>
#include <iostream>

using namespace libxl;
void getBomLineReplaceItem1(tag_t topLine, vector<tag_t> &bomLine);
void getItemJson1(int index, tag_t topLine, tag_t BomLine, bool isStart, map<string, string> typePropertyType, char parameters[100000], string result3, char *validdate);
void getItemJson1(int index, tag_t topLine, tag_t BomLine, bool isStart, map<string, string> typePropertyType, char parameters[100000], string result3, string fac, char *validdate);
void getBomLineProperty1(tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char * bomBaseNum, char * sortString, char parameters[100000]);
string getTime21()
{
	stringstream ss;
	time_t t = time(0);
	tm* local = localtime(&t);
	ss << local->tm_year + 1900 << '-';
	if (local->tm_mon < 9)
		ss << "0";
	ss << local->tm_mon + 1 << '-';
	if (local->tm_mday < 9)
		ss << "0";
	ss << local->tm_mday << ' ';
	if (local->tm_hour < 10)
		ss << "0";
	if (local->tm_min < 10)
		ss << "0";
	ss << local->tm_min;
	if (local->tm_sec < 10)
		ss << "0";
	ss << local->tm_sec;
	return ss.str();
}
string WStringToString1(const wstring& ws)

{

	string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
	setlocale(LC_ALL, "chs");
	const wchar_t* _Source = ws.c_str();
	size_t _Dsize = 2 * ws.size() + 1;
	char *_Dest = new char[_Dsize];
	memset(_Dest, 0, _Dsize);
	wcstombs(_Dest, _Source, _Dsize);
	string result = _Dest;
	delete[]_Dest;
	setlocale(LC_ALL, curLocale.c_str());
	return result;

}
wstring StringToWString1(const string s)
{
	setlocale(LC_ALL, "chs");
	const char* _Source = s.c_str();
	size_t _Dsize = s.size() + 1;
	wchar_t *_Dest = new wchar_t[_Dsize];
	wmemset(_Dest, 0, _Dsize);
	mbstowcs(_Dest, _Source, _Dsize);
	wstring result = _Dest;
	delete[]_Dest;
	setlocale(LC_ALL, "C");
	return result;
}
string get_excel_data1(libxl::Book* book, libxl::Sheet* sheet, int row, int col)
{
	string result;
	double temp;

	try
	{
		libxl::CellType cell_type = sheet->cellType(row, col);
		switch (cell_type)
		{
		case libxl::CELLTYPE_STRING:
			result = WStringToString1(sheet->readStr(row, col));
			break;
		case libxl::CELLTYPE_BLANK:
			result = "";
			break;
		case libxl::CELLTYPE_EMPTY:
			result = "";
			break;
		case libxl::CELLTYPE_NUMBER:
			temp = sheet->readNum(row, col);
			result = temp == (int)temp ? to_string((int)temp) : to_string(temp);

			break;
		case libxl::CELLTYPE_BOOLEAN:
			result = to_string(sheet->readBool(row, col));
			break;
		case libxl::CELLTYPE_ERROR:
			result = "";
			break;
		}

	}
	catch (exception e)
	{
		//	LERROR<<"col num"<<k<<"error:"<<e.what();
	}

	return result;
}
string& replace_allTest(string& str, const  string& old_value, const  string& new_value)
{
	if (strstr(str.c_str(), old_value.c_str()) != NULL) {
		vector<string> type_vec;
		Split(str.c_str(), old_value.c_str(), type_vec);
		char new_str[512] = "\0";
		for (int i = 0; i < type_vec.size(); i++)
		{
			strcat(new_str, type_vec[i].c_str());
			if (i < type_vec.size() - 1) {
				strcat(new_str, new_value.c_str());
			}
		}
		string new_value(new_str);
		str = new_value.c_str();
	}
	return str;
}
string getMRPByFacoty1(tag_t topLine) {

	printf("------MRP控制者------\n");
	tag_t revisions = NULLTAG;
	char *tc_root_file = getenv("TEMP");		//C:\Siemens\Teamcenter11
	char *tc_root = getenv("TC_ROOT");
	char* parameters = new char[100000000];
	//char parameters[100000] = "";//写入到文件的值
	strcat(parameters, "getDisopPropertys}}");
	char *matnr, *werks, *ml8_AddTrade, *ml8_ProcessingMode;

	AOM_ask_value_tag(topLine, "bl_line_object", &revisions);
	AOM_ask_value_string(revisions, "ml8_Factory", &werks);
	AOM_ask_value_string(revisions, "item_id", &matnr);

	strcat(parameters, matnr);
	strcat(parameters, ";");

	//ml8_AddTrade
	AOM_ask_value_string(revisions, "ml8_ProcessingMode", &ml8_ProcessingMode);

	char *itemType = NULL;
	AOM_ask_value_string(revisions, "object_type", &itemType);
	string work;
	work = werks;
	if ((strcmp(itemType, "ML8_RefrigeratorRevision") == 0) || (strcmp(itemType, "ML8_ColdRevision") == 0))
	{

	}
	else if (strcmp(werks, "I060") == 0 && strcmp(ml8_ProcessingMode, "外协外购") == 0) {
		AOM_ask_value_string(revisions, "ml8_AddTrade", &ml8_AddTrade);
		if (strcmp(ml8_AddTrade, "是") == 0) {
			work = "I010";
		}

	}

	strcat(parameters, work.c_str());
	//获取当前时间
	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);
	strcat(cmd, "\\portal\\plugins\\");
	strcat(cmd, "ML_SendSap.jar");
	strcat(cmd, "\" ");
	//传参
	cout << data_file << endl;
	strcat(cmd, data_file);
	//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);
	vector<string> vecRes;
	//string res = werks;
	work.append(";");
	printf("strResult %s \n", strResult.c_str());

	//if (!strResult.empty()) {
	Split(strResult, ";", vecRes);
	printf("vecRes size %d \n", vecRes.size());
	POM_AM__set_application_bypass(TRUE);
	AOM_lock(revisions);
	for (int i = 0; i < vecRes.size(); i++) {
		if (i == 0) {
			AOM_set_value_string(revisions, "ml8_MRP", vecRes[i].c_str());
			work.append(vecRes[i]);
		}
		else if (i == 1) {
			AOM_set_value_string(revisions, "ml8_PurchaseType", vecRes[i].c_str());
		}
		else if (i == 2) {
			string strin = replace_allTest(vecRes[i], "\n", "");
			AOM_set_value_string(revisions, "ml8_SpecialPurchase", strin.c_str());
		}
	}

	AOM_save(revisions);
	AOM_unlock(revisions);
	AOM_refresh(revisions, false);

	POM_AM__set_application_bypass(FALSE);
	return work;

}
bool IsCellEmpty1(int32_t cellType)
{
	return (cellType == libxl::CELLTYPE_BLANK) || (cellType == libxl::CELLTYPE_EMPTY);
}
int ML_SendSapBom_TCM(EPM_action_message_t msg)
{
	printf("=========================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;
	//获取任务对象
	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] = "";
	int arg_cnt = TC_number_of_arguments(msg.arguments);
	printf("参数个数为：%d\n", arg_cnt);
	bool isMessage = false;
	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;
			}
		}
	}

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


	char *temp_dir = getenv("TEMP");
	stringstream path;
	path << temp_dir << "\\connorcreate" << getTime21() << ".xlsx";
	char *datasetUid, *validdate;
	tag_t dataset;
	PREF_ask_char_value("ML_MRP", 0, &datasetUid);

	PREF_ask_char_value("ML_StartDateofValidity", 0, &validdate);

	ITK__convert_uid_to_tag(datasetUid, &dataset);
	(AE_export_named_ref(dataset, "excel", path.str().c_str()));
	bool isStart = true;
	char *tc_root_file = getenv("TEMP");		//C:\Siemens\Teamcenter11
	char *tc_root = getenv("TC_ROOT");
	char* parameters = new char[100000000];
	//char parameters[100000] = "";//写入到文件的值
	strcat(parameters, "getBomPropertys}}");
	strcat(parameters, "[");
	for (int i = 0; i < attachments_num; i++)
	{
		vector<string> facVec;
		map< string, string> sortMap;
		char *itemType = NULL;
		AOM_ask_value_string(attachments[i], "object_type", &itemType);
		vector<string> vecStr;
		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))
		{

			//获取所有包含替代项目组的BOM行
			vector<tag_t> bomLines;
			//获取子项
			tag_t top_line = NULLTAG, window = NULLTAG;
			BOM_create_window(&window);
			//设置顶层BOM
			BOM_set_window_top_line(window, NULLTAG, attachments[i], NULLTAG, &top_line);
			getBomLineReplaceItem1(top_line, bomLines);
			string mrp = getMRPByFacoty1(top_line);
			string result3 = "";
			printf("read excel model %s ,mrp %s \n", path.str().c_str(), mrp.c_str());
			if (!mrp.empty()) {

				Split(mrp, ";", vecStr);
				Book *book;
				book = xlCreateXMLBook();
				book->setKey(L"TommoT", L"windows-2421220b07c2e10a6eb96768a2p7r6gc");
				bool re = book->load(StringToWString1(path.str()).c_str());
				if (!re)
				{
					printf("open excel error \n");
					continue;

				}
				Sheet *sheet = book->getSheet(0);
				int rowNum = sheet->lastRow();
				int colNum = sheet->lastCol();
				for (auto j = 0; j < rowNum; j++)
				{
					printf("test %d \n", j);
					if (!IsCellEmpty1(sheet->cellType(j, 0))) {
						string result1 = get_excel_data1(book, sheet, j, 0); //WStringToString(sheet->readStr(j, 0));
						result1.append(";");
						if (!IsCellEmpty1(sheet->cellType(j, 1))) {
							string result2 = get_excel_data1(book, sheet, j, 1); //sheet->readStr(j, 1);
							result1.append(result2);

						}
						if (strcmp(result1.c_str(), mrp.c_str()) == 0) {
							result3 = get_excel_data1(book, sheet, j, 2);
							string str = get_excel_data1(book, sheet, j, 3);
							printf("facVec %s \n", str.c_str());
							if (strcmp("", str.c_str()) != 0) {
								facVec.push_back(str);
							}
						}
					}
				}

				for (auto j = 0; j < rowNum; j++)
				{
					if (!IsCellEmpty1(sheet->cellType(j, 0))) {
						string result1 = get_excel_data1(book, sheet, j, 0);
						//string result1 = WStringToString1(sheet->readStr(j, 0));
						result1.append(";");
						if (!IsCellEmpty1(sheet->cellType(j, 1))) {
							string result2 = get_excel_data1(book, sheet, j, 1); //sheet->readStr(j, 1);
							result1.append(result2);
						}
						printf("result1  %s \n", result1.c_str());
						for (int t = 0; t < facVec.size(); t++) {
							string facmrp = facVec[t];
							facmrp.append(";");
							facmrp.append(vecStr[1]);
							printf("facmrp %s\n", facmrp.c_str());
							if (strcmp(result1.c_str(), facmrp.c_str()) == 0) {
								string sor = get_excel_data1(book, sheet, j, 2);
								sortMap[facmrp] = sor;
								printf("readStr========== %s\n", sor.c_str());
							}
						}

					}
				}

				book->release();//释放对象！！！！！

			}
			printf("sortstr result3 %s \n", result3.c_str());
			if (bomLines.size() > 0)
			{
				for (int j = 0; j < bomLines.size(); j++)
				{
					tag_t bomLine = bomLines.at(j);
					//获取单个的json字符串
					if (isStart)
					{
						getItemJson1(j + 1, top_line, bomLine, isStart, typePropertyType, parameters, result3, validdate);
						isStart = false;
					}
					else
					{
						getItemJson1(j + 1, top_line, bomLine, isStart, typePropertyType, parameters, result3, validdate);
					}
				}
			}
			else
			{
				//获取单个的json字符串
				if (isStart)
				{
					getItemJson1(-1, top_line, NULLTAG, isStart, typePropertyType, parameters, result3, validdate);
					isStart = false;
				}
				else
				{
					getItemJson1(-1, top_line, NULLTAG, isStart, typePropertyType, parameters, result3, validdate);
				}
			}

			for (int t = 0; t < facVec.size(); t++) {
				string fac = facVec[t];
				fac.append(";");
				fac.append(vecStr[1]);
				if (sortMap.count(fac) == 1) {
					string sortstr = sortMap[fac];
					if (bomLines.size() > 0)
					{
						for (int j = 0; j < bomLines.size(); j++)
						{
							tag_t bomLine = bomLines.at(j);
							//获取单个的json字符串
							if (isStart)
							{
								getItemJson1(j + 1, top_line, bomLine, isStart, typePropertyType, parameters, sortstr, validdate);
								isStart = false;
							}
							else
							{
								getItemJson1(j + 1, top_line, bomLine, isStart, typePropertyType, parameters, sortstr, validdate);
							}
						}
					}
					else
					{
						//获取单个的json字符串
						if (isStart)
						{
							getItemJson1(-1, top_line, NULLTAG, isStart, typePropertyType, parameters, sortstr, facVec[t], validdate);
							isStart = false;
						}
						else
						{
							getItemJson1(-1, top_line, NULLTAG, isStart, typePropertyType, parameters, sortstr, facVec[t], validdate);
						}
					}
				}
				else
				{
					ifail = 1;
					string errorstr = fac;
					errorstr.append("没有找到对应的排序字符串");
					EMH_store_error_s1(EMH_severity_user_error, EMH_USER_error_base, errorstr.c_str());
				}
			}

			BOM_close_window(window);
		}

		MEM_free(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);
	strcat(cmd, "\\portal\\plugins\\");
	strcat(cmd, "ML_SendSap.jar");
	strcat(cmd, "\" ");
	//传参
	cout << data_file << endl;
	strcat(cmd, data_file);

	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);
		printf("下发失败\n");
		cout << strResult << endl;
		//发送消息到企业微信
		for (auto messageUserValue : messageUserValues) {
			BOMSendToWeixin(messageUserValue, rootTask, strResult);
		}
		POM_AM__set_application_bypass(TRUE);
		printf("开旁路设置属性\n");
		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))
			{
				ITKCALL(AOM_lock(attachments[i]));
				ITKCALL(AOM_set_value_string(attachments[i], "ml8_BOMSendERP", "失败"));
				ITKCALL(AOM_save(attachments[i]));
				ITKCALL(AOM_unlock(attachments[i]));
				ITKCALL(AOM_refresh(attachments[i], false));
			}
			DOFREE(itemType);
		}
		POM_AM__set_application_bypass(FALSE);
		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))
			{
				char * sendTime = NULL;

				AOM_ask_value_string(attachments[i], "ml8_BOMFirstTime", &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_BOMFirstTime", dateNow);
				}
				else
				{
					AOM_set_value_string(attachments[i], "ml8_BOMNewTime", dateNow);
				}
				AOM_set_value_string(attachments[i], "ml8_BOMSendERP", "成功");
				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 (!isMessage)
	{
		ifail = ITK_ok;
	}

	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, "未接收到返回值，请联系管理员处理！");
	}

	auto stopTime = std::chrono::high_resolution_clock::now();
	auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stopTime - startTime);
	std::cout << "ML_SendSapBom_TCM用时:" << duration.count() / 1000 << std::endl;
	printf("=========================BOM下发到SAP End===================\n");
	return ifail;
}



void getBomLineReplaceItem1(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, "") != 0)
		{
			bomLine.push_back(children_line[i]);
		}
		DOFREE(replaceProject);
	}
	DOFREE(children_line);
}
void getItemJson1(int index, tag_t topLine, tag_t BomLine, bool isStart, map<string, string> typePropertyType, char parameters[100000], string result3, string fac, char * validdate)
{

	if (isStart)
	{
		strcat(parameters, "{");
	}
	else
	{
		strcat(parameters, ",{");
	}
	//获取属性
	char * matnr = NULL;
	char * werks = NULL;
	char * bomusage = NULL;
	char * alternative = NULL;
	char * description = NULL;
	char * basequan = NULL;
	//char * sortString = NULL;
	//char * lineCode = NULL;

	tag_t revisions = NULLTAG;

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

	AOM_ask_value_string(topLine, "bl_item_item_id", &matnr);
	AOM_ask_value_string(revisions, "ml8_Factory", &werks);
	//AOM_ask_value_string(revisions, "ml8_LineCode", &lineCode);
	/*if (werks == NULL || strcmp(werks, "") == 0)
	{
		AOM_ask_value_string(revisions, "ml8_Factory", &werks);
	}*/
	AOM_ask_value_string(revisions, "ml8_BOMPurpose", &bomusage);
	if (index > -1)
	{
		char itc[10];
		_itoa(index, itc, 10);
		alternative = itc;
	}
	else
	{
		AOM_ask_value_string(revisions, "ml8_SAPBOMRevision", &alternative);
		if (alternative == NULL || strcmp(alternative, "") == 0)
		{
			alternative = "1";
		}
	}
	if (strstr(matnr, "-") != NULL)
	{
		//按照,进行拆分。拆分条件
		int matnrCount = 0;
		char ** matnrChar = new char *[64];
		//分割字符串
		split(matnr, "-", matnrChar, &matnrCount);

		matnr = matnrChar[0];
	}

	AOM_ask_value_string(topLine, "bl_item_object_name", &description);
	AOM_ask_value_string(revisions, "ml8_BOMBasicQuantity", &basequan);

	if (strcmp(result3.c_str(), "") == 0) {
		char * sortString;
		AOM_ask_value_string(revisions, "ml8_SortString", &sortString);
		result3 = sortString;
	}


	if (basequan == NULL || strcmp(basequan, "") == 0)
	{
		basequan = "1000";
	}

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


	strcat(parameters, "\"matnr\":\"");
	strcat(parameters, matnr);
	strcat(parameters, "\",");
	strcat(parameters, "\"werks\":\"");
	strcat(parameters, fac.c_str());
	strcat(parameters, "\",");
	strcat(parameters, "\"bomusage\":\"");
	strcat(parameters, bomusage);
	strcat(parameters, "\",");
	strcat(parameters, "\"alternative\":\"");
	//strcat(parameters, lineCode);
	strcat(parameters, alternative);
	strcat(parameters, "\",");
	strcat(parameters, "\"validdate\":\"");
	strcat(parameters, validdate);
	strcat(parameters, "\",");
	strcat(parameters, "\"description\":\"");
	strcat(parameters, description);
	strcat(parameters, "\",");
	strcat(parameters, "\"basequan\":\"");
	strcat(parameters, basequan);
	strcat(parameters, "\",");

	strcat(parameters, "\"itemdetail\":[");
	getBomLineProperty1(topLine, BomLine, typePropertyType, basequan, (char*)result3.c_str(), parameters);
	strcat(parameters, "]");
	strcat(parameters, "}");

	DOFREE(matnr);
	DOFREE(werks);
	DOFREE(bomusage);
	DOFREE(alternative);
	DOFREE(validdate);
	DOFREE(description);
	DOFREE(basequan);
}
void getItemJson1(int index, tag_t topLine, tag_t BomLine, bool isStart, map<string, string> typePropertyType, char parameters[100000], string result3, char *validdate)
{

	if (isStart)
	{
		strcat(parameters, "{");
	}
	else
	{
		strcat(parameters, ",{");
	}
	//获取属性
	char * matnr = NULL;
	char * werks = NULL, *ml8_ProcessingMode, *ml8_AddTrade;
	char * bomusage = NULL;
	char * alternative = NULL;
	char * description = NULL;
	char * basequan = NULL;
	//char * sortString = NULL;
	//char * lineCode = NULL;

	tag_t revisions = NULLTAG;

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

	AOM_ask_value_string(topLine, "bl_item_item_id", &matnr);
	AOM_ask_value_string(revisions, "ml8_Factory", &werks);
	string work;
	work = werks;
	char *itemType = NULL;
	AOM_ask_value_string(revisions, "ml8_ProcessingMode", &ml8_ProcessingMode);
	AOM_ask_value_string(revisions, "object_type", &itemType);
	if ((strcmp(itemType, "ML8_RefrigeratorRevision") == 0) || (strcmp(itemType, "ML8_ColdRevision") == 0))
	{

	}
	else if (strcmp(werks, "I060") == 0 && strcmp(ml8_ProcessingMode, "外协外购") == 0) {
		AOM_ask_value_string(revisions, "ml8_AddTrade", &ml8_AddTrade);
		if (strcmp(ml8_AddTrade, "是") == 0) {
			work = "I010";
		}

	}
	//AOM_ask_value_string(revisions, "ml8_LineCode", &lineCode);
	/*if (werks == NULL || strcmp(werks, "") == 0)
	{
		AOM_ask_value_string(revisions, "ml8_Factory", &werks);
	}*/
	AOM_ask_value_string(revisions, "ml8_BOMPurpose", &bomusage);
	if (index > -1)
	{
		char itc[10];
		_itoa(index, itc, 10);
		alternative = itc;
	}
	else
	{
		AOM_ask_value_string(revisions, "ml8_SAPBOMRevision", &alternative);
		if (alternative == NULL || strcmp(alternative, "") == 0)
		{
			alternative = "1";
		}
	}
	if (strstr(matnr, "-") != NULL)
	{
		//按照,进行拆分。拆分条件
		int matnrCount = 0;
		char ** matnrChar = new char *[64];
		//分割字符串
		split(matnr, "-", matnrChar, &matnrCount);

		matnr = matnrChar[0];
	}

	AOM_ask_value_string(topLine, "bl_item_object_name", &description);
	AOM_ask_value_string(revisions, "ml8_BOMBasicQuantity", &basequan);

	if (strcmp(result3.c_str(), "") == 0) {
		char * sortString;
		AOM_ask_value_string(revisions, "ml8_SortString", &sortString);
		result3 = sortString;
	}


	if (basequan == NULL || strcmp(basequan, "") == 0)
	{
		basequan = "1000";
	}

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


	strcat(parameters, "\"matnr\":\"");
	strcat(parameters, matnr);
	strcat(parameters, "\",");
	strcat(parameters, "\"werks\":\"");
	strcat(parameters, work.c_str());
	strcat(parameters, "\",");
	strcat(parameters, "\"bomusage\":\"");
	strcat(parameters, bomusage);
	strcat(parameters, "\",");
	strcat(parameters, "\"alternative\":\"");
	//strcat(parameters, lineCode);
	strcat(parameters, alternative);
	strcat(parameters, "\",");
	strcat(parameters, "\"validdate\":\"");
	strcat(parameters, validdate);
	strcat(parameters, "\",");
	strcat(parameters, "\"description\":\"");
	strcat(parameters, description);
	strcat(parameters, "\",");
	strcat(parameters, "\"basequan\":\"");
	strcat(parameters, basequan);
	strcat(parameters, "\",");

	strcat(parameters, "\"itemdetail\":[");
	getBomLineProperty1(topLine, BomLine, typePropertyType, basequan, (char*)result3.c_str(), parameters);
	strcat(parameters, "]");
	strcat(parameters, "}");

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

void getBomLineProperty1(tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char * bomBaseNum, char * sortString, 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);

		if (replaceProject != NULL && strcmp(replaceProject, "") != 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)
		{
			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]);
						strcat(parameters, "\"");
						strcat(parameters, ":");

						char * item_rev_value = NULL;
						TCGetPropertyValue(children_line[i], "BOMLine", values[0], &item_rev_value);
						if (strcmp(values[1], "itemno") == 0)
						{
							//需要*10后，格式化为4位长度后进行传递
							int number = std::atoi(item_rev_value);
							stringToLenth(number * 10, 4, &item_rev_value);
						}
						else if (strcmp(values[1], "compqty") == 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;
						}
						else if (strcmp(values[1], "itemtext1") == 0)
						{
							if (item_rev_value == NULL || strcmp(item_rev_value, "") == 0 || strcmp(item_rev_value, "Eac") == 0 || strcmp(item_rev_value, "Each.") == 0 || strcmp(item_rev_value, "每个") == 0)
							{
								item_rev_value = "ea";
							}
						}
						else if (strcmp(values[1], "sortstring") == 0)
						{
							item_rev_value = sortString;
						}
						else if (strcmp(values[1], "component") == 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 (strstr(item_rev_value, "\"") != NULL)
						{
							string resultString = replace_all_distinct(item_rev_value, "\"", "&\"");

							char resultChar[256] = "";

							strcpy(resultChar, resultString.c_str());

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

							item_rev_value = resultChar;

						}

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

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

				strcat(parameters, "\"");
				strcat(parameters, valueChar[1]);
				strcat(parameters, "\"");
				strcat(parameters, ":");

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

				if (strcmp(valueChar[1], "itemno") == 0)
				{
					//需要*10后，格式化为4位长度后进行传递
					int number = std::atoi(item_rev_value);
					stringToLenth(number * 10, 4, &item_rev_value);
				}
				else if (strcmp(valueChar[1], "compqty") == 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;
					item_rev_value = sumChar;
				}
				else if (strcmp(valueChar[1], "itemtext1") == 0)
				{
					if (item_rev_value == NULL || strcmp(item_rev_value, "") == 0 || strcmp(item_rev_value, "Eac") == 0 || strcmp(item_rev_value, "Each.") == 0 || strcmp(item_rev_value, "每个") == 0)
					{
						item_rev_value = "ea";
					}
				}
				else if (strcmp(valueChar[1], "sortstring") == 0)
				{
					item_rev_value = sortString;
				}
				else if (strcmp(valueChar[1], "component") == 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 (strstr(item_rev_value, "\"") != NULL)
				{
					string resultString = replace_all_distinct(item_rev_value, "\"", "&\"");

					char resultChar[256] = "";

					strcpy(resultChar, resultString.c_str());

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

					item_rev_value = resultChar;

				}
				strcat(parameters, "\"");
				strcat(parameters, item_rev_value);
				strcat(parameters, "\"");

				//printf(parameters);

				DOFREE(item_rev_value);
			}
			strcat(parameters, "}");

			DOFREE(constName);
		}


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

	DOFREE(children_line);
}
bool isTypeOf(tag_t objtag, const char * type_name) {
	tag_t type = NULLTAG;
	TCTYPE_ask_object_type(objtag, &type);
	tag_t item_type = NULLTAG;
	TCTYPE_find_type(type_name, "", &item_type);
	bool is_type = false;
	if (item_type != NULLTAG) {
		logical isok = FALSE;
		TCTYPE_is_type_of(type, item_type, &isok);
		if (isok) {
			is_type = true;
		}
	}
	return is_type;
}
int ML_Check_Route(EPM_action_message_t msg) {

	int ifail = ITK_ok, arg_cnt, att_cnt;
	char *arg = NULL, *argflag = NULL, *argvalue = NULL;
	arg_cnt = TC_number_of_arguments(msg.arguments);
	string type, prop,vals;
	if (arg_cnt > 0)
	{
		for (int i = 0; i < arg_cnt; i++)
		{
			//获取下一个参数（从0开始）
			arg = TC_next_argument(msg.arguments);
			//获取参数的名称和值
			ITK_ask_argument_named_value((const char*)arg, &argflag, &argvalue);
			if (strcmp(argflag, "itemtype") == 0)
			{
				if (argvalue != NULL)
				{
					type.assign(argvalue);
				}
			}
			else if (strcmp(argflag, "property") == 0) {
				if (argvalue != NULL)
				{
					prop.assign(argvalue);
				}
			}
			else if (strcmp(argflag, "value") == 0) {
				if (argvalue != NULL)
				{
					vals.assign(argvalue);
				}
			}
		}
		MEM_free(argflag);
	}
	tag_t task_tag = NULLTAG, rootTask_tag = NULLTAG, *attachments;
	EPM_ask_root_task(msg.task, &rootTask_tag);
	ITKCALL(ifail = EPM_ask_attachments(rootTask_tag, EPM_target_attachment, &att_cnt, &attachments));
	vector<string> typeVec;
	Split(type, ",", typeVec);

	vector<string> itemVec;
	vector<string> trueVec;

	for (int i = 0; i < att_cnt; i++)
	{

		tag_t attachment = attachments[i];

		for (int t = 0; t < typeVec.size(); t++) {
			if (isTypeOf(attachment, typeVec[t].c_str())) {
				if (strcmp(vals.c_str(), "") == 0) {
					printf("vals==null\n");
					char *proVal;
					AOM_ask_value_string(attachment, prop.c_str(), &proVal);
					printf("proVal==%s\n", proVal);

					if (proVal == NULL || strcmp(proVal, "") == 0) {
						EPM_set_task_result(msg.task, "NULL");
					}
					else {
						ITKCALL(EPM_set_task_result(msg.task, proVal));
					}
				}
				else {
					char *proVal;
					AOM_ask_value_string(attachment, prop.c_str(), &proVal);
					string valProp = proVal;
					printf("proVal==%s,vals=%s===\n", proVal,vals.c_str());
					string strin = replace_allTest(valProp, "\n", "");
					if (strcmp(strin.c_str(), vals.c_str()) == 0) {
						EPM_set_task_result(msg.task, "true");
					}
					else {
						ITKCALL(EPM_set_task_result(msg.task, "false"));
					}
				}
			}
		}
	}
	return ifail;
}