
#include <tc/preferences.h>
#include <epm/epm.h>
#include <tccore\aom_prop.h>
#include <time.h>
#include "string_utils.h"
#include "ocilib.h"
#include "chint_Handler.h"
#include "epm_handler_common.h"
#include "CRUL_server_call_httpserver.h"

void get_now_str(char *date_time)
{
	time_t the_time;
	struct tm *time_ptr;
	char *time_format = "%Y-%m-%d";

	the_time = time((time_t *)0);
	time_ptr = localtime(&the_time);
	strftime(date_time, 128, time_format, time_ptr);
}

int create_data_file(char *file_content, char *item_id, char **file_name) {
	time_t now;
	struct tm *p;
	FILE *filePtr = NULL;

	char *temp_dir = getenv("TEMP");
	char local_path[MAX_PATH] = "";

	time(&now);
	p = localtime(&now);
	if (temp_dir[strlen(temp_dir) - 1] == '\\')
	{
		sprintf_s(local_path, "%s%s-%d-%d-%d-%d-%d-%d.dat", temp_dir, item_id,
			1900 + p->tm_year, p->tm_mon + 1, p->tm_mday + 1, p->tm_hour, p->tm_min, p->tm_sec);
	}
	else
	{
		sprintf_s(local_path, "%s\\%s-%d-%d-%d-%d-%d-%d.dat", temp_dir, item_id,
			1900 + p->tm_year, p->tm_mon + 1, p->tm_mday + 1, p->tm_hour, p->tm_min, p->tm_sec);
	}

	if ((filePtr = fopen(local_path, "wt")) == NULL)
	{
		printf("Can not create the temp dat file!\n");
		return -1;
	}
	*file_name = (char *)MEM_alloc(sizeof(char) * 512);
	strcpy((*file_name), local_path);

	fwrite(file_content, sizeof(char), strlen(file_content), filePtr);
	fclose(filePtr);

	return ITK_ok;
}

int signoff(tag_t dataset, char *dat_file, char *ext) {
	tag_t spec_dataset_rev = NULLTAG, ref_object = NULLTAG;
	AE_reference_type_t reference_type;
	char ref_name[WSO_name_size_c + 1] = "excel";

	ITKCALL(AE_ask_dataset_latest_rev(dataset, &spec_dataset_rev));
	ITKCALL(AE_ask_dataset_named_ref(spec_dataset_rev, ref_name, &reference_type, &ref_object));
	if (reference_type == AE_PART_OF)
	{
		char pathname[SS_MAXPATHLEN] = "";
		ITKCALL(IMF_ask_file_pathname(ref_object, SS_WNT_MACHINE, pathname));
		char origin_file_name[IMF_filename_size_c + 1] = "";
		ITKCALL(IMF_ask_original_file_name(ref_object, origin_file_name));

		char new_ds_name[WSO_name_size_c + 1] = "";
		char *new_file_name = USER_new_file_name(new_ds_name, ref_name, ext, 0);
		char *temp_dir = getenv("temp");
		temp_dir = "D:\\TEMP";
		char temp_file[SS_MAXPATHLEN] = "";
		strcpy(temp_file, temp_dir);
		strcat(temp_file, "\\");
		strcat(temp_file, new_file_name);

		ITKCALL(IMF_export_file(ref_object, temp_file));

		char cmd[256] = "";
		strcpy(cmd, "SubstMacros-MSExcel.wsf");
		strcat(cmd, " \"");
		strcat(cmd, temp_file);
		strcat(cmd, "\" \"");
		strcat(cmd, dat_file);
		strcat(cmd, "\"");
		printf("cmd ==>%s\n", cmd);
		system(cmd);

		//strcpy(user_lib_env, local_path);


		POM_AM__set_application_bypass(true);
		tag_t new_file_tag = NULLTAG;
		IMF_file_t file_descriptor;
		ITKCALL(IMF_import_file(temp_file, new_file_name, SS_BINARY, &new_file_tag, &file_descriptor));
		ITKCALL(IMF_set_original_file_name(new_file_tag, origin_file_name));
		ITKCALL(IMF_close_file(file_descriptor));
		ITKCALL(AOM_save(new_file_tag));
		ITKCALL(AOM_unlock(new_file_tag));

		ITKCALL(AOM_lock(spec_dataset_rev));
		ITKCALL(AE_remove_dataset_named_ref_by_tag(spec_dataset_rev, ref_name, ref_object));
		ITKCALL(AE_add_dataset_named_ref(spec_dataset_rev, ref_name, AE_PART_OF, new_file_tag));
		ITKCALL(AOM_save(spec_dataset_rev));
		ITKCALL(AOM_unlock(spec_dataset_rev));
		POM_AM__set_application_bypass(false);
	}

	return ITK_ok;
}

int chint_ecn_signoff(EPM_action_message_t msg) {
	printf("=========================================================\n");
	printf("chint_ecn_signoff 开始执行\n");
	printf("=========================================================\n");

	int ifail = ITK_ok, occur_of_counts = 0, url_num = 0;
	char** url_vals = NULL, *task_name = NULL;
	tag_t root_task = NULLTAG, *targets = NULL;
	map<string, string> sign_map;
	sign_map.insert(pair<string, string>("编制", "zt2_Design"));
	sign_map.insert(pair<string, string>("校对", "zt2_Proofread"));
	sign_map.insert(pair<string, string>("审定", "zt2_Review"));
	sign_map.insert(pair<string, string>("标准化", "zt2_Normalization"));
	//sign_map.insert(pair<string, string>("会签", "zt2_Countersign"));
	sign_map.insert(pair<string, string>("批准", "zt2_Approve"));

	ITKCALL(EPM_ask_name2(msg.task, &task_name));
	printf("task_name ==>%s\n", task_name);
	//if (tc_strcmp(task_name, "会签") == 0) {
	//}
	ITKCALL(PREF_ask_char_values("database_tc", &url_num, &url_vals));
	string url = url_vals[0];
	url.append("/").append(url_vals[2]);
	printf("url ==>%s\n", url.c_str());
	if (ConnServer(url_vals[3], url_vals[4], (char*)url.c_str()) == -1) {
		printf("中间数据表访问失败\n");
		ifail = 919050;
		EMH_store_error(EMH_severity_error, ifail);
		return ifail;
	}
	//lidy20240531不是指派了dcproxy 那么会签就取这个节点对应人员的会签时间
	int cnt = 0;
	tag_t ptask = NULLTAG, flow = NULLTAG, *sub_tasks = NULLTAG, hq_task = NULLTAG;
	//ITKCALL(EPM_ask_parent_task(msg.task, &flow));
	ITKCALL(EPM_ask_root_task(msg.task, &flow));
	ITKCALL(EPM_ask_sub_tasks(flow, &cnt, &sub_tasks));
	for (int i = 0; i < cnt; i++) {
		char *os = NULL;
		ITKCALL(AOM_ask_value_string(sub_tasks[i], "object_name", &os));
		printf("sub_tasks:%s\n", os);
		if (tc_strcmp(os, "会签") == 0) {
			int cnt2 = 0;
			tag_t *sub_tasks2 = NULLTAG;
			ITKCALL(EPM_ask_sub_tasks(sub_tasks[i], &cnt2, &sub_tasks2));
			for (int j = 0; j < cnt2; j++) {
				char *type = NULL;
				ITKCALL(WSOM_ask_object_type2(sub_tasks2[j], &type));
				if (tc_strcmp(type, "EPMPerformSignoffTask") == 0) {
					hq_task = sub_tasks2[j];
				}
			}
			break;
		}
	}
	int num = 0;
	tag_t responsibleParty = NULLTAG, *signoff_attachments = NULLTAG;
	//ITKCALL(EPM_ask_responsible_party(msg.task, &responsibleParty));
	bool dcproxy = false;
	string huiqian = "";
	if (hq_task != NULLTAG) {
		ITKCALL(AOM_ask_value_tags(hq_task, "signoff_attachments", &num, &signoff_attachments));
		printf("signoff_attachments:%d\n", num);
		for (int i = 0; i < num; i++) {
			SIGNOFF_TYPE_t type;
			EPM_signoff_decision_t decision;
			tag_t member = NULLTAG, user = NULLTAG;
			date_t date;
			char *comment = NULL;
			ITKCALL(EPM_ask_signoff_member(signoff_attachments[i], &member, &type));
			ITKCALL(EPM_ask_signoff_decision(signoff_attachments[i], &decision, &comment, &date));
			char *mem = NULL, *dates = NULL;
			ITKCALL(AOM_ask_value_tag(member, "user", &user));
			ITKCALL(AOM_UIF_ask_value(user, "user_name", &mem));
			if (tc_strcmp(mem, "dcproxy") == 0) {
				dcproxy = true;
				break;
			}
			ITKCALL(DATE_date_to_string(date, "%Y-%m-%d", &dates));// %H-%M-%S
			printf("decision:%s==%s\n", mem, dates);
			if (huiqian.size() > 0)
				huiqian.append(" ");
			huiqian.append(mem).append(dates);
		}
	}

	ITKCALL(EPM_ask_root_task(msg.task, &root_task));
	ITKCALL(EPM_ask_attachments(root_task, EPM_target_attachment, &occur_of_counts, &targets));
	for (int t = 0; t < occur_of_counts; t++) {
		char* type = NULL;
		ITKCALL(WSOM_ask_object_type2(targets[t], &type));
		if (tc_strcmp(type, "ZT2_Change") != 0) {
			continue;
		}
		/*if (tc_strcmp(task_name, "会签") == 0) {
			ITKCALL(AOM_set_value_string(targets[t], "zt2_Countersign", name.c_str()));
			char now_date_str[128 + 1] = { "\0" };
			get_now_str(now_date_str);
			//date_t now;
			//ITKCALL(ITK_string_to_date(current_date_time_str, &now));
			printf("now_date_str ===>%s\n", now_date_str);
			ITKCALL(AOM_set_value_string(targets[t], "zt2_CountersignTime", now_date_str));
		}*/
		char* id = NULL;
		ITKCALL(AOM_ask_value_string(targets[t], "item_id", &id));
		printf("id ===>%s\n", id);
		string name = "";
		if (dcproxy) {
			vector<string> name_vec;
			string sql = "select \"principal\",\"coudata\" FROM CHINT_ECN_NOTIFICATION where \"result\"='是' and \"ecncode\"='";
			sql.append(id).append("'");
			int outputColumn1 = 0, outputValueCount1 = 0;
			char*** outputValue1 = NULL;
			printf("sql ===>%s\n", sql.c_str());
			QuerySQLNoInputParam((char*)sql.c_str(), &outputColumn1, &outputValueCount1, &outputValue1);
			for (int i = 0; i < outputValueCount1; i++) {
				vector<string> names;
				if (tc_strstr(outputValue1[i][0], ":") == NULL) {
					Split(outputValue1[i][0], ";", names);
				}
				else {
					Split(outputValue1[i][0], ":", names);
				}
				string name_date = names[0].append(outputValue1[i][1]);
				if (find(name_vec.begin(), name_vec.end(), name_date) == name_vec.end())
					name_vec.push_back(name_date);
			}
			for (int i = 0; i < name_vec.size(); i++) {
				if (name.size() > 0)
					name.append(" ");
				name.append(name_vec[i]);
			}
			printf("name ===>%s\n", name.c_str());
		}
		else {
			name.append(huiqian);
		}

		tag_t *datasets = NULL;
		int cnt = 0;
		ITKCALL(AOM_ask_value_tags(targets[t], "IMAN_reference", &cnt, &datasets));
		if (cnt < 1) {
			printf("未找到excel数据集\n");
			continue;
		}
		string info = "";
		map<string, string>::iterator it;
		for (it = sign_map.begin(); it != sign_map.end(); it++) {
			string prop = it->second.c_str();
			prop.append("Time");
			char *name_val = NULL, *date_val = NULL;
			ITKCALL(AOM_ask_value_string(targets[t], it->second.c_str(), &name_val));
			ITKCALL(AOM_ask_value_string(targets[t], prop.c_str(), &date_val));
			info.append(it->first);
			info.append("=");
			info.append(name_val);
			info.append(" ");
			info.append(date_val);
			info.append("|");
		}
		info.append("会签");
		info.append("=");
		info.append(name);
		info.append("|");
		char *data_file = NULL;
		create_data_file((char*)info.c_str(), id, &data_file);
		printf("data_file ==>%s\n", data_file);
		for (int i = 0; i < cnt; i++) {
			char* ref_type = NULL;
			ITKCALL(WSOM_ask_object_type2(datasets[i], &ref_type));
			if (tc_strcmp(ref_type, "MSExcelX") == 0) {
				signoff(datasets[i], data_file, "xlsx");
				break;
			}
		}
	}
	//if (tc_strcmp(task_name, "会签") == 0) {
	//}
	DisConnServer();
	printf("=========================================================\n");
	printf("chint_ecn_signoff 执行结束\n");
	printf("=========================================================\n");
	return ifail;
}

int chint_ecn_assign(EPM_action_message_t msg) {
	printf("=========================================================\n");
	printf("chint_ecn_assign 开始执行\n");
	printf("=========================================================\n");

	int ifail = ITK_ok, occur_of_counts = 0, url_num = 0;
	char** url_vals = NULL, *task_name = NULL;
	tag_t root_task = NULLTAG, *targets = NULL;

	tag_t query_tag = NULLTAG;
	ITKCALL(QRY_find2("管理 - 员工信息", &query_tag));
	if (query_tag == NULL)
	{
		printf("未找到查询：管理 - 员工信息\n");
		ifail = 919051;
		EMH_store_error(EMH_severity_error, ifail);
		return ifail;
	}
	ITKCALL(PREF_ask_char_values("database_tc", &url_num, &url_vals));
	string url = url_vals[0];
	url.append("/").append(url_vals[2]);
	printf("url ==>%s\n", url.c_str());
	if (ConnServer(url_vals[3], url_vals[4], (char*)url.c_str()) == -1) {
		printf("中间数据表访问失败\n");
		ifail = 919050;
		ITKCALL(EMH_store_error_s1(EMH_severity_error, ifail, "database_tc"));
		return ifail;
	}

	ITKCALL(EPM_ask_root_task(msg.task, &root_task));
	ITKCALL(EPM_ask_attachments(root_task, EPM_target_attachment, &occur_of_counts, &targets));
	for (int t = 0; t < occur_of_counts; t++) {
		char* type = NULL;
		ITKCALL(WSOM_ask_object_type2(targets[t], &type));
		if (tc_strcmp(type, "ZT2_Change") != 0) {
			continue;
		}
		char* id = NULL;
		ITKCALL(AOM_ask_value_string(targets[t], "item_id", &id));
		printf("id ===>%s\n", id);
		string sql = "select \"principal\",\"section\" FROM CHINT_ECN_NOTIFICATION where \"result\"='是' and \"ecncode\"='";
		sql.append(id).append("'");
		int outputColumn1 = 0, outputValueCount1 = 0;
		char*** outputValue1 = NULL;
		printf("sql ===>%s\n", sql.c_str());
		QuerySQLNoInputParam((char*)sql.c_str(), &outputColumn1, &outputValueCount1, &outputValue1);
		printf("outputValueCount1 ===>%d\n", outputValueCount1);
		//如果section列获取的数据中包含非技术部、工艺部的人员，当前节点无需指派人员
		boolean pro = false;
		for (int i = 0; i < outputValueCount1; i++) {
			if (tc_strcmp(outputValue1[i][1], "技术部") != 0 && tc_strcmp(outputValue1[i][1], "工艺部") != 0) {
				pro = true;
				break;
			}
		}
		if (pro) {
			continue;
		}
		vector<string> name_vec;
		for (int i = 0; i < outputValueCount1; i++) {
			printf("i ===>%d\n", i);
			if (name_vec.size() > 0 && find(name_vec.begin(), name_vec.end(), outputValue1[i][0]) != name_vec.end())
				continue;
			name_vec.push_back(outputValue1[i][0]);
			vector<string> names, names2;
			Split(outputValue1[i][0], ";", names);
			printf("names ===>%zd\n", names.size());
			if (tc_strcmp(names[0].c_str(), "null") == 0) {
				continue;
			}
			Split(names[0], ":", names2);
			printf("names2 ===>%zd\n", names2.size());
			if (find(name_vec.begin(), name_vec.end(), names2[0]) != name_vec.end())
				continue;
			name_vec.push_back(names2[0]);
			string id = "";
			if (names2.size() > 1) {
				id = names2[1];
			}
			else {
				//不管是;还是:都用冒号的逻辑
				id = names[1];
				/*使用分号后的内容调用OA接口，获取用户id
				char *url = NULL;
				ITKCALL(PREF_ask_char_value("CHINT_OA_GetUserItems", 0, &url));
				if (url == NULL) {
					printf("CHINT_OA_GetUserItems首选项配置不正确！\n");
					DisConnServer();
					ifail = 919052;
					EMH_store_error_s1(EMH_severity_error, ifail, "CHINT_OA_GetUserItems");
					return ifail;
				}
				printf("url ===>%s\n", url);
				string userXML = getUserIdOAUUID(names[1], url);
				//printf("userXML ===>%s\n", userXML.c_str());
				id = readXmlEmailId(userXML);
				if (tc_strcmp(id.c_str(), "Fault") == 0) {
					printf("OA获取用户ID失败！\n");
					id = "";
					//DisConnServer();
					//ifail = 919052;
					//EMH_store_error_s1(EMH_severity_error, ifail, userXML.c_str());
					//return ifail;
				}
				else {
					vector<string> emailId;
					Split(id, "@", emailId);
					id = emailId[0];
				}*/
			}
			printf("id ===>%s\n", id.c_str());
			if (id.size() == 0) {
				printf("未找到用户id：%s\n", outputValue1[i][0]);
				continue;
			}
			char **qkey = NULL, **qvalue = NULL, *userid = (char *)id.c_str();
			int num_found = 0;
			tag_t *qresult = NULL;

			const char *cpxh = "用户 ID";//GbkToUtf8("产品型号").c_str();
			qkey = (char **)MEM_alloc(1 * sizeof(char*));
			qvalue = (char **)MEM_alloc(1 * sizeof(char*));
			qkey[0] = (char *)MEM_alloc((tc_strlen(cpxh) + 1) * sizeof(char));
			qvalue[0] = (char *)MEM_alloc((tc_strlen(userid) + 1) * sizeof(char));
			tc_strcpy(qkey[0], cpxh);
			tc_strcpy(qvalue[0], userid);
			ITKCALL(QRY_execute(query_tag, 1, qkey, qvalue, &num_found, &qresult));
			if (num_found == 0) {
				printf("未找到用户：%s\n", userid);
				DisConnServer();
				ifail = 919052;
				EMH_store_error_s1(EMH_severity_error, ifail, userid);
				return ifail;
			}
			//移除当前节点指派的dcproxy账户
			int signoff_count = 0;
			tag_t *signoffs = NULL, parent = NULLTAG;
			ITKCALL(EPM_ask_parent_task(msg.task, &parent));
			ITKCALL(EPM_ask_attachments(msg.task, EPM_signoff_attachment, &signoff_count, &signoffs));
			for (int i = 0; i < signoff_count; i++) {
				tag_t member = NULLTAG;
				SIGNOFF_TYPE_t stype;
				char *name = NULL, *os = NULL, *type = NULL;
				ITKCALL(EPM_ask_signoff_member(signoffs[i], &member, &stype));
				ITKCALL(AOM_ask_value_string(member, "object_string", &os));
				printf("member = %s\n", os);
				if (tc_strstr(os, "dcproxy") != NULL) {
					ITKCALL(EPM_remove_signoffs(parent, 1, &member));
				}
			}
			//将人员指派至当前节点
			int signoff_cnt = 0;
			tag_t *signoff_tags = NULLTAG;
			ITKCALL(EPM_create_adhoc_signoff(msg.task, qresult[0], &signoff_cnt, &signoff_tags));
		}
	}
	DisConnServer();

	POM_AM__set_application_bypass(true);
	ITKCALL(EPM_promote_task(msg.task, ""));
	POM_AM__set_application_bypass(false);
	printf("=========================================================\n");
	printf("chint_ecn_assign 执行结束\n");
	printf("=========================================================\n");
	return ifail;
}