#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"

#define DOFREE(obj)								\
{												\
	if(obj)										\
	{											\
	MEM_free(obj);							\
	obj = NULL;								\
	}											\
}

bool create_adhoc_signoff(tag_t current_task, vector<tag_t> user)
{
	//获取任务负责人
	int perform_count = 0;
	tag_t * perform_attaches = NULLTAG;
	AOM_ask_value_tags(current_task, "valid_signoffs", &perform_count, &perform_attaches);

	for (int i = 0; i < user.size(); i++) {
		int signoff_cnt = 0;
		tag_t * signoffs = NULLTAG;
		tag_t tmp_select_signoff_task = NULLTAG;
		if (user[i] != NULLTAG)
		{
			bool isHave = false;
			//判断是否已包含指定人员
			if (perform_count > 0)
			{
				for (int j = 0; j < perform_count; j++)
				{
					tag_t user_tag = NULLTAG;
					AOM_ask_value_tag(perform_attaches[j], "fnd0Assignee", &user_tag);
					if (user_tag != NULL_TAG) {
						//判断userID是否相同
						char * user_id = NULL;
						SA_ask_user_identifier2(user_tag, &user_id);
						char * checkUser_id = NULL;
						SA_ask_user_identifier2(user[i], &checkUser_id);
						if (strcmp(user_id, checkUser_id) == 0)
						{
							isHave = true;
							DOFREE(user_id);
							DOFREE(checkUser_id);
							break;
						}
						DOFREE(user_id);
						DOFREE(checkUser_id);
					}
				}
			}
			if (isHave)
			{
				DOFREE(signoffs);
				continue;
			}

			EPM_ask_sub_task(current_task, EPM_select_signoff_team_task, &tmp_select_signoff_task);
			if (tmp_select_signoff_task != NULLTAG)
			{
				EPM_create_adhoc_signoff(tmp_select_signoff_task, user[i], &signoff_cnt, &signoffs);
				EPM_set_adhoc_signoff_selection_done(tmp_select_signoff_task, true);
				//EPM_trigger_action(tmp_select_signoff_task, EPM_complete_action, "");
			}
			else
			{
				//更改执行人
				AOM_lock(current_task);
				AOM_set_value_tag(current_task, "fnd0Performer", user[i]);
				AOM_save(current_task);
				AOM_unlock(current_task);
				AOM_refresh(current_task, FALSE);
			}
		}
		DOFREE(signoffs);
	}
	return true;
}


void TCFindItem(char * queryName, int n_entries,char ** qry_entries,char ** qry_values, int * n_found, tag_t ** dba_mbrs)
{
	tag_t query = NULLTAG;
	QRY_find2(queryName, &query);
	QRY_execute(query, n_entries, qry_entries, qry_values, n_found, dba_mbrs);
}



char * getLovKey(int theAttrId, char * value)
{
	char* key_lov_name;
	int  options = 0;
	int  n_lov_entries = 0;
	char** lov_keys;
	char** lov_values;
	logical* deprecated_staus;
	char* owning_site;
	int n_shared_sites = 0;
	char** shared_sites;
	char* format = NULL;
	ICS_attribute_ask_property(theAttrId, "FORMAT1", &format);

	ICS_keylov_get_keylov(format, &key_lov_name, &options, &n_lov_entries, &lov_keys, &lov_values, &deprecated_staus,
		&owning_site, &n_shared_sites, &shared_sites);
	if (n_lov_entries > 0) {
		for (int q = 0; q < n_lov_entries; q++) {
			if (strcmp(value, lov_values[q]) == 0) {

				printf("lov_values[q]%s\n", value);
				printf("lov_keys[q]%s\n", lov_keys[q]);

				value = lov_keys[q];
				break;
			}
		}
	}
	return value;
}

char * getClassProperty(tag_t item, char * propertyName)
{
	char * result = "";
	tag_t ico_tag = NULLTAG;
	ICS_ask_classification_object(item, &ico_tag);
	int theAttributeCount, *theAttributeIds, *theAttributeValCounts;
	char ***theAttributeValues;
	ICS_ico_ask_attributes(ico_tag, &theAttributeCount, &theAttributeIds, &theAttributeValCounts, &theAttributeValues);
	for (int t = 0; t < theAttributeCount; t++) {
		char theAttributeId[20] = "\0";
		printf("theAttributeIds=%d ,theAttributeValCounts=%d\n", theAttributeIds[t], theAttributeValCounts[t]);
		sprintf(theAttributeId, "%d", theAttributeIds[t]);
		if (theAttributeValCounts[t]>0 && strcmp(theAttributeId, propertyName) == 0) {
			printf("icoLineCode=%s\n", theAttributeValues[t][0]);
			result = theAttributeValues[t][0];//getLovKey(theAttributeIds[t], theAttributeValues[t][0]);
			break;
		}
	}
	return result;
}


void TCGetPropertyValue(tag_t item,char * type,char * propertyName,char ** propertyValue)
{
	//判断是否包含.号
	if (strstr(propertyName, ".") != NULL)
	{
		//根据等号拆分条件和值
		int itemPropertyCount = 0;
		char ** itemPropertyChar = new char *[64];
		//分割字符串
		split(propertyName, ".", itemPropertyChar, &itemPropertyCount);

		char * itemAddress = itemPropertyChar[0];

		if (strcmp(type, "Revision") == NULL)
		{
			//传进来的是版本
			if (strcmp(itemAddress, "item") == 0)
			{
				ITEM_ask_item_of_rev(item, &item);
			}
			else if (strcmp(itemAddress, "revMaster") == 0)
			{
				tag_t master_form_rel_type = NULLTAG, *form_list = NULLTAG;
				int form_count = 0;
				//获取版本表单
				GRM_find_relation_type(TC_master_form_rtype, &master_form_rel_type);
				GRM_list_secondary_objects_only(item, master_form_rel_type, &form_count, &form_list);
				if (form_count == 0)
				{
					printf("未找到form,继续...");
				}
				else
				{
					item = form_list[form_count - 1];
				}
				DOFREE(form_list);
			}
			//判断拆分出的数量是否大于2
			if (itemPropertyCount > 2)
			{
				//遍历查找关系对象
				for (int i = 1; i < itemPropertyCount - 1; i++)
				{
					AOM_ask_value_tag(item, itemPropertyChar[i], &item);
				}
			}
			if (strcmp(itemAddress, "class") == 0)
			{
				*propertyValue = getClassProperty(item, itemPropertyChar[itemPropertyCount - 1]);
			}
			else
			{
				if (item == NULL_TAG)
				{
					*propertyValue = "";
				}
				else
				{
					AOM_UIF_ask_value(item, itemPropertyChar[itemPropertyCount - 1], propertyValue);
				}
			}
		}
		else if (strcmp(type, "BOMLine") == NULL)
		{
			tag_t revisions = NULLTAG;

			AOM_ask_value_tag(item, "bl_line_object", &revisions);
			//传进来的是对象
			if (strcmp(itemAddress, "item") == 0)
			{
				ITEM_ask_item_of_rev(revisions, &item);
			}
			else if (strcmp(itemAddress, "rev") == 0)
			{
				item = revisions;
			}
			else if (strcmp(itemAddress, "revMaster") == 0)
			{
				tag_t master_form_rel_type = NULLTAG, *form_list = NULLTAG;
				int form_count = 0;
				//获取版本表单
				GRM_find_relation_type(TC_master_form_rtype, &master_form_rel_type);
				GRM_list_secondary_objects_only(revisions, master_form_rel_type, &form_count, &form_list);
				if (form_count == 0)
				{
					printf("未找到form,继续...");
				}
				else
				{
					item = form_list[form_count - 1];
				}
				DOFREE(form_list);
			}
			//判断拆分出的数量是否大于2
			if (itemPropertyCount > 2)
			{
				//遍历查找关系对象
				for (int i = 1; i < itemPropertyCount - 1; i++)
				{
					AOM_ask_value_tag(item, itemPropertyChar[i], &item);
				}
			}
			if (strcmp(itemAddress, "class") == 0)
			{
				*propertyValue = getClassProperty(revisions, itemPropertyChar[itemPropertyCount - 1]);
			}
			else
			{
				if (item == NULL_TAG)
				{
					*propertyValue = "";
				}
				else
				{
					AOM_UIF_ask_value(item, itemPropertyChar[itemPropertyCount - 1], propertyValue);
				}
			}
		}
		else if (strcmp(type, "Item") == NULL)
		{
			tag_t revisions = NULLTAG;

			ITEM_ask_latest_rev(item, &revisions);
			//传进来的是对象
			if (strcmp(itemAddress, "rev") == 0)
			{
				item = revisions;
			}
			else if (strcmp(itemAddress, "revMaster") == 0)
			{
				tag_t master_form_rel_type = NULLTAG, *form_list = NULLTAG;
				int form_count = 0;
				//获取版本表单
				GRM_find_relation_type(TC_master_form_rtype, &master_form_rel_type);
				GRM_list_secondary_objects_only(revisions, master_form_rel_type, &form_count, &form_list);
				if (form_count == 0)
				{
					printf("未找到form,继续...");
				}
				else
				{
					item = form_list[form_count - 1];
				}
				DOFREE(form_list);
			}
			//判断拆分出的数量是否大于2
			if (itemPropertyCount > 2)
			{
				//遍历查找关系对象
				for (int i = 1; i < itemPropertyCount - 1; i++)
				{
					AOM_ask_value_tag(item, itemPropertyChar[i], &item);
				}
			}

			if (strcmp(itemAddress, "class") == 0)
			{
				*propertyValue = getClassProperty(revisions, itemPropertyChar[itemPropertyCount - 1]);
			}
			else
			{
				if (item == NULLTAG)
				{
					*propertyValue = "";
				}
				else
				{
					AOM_UIF_ask_value(item, itemPropertyChar[itemPropertyCount - 1], propertyValue);
					//char * type = NULL;
					//AOM_ask_value_string(item, "object_type", &type);
					////获取对象类型
					//tag_t tAttrID = NULLTAG;
					//POM_attr_id_of_attr(itemPropertyChar[itemPropertyCount - 1], type, &tAttrID);
					//if (tAttrID == NULLTAG)
					//{
					//	*propertyValue = "";
					//}
					//else
					//{
					//	AOM_ask_value_string(item, itemPropertyChar[itemPropertyCount - 1], propertyValue);
					//}
				}
			}
		}
	}
	else
	{
		*propertyValue = propertyName;
	}
}

void BOMSendToWeixin(char * userId, tag_t rootTask_tag, string message)
{
	string jsonStr("{\\\"touser\\\":\\\""), strResult;
	jsonStr.append(userId);
	if (rootTask_tag != NULLTAG)
	{
		jsonStr.append("\\\",\\\"msgtype\\\":\\\"text\\\",\\\"agentid\\\":1000060,\\\"text\\\":{\\\"content\\\":\\\"BOM发送到ERP失败。\\n流程发起者：【");
		//获取流程发起者
		tag_t owning_user = NULLTAG;
		char * owning_id = NULL, *process_name = NULL;
		AOM_ask_owner(rootTask_tag, &owning_user);
		SA_ask_user_identifier2(owning_user, &owning_id);
		jsonStr.append(owning_id);
		jsonStr.append("】\\n流程名称：【");
		//获取流程名称
		EPM_ask_name2(rootTask_tag, &process_name);
		jsonStr.append(process_name);

		DOFREE(owning_id);
		DOFREE(process_name);
	}
	else
	{
		jsonStr.append("\\\",\\\"msgtype\\\":\\\"text\\\",\\\"agentid\\\":1000060,\\\"text\\\":{\\\"content\\\":\\\"使用菜单BOM发送到ERP失败。\\n");
	}
	
	jsonStr.append("】\\n异常日志：【");
	jsonStr.append(message);
	jsonStr.append("】");
	jsonStr.append("\\\"}}");
	char toJar[1000] = "";
	strcat(toJar, "java -jar ");
	strcat(toJar, "C:\\PLM\\sendToWeixin.jar ");
	strcat(toJar, jsonStr.c_str());
	//system(toJar);
	//_popen(toJar, "r");

	char buf[8000] = { 0 };
	FILE *pf = NULL;
	if ((pf = _popen(toJar, "r")) == NULL) {
		printf("接口返回:\n%s", "1");
	}

	while (fgets(buf, sizeof buf, pf)) {
		strResult += buf;
	}
	_pclose(pf);
	cout << strResult << endl;
}

void itemSendToWeixin(char * userId, tag_t rootTask_tag, string message)
{
	string jsonStr("{\\\"touser\\\":\\\""), strResult;
	jsonStr.append(userId);
	jsonStr.append("\\\",\\\"msgtype\\\":\\\"text\\\",\\\"agentid\\\":1000060,\\\"text\\\":{\\\"content\\\":\\\"物料发送到ERP失败。\\n流程发起者：【");
	//获取流程发起者
	tag_t owning_user = NULLTAG;
	char * owning_id = NULL, *process_name = NULL;
	AOM_ask_owner(rootTask_tag, &owning_user);
	SA_ask_user_identifier2(owning_user, &owning_id);
	jsonStr.append(owning_id);
	jsonStr.append("】\\n流程名称：【");
	//获取流程名称
	EPM_ask_name2(rootTask_tag, &process_name);
	jsonStr.append(process_name);
	jsonStr.append("】\\n异常日志：【");
	jsonStr.append(message);
	jsonStr.append("】");
	jsonStr.append("\\\"}}");
	char toJar[1000] = "";
	strcat(toJar, "java -jar ");
	strcat(toJar, "C:\\PLM\\sendToWeixin.jar ");
	strcat(toJar, jsonStr.c_str());
	//system(toJar);
	//_popen(toJar, "r");

	char buf[8000] = { 0 };
	FILE *pf = NULL;
	if ((pf = _popen(toJar, "r")) == NULL) {
		printf("接口返回:\n%s", "1");
	}

	while (fgets(buf, sizeof buf, pf)) {
		strResult += buf;
	}
	_pclose(pf);
	cout << strResult << endl;
	DOFREE(owning_id);
	DOFREE(process_name);
}

void GetFiles(string path, vector<string>& files)
{
	//文件句柄  
	long hFile = 0;
	//文件信息  
	struct _finddata_t fileinfo;
	std::string p;
	if ((hFile = _findfirst(p.assign(path).append("/*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			//如果是目录,迭代之  
			//如果不是,加入列表  
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					GetFiles(p.assign(path).append("/").append(fileinfo.name), files);
			}
			else
			{
				files.push_back(p.assign(path).append("/").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

LPCWSTR stringToLPCWSTR(std::string orig)
{
	/*size_t origsize = orig.length() + 1;
	const size_t newsize = 100;
	size_t convertedChars = 0;
	wchar_t *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(orig.length() - 1));
	mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);

	return wcstring;*/
	int len;
	int slength = (int)orig.length() + 1;
	len = MultiByteToWideChar(CP_ACP, 0, orig.c_str(), slength, 0, 0);
	wchar_t* buf = new wchar_t[len];
	MultiByteToWideChar(CP_ACP, 0, orig.c_str(), slength, buf, len);
	//std::wstring r(buf);
	///delete[] buf;

	//LPCWSTR result = r.c_str();
	return buf;
}

const char * inputFileToFtp(char * filePath)
{
	string ftpFilePath = NULL;
	//ftp地址
	string ftpSvrIp = "10.18.1.105";
	//ftp端口
	int port = 21;
	//用户名
	string userName = "Administrator";
	//用户密码
	string password = "PlmTst_8023";
	//上传文件源路径
	string sourceFilePath = filePath;
	//上传文件目的路径
	string resultFilePath = "/工位SOP文件/";
	string desFilePath = "./工位SOP文件/";

	vector<string> files;

	//判断上传的是文件还是文件夹标识       
	int size = 0;
	if (sourceFilePath.find(".") == string::npos)
	{
		//获取文件夹下所有文件名
		GetFiles(sourceFilePath, files);
		char str[30];
		size = files.size();
	}
	HINTERNET hint = NULL;
	HINTERNET hftp = NULL;
	do {
		hint = InternetOpen(0, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
		if (hint == NULL)
		{
			break;
		}
		//创建ftp连接
		hftp = InternetConnect(hint, stringToLPCWSTR(ftpSvrIp), port, stringToLPCWSTR(userName), stringToLPCWSTR(password), INTERNET_SERVICE_FTP, 0, 0);
		if (hftp == NULL)
		{
			break;
		}
		//如果目的路径不存在，一级一级创建
		//目的路径格式为:"./dir/dir1/.../"
		int pos = 1;
		string tempPath;
		while (pos>0)
		{
			// 从第二个“/”开始依次找到目的路径中的“/”位置
			pos = desFilePath.find_first_of('/', pos + 1);
			if (pos == -1)
				break;
			tempPath = desFilePath.substr(0, pos + 1);
			if (_access(tempPath.c_str(), 0) == -1)
			{
				FtpCreateDirectory(hftp, stringToLPCWSTR(tempPath));
			}
		}

		//如果FtpSetCurrentDirectory一直报错，看一下desFilePath路径是否创建成功，用资源管理器看能否直接访问ftp
		if (FtpSetCurrentDirectory(hftp, stringToLPCWSTR(desFilePath)))
		{
			//上传文件源为一个文件
			if (0 == size)
			{
				//获取上传路径中的文件名
				int pos = sourceFilePath.find_last_of('/');
				string desfilename = sourceFilePath.substr(pos + 1);
				int i = FtpPutFile(hftp, stringToLPCWSTR(sourceFilePath), stringToLPCWSTR(desfilename), FTP_TRANSFER_TYPE_BINARY, 0);
			}
			//上传文件源为文件夹
			else
			{
				for (int i = 0; i < size; i++)
				{
					std::string tempFilePath = files[i].c_str();
					//获取上传路径中的文件名
					int pos = tempFilePath.find_last_of('/');
					string desfilename = tempFilePath.substr(pos + 1);
					//desfilename = desFilePath + desfilename;
					int result = FtpPutFile(hftp, stringToLPCWSTR(tempFilePath), stringToLPCWSTR(desfilename), FTP_TRANSFER_TYPE_ASCII, 0);

					if (result == 0)
					{
						printf("上传文件失败！\n");
						return NULL;
					}
					else
					{
						ftpFilePath = "FTP://" + ftpSvrIp + resultFilePath + desfilename;
					}
				}
			}
		}
	} while (0);

	InternetCloseHandle(hftp);
	InternetCloseHandle(hint);

	if (ftpFilePath.length() > 0)
	{
		cout << "上传文件完成" << endl;
	}

	return ftpFilePath.c_str();
}

char * getLineCode(char * lineCode)
{
	char * result = "ALL";
	int theCount1;
	char **theICOUIDs, **theICOIds, **theClassIds, **theWSOUIDs;
	tag_t *theICOTags, *theWSOTags;
	ICS_class_ask_icos("组计数器字典", "", &theCount1, &theICOTags, &theICOUIDs, &theICOIds, &theClassIds, &theWSOTags, &theWSOUIDs);
	printf("theCount1=%d\n", theCount1);
	int theAttributeCount, *theAttributeIds, *theAttributeValCounts;
	char ***theAttributeValues;
	
	for (int m = 0; m < theCount1; m++)
	{
		ICS_ico_ask_attributes(theICOTags[m], &theAttributeCount, &theAttributeIds, &theAttributeValCounts, &theAttributeValues);
		printf("theICOIds=%s,theICOUID==%s\n", theICOIds[m], theICOUIDs[m]);

		char * icoLineCode = NULL;
		char * icoERPCode = NULL;

		for (int t = 0; t < theAttributeCount; t++) {
			char theAttributeId[20] = "\0";
			printf("theAttributeIds=%d ,theAttributeValCounts=%d\n", theAttributeIds[t], theAttributeValCounts[t]);
			sprintf(theAttributeId, "%d", theAttributeIds[t]);
			if (theAttributeValCounts[t]>0 && strcmp(theAttributeId,"1002") == 0) {
				printf("icoLineCode=%s\n", theAttributeValues[t][0]);
				icoLineCode = theAttributeValues[t][0];
			}
			else if (theAttributeValCounts[t]>0 && strcmp(theAttributeId, "1101") == 0) {
				printf("icoERPCode=%s\n", theAttributeValues[t][0]);
				icoERPCode = theAttributeValues[t][0];
			}
		}
		if (strcmp(lineCode, icoLineCode) == 0 && icoERPCode != NULL && strcmp(icoERPCode, "") != 0)
		{
			result = icoERPCode;
			break;
		}

	}
	return result;
}

char* removeSpaces(char* str) {
	int i, j;
	// 对字符串进行迭代，查找非空字符并复制到前面的位置
	for (i = j = 0; str[i] != '\0'; i++)
		if (str[i] != ' ')
			str[j++] = str[i];

	// 在末尾添加'\0'来结束新字符串
	str[j] = '\0';
	return str;
}

char* removeChar(char* str, char charToRemove) {
	char* newStr = str;
	char* p = str;
	while (*p) {
		if (*p != charToRemove) {
			*newStr++ = *p;
		}
		p++;
	}
	*newStr = '\0'; // 添加字符串终止符
	return str;
}

void removeFirstFourChars(char* str) {
	if (str == nullptr) return;
	char* newStart = std::next(str, 4); // 获取新的起始位置
	std::copy(newStart, str + std::strlen(str), str); // 拷贝剩余字符
	*std::strrchr(str, '\0') = '\0'; // 修正字符串末尾
}

bool startsWith(const char* str, char first, char second) {
	return str && str[0] == first && str[1] == second;
}

char* getFirstStr(const char* str, int index) {
	if (str == nullptr) {
		return nullptr;
	}
	int length = strlen(str);
	if (length <= index) {
		// 创建新的字符串并复制内容
		char* result = new char[length + 1];
		strcpy(result, str);
		return result;
	}
	else {
		// 创建新的字符串并复制前四个字符
		char* result = new char[index + 1];
		strncpy(result, str, index);
		result[index] = '\0'; // 添加字符串结束标记
		return result;
	}
}

//获取分类属性
void getClassValue(char* value, int id, char** disValue) {
	//printf("===================================\n");
	//printf("获取分类属性 开始\n");
	//printf("===================================\n");
	char* format = NULL;
	ITKCALL(ICS_attribute_ask_property(id, "FORMAT1", &format));
	//printf(">> Format: %s\n", format);
	if (format != NULL && strcmp("", format) != 0 && strcmp(" ", format) != 0) {
		char* key_lov_name;
		int  options = 0;
		int  n_lov_entries = 0;
		char** lov_keys;
		char** lov_values;
		logical* deprecated_staus;
		char* owning_site;
		int n_shared_sites = 0;
		char** shared_sites;
		ICS_keylov_get_keylov(format, &key_lov_name, &options, &n_lov_entries, &lov_keys, &lov_values, &deprecated_staus,
			&owning_site, &n_shared_sites, &shared_sites);
		//printf(">> 下拉值数量: %d\n", n_lov_entries);
		if (n_lov_entries == 0) {
			*disValue = value;
		}
		else {
			for (int j = 0; j < n_lov_entries; j++) {
				if (strcmp(value, lov_keys[j]) == 0) {
					//printf("lov的选值=>:[%s]\n", lov_values[j]);
					*disValue = lov_values[j];
					break;
				}
			}
			if (key_lov_name != NULL) {
				DOFREE(key_lov_name);
			}
			if (lov_keys != NULL) {
				DOFREE(lov_keys);
			}
			if (lov_values != NULL) {
				DOFREE(lov_values);
			}
			if (deprecated_staus != NULL) {
				DOFREE(deprecated_staus);
			}
			if (owning_site != NULL) {
				DOFREE(owning_site);
			}
			if (shared_sites != NULL) {
				DOFREE(shared_sites);
			}
		}
	}
	if (format != NULL) {
		DOFREE(format);
	}
	//printf("===================================\n");
	//printf("获取分类属性 结束\n");
	//printf("===================================\n");
}