#pragma warning (disable: 4996) 
#pragma warning (disable: 4819) 
#pragma warning (disable: 4995) 

#include "w2_Clear_Form_PropValue.h"
#include "error_handling.h"
#include <string>
#include <vector>
#include <map>
#include <fstream>

#include <epm/epm.h>
#include <epm/epm_toolkit_tc_utils.h>
#include <ict/ict_userservice.h>
#include <tccore/item.h>
#include <ae/ae.h>
#include <tc/folder.h>
#include <tccore/aom.h>
#include <sa/sa.h>
#include <tccore/aom_prop.h>
#include <property/prop_errors.h>
#include <tccore/workspaceobject.h>
#include <tc/preferences.h>
#include <tccore/imantype.h>
#include <tccore//grm.h>
#include <tccore/grmtype.h>
#include <sa/am.h>
#include <cfm/cfm.h>
#include <bom/bom.h>
#include <tccore/uom.h>
#include <ps/ps.h>
#include <epm/signoff.h>
#include <fclasses/tc_date.h>
#include <ics\ics2.h>
#include "tc_util.h"
//#include <iostream>
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif


	int delete_msword(tag_t dataset,char *ext,char *newRevType)
	{
		tag_t spec_dataset_rev = NULLTAG , ref_object = NULLTAG;
		AE_reference_type_t reference_type;
		printf("\n111111111111\n");
		AE_ask_dataset_latest_rev(dataset, &spec_dataset_rev);

		char ref_name[WSO_name_size_c + 1] = "word";
		//printf("\n22222222222\n");
		AE_ask_dataset_named_ref(spec_dataset_rev, ref_name, &reference_type, &ref_object);
		if(reference_type == AE_PART_OF)
		{
			printf("\n3333333333333\n");
			char pathname[SS_MAXPATHLEN] = "";
			IMF_ask_file_pathname(ref_object, SS_WNT_MACHINE, pathname);
			char origin_file_name[IMF_filename_size_c + 1] = "";
			IMF_ask_original_file_name(ref_object, origin_file_name);
			printf("\n44444444444444\n");
			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";
			printf("\n555555555555\n");
			char temp_file[SS_MAXPATHLEN] = "";
			strcpy(temp_file, temp_dir);
			strcat(temp_file, "\\");
			strcat(temp_file, new_file_name);

			IMF_export_file(ref_object, temp_file);
			printf("\n66666666666666\n");

			int   iCnt;
			char *user_lib_env,pTempStr[500];
			char local_path[MAX_PATH] = "";
			char cmd[256] = "";

			strcpy( cmd, "DeleteMacros-MSWord.wsf" );

			strcat( cmd, " \"" ); 
			strcat( cmd, temp_file ); 
			strcat( cmd, "\"" );
			printf( "\n%s\n",cmd );
			system( cmd );
			printf("\n777777777777\n");
			//strcpy(user_lib_env, local_path);


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

			AOM_lock(spec_dataset_rev);

			AE_remove_dataset_named_ref_by_tag(spec_dataset_rev, ref_name, ref_object);

			AE_add_dataset_named_ref(spec_dataset_rev, ref_name, AE_PART_OF, new_file_tag);
			AOM_save(spec_dataset_rev);
			AOM_unlock(spec_dataset_rev);
		}
		return ITK_ok;
	}




	int delete_msexcel(tag_t dataset,  char *ext,char *newREV_type)
	{
		tag_t spec_dataset_rev = NULLTAG,
			ref_object = NULLTAG;

		AE_reference_type_t reference_type;

		AE_ask_dataset_latest_rev(dataset, &spec_dataset_rev);

		char ref_name[WSO_name_size_c + 1] = "excel";
		AE_ask_dataset_named_ref(spec_dataset_rev, ref_name, &reference_type, &ref_object);
		if(reference_type == AE_PART_OF)
		{
			char pathname[SS_MAXPATHLEN] = "";
			IMF_ask_file_pathname(ref_object, SS_WNT_MACHINE, pathname);
			char origin_file_name[IMF_filename_size_c + 1] = "";
			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);

			IMF_export_file(ref_object, temp_file);


			int   iCnt;
			char *user_lib_env,pTempStr[500];
			char local_path[MAX_PATH] = "";
			char cmd[256] = "";


			strcpy( cmd, "DeleteMacros-MSExcel.wsf" );
			strcat( cmd, " \"" ); 
			strcat( cmd, temp_file ); 
			strcat( cmd, "\"" );
			printf( "\n%s\n",cmd );
			system( cmd );

			//strcpy(user_lib_env, local_path);


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

			AOM_lock(spec_dataset_rev);
			//CALL(AOM_load (dataset));
			//CALL(AOM_load(spec_dataset_rev));
			AE_remove_dataset_named_ref_by_tag(spec_dataset_rev, ref_name, ref_object);
			AE_add_dataset_named_ref(spec_dataset_rev, ref_name, AE_PART_OF, new_file_tag);
			AOM_save(spec_dataset_rev);
			AOM_unlock(spec_dataset_rev);
		}

		return ITK_ok;
	}






	int W2_Revise_clear_form( METHOD_message_t* msg, va_list args )
	{
		int ifail = ITK_ok, i = 0, j = 0;
		
		char  rev_type[ITEM_type_size_c + 1],
			*optionname= "W2_Revise_clear_form";\
			map<int, string> prop_map;			
		//int	msgid = va_arg(args,int );
		tag_t new_rev = va_arg(args,tag_t );
		char*  operation = va_arg(args,char*  );
		

		printf("*******************************************************\n");
		printf("*      W2_Revise_clear_form is comming         *\n");
		printf("*******************************************************\n");

		printf("new_rev==============================%d\n",new_rev);
		printf("operation==============================%s\n",operation);

		//-------------读取首选项(origin+rev_type+_str),itemrev与Form关系、Form类型、清空属性名
		int option_value_count;
		char **option_values;
		char *PREF_W2_Revise_clear_form="Chint_Revise_ItemRev";//首选项名称
		// DocumentRevision:设计,设计日期,校对,校对日期,工艺,工艺日期,标准化,标准化日期,审定,审定日期,批准,批准日期
		if(strcmp(operation,"Revise")!=0 && strcmp(operation,"SaveAs")!=0){
			return ifail;
		}
		ITKCALL(PREF_ask_char_values(PREF_W2_Revise_clear_form,&option_value_count,&option_values));
		printf("=====option_value_count======%d\n",option_value_count);
		if(option_value_count == 0)
		{
			printf("请在option中配置选项%s！\n",PREF_W2_Revise_clear_form);
			return ifail;
		}
		for(int i=0;i<option_value_count;i++){
			char charlist[100][100];
			int col =0;  
			char *substr= strtok(option_values[i], ":");
			printf("substr :%s\n", substr);    
			while (substr != NULL) {    
				strcpy(charlist[col],substr);
				col++;  
				printf("%s\n", substr);    
				substr = strtok(NULL,":");
			}
			char *type=new char[32];
			ITKCALL(WSOM_ask_object_type(new_rev,type));
			printf("type  :%s\n", type);    
			if(strcmp(type,charlist[0])==0){
				char charlist2[100][100];
				int col2 =0;  
				char *substr= strtok(charlist[1], ",");
				while (substr != NULL) {    
					strcpy(charlist2[col2],substr);
					col2++;  
					printf("%s\n", substr);    
					substr = strtok(NULL,",");
				}
				ITKCALL( AOM_lock( new_rev ) );
				for(int m=0;m<col2;m++){
					ITKCALL(AOM_set_value_string(new_rev,charlist2[m],""));
					ITKCALL( AOM_save( new_rev ) );
				}

				ITKCALL( AOM_unlock( new_rev ) );
				ITKCALL( AOM_refresh( new_rev,true ) );
			}


		}
		MEM_free(option_values);



		char rev_id[ITEM_id_size_c+1]="";
		char item_id[ITEM_id_size_c+1]="";
		char* newREV_type=NULL;
		tag_t master_form_rel_type = NULLTAG;
		tag_t item = NULLTAG;

		ITEM_ask_rev_id(new_rev,rev_id);
		ITEM_ask_item_of_rev( new_rev, &item);
		ITEM_ask_id(item, item_id);
		GRM_find_relation_type( TC_master_form_rtype, &master_form_rel_type  );
		AOM_ask_value_string(new_rev,"object_type",&newREV_type);

		//获得数据集
		tag_t relation_type=NULLTAG;
		//tag_t attach_relation_type = NULLTAG;
		GRM_find_relation_type(TC_specification_rtype, &relation_type);
		tag_t *secondary_objects=NULLTAG;
		int ds_count = 0;
		char *dataset_type = NULL, *desc_value=NULL,*file_path = NULL,*desc_path;
		GRM_list_secondary_objects_only(new_rev, relation_type, &ds_count, &secondary_objects);

		for (int j = 0; j < ds_count; j++)
		{
			AOM_ask_value_string(secondary_objects[j], "object_type", &dataset_type);

			if(strcmp(dataset_type, "MSWord") ==0 )
			{
				delete_msword(secondary_objects[j],"doc",newREV_type);
			}
			else if(strcmp(dataset_type, "MSWordX") ==0)
			{
				delete_msword(secondary_objects[j],"docx",newREV_type);
			}
			else if(strcmp(dataset_type, "MSExcel") ==0 )
			{
				delete_msexcel(secondary_objects[j],"xls",newREV_type);
			}
			else if(strcmp(dataset_type, "MSExcelX") ==0)
			{
				delete_msexcel(secondary_objects[j],"xlsx",newREV_type);
			}

			MEM_free(dataset_type);

		}
		DOFREE(secondary_objects);


		GRM_find_relation_type(TC_attaches_rtype, &relation_type);

		GRM_list_secondary_objects_only(new_rev, relation_type, &ds_count, &secondary_objects);
		for (int j = 0; j < ds_count; j++)
		{
			AOM_ask_value_string(secondary_objects[j], "object_type", &dataset_type);

			if(strcmp(dataset_type, "MSWord") ==0 )
			{
				delete_msword(secondary_objects[j],"doc",newREV_type);
			}
			else if(strcmp(dataset_type, "MSWordX") ==0)
			{
				delete_msword(secondary_objects[j],"docx",newREV_type);
			}
			else if(strcmp(dataset_type, "MSExcel") ==0 )
			{
				delete_msexcel(secondary_objects[j],"xls",newREV_type);
			}
			else if(strcmp(dataset_type, "MSExcelX") ==0)
			{
				delete_msexcel(secondary_objects[j],"xlsx",newREV_type);
			}

			MEM_free(dataset_type);

		}
		DOFREE(secondary_objects);
		if(newREV_type!=NULL)
		{
			MEM_free(newREV_type);
			newREV_type=NULL;
		}
		printf("*******************************************************\n");
		printf("*        W2_Clear_Form_PropValue is end           *\n");
		printf("*******************************************************\n");

		return ifail;
	}

//图纸版本升版时触发
int ZT2_Design_Revise_process( METHOD_message_t* msg, va_list args )
{
	printf("图纸修订开始\r\n");
	int ifail = ITK_ok, i = 0, j = 0;
	char  rev_type[ITEM_type_size_c + 1];
	tag_t new_rev = va_arg(args,tag_t );
	char*  operation = va_arg(args,char*  );
	if(strcmp(operation,"Revise")!=0 ){
			return ifail;
	}
	char* type1;
	char* item_revision_id;
	ITKCALL(AOM_ask_value_string(new_rev, "object_type", &type1));
	ITKCALL(AOM_ask_value_string(new_rev, "item_revision_id", &item_revision_id));
	//printf("版本:%s\r\n",item_revision_id);
	
	if(!(strcmp(type1,"ZT2_Design3DRevision")==0 || strcmp(type1,"Part Revision")==0))
	{
		printf("非图纸修订\r\n");
		return ifail;
	}
	tag_t rev = NULLTAG,item = NULLTAG;
	//METHOD_PROP_MESSAGE_OBJECT(msg,rev);
	ITEM_ask_item_of_rev(new_rev,&item);
	int cnt,rel_cnt;
	tag_t *tags,*rels;
	ITEM_list_all_revs_alpha(item,&cnt,&tags);
	//printf("版本个数:%d\r\n",cnt);
	//for(auto i=cnt-1;i>=0;i--)
	//{
		
	//	ITKCALL(AOM_ask_value_string(tags[i], "item_revision_id", &item_revision_id));
	//	printf("版本:%s\r\n",item_revision_id);
	//}
	
	if(cnt>1)
	{
		rev =tags[cnt-2]; 
	}else
	{
		rev =tags[0]; 
	}

	//printf("-----------------\r\n");
	ITKCALL(AOM_ask_value_string(rev, "item_revision_id", &item_revision_id));
	printf("版本:%s\r\n",item_revision_id);
	int n_reference, *level;
	tag_t *references;
	char **relations;
	printf("开始获取引用对象\r\n");
	ITKCALL(WSOM_where_referenced(rev, 1, &n_reference, &level, &references, &relations));
	vector<tag_t> procs ;
	for(auto i=0;i<n_reference;i++)
	{
		char* type1;
		ITKCALL(AOM_ask_value_string(references[i], "object_type", &type1));
		//printf("%d---object_type:%s\r\n",i,type1);
		if(strcmp(type1,"MEProcessRevision")==0)
		{
			procs.push_back(references[i]);
		}
		MEM_free(type1);
	}
	printf("一共挂载%d条工艺路线\r\n",procs.size());
	tag_t dataset_rel, relation_tag;
	GRM_find_relation_type("IMAN_METarget", &dataset_rel);
	POM_AM__set_application_bypass(true);
	for(auto it=procs.begin();it!= procs.end();it++)
	{
		int fff = GRM_create_relation(*it, new_rev, dataset_rel, NULLTAG, &relation_tag);
		GRM_save_relation(relation_tag);
		AOM_unlock(relation_tag);		
	}
	POM_AM__set_application_bypass(false);
	printf("图纸修订结束\r\n");
	return ifail;			
			
}



	extern int Register_revise_msg( void )
	{
		int status = ITK_ok;
		char *err_string,*err_function;
		int err_line = -1;
		printf("W2_Revise_clear_form函数！\n");

		METHOD_id_t mth_tag;
		ITKCALL(status = METHOD_find_method("ItemRevision", ITEM_deep_copy_msg ,&mth_tag));
		if (mth_tag.id != 0){
			ITKCALL( METHOD_add_action(mth_tag, METHOD_post_action_type, W2_Revise_clear_form, NULL));
			printf("注册W2_Revise_clear_form函数成功！\n");
		}
		ITKCALL(status = METHOD_find_method("ItemRevision",ITEM_deep_copy_msg,&mth_tag));
		
		if (mth_tag.id != 0){
		
			ITKCALL( METHOD_add_action(mth_tag, METHOD_post_action_type, ZT2_Design_Revise_process, NULL));
			printf("注册ZT2_Design_Revise_process函数成功！\n");
		}

		return status;
	}







#ifdef __cplusplus
}
#endif







