
#include "epm/epm.h"
#include <tc/preferences.h>
#include <tccore/aom_prop.h>
#include <tccore/item.h>
#include <ics/ics.h>
#include <ics/ics2.h>
#include "ocilib.h"
#include "string_utils.h"
#include "epm_handler_common.h"
#include "tc_util.h"

/*获取分类属性
classId 分类ID
value 真实值
id 属性ID
disValue 显示值
*/
void getClassValue(char* classId, char* value, int id, char** disValue) {
	printf("===================================\n");
	printf("获取分类属性 开始\n");
	printf("===================================\n");
	int count = 0;
	int* ids;
	int* arraySize;
	int* formats;
	int* options;
	char** names;
	char** shortNames;
	char** annotations;
	char** unit;
	char** minValues;
	char** maxValues;
	char** defaultValues;
	char** descriptions;
	ITKCALL(ICS_class_describe_attributes(classId, &count, &ids, &names, &shortNames, &annotations, &arraySize,
		&formats, &unit, &minValues, &maxValues, &defaultValues, &descriptions, &options));

	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;
		ITKCALL(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");
}

string getCshVal2(string name, string code) {

	string strResult = "", schVal = "";
	//cmd指令
	char cmd[256] = "";
	strcpy(cmd, "java -jar \"");
	//strcat(cmd, jar_file);
	strcat(cmd, getenv("TC_ROOT"));
	strcat(cmd, "\\bin\\findCshSql.jar");
	strcat(cmd, "\" \"");
	strcat(cmd, name.c_str());
	strcat(cmd, "\" \"");
	strcat(cmd, code.c_str());
	strcat(cmd, "\"");
	printf("cmd：%s\n", cmd);
	char buf[8000] = { 0 };
	FILE* pf = NULL;
	if ((pf = _popen(cmd, "r")) == NULL) {
		printf("接口返回1");
	}

	while (fgets(buf, sizeof buf, pf)) {
		strResult += buf;
	}
	printf("接口返回：%s", strResult.c_str());
	_pclose(pf);

	return strResult;
}

EPM_decision_t chint_csh_check(EPM_rule_message_t msg) {
	printf("*********************  chint_csh_check is comming ！ *********************\n");

	EPM_decision_t customError = EPM_go;

	int url_num = 0;
	char** url_vals = NULL;
	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)
	{
		ITKCALL(EMH_store_error_s1(EMH_severity_user_error, EMH_USER_error_base, "错误:TC数据库连接失败"));
		customError = EPM_nogo;
		return customError;
	}

	tag_t pRoot = NULLTAG;
	ITKCALL(EPM_ask_root_task(msg.task, &pRoot));
	int target_count = 0;
	tag_t *targets = NULL;
	ITKCALL(EPM_ask_attachments(pRoot, EPM_target_attachment, &target_count, &targets));
	//map<string, string> map;
	string msgs = "";
	for (int t = 0; t < target_count; t++) {
		char* type = NULL;
		ITKCALL(WSOM_ask_object_type2(targets[t], &type));
		if (tc_strcmp(type, "ZT2_Design3DRevision") != 0) {
			continue;
		}
		char* item_id = NULL;
		ITKCALL(AOM_ask_value_string(targets[t], "item_id", &item_id));
		string id = item_id;
		//总装图号为前四位+300000P 拼接-后的尾缀
		string topID = id.substr(0, 4);
		topID.append("300000P").append(id.substr(11));
		tag_t top_classificationObject = NULLTAG, topItem = NULLTAG;
		ITKCALL(ITEM_find_item(topID.c_str(), &topItem));
		ITKCALL(ICS_ask_classification_object(topItem, &top_classificationObject));
		if (top_classificationObject == NULLTAG) {
			msgs.append(id).append("总装图未发送分类;\n");
			continue;
		}
		//找到总装图的分类属性：是否参数化设计，如果值为是，则进行下述的判断逻辑，如果为否，则跳过，无法检查
		int n_attrs = 0;
		char** attr_names = NULL, ** attr_vals = NULL;
		ITKCALL(ICS_ask_attributes_of_classification_obj(top_classificationObject, &n_attrs, &attr_names, &attr_vals));
		boolean weihu = true;
		for (int ii = 0; ii < n_attrs; ii++) {
			if (strcmp(attr_names[ii], "是否参数化设计") == 0) {
				weihu = false;
				printf("是否参数化设计==>%s\n", attr_vals[ii]);
				if (!attr_vals[ii] || tc_strlen(attr_vals[ii]) == 0) {
					//没维护的话，提示让维护总装图分类属性：是否参数化设计
					msgs.append("请维护总装图分类属性：是否参数化设计;\n");
				}
				else if (strcmp(attr_vals[ii], "是") == 0) {
					char selectRxfs[200];
					sprintf(selectRxfs, "select param_code from CHINT_CSH_CHECK_RULE where drawingno='%s'", id.substr(0, 11).c_str());
					int outputColumn3 = 0, outputValueCount3 = 0;
					char*** outputValue3 = NULL;
					printf("search CHINT_CSH_CHECK_RULE ===> %s\n", selectRxfs);
					QuerySQLNoInputParam(selectRxfs, &outputColumn3, &outputValueCount3, &outputValue3);
					if (outputValueCount3 == 0) {
						//errs.append(id).append("，");
						msgs.append(id).append("图纸未查询到参数代号;\n");
					}
					else {
						string errs = "";
						for (int i = 0; i < outputValueCount3; i++) {
							string val = getCshVal2(id.substr(12).c_str(), outputValue3[i][0]);
							if (val.size() == 0) {
								errs.append(outputValue3[i][0]).append(";");
							}
						}
						if (errs.size() > 0) {
							msgs.append(id).append("图纸所需的参数化数据：").append(errs).append("缺少数据，请先去参数化软件提交后，再执行流程提交;\n");
						}
					}
				}
				break;
			}
		}
		if (weihu) {
			//没维护的话，提示让维护总装图分类属性：是否参数化设计
			msgs.append("请维护总装图分类属性：是否参数化设计;\n");
		}
	}
	printf("msgs：%s\n", msgs.c_str());
	DisConnServer();
	if (msgs.size() > 0) {
		ITKCALL(EMH_store_error_s1(EMH_severity_user_error, 919502, msgs.c_str()));
		customError = EPM_nogo;
	}
	return customError;
}