#include "epm_handler_common.h"
#include "jk_custom_erp.h"
#include "jk_custom.h"
#include <tc/tc.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 <map>
#include "epm/signoff.h"
#include <ctime>
#include <vector>
#include <locale>
#include <codecvt>
#include "ae/dataset.h"
#include <server_exits/user_server_exits.h>
#include <tccore/custom.h>
#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 <form/form.h>
#include <form/formtype.h>
#include <ics\ics.h>
#include <stdarg.h>
#include <iostream>
#include "libxl.h"
extern "C" int POM_AM__set_application_bypass(logical bypass);
using namespace std;

int searchItemRev(string item_id,string  item_rev,vector<tag_t> &vector)
{
	cout<<"版本----"<<item_rev<<endl;
	cout<<item_rev<<endl;
	//查询构建器
	tag_t query_tag;
	int entry_count;
	char **entries;
	char **values;
	int num_found=0;
	int ifail=0;
	char *message;
	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));
		tag_t* results=NULLTAG;
//	const char query_name_ggtz[1][QRY_name_size_c + 1]={"零组件版本..."};//查询构建器的名称
	ITKCALL(QRY_find("零组件版本...",&query_tag));
	if(query_tag==NULLTAG)
	{
		WriteLog("query_tag=NULLTAG,没找到 [%s]查询构建器！\n","零组件版本..." );
		ITK_exit_module(1);
		return 0;
	}
	else 
	{
		WriteLog("找到查询构建器\n");
	}

	ITKCALL(QRY_find_user_entries(query_tag,&entry_count,&entries,&values));//entries：查询条件表达式；values：查询条件值（MEM_free释放）
	if(entry_count==0)
	{
		WriteLog("entry_count=0,查询构建器中没有配置查询条件！\n");
		//ITK_exit_module(1);
		if(entries!=NULL){
			MEM_free(entries);
			entries= NULL;
		}
		if(values!=NULL){
			MEM_free(values);
			values= NULL;
		}
		
	}

	//date_tag.second = p->tm_sec ;

	for(int n=0;n<entry_count;n++)
	{
		printf("entries[%d]=%s\n",n,entries[n]);
		if(tc_strcmp(entries[n],"零组件 ID")==0){
			//strcpy(values[n],nowtime1);
			tc_strcpy(other_entrys[0],"零组件 ID");
			tc_strcpy(other_values[0],item_id.c_str());
			printf("other_values[0] %s\n",other_values[0]);

		}else	if(tc_strcmp(entries[n],"版本")==0){
			//strcpy(values[n],nowtime1);
			tc_strcpy(other_entrys[1],"版本");
				cout<<item_rev<<endl;
			tc_strcpy(other_values[1],item_rev.c_str());
			printf("other_values[1] %s\n",other_values[1]);

		}else
		{
			continue;
		}

		printf("values[%d]=%s\n",n,values[n]);

	}

	ITKCALL(ifail = QRY_execute(query_tag,1,other_entrys,other_values,&num_found,&results));

	if(ifail !=ITK_ok){
		EMH_ask_error_text(ifail, &message);
		WriteLog("程序异常 : \"%d\",\"%s\"\n",ifail,message);
		MEM_free(message);
		if(entries!=NULL){
			MEM_free(entries);
			entries= NULL;
		}
		if(values!=NULL){
			MEM_free(values);
			values= NULL;
		}
		return 0;
	}
	if(num_found==0)
	{
		printf("num_found=0,查询构建器中没找到满足条件的数据！\n");
		//ITK_exit_module(1);
		if(entries!=NULL){
			MEM_free(entries);
			entries= NULL;
		}
		if(values!=NULL){
			MEM_free(values);
			values= NULL;
		}
	}else
	{
		vector.push_back(results[0]);

	}
	//开始获取项目信息
	printf("查询构建器得到ITEM数num_found: \"%d\" \n", num_found);
	return 0;
}
//判断的那远哥是否为空
bool IsCellEmpty(int cellType)
{
	if((cellType == libxl::CELLTYPE_BLANK) || (cellType == libxl::CELLTYPE_EMPTY)){
		return false;
	}
	else
	{
		return true;
	}
}
int  jk_remove_allStatus(EPM_action_message_t msg)
{
	//参数定义
	int ifail = EPM_go , 
		arg_cnt = 0 , 
		i = 0 ,
		att_cnt = 0;

	tag_t task_tag  = NULLTAG , 
		root_task_tag =NULLTAG , 
		*attachments = NULL;
	
	char * argflag = NULL ,
		*argvalue =NULL ,
		*arg = NULL , 
		arg_value[1024] = "\0",
		type_class[WSO_object_type_size_c+1] ="\0";
	//记录错误信息
	map<string,int> errMap;
	vector<string> type_vec;//存放所有的要去除的发布状态
	vector<tag_t> itemRev;//存放所有的要去除状态的版本
		arg_cnt = TC_number_of_arguments(msg.arguments);
	ECHO("参数个数为：%d\n",arg_cnt);
	if (arg_cnt > 0)
	{
		for (i=0;i<arg_cnt;i++)
		{
			//获取下一个参数（从0开始）
			arg = TC_next_argument(msg.arguments);
			//获取参数的名称和值
			ifail = ITK_ask_argument_named_value((const char*)arg, &argflag, &argvalue);
			//需要检查哪些对象的类型
			if (stricmp(argflag, "remove_status") == 0)
			{
				if(argvalue != NULL)
				{
					strcpy(arg_value,argvalue);
					Split(arg_value,";",type_vec);
				}else{

					string key_id;
					key_id.assign("缺少remove_status参数");
					errMap.insert(pair<string,int>(key_id,HANDLER_ARGUMENT_ERROR));
				}
			}
		}
		//
		//获取目标对象
	task_tag = msg.task;
	if(task_tag == NULLTAG)
	{
		
		return EPM_nogo;
	}
	EPM_ask_root_task(task_tag, &root_task_tag);
	EPM_ask_attachments(root_task_tag, EPM_target_attachment, &att_cnt, &attachments);
	

	for(i = 0 ;i < att_cnt;i++){

		tag_t excelTag = attachments[i];
		//获取对象的类型 PSBOMViewRevision
		ITKCALL( WSOM_ask_object_type(excelTag, type_class));
		ECHO("对象类型%s\n",type_class);
		if(strcmp(type_class,"MSExcel")==0)
		{
//			ITK__convert_uid_to_tag("T1exiQYYYvbLjA",&excelTag);
			libxl::Book* book = nullptr;
			book = xlCreateBook();//xls文件用xlCreateBook() 函数打开，xlsx文件是xml结构，所以得用xlCreateXMLBook() 函数来打开。
			book->setKey(L"Halil Kural", L"windows-2723210a07c4e90162b26966a8jcdboe");//如果购买了该库，则设置相应的key，若没有购买，则不用这行
			int n_refs = 0;
			tag_t* refs = NULL;

			ifail = AE_ask_all_dataset_named_refs(excelTag, "excel", &n_refs, &refs);
			if (ifail != ITK_ok) { /* your error logic here */ }

			char current_date_time_str[128 + 1] = {"\0"};
			get_current_date_and_time(current_date_time_str);
			string time_now=current_date_time_str;
			time_now="E:\\TEMP\\"+time_now+".xls";
			cout<<"文件路径----------"<<time_now;
			ifail = AE_export_named_ref(excelTag, "excel", time_now.c_str());
			if (ifail != ITK_ok) { /* your error logic here */ }
			//检查是否存在单元格名称为“xxxx”
			wstringstream excel_path;

			//	excel_path<<"C:\\TEMP\\export_text.xls";
			excel_path<<time_now.c_str();
			libxl::Sheet* sheet;
			if (book->load(excel_path.str().c_str()))
			{
				cout<<"88888888"<<endl;
				sheet = book->getSheet(0);//获得第1个sheet页
				int lastRow=sheet->lastRow();
				cout<<"共有"<<lastRow<<"行"<<endl;
				for(int i=1;i<lastRow;i++)
				{
					if(IsCellEmpty(sheet->cellType(i, 0))&&IsCellEmpty(sheet->cellType(i, 1))){
						string value0=ws2s(sheet->readStr(i, 0));//虚拟件id
						string value1=ws2s(sheet->readStr(i, 1));//虚拟件技术型号
						cout<<value0<<endl;
						cout<<value1<<endl;
						if(value0.length()>1&&value1.length()>1	)
						{
							searchItemRev(value0,value1,itemRev);
						}
					}else
					{
						continue;
					}
				}
			}
			if (book->save(excel_path.str().c_str()))//保存到example.xls
        {
            //.....
        }
        else
        {
            std::cout << book->errorMessage() << std::endl;
        }
        book->release();//释放对象！！！！
		}
		
	}

		//把所有的版本去除状态
		//删除物料和版本的状态
			cout<<"mark1"<<endl;
	
			//获取对象的状态，如果包含
	


	POM_AM__set_application_bypass(true);
	//	removeReleaseStatus("删除状态流程",target_vec);
	cout<<"mark1"<<endl;
	for(int i=0;i<type_vec.size();i++)
	{
		string status=type_vec[i];
		for(int j=0;j<itemRev.size();j++)
		{
			tag_t rev=itemRev[j];
			int num=0;tag_t *releaseTags=NULLTAG;
			ITKCALL(ifail=AOM_ask_value_tags(rev,"release_status_list",&num,&releaseTags));
			for(int k=0;k<num;k++)
			{
				char *releaseName=NULL;
				AOM_ask_value_string(releaseTags[k],"object_name",&releaseName);
				if(strcmp(releaseName,status.c_str())==0)
				{
					removeReleaseStatusByName(status,root_task_tag,itemRev);
					cout<<"mark2"<<endl;
					removeRevFromTask(root_task_tag,itemRev);
				}
				if(releaseName!=NULL)
				{
					MEM_free(releaseName);
					releaseName=NULL;
				}
			}
			if(releaseTags!=NULL)
			{
				MEM_free(releaseTags);
				releaseTags=NULL;
			}
		}
		
	}

	cout<<"mark3"<<endl;
	POM_AM__set_application_bypass(false);
	cout<<"mark4"<<endl;

	}
	return 0;
}