#include "util.h"

int bs_sap_material(EPM_action_message_t msg)
{
	printf("start sap material\n");
	int ifail = ITK_ok, att_count;
	tag_t rootTask, *attachments, relation_type;
	char *obj_type;
	int pref_cnt;
	char **pref_vals;
	EPM_ask_root_task(msg.task, &rootTask);
	map<int, string> class_map;

	EPM_ask_attachments(rootTask, EPM_target_attachment, &att_count, &attachments);
	TC_argument_list_t * arguments = msg.arguments;
	int arg_cnt = TC_number_of_arguments(arguments), status = 0;
	POM_AM__set_application_bypass(true);
	map<string, string> paras,rel_map;
	map<string, string> prop_map;

	vector<string> rel_vec;
	for (auto i = 0; i < arg_cnt; i++)
	{
		char *temp_key, *temp_val;
		ITK_ask_argument_named_value(TC_next_argument(arguments), &temp_key, &temp_val);
		paras[temp_key] = temp_val;
	}
	string d0 = "D00", d1 = "D0";
	for(int i=0;i<67;i++)
	{
		if(i>8)
		{
			
			class_map[1000+i] =  d1 + to_string(i + 1);
		}else
		{
			class_map[1000 + i] = d0 + to_string(i + 1);
		}
	}

	PREF_ask_char_values("connor_sap", &pref_cnt, &pref_vals);

	split(pref_vals[4], ",", &rel_vec);
	for(int i=0;i<rel_vec.size();i++)
	{
		vector<string> temp_vec;
		split(rel_vec[i], "=", &temp_vec);
		if(temp_vec.size()==2)
		{
			rel_map[temp_vec[0]] = temp_vec[1];
		}
	}
	vector<string> rel_vec2;
	split(pref_vals[5], ",", &rel_vec2);

	for (int i = 0; i<rel_vec2.size(); i++)
	{
		vector<string> temp_vec;
		split(rel_vec2[i], "=", &temp_vec);
		if (temp_vec.size() == 2)
		{
			prop_map[temp_vec[0]] = temp_vec[1];
		}
	}

	GRM_find_relation_type("IMAN_master_form", &relation_type);
	printf("create class\n");
	Testclass ^test = gcnew Testclass();
	printf("create success\n");
	String^ url = convert_to_cstring(pref_vals[0]);
	String^ user = convert_to_cstring(pref_vals[2]);
	String^ password = convert_to_cstring(pref_vals[3]);
	// prop_map["MTART"] = "jd2_wllx";
	// prop_map["MATNR"] = "item_id";
	// prop_map["MAKTX"] = "jd2_wlms";
	// prop_map["MEINS"] = "jd2_dldw";
	// prop_map["MATKL"] = "jd2_wlz";
	// prop_map["PRDHA"] = "jd2_cpcc";
	// prop_map["EXTWG"] = "jd2_wbwlz";
	// prop_map["MSTAE"] = "release_status_list";
	// prop_map["VOLUM"] = "jd2_tj";
	// prop_map["VOLEH"] = "jd2_tjdw";
	// prop_map["BISMT"] = "jd2_jwlh";
	// prop_map["ZEINR"] = "jd2_th";
	// prop_map["BRGEW"] = "jd2_mz";
	// prop_map["NTGEW"] = "jd2_jz";
	// prop_map["GEWEI"] = "jd2_zldw";
	// prop_map["CLASS"] = "jd2_wllx";
	printf("start111\n");
	for (int i = 0; i < att_count; i++)
	{
		if (isTypeOf(attachments[i], "Form"))
		{
			int rel_cnt,*levels;
			tag_t *rels,rev=NULLTAG,form;
			char **relations;
			form = attachments[i];
			WSOM_where_referenced2(form, 1, &rel_cnt, &levels, &rels, &relations);
			for(int j=0;j<rel_cnt;j++)
			{
				if(tc_strcmp(relations[j],"IMAN_master_form")==0)
				{
					rev = rels[j];
				}
			}
			if(rev==NULLTAG)
			{
				printf("revision get error\n");
				continue;
			}
			// GRM_list_secondary_objects_only(attachments[i], relation_type, &rel_cnt, &rels);
			System::Collections::Generic::Dictionary<String^, String^> ^dic = gcnew System::Collections::Generic::Dictionary<String^, String^>();
			for (auto j = prop_map.begin(); j != prop_map.end(); j++)
			{
				char *val="";
				string temp_val;
				if (j->second == "item_id")
				{
					AOM_ask_value_string(rev, j->second.c_str(), &val);
					temp_val = val;
				}
				else if (j->second == "release_status_list") {
					// int status_cnt;
					// tag_t *rel_status;
					// AOM_ask_value_tags(form, j->second.c_str(), &status_cnt, &rel_status);
					// if (status_cnt)
					// 	AOM_UIF_ask_value(rel_status[status_cnt - 1], "object_string", &val);
					// temp_val = rel_map[val];
					temp_val = paras["status"];
				}else if(j->second=="jd2_dldw")
				{
					AOM_UIF_ask_value(form, j->second.c_str(), &val);
					temp_val = val;
				}
				else
				{
					tag_t lov;
					AOM_ask_lov(form, j->second.c_str(), &lov);
					if (lov)
						AOM_ask_value_string(form, j->second.c_str(), &val);
					else
						AOM_UIF_ask_value(form, j->second.c_str(), &val);
					temp_val = val;
				}
				dic[convert_to_cstring(j->first.c_str())] = convert_to_cstring(temp_val.c_str());
			}
			tag_t class_obj;
			ICS_ask_classification_object(rev, &class_obj);
			if (class_obj)
			{
				char ***vals;
				int cnt, *ids,*val_count;
				ICS_ico_ask_attributes(class_obj, &cnt, &ids, &val_count, &vals);
				for(int j=0;j<cnt;j++)
				{
					printf("id:%d\n", ids[j]);
					if(class_map.find(ids[j])!=class_map.end())
					{
						if(val_count[j])
							dic[convert_to_cstring(class_map[ids[j]].c_str())] = convert_to_cstring(vals[j][0]);
					}
				}
			}
			dic["MBRSH"] = "M";
			dic["SPART"] = "00";
			dic["KLART"] = "001";
			string result = ConvertToString(test->send_material(url, user, password, dic));
			printf("result:%s\n", result.c_str());
			if(result.length()&&result[0]=='E')
			{
				char *val;
				AOM_ask_value_string(rev, "item_id", &val);
				stringstream err;
				err << val << " ·¢ËÍ´íÎó:" << result;
				POM_AM__set_application_bypass(false);

				EMH_store_error_s1(EMH_severity_error, EMH_ATTR_error_base, err.str().c_str());

				return 1;
			}

		}
	}

	POM_AM__set_application_bypass(false);

	return 0;
}


void get_bom(System::Collections::Generic::List<System::Collections::Generic::Dictionary<String^, String^>^> ^a_list,tag_t line,char *werks,char *stlan,string pid, tag_t relation_type,boolean is_hl,boolean is_judge)
{
	int line_cnt;
	tag_t *lines;
	BOM_line_ask_child_lines(line, &line_cnt, &lines);
	char *id;
	AOM_UIF_ask_value(line, "bl_item_item_id", &id);
	if(a_list->Count==0)
	{
		pid = pid.length()>0?pid:id;
		int index = pid.find('-');
		if (index != -1)
			pid = pid.substr(index + 1);
	}
	for (int j = 0; j < line_cnt; j++)
	{
		System::Collections::Generic::Dictionary<String^, String^> ^dic = gcnew System::Collections::Generic::Dictionary<String^, String^>();
		dic["MATNR"] = convert_to_cstring(pid.length()>0?pid.c_str():id);
		dic["WERKS"] = convert_to_cstring(werks);
		dic["STLAN"] = convert_to_cstring(stlan);
		dic["BMENG"] = "1";
		dic["STLST"] = "1";
		dic["POSTP"] = "L";
		char *val;
		// AOM_UIF_ask_value(lines[j], "bl_sequence_no", &val);
		// dic["POSNR"] = convert_to_cstring(val);
		char *child_id;
		AOM_UIF_ask_value(lines[j], "bl_child_id", &child_id);
		dic["IDNRK"] = convert_to_cstring(child_id);

		// AOM_UIF_ask_value(lines[j], "bl_quantity", &val);

		AOM_UIF_ask_value(lines[j], "bl_uom", &val);
		dic["MEINS"] = convert_to_cstring(val);
		dic["STLAL"] = is_hl ? convert_to_cstring("02") : convert_to_cstring("01");
		char *val1, *val2,*hl,*sffs;
		tag_t tag,*rels;
		int rel_cnt;

		AOM_ask_value_tag(lines[j], "bl_line_object", &tag);
		AOM_UIF_ask_value(tag, "jd2_ishl", &hl);
		boolean child_is_hl = tc_strcmp(hl, "ÊÇ") ? false : true;

		GRM_list_secondary_objects_only(tag, relation_type, &rel_cnt, &rels);
		AOM_ask_value_string(lines[j], "JD2_SFHL", &sffs);
		printf("JD2_SFHL:%s\n", sffs);
		if(tc_strcmp(sffs,"1")==0)
		{
			AOM_ask_value_string(lines[j], "JD2_sl", &val);
		}else
		{
			AOM_ask_value_string(lines[j], "bl_quantity", &val);
		}

		dic["MENGE"] = convert_to_cstring(val);

		if(is_judge){
			if (rel_cnt)
			{
				AOM_ask_value_string(rels[0], "jd2_cglx", &val1);
				AOM_ask_value_string(rels[0], "jd2_tscg", &val2);
			}
			if (tc_strcmp(val1, "F") == 0 && tc_strcmp(val2, "50") == 0)
			{
				continue;
			}
			if (tc_strcmp(val1, "E") == 0 && tc_strcmp(val2, "50") == 0)
			{
				get_bom(a_list, lines[j], werks, stlan, id, relation_type, child_is_hl, is_judge);
				continue;
			}
			if (tc_strcmp(val1, "F") == 0 && tc_strlen(val2) == 0)
			{
				a_list->Add(dic);
				continue;
			}
		}
		a_list->Add(dic);

		get_bom(a_list, lines[j], werks, stlan,"",relation_type, child_is_hl, is_judge);
	}
}

int bs_sap_bom(EPM_action_message_t msg)
{
	printf("start sap bom1\n");
	int ifail = ITK_ok, att_count;
	tag_t rootTask, *attachments, relation_type, win;
	char *obj_type;
	int pref_cnt;
	char **pref_vals;
	EPM_ask_root_task(msg.task, &rootTask);

	EPM_ask_attachments(rootTask, EPM_target_attachment, &att_count, &attachments);
	TC_argument_list_t * arguments = msg.arguments;
	int arg_cnt = TC_number_of_arguments(arguments), status = 0;
	POM_AM__set_application_bypass(true);
	map<string, string> paras;

	for (auto i = 0; i < arg_cnt; i++)
	{
		char *temp_key, *temp_val;
		ITK_ask_argument_named_value(TC_next_argument(arguments), &temp_key, &temp_val);
		paras[temp_key] = temp_val;
	}
	PREF_ask_char_values("connor_sap", &pref_cnt, &pref_vals);
	GRM_find_relation_type("IMAN_master_form", &relation_type);
	Testclass ^test = gcnew Testclass();
	String^ url = convert_to_cstring(pref_vals[1]);
	String^ user = convert_to_cstring(pref_vals[2]);
	String^ password = convert_to_cstring(pref_vals[3]);

	BOM_create_window(&win);
	for (int i = 0; i < att_count; i++)
	{
		if (isTypeOf(attachments[i], "PSBOMViewRevision"))
		{
			printf("execute\n");
			int rel_cnt, line_cnt;
			System::Collections::Generic::List<System::Collections::Generic::Dictionary<String^, String^>^> ^a_list = gcnew System::Collections::Generic::List<System::Collections::Generic::Dictionary<String^, String^>^>();
			tag_t top_line, *lines, rev, *rels;
			char *id, *werks, *stlan,*hl;
			BOM_set_window_top_line_bvr(win, attachments[i], &top_line);
			AOM_ask_value_tag(top_line, "bl_line_object", &rev);
			GRM_list_secondary_objects_only(rev, relation_type, &rel_cnt, &rels);
			AOM_ask_value_string(rev, "item_id", &id);
			AOM_ask_value_string(rels[0], "jd2_gc", &werks);
			AOM_ask_value_string(rels[0], "jd2_BOMyt", &stlan);
			AOM_UIF_ask_value(rev, "jd2_ishl", &hl);
			boolean is_hl = tc_strcmp(hl,"ÊÇ")?false:true;
			
			if (tc_strlen(werks)==0||tc_strlen(stlan)==0)
				continue;
			boolean is_judege = id[0] == '9'&&id[1] == '9';
			get_bom(a_list, top_line, werks, stlan,"", relation_type,is_hl,is_judege);
			string result = ConvertToString(test->send_bom(url, user, password, a_list));
			printf("result:%s\n", result.c_str());
			if(result.length()&&result[0]=='E')
			{
				BOM_close_window(win);
				POM_AM__set_application_bypass(false);
				EMH_store_error_s1(EMH_severity_error, EMH_ATTR_error_base, result.c_str());

				return 1;
			}
		}
	}
	BOM_close_window(win);
	POM_AM__set_application_bypass(false);
	EMH_clear_errors();

	return 0;
}

