#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"

void getTCMUserMesSpecialProcessJson(int index, tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char parameters[100000]);
void getTCMUserMesSpecialProcessProperty(tag_t topLine, tag_t BomLine, char * prodOrderNo, char * ERPCode, map<string, string> typePropertyType, char parameters[100000]);

bool isUserMesSpecialProcessStart = true;

void getTCMUserMesSpecialProcessProperty(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 ((strstr(itemType, "Revision") == NULL) || (strstr(itemType, "Master") != NULL)
		|| (strstr(itemType, "master") != NULL) || (strstr(itemType, "BOM") != NULL) || (strstr(itemType, "bom") != NULL) || (strstr(itemType, "Bom") != NULL))
	{
		DOFREE(itemType);
		return;
	}
	//获取子项
	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 (isUserMesSpecialProcessStart)
	{
		getTCMUserMesSpecialProcessJson(-1, top_line, NULLTAG, typePropertyType, parameters);
		isUserMesSpecialProcessStart = false;
	}
	else
	{
		getTCMUserMesSpecialProcessJson(-1, top_line, NULLTAG, typePropertyType, parameters);
	}

	BOM_close_window(window);
	MEM_free(itemType);
}

int ML_TCMUserSendMesSpecialProcess(void * returnValue)
{
	printf("=========================TCM BOM下发到SAP Start===================\n");
	//POM_AM__set_application_bypass(true);
	int ifail = ITK_ok;
	tag_t item = NULLTAG;
	char * messageUser = NULL;
	USERARG_get_tag_argument(&item);
	USERARG_get_string_argument(&messageUser);

	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, "getTCMMesSpecialProcessPropertys}}");
	strcat(parameters, messageUser);
	strcat(parameters, "}}");
	/*strcat(parameters, "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">");
	strcat(parameters, "<soapenv:Header/>");
	strcat(parameters, "<soapenv:Body>");
	strcat(parameters, "<tem:PostSpecialProcessData>");
	strcat(parameters, "<tem:dataList>");*/
	strcat(parameters, "[");

	getTCMUserMesSpecialProcessProperty(item, typePropertyType, parameters);

	strcat(parameters, "]");
	/*strcat(parameters, "</tem:dataList>");
	strcat(parameters, "</tem:PostSpecialProcessData>");
	strcat(parameters, "</soapenv:Body>");
	strcat(parameters, "</soapenv:Envelope>");*/

	isUserMesSpecialProcessStart = 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, NULLTAG, strResult);
		}
	}
	else
	{
		POM_AM__set_application_bypass(TRUE);
		//获取首次发送时间
		char *itemType = NULL;
		AOM_ask_value_string(item, "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(item);
			/*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(item);
			AOM_unlock(item);
			AOM_refresh(item, false);
			DOFREE(sendTime);
		}
		DOFREE(itemType);
		POM_AM__set_application_bypass(FALSE);
	}
	messageUserValues.clear();
	vector<char *>().swap(messageUserValues);
	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());
	}
	printf("=========================TCM BOM下发到SAP End===================\n");
	return ifail;
}

void getTCMUserMesSpecialProcessJson(int index, tag_t topLine, tag_t BomLine, map<string, string> typePropertyType, char parameters[100000])
{
	//获取订单BOM属性
	char * prodOrderNo = NULL;//生产订单号
	char * ERPCode = NULL;//ERP班组编码

	tag_t revisions = NULLTAG;

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

	//AOM_ask_value_string(revisions, "ml8_ProdOrderNo", &prodOrderNo);
	//AOM_ask_value_string(revisions, "ml8_ERPCode", &ERPCode);

	getTCMUserMesSpecialProcessProperty(topLine, BomLine, prodOrderNo, ERPCode, typePropertyType, parameters);

	DOFREE(prodOrderNo);
	DOFREE(ERPCode);
}

void getTCMUserMesSpecialProcessProperty(tag_t topLine, tag_t BomLine, char * prodOrderNo, char * ERPCode, 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++)
	{
		//判断类型是否为专项工序
		char * itemType = NULL;
		AOM_ask_value_string(children_line[i], "fnd0bl_line_object_type", &itemType);

		if (strcmp(itemType, "ML8_SpecOpRevision") != 0)
		{
			DOFREE(itemType);
			continue;
		}
		tag_t opRevisions = NULLTAG;
		AOM_ask_value_tag(children_line[i], "bl_line_object", &opRevisions);
		char * itemId = NULL;
		AOM_ask_value_string(children_line[i], "bl_item_item_id", &itemId);
		char * objectName = NULL;
		AOM_ask_value_string(children_line[i], "bl_item_object_name", &objectName);
		char * line = NULL;
		AOM_ask_value_string(opRevisions, "ml8_Line", &line);
		if (line == NULL || strcmp(line, "") == 0)
		{
			line = "ALL";
		}
		else
		{
			line = getLineCode(line);
		}

		//获取专项工序下的工步信息
		int  stepCount;
		tag_t * step_Bomline = NULLTAG;

		BOM_line_ask_all_child_lines(children_line[i], &stepCount, &step_Bomline);

		for (int j = 0; j < count; j++)
		{
			//判断类型工步类型
			char * stepItemType = NULL;
			AOM_ask_value_string(step_Bomline[j], "fnd0bl_line_object_type", &stepItemType);
			tag_t revisions = NULLTAG;
			AOM_ask_value_tag(step_Bomline[j], "bl_line_object", &revisions);

			map<char *, char *> propertyMap;

			if (strcmp(stepItemType, "ML8_FPStepRevision") == 0)
			{
				//获取版本属性枪头压力上限、枪头压力下限、压差上限、压差下限、料温上限、料温下限
				char * spearHeadPressureMax = NULL;
				char * spearHeadPressureMin = NULL;
				char * pressureScopeMax = NULL;
				char * pressureScopeMin = NULL;
				char * materialCMax = NULL;
				char * materialCMin = NULL;

				AOM_ask_value_string(revisions, "ml8_SpearHeadPressureMax", &spearHeadPressureMax);
				AOM_ask_value_string(revisions, "ml8_SpearHeadPressureMin", &spearHeadPressureMin);
				AOM_ask_value_string(revisions, "ml8_PressureScopeMax", &pressureScopeMax);
				AOM_ask_value_string(revisions, "ml8_PressureScopeMin", &pressureScopeMin);
				AOM_ask_value_string(revisions, "ml8_MaterialCMax", &materialCMax);
				AOM_ask_value_string(revisions, "ml8_MaterialCMin", &materialCMin);

				propertyMap["枪头压力上限（bar）"] = spearHeadPressureMax;
				propertyMap["枪头压力下限（bar）"] = spearHeadPressureMin;
				propertyMap["压差上限（bar）"] = pressureScopeMax;
				propertyMap["压差下限（bar）"] = pressureScopeMin;
				propertyMap["料温上限（℃）"] = materialCMax;
				propertyMap["料温下限（℃）"] = materialCMin;

				DOFREE(spearHeadPressureMax);
				DOFREE(spearHeadPressureMin);
				DOFREE(pressureScopeMax);
				DOFREE(pressureScopeMin);
				DOFREE(materialCMax);
				DOFREE(materialCMin);
			}
			else if (strcmp(stepItemType, "ML8_GZStepRevision") == 0)
			{
				//获取版本属性灌注量公差上限、灌注量公差下限
				char * fillToleranceMax = NULL;
				char * fillToleranceMin = NULL;

				AOM_ask_value_string(revisions, "ml8_FillToleranceMax", &fillToleranceMax);
				AOM_ask_value_string(revisions, "ml8_FillToleranceMin", &fillToleranceMin);

				propertyMap["灌注量公差上限"] = fillToleranceMax;
				propertyMap["灌注量公差下限"] = fillToleranceMin;

				DOFREE(fillToleranceMax);
				DOFREE(fillToleranceMax);
			}

			//遍历MAP拼接字符串
			for (map<char*, char*>::iterator ii = propertyMap.begin(); ii != propertyMap.end(); ii++)
			{
				//拼接json字符串
				if (isUserMesSpecialProcessStart)
				{
					strcat(parameters, "{");
					isUserMesSpecialProcessStart = FALSE;
				}
				else
				{
					strcat(parameters, ",{");
				}

				strcat(parameters, "\"");
				strcat(parameters, "LineCode");
				strcat(parameters, "\"");
				strcat(parameters, ":");
				strcat(parameters, "\"");
				strcat(parameters, line);
				strcat(parameters, "\",");
				strcat(parameters, "\"");
				strcat(parameters, "ProcessCode");
				strcat(parameters, "\"");
				strcat(parameters, ":");
				strcat(parameters, "\"");
				strcat(parameters, itemId);
				strcat(parameters, "\",");
				strcat(parameters, "\"");
				strcat(parameters, "ProcessName");
				strcat(parameters, "\"");
				strcat(parameters, ":");
				strcat(parameters, "\"");
				strcat(parameters, objectName);
				strcat(parameters, "\",");
				strcat(parameters, "\"");
				strcat(parameters, "ParameterName");
				strcat(parameters, "\"");
				strcat(parameters, ":");
				strcat(parameters, "\"");
				strcat(parameters, ii->first);
				strcat(parameters, "\",");
				strcat(parameters, "\"");
				strcat(parameters, "ParameterValue");
				strcat(parameters, "\"");
				strcat(parameters, ":");
				strcat(parameters, "\"");
				strcat(parameters, ii->second);
				strcat(parameters, "\"");

				strcat(parameters, "}");
			}

			propertyMap.clear();
			map<char*, char*>().swap(propertyMap);
			DOFREE(stepItemType);
		}

		DOFREE(step_Bomline);
		DOFREE(objectName);
		DOFREE(itemType);
		DOFREE(itemId);
		DOFREE(line);
	}

	DOFREE(children_line);
}