#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"

void getTCMItemJsonCostCollector(int index, tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char parameters[100000]);
void getTCMBomLinePropertyCostCollector(tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char * bomBaseNum, char parameters[100000]);
void getTCMBomLineChildPropertyCostCollector(tag_t topLine, map<string, string> typePropertyType, char parameters[100000]);

bool isBomCostCollectorStart = true;

void getTCMItemBomPropertyCostCollector(tag_t item, map<string, string> typePropertyType, char parameters[100000] = "")
{
	char *itemType = NULL;
	AOM_ask_value_string(item, "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))
	{
		//判断是否发布
		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);
			return;
		}
		//char * lineCode = NULL;//产线代码
		//AOM_ask_value_string(item, "ml8_LineCode", &lineCode);
		//if (lineCode == NULL || strcmp(lineCode, "") == 0)
		//{
		//	MEM_free(lineCode);
		//	MEM_free(itemType);
		//	return;
		//}
		//获取所有包含替代项目组的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);
		//获取单个的json字符串
		if (isBomCostCollectorStart)
		{
			getTCMItemJsonCostCollector(-1, top_line, NULLTAG, typePropertyType, parameters);
			isBomCostCollectorStart = false;
		}
		//else
		//{
		//	getTCMItemJsonCostCollector(-1, top_line, NULLTAG, typePropertyType, parameters);
		//}
		//获取子BOM的属性
		//getTCMBomLineChildPropertyCostCollector(top_line, typePropertyType, parameters);

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

	MEM_free(itemType);
}

int ML_TCMSendSapCostCollector(EPM_action_message_t msg)
{
	printf("=========================TCM USER 成本收集器下发到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] = "", infoname[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, "infoname") == 0)
			{
				if (argvalue != NULL)
				{
					strcpy(infoname, 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_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]));
		}
	}

	char *tc_root_file = getenv("tc_root");		//C:\Siemens\Teamcenter11
	char parameters[100000] = "";//写入到文件的值
	strcat(parameters, "getTCMBomCostCollectorPropertys}}");
	strcat(parameters, messageUser);
	strcat(parameters, "}}");
	strcat(parameters, infoname);
	strcat(parameters, "}}");
	strcat(parameters, "<n0:MT_TCM2SAP_CS01 xmlns:n0=\"urn:changhong.com:TCM:mlsc\">");

	for (int i = 0; i < attachments_num; i++)
	{
		getTCMItemBomPropertyCostCollector(attachments[i], typePropertyType, parameters);
	}
	strcat(parameters, "</n0:MT_TCM2SAP_CS01>");
	isBomCostCollectorStart = 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))
			{
				//获取当前时间
				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);
	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());
	}

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

void getTCMItemJsonCostCollector(int index, tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char parameters[100000])
{
	//获取属性
	char * matnr = NULL;//物料编码
	char * werks = NULL;//工厂

	tag_t revisions = NULLTAG;

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

	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);

	//获取当前时间
	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, "创建成本收集器接口");
	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, "</HEADER>");
	strcat(parameters, "</MSG_BODY>");
	strcat(parameters, "</DATA>");

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

void getTCMBomLineChildPropertyCostCollector(tag_t topLine, map<string, string> typePropertyType, char parameters[100000])
{
	int  count;
	tag_t *children_line = NULLTAG;

	BOM_line_ask_all_child_lines(topLine, &count, &children_line);

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

		tag_t revisions = NULLTAG;

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

		getTCMItemBomPropertyCostCollector(revisions, typePropertyType, parameters);

		/*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);

			getTCMItemBomPropertyCostCollector(revisions, typePropertyType, parameters);
		}
		DOFREE(children_bomLine);*/
	}

	DOFREE(children_line);
}