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

#include <tc/tc.h>
#include "epm_handler_common.h"

#include <ict/ict_userservice.h>
#include <tccore/custom.h>
#include <epm/epm_toolkit_tc_utils.h>
#include <tccore/aom.h>
#include <tccore/aom_prop.h>
#include <tccore/item.h>
#include <bom/bom.h>
#include "ps/ps.h";
#include "ps/vrule.h"
#include "sstream"
#include <tccore/grm.h>
#include "epm/epm.h"
#include "sa/sa.h"
#include "libxl.h"
#include <map>
#include "epm/signoff.h"
#include <ctime>
#include <vector>
#include <locale>
#include <codecvt>
#include "ae/dataset.h"
#include <iostream>
#include <stdlib.h>
#include <tccore/aom.h>
#include <tc/emh.h>
#include <ict/ict_userservice.h>
#include <tc/tc.h>
#include <tccore/tctype.h>
#include <sa/tcfile.h>
#include <ss/ss_errors.h>
extern "C" int POM_AM__set_application_bypass(logical bypass);
using namespace libxl;
typedef struct{
	string ITEM_ID;//id号
}PROPERTY_STRUCT;
string wsTos(const std::wstring& wstr)
{
	
	if (wstr.empty()||wstr.length()==0) return std::string();
	int size_needed = WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
	std::string strTo(size_needed, 0);
	WideCharToMultiByte(CP_ACP, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
	return strTo;
}

int search(string item_id,string rev,string object_name)
{
	char** entries;
	char** values;
	int count = 0 ,entry_count = 0,status = 0,num_found=0;
	char ** values_list = NULL ;//** values = NULL, ** entries = NULL;
	tag_t query_tag = NULLTAG ,*results = NULL;

	//构建器
	ITKCALL(QRY_find("零组件版本...",&query_tag));
	if(query_tag==NULLTAG)
	{
		printf("没找到 [%s]查询构建器！\n","零组件版本..." );
		return 0;
	}
	printf("找到 [%s]查询构建器！\n","零组件版本..." );

	ITKCALL(QRY_find_user_entries(query_tag,&entry_count,&entries,&values));//entries：查询条件表达式；values：查询条件值（MEM_free释放）
	if(entry_count==0)
	{
		cout<<"查询构建器中没有配置查询条件！"<<endl;
		ITK_exit_module(1);
		if(entries!=NULL){
			MEM_free(entries);
			entries= NULL;
		}
		if(values!=NULL){
			MEM_free(values);
			values= NULL;
		}
		return 0;
	}
	for(int n=0;n<entry_count;n++)
	{
//		cout<<"查询名称属性"<<endl;	
//		printf("entries[%d]=%s\n",n,entries[n]);
//
//		printf("values[%d]=%s\n",n,values[n]);

	}

	char *other_values[2] ;
	char *other_entrys[2] ;
	other_values[0]= (char*)calloc(48,sizeof(char));
	other_values[1]= (char*)calloc(48,sizeof(char));
	other_entrys[0] = (char*)calloc(48,sizeof(char));
	other_entrys[1] = (char*)calloc(48,sizeof(char));
	tc_strcpy(other_entrys[0],"零组件 ID");
	tc_strcpy(other_entrys[1],"版本");

	tc_strcpy(other_values[0],item_id.c_str());
	tc_strcpy(other_values[1],rev.c_str());
	//			printf("执行查询[%s][%s]\n",other_entrys[0],other_values[0]);
	ITKCALL(status = QRY_execute(query_tag,2,other_entrys,other_values,&num_found,&results));
	printf("执行查询结果[%d]\n",status);
	printf("查询到对象%d个",num_found);
	free(other_values[0]);
	free(other_values[1]);
	free(other_entrys[0]);
	free(other_entrys[1]);
	if(status !=ITK_ok){
		char * message =NULL;
		EMH_ask_error_text(status, &message);
		printf("查询异常 : \"%d\",\"%s\"\n",status,message);
		MEM_free(message);
		message =NULL;
		return 0;
	}
	for(int n=0;n<num_found;n++)
	{
		cout<<"------>modify"<<endl;
		tag_t obj=results[n];
		ITKCALL(status=AOM_load(obj));
		ITKCALL(status=AOM_lock(obj));
		ITKCALL(status=AOM_refresh(obj,1));
		POM_AM__set_application_bypass(true);
		ITKCALL(AOM_set_value_string(obj,"object_name",object_name.c_str()));
		POM_AM__set_application_bypass(false);
		ITKCALL(status=(AOM_save(obj)));  
		ITKCALL(status=(AOM_refresh(obj,0)));  
		ITKCALL(status=(AOM_unlock(obj)));  
	}
	return 0;
}

/*
 * 下载版本附加关系下的数据集，xls型的表格，读取其中内容，然后修改版本的object_name
 */
int Modify_Attributes(EPM_rule_message_t msg)
{
	Book* book = nullptr;
	book = xlCreateBook();//xls文件用xlCreateBook() 函数打开，xlsx文件是xml结构，所以得用xlCreateXMLBook() 函数来打开。
	book->setKey(L"Halil Kural", L"windows-2723210a07c4e90162b26966a8jcdboe");//如果购买了该库，则设置相应的key，若没有购买，则不用这行
	EPM_decision_t decision = EPM_go;
	int ifail = ITK_ok, arg_cnt = 0, i = 0, att_cnt = 0;
	tag_t task_tag = NULLTAG, rootTask_tag = NULLTAG, *attachments = NULL;
	char * object_TYPE_1 = NULL;
	char * object_string = NULL;
	string value_type = "";
	string value_property="";
	
	//获取当前触发的任务
	task_tag = msg.task;
	//获取根流程节点
	ifail = EPM_ask_root_task(task_tag, &rootTask_tag);
	//获取目标引用对象
	ifail = EPM_ask_attachments(rootTask_tag, EPM_target_attachment, &att_cnt, &attachments);
	//循环目标对象
	for (i = 0; i < att_cnt; i++) {
	//下载数据集
		tag_t rev_tag=attachments[i];
		AOM_ask_value_string(rev_tag,"object_type",&object_TYPE_1);
		cout<<object_TYPE_1<<endl;
	
			cout<<"111111111111111111"<<endl;
			tag_t relation_type_tag = NULLTAG;
			ifail = GRM_find_relation_type("TC_Attaches", &relation_type_tag);
			if (ifail != ITK_ok) { /* your error logic here */ }
			   int n_specs = 0;
			tag_t* specs = NULL;

			ITKCALL(ifail = GRM_list_secondary_objects_only(rev_tag, relation_type_tag, &n_specs, &specs));
			if (ifail != ITK_ok) { /* your error logic here */ }
			for (int j = 0; j < n_specs; j++)
			{
				cout<<"2222222222222"<<endl;
				 tag_t type_tag = NULLTAG; char type_name[TCTYPE_name_size_c+1] = "";
				ifail = TCTYPE_ask_object_type (specs[j], &type_tag);
				if (ifail != ITK_ok) { /* your error logic here */ }

				ifail = TCTYPE_ask_name(type_tag, type_name);
				if (ifail != ITK_ok) { /* your error logic here */ }
				cout<<"type_name-----------"<<type_name<<endl;
				if (strcmp(type_name, "MSExcel") == 0||strcmp(type_name, "MSExcelX") == 0)
				{
					cout<<"333333333333333"<<endl;
					int n_refs = 0;
					tag_t* refs = NULL;

					ITKCALL(ifail = AE_ask_all_dataset_named_refs(specs[j], "excel", &n_refs, &refs));
					if (ifail != ITK_ok) { /* your error logic here */ }

					ITKCALL(ifail = AE_export_named_ref(specs[j], "excel", "D:\\TEMP\\Ctest.xls"));
					if (ifail != ITK_ok) { /* your error logic here */ }
					//检查是否存在单元格名称为“xxxx”
					wstringstream excel_path;
					excel_path<<"D:\\TEMP\\Ctest.xls";
					if (book->load(excel_path.str().c_str()))//不支持中文字符名称的文件加载
					{
						cout<<"88888888"<<endl;
						Sheet* sheet = book->getSheet(0);//获得第1个sheet页
						for(int k=1;k<2001;k++)
						{
							cout<<k<<endl;
							string itemid_val ;
							string rev_value;
							string name_value;
							itemid_val = wsTos(sheet->readStr(k, 0));
							rev_value=wsTos(sheet->readStr(k, 1));
							name_value=wsTos(sheet->readStr(k, 2));
							printf("id:%s\n", itemid_val.c_str());
							printf("版本:%s\n", rev_value.c_str());
							printf("名称:%s\n", name_value.c_str());
							//查询构建器查询物料版本并修改
							search(itemid_val,rev_value,name_value);
							
						}

					
							
					}
				}
			}

	
		
		
	}
	if (attachments != NULL)
	{
		MEM_free(attachments);
		attachments = NULL;
	}
	if (object_TYPE_1 != NULL)
	{
		MEM_free(object_TYPE_1);
		object_TYPE_1 = NULL;
	}
	if (object_string != NULL)
	{
		MEM_free(object_string);
		object_string = NULL;
	}
	 time_t t;
    struct tm * lt;
    time (&t);//获取Unix时间戳。
    lt = localtime (&t);//转为时间结构。
    printf ( "%d/%d/%d %d:%d:%d\n",lt->tm_year+1900, lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);//输出结果
	return EPM_nogo;
	
		
	}

