#include <tc\tc.h>
#include <property\propdesc.h>
#include <epm\epm.h>
#include <epm\epm_toolkit_tc_utils.h>
#include <tccore\item.h>
#include <tccore\grmtype.h>
#include <tccore\grm.h>
#include <tccore\imantype.h>
#include <sa\am.h>
#include <tccore\aom.h>
#include <tccore\aom_prop.h>
#include <property\prop_errors.h>
#include <tccore\workspaceobject.h>
#include <ics\ics.h>
#include <ics\ics2.h>
#include <qry\qry.h>
#include <epm\signoff.h>
#include <direct.h>
#include <pom\pom\pom.h>
#include <pom\pom\pom_errors.h>
#include <fclasses\tc_date.h>
#include <tc/preferences.h>
#define MAX_PATH_LENGTH 2000
/******************************************************
* @headerfile			standard c & cpp header files
********************************************************/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <iostream>
#include <algorithm>

#include "epm_handler_common.h"
#include "error_handling.h"
#include "common_itk_util.h"
#include "string_helper.h"
#include "ocilib.h"
#include "erp_utils.h"
using namespace std;

FILE* jklogFile = NULL;

void jk2_CreateLogFile(char* FunctionName)
{
	int i=0, ifail = ITK_ok;
	date_t status_now;
	//char* date_string = NULL;
	char date_string[MAX_PATH_LENGTH];
	char logFileDir[MAX_PATH_LENGTH];
	char logFileName[MAX_PATH_LENGTH];

	char* session_uid = NULL;
	tag_t session_tag = NULLTAG;
	time_t now;
	struct tm *p;

	time(&now);

	jklogFile = NULL;
	//current_time(&status_now);
	p=localtime(&now); 

	memset(date_string, 0, sizeof(date_string));
	sprintf(date_string,"%4d%02d%02d%02d%02d%02d",1900+p->tm_year,p->tm_mon+1 ,p->tm_mday ,p->tm_hour,p->tm_min ,p->tm_sec );
	//if( DATE_date_to_string( status_now, "%Y%m%d%H%M%S", &date_string) != ITK_ok )
	//ifail = ITK_date_to_string (status_now, &date_string );
	//if (ifail)
	//{
	//	printf("!*ERROR*!: Failed to get current date time\n");
	//	goto CLEANUP;
	//}

	memset(logFileDir, 0, sizeof(logFileDir));
	memset(logFileName, 0, sizeof(logFileName));
	//get log dir
	sprintf(logFileDir, "%s", getenv("TC_USER_LOG_DIR"));
	printf("\n log file dir: %s\n", logFileDir);
	//try to change dir to TC_USER_LOG_DIR
	if(chdir(logFileDir)!=ITK_ok)
	{
		//not set TC_USER_LOG_DIR
		//log in to default TC_LOG
		memset(logFileDir, 0, sizeof(logFileDir));
		sprintf(logFileDir, "%s", getenv("TEMP"));
		printf("\n TC_USER_LOG_DIR invalide, log file dir: %s\n", logFileDir);
		if(chdir(logFileDir)!=ITK_ok)
		{
			//still can not change to log dir
			printf("!*ERROR*!: Failed to change dir to TC_USER_LOG_DIR\n");
			goto CLEANUP;
		}
	}
	
	//get session_uid to make sure the log file name unique
	POM_ask_session(&session_tag);
	ITK__convert_tag_to_uid(session_tag, &session_uid);
	

	//get logFileName
	sprintf(logFileName, "%s_%s_%s.log", FunctionName, session_uid, date_string);
	printf("log file name: %s\n", logFileName);

	//for(i = 0; _access((char *)logFileName, 4) == 0; i++)
	{
		memset(logFileName, 0, sizeof(logFileName));
		sprintf(logFileName, "%s_%s_%s_%d.log", FunctionName, session_uid, date_string, i);
	}
	printf("final log file name: %s\n", logFileName);

	//create log file
	jklogFile = fopen(logFileName, "w");	

CLEANUP:
	//DOFREE(date_string);
	DOFREE(session_uid);
}
int jk_AutoSign_Handler(EPM_action_message_t msg){
	int ifail = ITK_ok,arg_cnt=0,i=0;
	tag_t root_task =NULLTAG;
	char arg1value[1024] = "",arg2value[1024] = "",arg3value[1024]="",arg4value[1024]="";
	char *argflag =NULL,*argvalue=NULL ,*arg = NULL;
	char *rootTaskUid = NULL;
	char sql[4000] ="\0";
	char ** sqlArgs =NULL ;
//	char tc_log_file_name[128]="\0";    //日志文件路径
	int sqlArgsCount = 9;

	vector<string> pref_vec ;

	time_t				now;
	struct				tm *p;
	time(&now);
	p = localtime(&now);
//	sprintf(tc_log_file_name, "%s\\tx_AutoSign_log_[%d-%d-%d-%d-%02d].txt",getenv("TEMP"),1900+p->tm_year,p->tm_mon+1 ,p->tm_mday,p->tm_hour,p->tm_min  );
//	printf("tc_log_file_name=%s\n",tc_log_file_name);
//	tx_CreateLogFile(tc_log_file_name);

	//TODO  首选项配置
	getPrefStrings("jk_AutoSign_DB_Configer",TC_preference_site, pref_vec);
	if(pref_vec.size() < 3){
//		WriteLog("ERROR:没有获取到首选项[AutoSign_DB_Configer]\n");
//		CloseLog();
		return ifail;
	}
	if(ConnServer((char*)pref_vec[0].c_str(),(char*)pref_vec[1].c_str(),(char*)pref_vec[2].c_str()) == -1){
//		WriteLog("ERROR:ORACLE数据库登录失败\n");
//		CloseLog();
		return ifail;
	}
		cout<<"1-------------------------"<<endl;
	arg_cnt = TC_number_of_arguments(msg.arguments);
		cout<<"2-------------------------"<<endl;

//	WriteLog("INFO:参数个数为：%d",arg_cnt);
	if (arg_cnt > 0)
	{
		cout<<"3-------------------------"<<endl;

		for (i=0;i<arg_cnt;i++)
		{
		cout<<"4-------------------------"<<endl;

			arg = TC_next_argument(msg.arguments);
		cout<<"5-------------------------"<<endl;

			ITKCALL(ifail = ITK_ask_argument_named_value((const char*)arg, &argflag, &argvalue));
			if (stricmp(argflag, "SignUserName") == 0)
			{
				if(argvalue != NULL)
				{
					strcpy(arg1value,argvalue);//把argvalue值赋值到arg1value中
//					WriteLog("INFO:SignUserName=%s",arg1value);
				}
			}
			else if(stricmp(argflag, "SignDate") == 0)
			{
				if(argvalue != NULL)
				{
					strcpy(arg2value,argvalue);
//					WriteLog("INFO:SignDate=%s",arg2value);
				}
			}
			else if(stricmp(argflag,"SignDateFormat") == 0)
			{
				if(argvalue != NULL)
				{
					strcpy(arg3value,argvalue);
//					WriteLog("INFO:SignDateFormat=%s",arg3value);
				}
			}else if (stricmp(argflag, "SignName") == 0)
			{
				if(argvalue != NULL)
				{
					strcpy(arg4value,argvalue);
//					WriteLog("INFO:SignName=%s",arg4value);
				}
			}
		cout<<"6-------------------------"<<endl;

		}
		MEM_free(argflag);
		MEM_free(argvalue);
	}
	ITKCALL(EPM_ask_root_task( msg.task, &root_task ));
	ITK__convert_tag_to_uid(root_task,&rootTaskUid);
//	WriteLog("INFO:ProcessUid=%s",rootTaskUid);
	//增加发起者 开始日期 作业名
	char *job_name=NULL;
	ITKCALL(ifail=AOM_ask_value_string(root_task,"job_name",&job_name));
	date_t date_t_i;
	ITKCALL(ifail=AOM_ask_value_date(root_task,"fnd0StartDate",&date_t_i));
	char shijain[100]="";
	sprintf(shijain,"%d年%d月%d日 %d分%d秒",date_t_i.year,date_t_i.month +1,date_t_i.day,date_t_i.hour,date_t_i.minute);
	string timeString=shijain;
	cout<<"7-------------------------"<<endl;
	//	WriteLog("INFO:ProcessUid=%s",rootTaskUid);
	tag_t owning_user;
	cout<<"8-------------------------"<<endl;
	ITKCALL(ifail=AOM_ask_value_tag(root_task,"owning_user",&owning_user));
	cout<<"9-------------------------"<<endl;
	char *user_name=NULL;
	ITKCALL(ifail=AOM_ask_value_string(owning_user,"user_name",&user_name));
	cout<<"user_name---------"<<user_name<<endl;
	string usernameString=user_name;
	sqlArgs = (char **)MEM_alloc(9*sizeof(char*));

	for(i = 0;i < sqlArgsCount;i++){
		sqlArgs[i] = (char *)MEM_alloc(1028*sizeof(char));
	
	}
	
	strcpy(sqlArgs[0],rootTaskUid);
	strcpy(sqlArgs[1],arg1value);
	strcpy(sqlArgs[2],arg2value);
	strcpy(sqlArgs[3],arg3value);
	strcpy(sqlArgs[4],arg4value);
	strcpy(sqlArgs[5],"0");
	strcpy(sqlArgs[6],job_name);
	cout<<"9.1-------------------------"<<endl;
	strcpy(sqlArgs[7],timeString.c_str());
	cout<<"9.2-------------------------"<<endl;
	strcpy(sqlArgs[8],usernameString.c_str());
	cout<<"10-------------------------"<<endl;
	sprintf(sql,"INSERT INTO JK_PCN_AUTOSIGN ( PUID , SIGN_NAME_INFO , SIGN_DATE_INFO , SIGN_DATE_FORMATE , SIGN_NAME , PSTATUS, JOB_NAME, START_DATE, USER_NAME ) VALUES ( :1 , :2 , :3 , :4 , :5 , :6 , :7 , :8 , :9)");
	cout<<"11-------------------------"<<endl;
	if(-1 == ExecuteSQL(sql,sqlArgsCount,sqlArgs)){
		cout<<"12-------------------------"<<endl;
//		WriteLog("ERROR:写入数据库失败");
	}else{
//		WriteLog("INFO:写入数据库成功");
	}
	
	for(i = 0;i < sqlArgsCount;i++){
		MEM_free(sqlArgs[i]);
	}
	MEM_free(rootTaskUid);
	MEM_free(sqlArgs);
	if(user_name!=NULL)
	{
		MEM_free(user_name);
		user_name=NULL;
	}
	if(job_name!=NULL)
	{
		MEM_free(job_name);
		job_name=NULL;
	}
	sqlArgs = NULL;
	DisConnServer();
	CloseLog();
	return ifail;
}