#define _CRT_SECURE_NO_WARNINGS
#include "epm_handler_common.h"

#define DOFREE(obj)								\
{												\
	if(obj)										\
	{											\
	MEM_free(obj);							\
	obj = NULL;								\
	}											\
}
string GbkToUtf8(const char* src_str) {
	int len = MultiByteToWideChar(CP_ACP, 0, src_str, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_ACP, 0, src_str, -1, wstr, len);
	len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
	string strTemp = str;
	if (wstr) delete[] wstr;
	if (str) delete[] str;
	return strTemp;
}
bool create_adhoc_signoff(tag_t current_task, vector<tag_t> user)
{
	tag_t tmp_select_signoff_task = NULLTAG;
	AOM_refresh(current_task, FALSE);
	EPM_ask_sub_task(current_task, EPM_select_signoff_team_task, &tmp_select_signoff_task);
	//if (tmp_select_signoff_task != NULLTAG)
	//{
	//	//获取successors
	//	int successors_count = 0;
	//	tag_t * successors_attaches = NULLTAG;
	//	AOM_ask_value_tags(tmp_select_signoff_task, "successors", &successors_count, &successors_attaches);
	//	for (int i = 0; i < successors_count; i++) {
	//		//设置signoff_attachments的值为空
	//		AOM_lock(successors_attaches[i]);
	//		AOM_set_value_tags(successors_attaches[i], "signoff_attachments", 0, NULLTAG); 
	//		AOM_save(successors_attaches[i]);
	//		AOM_unlock(successors_attaches[i]);
	//		AOM_refresh(successors_attaches[i], FALSE);
	//	}
	//	DOFREE(successors_attaches);
	//}

	//获取任务负责人
	int perform_count = 0;
	tag_t * perform_attaches = NULLTAG;
	AOM_ask_value_tags(current_task, "valid_signoffs", &perform_count, &perform_attaches);

	printf("已包含人员%d===================\n", perform_count);
	for (int i = 0; i < user.size(); i++) {
		int signoff_cnt = 0;
		tag_t * signoffs = 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;
			}

			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
			{

				printf("更改执行人员===================\n");
				//更改执行人
				//AOM_lock(current_task);
				EPM_assign_responsible_party(current_task, user[i]);
				//EPM_set_task_decision2(current_task, signoffs[0], CR_approve_decision, "");
				////connor_set_prop_value_tag(current_task, "fnd0Assignee", user[i]);
				//AOM_set_value_tag(current_task, "fnd0Assigner", user[i]);
				//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);
}

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++)
				{
					if (item == NULL_TAG) {
						break;
					}
					PROP_type_t type_t;
					char *type = NULL;
					tag_t *childs = NULL;
					int count = 0;
					AOM_ask_property_type(item, itemPropertyChar[i], &type_t, &type);
					printf("关系：%s ==> %s\n", itemPropertyChar[i], type);
					if (type_t == PROP_reference) {
						AOM_ask_value_tag(item, itemPropertyChar[i], &item);
					}
					else {
						AOM_ask_value_tags(item, itemPropertyChar[i], &count, &childs);
						if (count == 0) {
							item = NULL_TAG;
						}
						else {
							item = childs[0];
						}
					}
				}
			}
			if (item == NULL_TAG)
			{
				*propertyValue = "";
			}
			else
			{
				AOM_ask_value_string(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 (item == NULL_TAG)
			{
				*propertyValue = "";
			}
			else
			{
				AOM_ask_value_string(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 (item == NULLTAG)
			{
				*propertyValue = "";
			}
			else
			{
				AOM_ask_value_string(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) {
	printf("message:%s", message);
	string jsonStr("{\\\"touser\\\":\\\"");
	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());
	printf("cmd:%s", toJar);
	//system(toJar);
	//_popen(toJar, "r");

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

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

	DOFREE(owning_id);
	DOFREE(process_name);
}
void itemSendToWeixin_srm(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;
}
LPCSTR stringToLPCWSTR1(std::string orig)
{
	return orig.c_str();
}

char * inputFileToFtp(char * filePath)
{
	//printf("下载到：%s Start===================\n", temp_file);
	string ftpFilePath = "";
	//ftp地址
	string ftpSvrIp = "172.18.254.18";
	//string ftpSvrIp = "ftp.meiling.com";
	//ftp端口
	int port = 21;
	//用户名
	string userName = "plm";
	//用户密码
	string password = "Plm_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);
				if (i == 0)
				{
					printf("上传文件失败！\n");
					return NULL;
				}
				else
				{
					ftpFilePath = "FTP://" + ftpSvrIp + resultFilePath + desfilename;
				}
			}
			//上传文件源为文件夹
			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;
	}

	char * strc = new char[strlen(ftpFilePath.c_str()) + 1];
	strcpy(strc, ftpFilePath.c_str());
	return strc;
}

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, "1003") == 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 (icoLineCode != NULL && strcmp(lineCode, icoLineCode) == 0 && icoERPCode != NULL && strcmp(icoERPCode, "") != 0)
		{
			result = icoERPCode;
			break;
		}

	}
	return result;
}