#include <epm/epm.h>
#include <string>
#include <map>
#include "epm_handler_common.h"
#include <tccore/aom.h>
#include <tccore/aom_prop.h>
#include "common_itk_util.h"
#include "tc_util.h"
#include <tc/preferences.h>
#include <fclasses\tc_date.h>
#include "CRUL_server_call_httpserver.h"
#include "ocilib.h"
#include "cJSON.h"
using namespace std;



string getTime()
{
	stringstream ss;
	time_t t = time(0);
	tm* local = localtime(&t);
	ss << local->tm_year + 1900 << '-';
	if (local->tm_mon < 9)
		ss << "0";
	ss << local->tm_mon + 1 << '-';
	if (local->tm_mday < 10)
		ss << "0";
	ss << local->tm_mday << ' ';
	if (local->tm_hour < 10)
		ss << "0";
	ss << local->tm_hour << ':';
	if (local->tm_min < 10)
		ss << "0";
	ss << local->tm_min << ':';
	if (local->tm_sec<10)
		ss << "0";
	ss << local->tm_sec;
	return ss.str();
}

//变更对象发送到OA
int CHINT_CHANGEBOM_TO_SRM(EPM_action_message_t msg) {

	int ifail = ITK_ok;
	ECHO("=========================================================\n");
	ECHO("CHINT_CHANGEBOM_TO_SRM 开始执行\n");
	ECHO("=========================================================\n");
	tag_t root_task = NULLTAG, *sub_tasks = NULL, current_task = NULLTAG, type_tag = NULLTAG;
	int sub_task_count = 0, occur_of_counts = 0, url_num = 0;
	tag_t* taskAttches = NULLTAG;
	tag_t cur_task = NULLTAG;
	char* jobName = NULL;
	current_task = msg.task;
	ITKCALL(AOM_ask_value_string(current_task, "job_name", &jobName));
	ITKCALL(EPM_ask_root_task(msg.task, &root_task));
	ITKCALL(EPM_ask_sub_tasks(root_task, &sub_task_count, &sub_tasks));
	ITKCALL(EPM_ask_attachments(root_task, EPM_target_attachment, &occur_of_counts, &taskAttches));

	char** url_vals = NULL;
	ITKCALL(PREF_ask_char_values("database_tc", &url_num, &url_vals));
	string sqlurl = url_vals[0];
	sqlurl.append("/").append(url_vals[2]);
	printf("sqlurl ==> %s \n", sqlurl.c_str());
	if (ConnServer(url_vals[3], url_vals[4], (char*)sqlurl.c_str()) == -1) {
		ITKCALL(EMH_store_error_s1(EMH_severity_user_error, EMH_USER_error_base, "错误:TC数据库连接失败"));
		return EMH_USER_error_base;
	}
	//获取url地址
	int url_cnt = 0;
	char** url = NULL, *urlId = NULL;//
	ITKCALL(PREF_ask_char_values("CHINT_ChangeBOMURL", &url_cnt, &url));
	vector<string> urls;
	for (int i = 0; i < url_cnt; i++) {
		vector<string> vec1, vec2;
		Split(url[i], "=", vec1);
		Split(vec1[0], ":", vec2);
		if (tc_strcmp(vec2[1].c_str(), "1") == 0) {
			urls.push_back(vec1[1]);
		}
	}
	if (urls.size() == 0) {
		printf("CHINT_ChangeBOMURL首选项中未找到可用地址\n");
		return ifail;
	}
	ITKCALL(PREF_ask_char_value("CHINT_OAUserID_RUL", 0, &urlId));
	char* log_file = NULL;
	CreateLogFile("CHINT_CHANGEBOM_TO_SRM", &log_file); //
	//获取当前流程目标
	//获取登陆组
	tag_t group;
	char *groupName, *taskUid;
	ITKCALL(POM_ask_group(&groupName, &group));
	ITKCALL(AOM_ask_value_string(group, PROP_GROUP_NAME, &groupName));
	ITK__convert_tag_to_uid(msg.task, &taskUid); //流程uid
	for (int count = 0; count < occur_of_counts; count++) {
		char *type;
		tag_t taskTag = taskAttches[count];
		ITKCALL(AOM_ask_value_string(taskTag, "object_type", &type));
		if (strcmp(type, "ZT2_Change") == 0) {
			int ref_cnt = 0;
			tag_t *refs = NULLTAG;
			ITKCALL(AOM_ask_value_tags(taskTag, "IMAN_reference", &ref_cnt, &refs));
			string ecnuid = "";
			tag_t bomec = NULLTAG;
			for (int i = 0; i < ref_cnt; i++) {
				char *type = NULL;
				ITKCALL(WSOM_ask_object_type2(refs[i], &type));
				if (tc_strcmp(type, "ZT2_BOMEC") == 0) {
					bomec = refs[i];
					break;
				}
			}
			if (bomec == NULLTAG) {
				continue;
			}
			//如果当前流程目标下的变更单，对应的影响分析如果仅包含技术工艺，无其他部门，则不需要触发此handler 
			char *item_id = NULL;
			ITKCALL(AOM_ask_value_string(taskTag, "item_id", &item_id));
			//获取属性 查询数据库填写JSON
			int property1Cnt = 0, property2Cnt = 0, property3Cnt = 0, property4Cnt = 0, property5Cnt = 0, 
				property6Cnt = 0, property7Cnt = 0, property8Cnt = 0, property9Cnt = 0, property10Cnt = 0, 
				property11Cnt = 0, property12Cnt = 0, property13Cnt = 0, property14Cnt = 0, index = 0;
			char* zt2_ContractName = NULL, *zt2_WBSNo = NULL,
				**zt2_property1 = NULL, **zt2_property2 = NULL, **zt2_property3 = NULL, **zt2_property4 = NULL, **zt2_property5 = NULL, 
				**zt2_property6 = NULL, **zt2_property7 = NULL, **zt2_property8 = NULL, **zt2_property9 = NULL, **zt2_property10 = NULL, 
				**zt2_property11 = NULL, **zt2_property12 = NULL, **zt2_property13 = NULL, **zt2_property14 = NULL;
			date_t changeDate;
			ITKCALL(AOM_ask_value_string(taskTag, "zt2_WBSNo", &zt2_WBSNo));//wbs号
			ITKCALL(AOM_ask_value_string(taskTag, "zt2_ContractName", &zt2_ContractName)); // 合同名称
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property1", &property1Cnt, &zt2_property1));//
			ITKCALL(AOM_ask_value_strings(bomec, "zt2_property2", &property2Cnt, &zt2_property2));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property3", &property3Cnt, &zt2_property3));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property4", &property4Cnt, &zt2_property4));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property5", &property5Cnt, &zt2_property5));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property6", &property6Cnt, &zt2_property6));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property7", &property7Cnt, &zt2_property7));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property8", &property8Cnt, &zt2_property8));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property9", &property9Cnt, &zt2_property9));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property10", &property10Cnt, &zt2_property10));//
			ITKCALL(AOM_ask_value_strings(bomec, "zt2_property11", &property11Cnt, &zt2_property11));//
			ITKCALL(AOM_ask_value_strings(bomec, "zt2_property12", &property12Cnt, &zt2_property12));//
			ITKCALL(AOM_ask_value_strings(bomec, "zt2_property13", &property13Cnt, &zt2_property13));//
			ITKCALL(AOM_UIF_ask_values(bomec, "zt2_property13", &property14Cnt, &zt2_property14));//
			if (property1Cnt > index) index = property1Cnt;
			if (property2Cnt > index) index = property2Cnt;
			if (property3Cnt > index) index = property3Cnt;
			if (property4Cnt > index) index = property4Cnt;
			if (property5Cnt > index) index = property5Cnt;
			if (property6Cnt > index) index = property6Cnt;
			if (property7Cnt > index) index = property7Cnt;
			if (property8Cnt > index) index = property8Cnt;
			if (property9Cnt > index) index = property9Cnt;
			if (property10Cnt > index) index = property10Cnt;
			if (property11Cnt > index) index = property11Cnt;
			if (property12Cnt > index) index = property12Cnt;
			if (property13Cnt > index) index = property13Cnt;
			if (property14Cnt > index) index = property14Cnt;

			//ITKCALL(POM_get_user_id(&userId));
			tag_t user = NULLTAG;
			char* userId = NULL;
			ITKCALL(AOM_ask_value_tag(taskTag, "owning_user", &user));
			ITKCALL(AOM_ask_value_string(user, "user_id", &userId));
			string date = getTime();
			//json添加字段
			/*S_ProductFeature	产品特性	字符串	A; B; C
				S_GCFeeature	过程特性	字符串	A; B; C*/
			//cJSON_AddStringToObject(paramValue, S_GCDM, groupName);//工厂
			cJSON* datas = cJSON_CreateArray();
			for (int i = 0; i < index; i++) {
				cJSON* data = cJSON_CreateObject();
				if (i < property1Cnt) {
					cJSON_AddStringToObject(data, "ZCITEM", zt2_property1[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZCITEM", "");
				}
				cJSON_AddStringToObject(data, "ZCORDER", item_id);
				cJSON_AddStringToObject(data, "POSID", zt2_WBSNo);
				cJSON_AddStringToObject(data, "WERKS", groupName);
				cJSON_AddStringToObject(data, "POST1", zt2_ContractName);
				if (i < property2Cnt) {
					cJSON_AddStringToObject(data, "ZCFLAG", zt2_property2[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZCFLAG", "");
				}
				if (i < property3Cnt) {
					cJSON_AddStringToObject(data, "MATNR", zt2_property3[i]);
				}
				else {
					cJSON_AddStringToObject(data, "MATNR", "");
				}
				if (i < property4Cnt) {
					cJSON_AddStringToObject(data, "MAKTX", zt2_property4[i]);
				}
				else {
					cJSON_AddStringToObject(data, "MAKTX", "");
				}
				if (i < property5Cnt) {
					cJSON_AddStringToObject(data, "ZOLD_IDNRK", zt2_property5[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZOLD_IDNRK", "");
				}
				if (i < property6Cnt) {
					cJSON_AddStringToObject(data, "ZOLD_MAKTX", zt2_property6[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZOLD_MAKTX", "");
				}
				if (i < property7Cnt) {
					cJSON_AddStringToObject(data, "ZOLD_UNIT", zt2_property7[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZOLD_UNIT", "");
				}
				if (i < property8Cnt) {
					cJSON_AddStringToObject(data, "ZNEW_IDNRK", zt2_property8[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZNEW_IDNRK", "");
				}
				if (i < property9Cnt) {
					cJSON_AddStringToObject(data, "ZNEW_MAKTX", zt2_property9[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZNEW_MAKTX", "");
				}
				if (i < property10Cnt) {
					cJSON_AddStringToObject(data, "ZNEW_UNIT", zt2_property10[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZNEW_UNIT", "");
				}
				if (i < property11Cnt) {
					cJSON_AddStringToObject(data, "ZZYYDL", zt2_property11[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZZYYDL", "");
				}
				if (i < property12Cnt) {
					cJSON_AddStringToObject(data, "ZZYYXL", zt2_property12[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZZYYXL", "");
				}
				if (i < property13Cnt) {
					cJSON_AddStringToObject(data, "ZPRO_TYPE", zt2_property13[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZPRO_TYPE", "");
				}
				if (i < property14Cnt) {
					cJSON_AddStringToObject(data, "ZPRO_DES", zt2_property14[i]);
				}
				else {
					cJSON_AddStringToObject(data, "ZPRO_DES", "");
				}
				cJSON_AddStringToObject(data, "ZNAME", userId);
				cJSON_AddStringToObject(data, "ZDATE", date.c_str());

				cJSON_AddItemToArray(datas, data);
			}

			char *json_to_char = cJSON_Print(datas);
			//lidy20240710
			string xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" ";
			xml.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><SOAP-ENV:Body><m:ChangeDifferenceSync xmlns:m=\"http://tempuri.org/\"><m:data>");
			xml.append(json_to_char);
			xml.append("</m:data></m:ChangeDifferenceSync></SOAP-ENV:Body></SOAP-ENV:Envelope>");
			//WriteLog("\nworkflowCode=EH_TE_ChangeNotice\nuserCode=%s\nfinishStart=true\n", userCode.c_str());
			string msg = "组织之后的XMLJSON：\n";
			msg.append(xml);
			//WriteLog("组织之后的XMLJSON：\n%s\n", xml.c_str());
			WriteLog2(msg.c_str());
			string returnMsg = "";// ecnSendOA(userCode.c_str(), json_to_char, url);
			for (int i = 0; i < urls.size(); i++) {
				returnMsg.append(ecnSendSRM(xml, urls[i]));
			}
			WriteLog("解析结果：\n%s", returnMsg.c_str());
			//if (returnMsg.size() != 0) {
			if (tc_strcmp(returnMsg.c_str(), "S") != 0) {
				ITKCALL(EMH_store_error_s1(EMH_severity_user_error, EMH_USER_error_base, returnMsg.c_str()));
			}
		}
	
	}
	CloseLog();
	//string str = uploadMinio("uploadMinio.jar", log_file);
	char date_string[MAX_PATH_LENGTHE], logFileName[MAX_PATH_LENGTHE];;
	time_t now;
	struct tm *p;
	time(&now);
	//current_time(&status_now);
	p = localtime(&now);
	memset(date_string, 0, sizeof(date_string));
	sprintf(date_string, "%4d%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);
	sprintf(logFileName, "%s\\%s_%s.log", LOG_PATH, taskUid, date_string);
	//file_xcopy_stod(log_file, logFileName);
	//printf("str %s \n", str.c_str());
	return ifail;
}