#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"

int ML_AddItemToAttachments(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 resultString[1024] = "";

	for (int i = 0; i < attachments_num; i++)
	{
		char *itemType = NULL;

		AOM_ask_value_string(attachments[i], "object_type", &itemType);
		printf("type_class : %s \r\n", itemType);
		//过滤掉非时间表的对象
		if ((strstr(itemType, "Schedule") == NULL) || (strstr(itemType, "Task") != NULL))
		{
			DOFREE(itemType);
			continue;
		}

		//tag_t scheduleTaskTags = NULLTAG;
		//获取时间表
		//AOM_ask_value_tag(attachments[i], "original_task_tag", &scheduleTaskTags);
		//获取基线对应的时间表任务
		tag_t scheduleTags = NULLTAG;
		//获取时间表
		AOM_ask_value_tag(attachments[i], "activeschbaseline_tag", &scheduleTags);

		int forNumm = 0;
		tag_t * formTags = NULLTAG;

		//获取时间表下的表单
		AOM_ask_value_tags(scheduleTags, "IMAN_reference", &forNumm, &formTags);

		int * attachment_types = (int*)MEM_alloc(sizeof(int));
		for (int i = 0; i < forNumm; i++)
		{
			attachment_types[i] = EPM_target_attachment;
		}

		POM_AM__set_application_bypass(true);
		//添加到流程目标下
		EPM_add_attachments(rootTask, forNumm, formTags, attachment_types);
		POM_AM__set_application_bypass(false);

		DOFREE(itemType);
		DOFREE(formTags);
	}

	DOFREE(attachments);

	auto stopTime = std::chrono::high_resolution_clock::now();
	auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stopTime - startTime);
	//std::cout << "ML_AddItemToAttachments用时:" << duration.count() / 1000 << std::endl;
	string usetime = "ML_AddItemToAttachments用时:";
	usetime.append(std::to_string(duration.count() / 1000));
	WriteLog(true, usetime.c_str());
	printf("=========================将表单添加到任务目标下 End===================\n");
	return ifail;
}