#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"

void IsRelease(tag_t topLine, vector<char *> itemidValues, int &size, int *&tagType, tag_t *&itemTag, char * user_id);
void ChildIsRelease(tag_t topLine, char messageValue[100000]);

int ML_AddReleaseItemToAttachments(EPM_action_message_t msg)
{
	printf("=========================将未发布对象移动到流程目标下 Start===================\n");
	auto startTime = std::chrono::high_resolution_clock::now();
	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 * ownerId = "";

	//获取当前登陆人员
	tag_t current_user = NULLTAG, current_member = NULLTAG;

	SA_ask_current_groupmember(&current_member);
	SA_ask_groupmember_user(current_member, &current_user);
	SA_ask_user_identifier2(current_user, &ownerId);

	char *argflag = NULL, *argvalue = NULL, *arg = NULL;
	char arg1value[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, "itemType") == 0)
			{
				//strcmp("","");
				if (argvalue != NULL)
				{
					strcpy(arg1value, argvalue);
				}
			}
		}
		DOFREE(argflag);
		DOFREE(argvalue);
		DOFREE(arg);
	}

	char  messageValue[100000] = "";
	for (int i = 0; i < attachments_num; i++)
	{
		vector<char *> itemidValues;

		char *itemType = NULL;

		AOM_ask_value_string(attachments[i], "object_type", &itemType);
		printf("type_class : %s \r\n", itemType);
		//过滤掉非文件夹的对象
		if (strcmp(arg1value, itemType) != 0)
		{
			DOFREE(itemType);
			continue;
		}
		//创建BOMWindow
		tag_t top_line = NULLTAG, window = NULLTAG;
		BOM_create_window(&window);
		//设置顶层BOM
		BOM_set_window_top_line(window, NULLTAG, attachments[i], NULLTAG, &top_line);

		int  children_count = 0;
		tag_t *children_line = NULLTAG;

		BOM_line_ask_all_child_lines(top_line, &children_count, &children_line);

		int size = 0;
		int *tagType = (int *)MEM_alloc(1024 * sizeof(int));//EPM_reference_attachment
		tag_t * itemTag = (tag_t *)MEM_alloc(1024 * sizeof(tag_t));

		//获取文档小类ml8_SubClass
		char * subClass = NULL;
		AOM_ask_value_string(attachments[i], "ml8_SubClass", &subClass);
		char * objectString = NULL;
		AOM_ask_value_string(attachments[i], "object_string", &objectString);
		if (subClass != NULL && strcmp(subClass, "总装图") == 0)
		{
			//判断他所有子级的A版全部有发布状态才能提交，否则报错；
			ChildIsRelease(top_line, messageValue);
			if (strlen(messageValue) > 2)
			{
				ifail = 1;
			}
		}
		else if (subClass == NULL || strcmp(subClass,"") == 0)
		{
			strcat(messageValue, objectString);
			strcat(messageValue, "文档小类为空！");
			ifail = 1;
		}
		else
		{
			//将所有子级A版工作中的且所有者是自己的子件带入流程（流程中不带入，有状态不带入）
			for (int j = 0; j < children_count; j++)
			{
				tag_t revision = NULLTAG;

				AOM_ask_value_tag(children_line[j], "bl_line_object", &revision);
				tag_t item = NULLTAG;
				ITEM_ask_item_of_rev(revision, &item);
				//获取所有版本
				int revisionNum = 0;
				tag_t * revisions = NULLTAG;
				AOM_ask_value_tags(item, "revision_list", &revisionNum, &revisions);

				tag_t attOwning_user = NULL_TAG;
				char * userId = NULL;

				AOM_ask_value_tag(revisions[0], "owning_user", &attOwning_user);
				SA_ask_user_identifier2(attOwning_user, &userId);

				printf("userId : %s \r\n", userId);
				printf("ownerId : %s \r\n", ownerId);
				if (strcmp(userId, ownerId) != 0)
				{
					DOFREE(revisions);
					DOFREE(userId);
					continue;
				}

				int releaseCount = 0;
				tag_t * releaseTag = NULL_TAG;
				//判断子件是否发布
				AOM_ask_value_tags(revisions[0], "release_status_list", &releaseCount, &releaseTag);


				int processCount = 0;
				tag_t * processTag = NULL_TAG;
				//判断子件是否在流程中
				AOM_ask_value_tags(revisions[0], "process_stage_list", &processCount, &processTag);

				/*bool isRelease = false;
				for (int k = 0; k < revisionNum; k++)
				{

				printf("发布状态%d===================\n", releaseCount);
				if (releaseCount > 0)
				{
				isRelease = true;
				DOFREE(releaseTag);
				break;
				}
				DOFREE(releaseTag);
				}*/
				//int releaseCount = 0;
				//tag_t * releaseTag = NULL_TAG;
				////判断子件是否发布
				//AOM_ask_value_tags(revision, "release_status_list", &releaseCount, &releaseTag);

				//printf("发布状态%d===================\n", releaseCount);
				if (releaseCount <= 0 && processCount <= 0)
				{
					char * revItemId = NULL;
					AOM_ask_value_string(revision, "item_id", &revItemId);
					if (!count(itemidValues, revItemId))
					{
						//添加到目标下
						tagType[size] = EPM_target_attachment;
						itemTag[size] = revision;
						size++;
						itemidValues.push_back(revItemId);
					}
					DOFREE(revItemId);
				}
				IsRelease(children_line[j], itemidValues, size, tagType, itemTag, ownerId);
				DOFREE(processTag);
				DOFREE(releaseTag);
				DOFREE(revisions);
				DOFREE(userId);
			}

			if (size > 0)
			{
				POM_AM__set_application_bypass(true);
				//添加到流程目标下
				EPM_add_attachments(rootTask, size, itemTag, tagType);
				POM_AM__set_application_bypass(false);
			}
		}

		BOM_close_window(window);

		DOFREE(subClass);
		DOFREE(objectString);
		DOFREE(itemType);
		DOFREE(children_line);
	}
	DOFREE(attachments);
	DOFREE(ownerId);
	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_AddReleaseItemToAttachments用时:" << duration.count() / 1000 << std::endl;
	string usetime = "ML_AddReleaseItemToAttachments用时:";
	usetime.append(std::to_string(duration.count() / 1000));
	WriteLog(true, usetime.c_str());
	printf("=========================将未发布对象移动到流程目标下 End===================\n");
	return ifail;
}

void IsRelease(tag_t topLine, vector<char *> itemidValues, int &size, int *&tagType, tag_t *&itemTag, char * user_id)
{
	bool reault = true;
	int  children_count = 0;
	tag_t *children_line = NULLTAG;

	BOM_line_ask_all_child_lines(topLine, &children_count, &children_line);

	for (int i = 0; i < children_count; i++)
	{
		tag_t revision = NULLTAG;

		AOM_ask_value_tag(children_line[i], "bl_line_object", &revision);
		tag_t item = NULLTAG;
		ITEM_ask_item_of_rev(revision, &item);
		///获取所有版本
		int revisionNum = 0;
		tag_t * revisions = NULLTAG;
		AOM_ask_value_tags(item, "revision_list", &revisionNum, &revisions);



		int releaseCount = 0;
		tag_t * releaseTag = NULL_TAG;
		//判断子件是否发布
		AOM_ask_value_tags(revisions[0], "release_status_list", &releaseCount, &releaseTag);

		int processCount = 0;
		tag_t * processTag = NULL_TAG;
		//判断子件是否在流程中
		AOM_ask_value_tags(revisions[0], "process_stage_list", &processCount, &processTag);


		tag_t attOwning_user = NULL_TAG;
		char * userId = NULL;

		AOM_ask_value_tag(revisions[0], "owning_user", &attOwning_user);
		SA_ask_user_identifier2(attOwning_user, &userId);
		if (strcmp(userId, user_id) != 0)
		{
			DOFREE(releaseTag);
			DOFREE(processTag);
			DOFREE(revisions);
			DOFREE(userId);
			continue;
		}

		/*printf("发布状态%d===================\n", releaseCount);
		if (releaseCount > 0)
		{
		isRelease = true;
		DOFREE(releaseTag);
		break;
		}
		DOFREE(releaseTag);*/

		//bool isRelease = false;
		//for (int j = 0; j < revisionNum; j++)
		//{
		//	int releaseCount = 0;
		//	tag_t * releaseTag = NULL_TAG;
		//	//判断子件是否发布
		//	AOM_ask_value_tags(revisions[j], "release_status_list", &releaseCount, &releaseTag);

		//	printf("发布状态%d===================\n", releaseCount);
		//	if (releaseCount > 0)
		//	{
		//		isRelease = true;
		//		DOFREE(releaseTag);
		//		break;
		//	}
		//	DOFREE(releaseTag);
		//}
		//int releaseCount = 0;
		//tag_t * releaseTag = NULL_TAG;
		////判断子件是否发布
		//AOM_ask_value_tags(revision, "release_status_list", &releaseCount, &releaseTag);

		//printf("发布状态%d===================\n", releaseCount);
		if (releaseCount <= 0 && processCount <= 0)
		{
			char * revItemId = NULL;
			AOM_ask_value_string(revision, "item_id", &revItemId);
			if (!count(itemidValues, revItemId))
			{
				tagType[size] = EPM_target_attachment;
				itemTag[size] = revision;
				size++;
				itemidValues.push_back(revItemId);
			}
			DOFREE(revItemId);
		}
		IsRelease(children_line[i], itemidValues, size, tagType, itemTag,user_id);

		DOFREE(processTag);
		DOFREE(releaseTag);
		DOFREE(revisions);
		DOFREE(userId);
	}
	DOFREE(children_line);
}


void ChildIsRelease(tag_t topLine, char messageValue[100000])
{
	bool reault = true;
	int  count = 0;
	tag_t *children_line = NULLTAG;

	BOM_line_ask_all_child_lines(topLine, &count, &children_line);

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

		AOM_ask_value_tag(children_line[i], "bl_line_object", &revision);
		tag_t item = NULLTAG;
		ITEM_ask_item_of_rev(revision, &item);
		///获取所有版本
		int revisionNum = 0;
		tag_t * revisions = NULLTAG;
		AOM_ask_value_tags(item, "revision_list", &revisionNum, &revisions);

		char *objectString = NULL;
		AOM_ask_value_string(revisions[0], "object_string", &objectString);

		int releaseCount = 0;
		tag_t * releaseTag = NULL_TAG;
		//判断子件是否发布
		AOM_ask_value_tags(revisions[0], "release_status_list", &releaseCount, &releaseTag);

		printf("发布状态%d===================\n", releaseCount);
		if (releaseCount <= 0)
		{
			strcat(messageValue, objectString);
			strcat(messageValue, "未发布！");
		}
		else
		{
			ChildIsRelease(children_line[i], messageValue);
		}


		DOFREE(releaseTag);
		DOFREE(objectString);
		DOFREE(revisions);
		//DOFREE(releaseTag);
		//DOFREE(revisions);
	}
	DOFREE(children_line);
}