package com.engine.tjyh.xc.util;

import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.*;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 
 * @ClassName: WorkflowCreateHandler 
 * @Description: TODO
 * }
 * @author shil
 * @date 2020-03-25 下午5:03:03
 *
 */
public class WorkflowCreateHandler extends BaseBean {

	public WorkflowCreateHandler() {
		super();
	}

	/***
	 *
	 * @param workflowid
	 * @return
	 */
	public String findWorkflowForm(String workflowid)
	{
		String tablename = "";
		String cDandT = TimeUtil.getCurrentDateString()+" "+ TimeUtil.getCurrentTimeString();
		RecordSet ws = new RecordSet();
		ws.execute("select t2.tablename from workflow_base t1,workflow_bill t2 where t2.id=t1.formid and t1.id ='"+workflowid+"'");
		if(ws.next()){
			tablename = Util.null2String(ws.getString("tablename"));
		}else{
			tablename = "-1";
			writeLog("shauter 当前时间:"+cDandT+"-workflowid="+workflowid+"-没有设置表单");
		}
		return tablename;

	}
	
	/**
	 * 
	 * @Title: bulidWorkflowTitle 
	 * @Description: TODO(构建流程标题) 
	 * @param @param workflowid
	 * @param @param creatorid
	 * @param @return    设定文件 
	 * @return String    返回类型 
	 * @throws
	 */
	public String bulidWorkflowTitle(String workflowid,String creatorid)
	{
		StringBuffer workflowtitle=new StringBuffer("");
		ResourceComInfo ResourceComInfo = null;
		try {
			ResourceComInfo = new ResourceComInfo();
		} catch (Exception e) {
			e.printStackTrace();
		}
		String latsname = ResourceComInfo.getLastname(creatorid);
		workflowtitle.append(findWorkflowName(""+workflowid)+"--"+latsname);
		return workflowtitle.toString();
	}
	
	/**
	 * 
	 * @Title: findWorkflowName 
	 * @Description: TODO(获取流程名称) 
	 * @param @param workflowid
	 * @param @return    设定文件 
	 * @return String    返回类型 
	 * @throws
	 */
	public String findWorkflowName(String workflowid){
		String workflowname="";
		WorkflowComInfo WorkflowComInfo = null;
		try {
			WorkflowComInfo = new WorkflowComInfo();
			workflowname = WorkflowComInfo.getWorkflowname(""+workflowid);
		} catch (Exception e) {
			e.printStackTrace();
			workflowname ="-1";
		}
		return workflowname;
	}
	
	/**
	 * 
	 * @Title: findDataIDByReqID 
	 * @Description: TODO(获取表单数据id) 
	 * @param @param workflowid
	 * @param @param requestid
	 * @param @return    设定文件 
	 * @return String    返回类型 
	 * @throws
	 */
	public String findDataIDByReqID(String workflowid,String requestid){
		String dataid="";
		RecordSet rs = new RecordSet();
	    rs.execute("select id from "+findWorkflowForm(workflowid)+" where requestid='"+requestid+"' ");
		rs.next();
		dataid = Util.null2String(rs.getString(1));
	    return dataid;
	}
	/**
	 * 
	 * @Title: expoundRequest 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param @param requestid
	 * @param @return    设定文件 
	 * @return String    返回类型 
	 * @throws
	 */
	
	public String expoundRequest(String requestid)
	{
		writeLog("--------------requestid:"+requestid);
		String dec = "";
		int ireqid = Util.getIntValue(requestid, 0);
	    if(ireqid>0){
	    	
	    }else if(ireqid==-1){
        	dec = "创建流程失败";
	    }else if(ireqid==-2){
        	dec = "用户没有流程创建权限";
	    }else if(ireqid==-3){
        	dec = "创建流程基本信息失败";
	    }else if(ireqid==-4){
        	dec = "保存表单主表信息失败";
	    }else if(ireqid==-5){
        	dec = "更新紧急程度失败";
	    }else if(ireqid==-6){
        	dec = "流程操作者失败";
	    }else if(ireqid==-7){
        	dec = "流转至下一节点失败";
	    }else if(ireqid==-8){
        	dec = "节点附加操作失败";
	    }
	    return dec;
	}

	/**
	 * 
	 * @Title: WorkflowCreateByMainTableMap 
	 * @param @param creatorId    创建人Id
	 * @param @param workflowId   流程Id
	 * @param @param requestName  请求标题
	 * @param @param IsNextFlow   是否提交到下一节点
	 * @param @param requestMap   Map格式的主表数据<fieldname,fieldvalue>=<字段名称,字段值>
	 * @param @return    设定文件 
	 * @return String    返回类型 
	 * @throws
	 */
	public String WorkflowCreateByRequestMap(String creatorId ,String workflowId ,String requestName ,String IsNextFlow,Map<String,String> requestMainMap)
	{
		writeLog("creatorId:"+creatorId);
		writeLog("workflowId:"+workflowId);
		writeLog("requestName:"+requestName);
		writeLog("IsNextFlow:"+IsNextFlow);
		
		String requestid = "";
		RequestInfo requestInfo = new RequestInfo();
		requestInfo.setCreatorid(creatorId);//创建人Id
		requestInfo.setWorkflowid(workflowId);//工作流Id
		requestInfo.setDescription(requestName);//请求标题
		requestInfo.setRequestlevel("0");
		if(!"".equals(IsNextFlow))
		{
			requestInfo.setIsNextFlow(IsNextFlow);
		}
		
		//主表字段
		MainTableInfo mainTableInfo = new MainTableInfo();
		Property[] propertyArray = new Property[requestMainMap.size()];
		int p = 0;
		for (Entry<String, String> entry : requestMainMap.entrySet()) 
		{
			 propertyArray[p] = new Property();
			 propertyArray[p].setName(Util.null2String(entry.getKey()));
			 propertyArray[p].setValue(Util.null2String(entry.getValue()));
			 writeLog("\r\n---p="+p+"---Key="+entry.getKey()+"---Value="+entry.getValue());
			 p++;
		}
		writeLog("-----创建流程传递的参数个数p="+p);
		mainTableInfo.setProperty(propertyArray);
		requestInfo.setMainTableInfo(mainTableInfo);
		RequestService service = new RequestService();

		try {
			//流程
			try {
				requestid = service.createRequest(requestInfo);//创建请求id
			} catch (Exception e) {
				writeLog("======="+e.getMessage());
			}
		    //记录日志
		    StringBuffer sbf = new StringBuffer("\r\n---创建工作流记录日志开始");
		    WorkflowComInfo wfcif =new WorkflowComInfo();
		    RequestComInfo rcif = new RequestComInfo();
		    ResourceComInfo rscif = new ResourceComInfo();
		    sbf.append("\r\n-----姓名:"+rscif.getLastname(rcif.getRequestCreater(requestid)));
		    sbf.append("\r\n-----时间:"+rcif.getRequestCreateTime(requestid));
		    sbf.append("\r\n-----创建流程:"+wfcif.getWorkflowname(workflowId));
		    sbf.append("\r\n-----请求:"+rcif.getRequestname(requestid));
		    sbf.append("\r\n-----请求:"+requestid);
		    sbf.append("\r\n-----创建工作流记录日志结束");
		    writeLog(sbf.toString());
		    System.out.println(""+sbf.toString());
		} catch (Exception e) {
			writeLog("错误：" + e);
			System.out.println("错误：" + e);
		}
		return requestid;
	}



	/***
	 *
	 * @param ireqid
	 * @param detailList
	 * @param tablename
	 * @param dataid
	 * @return
	 */
	public String insertTableDt1(int ireqid, List<Map<String,String>> detailList, String tablename, String dataid, Set<String> fileSet)
	{
		String message = "0" ;
		if(!"".equals(dataid) && dataid !=null)
		{
			RecordSet rs = new RecordSet();
			//插入明细表
			String tablename_dt1 = tablename+"_dt1";		//明细表名
			for(Map<String,String> detailMap : detailList)
			{
				String dttablename = "" ;
				String dttablenvalue = "" ;
				for (Entry<String, String> entry : detailMap.entrySet())
				{
					String fieldname = Util.null2String(entry.getKey());
					String fieldvalue = Util.null2String(entry.getValue());

					dttablename += dttablename==""? fieldname :","+fieldname ;
					if(fileSet.contains(fieldname))
					{
						dttablenvalue += dttablenvalue == "" ? fieldvalue : ","+fieldvalue ;
					}else{
						dttablenvalue += dttablenvalue == "" ? "'"+fieldvalue.replace("'", "''").trim()+"'" : ",'"+fieldvalue.replace("'", "''").trim()+"'" ;
					}
				}
				writeLog("dttablename:"+dttablename);
				writeLog("dttablenvalue:"+dttablenvalue);
				if(dttablename !="" && dttablenvalue !="")
				{
					String sql = "insert into "+tablename_dt1+" (mainid,"+dttablename+") values ("+dataid+","+dttablenvalue+")";
					writeLog(sql);
					boolean boo = rs.execute(sql);
					if(!boo)
					{
						message = "-1" ;
					}
				}else{
					message = "-2" ;
				}
			}
		}else{
			message = "-3" ;
		}
		return message;
	}

	/**
	 *
	 * @param detailList
	 * @param tablename
	 * @param dataid
	 * @return
	 */
	public String insertTableDtMX(List<Map<String,String>> detailList, String tablename, String dataid,Set<String> fileSet)
	{
		String message = "0" ;
		if(!"".equals(dataid) && dataid !=null)
		{
			RecordSet rs = new RecordSet();
			//插入明细表
			String tablename_dt = tablename;
			writeLog("tablename_dt="+tablename_dt);
			for(Map<String,String> detailMap : detailList)
			{
				String dttablename = "" ;
				String dttablenvalue = "" ;
				try {

					for (Entry<String, String> entry : detailMap.entrySet()) {
						String fieldname = Util.null2String(entry.getKey());
						String fieldvalue = "'" + Util.null2String(entry.getValue()) + "'";

						dttablename += dttablename == "" ? fieldname : "," + fieldname;
						if (fileSet.contains(fieldname)) {
							dttablenvalue += dttablenvalue == "" ? fieldvalue : "," + fieldvalue;
						} else {
							dttablenvalue += dttablenvalue == "" ? "'" + fieldvalue.replace("'", "''").trim() + "'" : ",'" + fieldvalue.replace("'", "''").trim() + "'";
						}
					}
				}catch (Exception e){
					System.out.println(e.toString());
					e.printStackTrace();
				}
				writeLog("dttablename:"+dttablename);
				writeLog("dttablenvalue:"+dttablenvalue);
				if(dttablename !="" && dttablenvalue !="")
				{
					String sql = "insert into "+tablename_dt+" (mainid,"+dttablename+") values ("+dataid+","+dttablenvalue+")";
					writeLog(sql);
					boolean boo = rs.execute(sql);
					if(!boo)
					{
						message = "-1" ;
					}
				}else{
					message = "-2" ;
				}
			}
		}else{
			message = "-3" ;
		}
		return message;
	}

	/***
	 *
	 * @param requestid
	 * @param formtable
	 * @param requestMap
	 * @return
	 */
	public String updateWorkflowBySap(String requestid, String formtable, Map<String,String> requestMap)
	{
		RecordSet rs = new RecordSet();
		BaseBean bb = new BaseBean();
		String msg = "" ;
		try{
			String tableset = "" ;
			for (Entry<String, String> entry : requestMap.entrySet())
			{
				String fieldname = Util.null2String(entry.getKey()).trim();
				String fieldvalue = Util.null2String(entry.getValue()).replace("'", "''").trim();
				tableset += tableset =="" ? fieldname+"='"+fieldvalue.replace("'", "''").trim()+"'" :","+fieldname+"='"+fieldvalue.replace("'", "''").trim()+"'" ;
			}
			if(!"".equals(tableset))
			{
				String sql = " update "+formtable+" set "+tableset+" where requestid="+requestid;
				bb.writeLog("sql:"+sql);
				boolean flag = rs.executeUpdate(sql);
				if(flag){
					msg = "1";
				}else{
					msg = "0";
				}
			}else{
				msg = "-1";
			}
		}catch (Exception e){
			msg = "-1";
		}
		bb.writeLog("msg:"+msg);
		return msg;
	}

	/***
	 *
	 * @param detailList
	 * @param detailid
	 * @return
	 */
	public DetailTableInfo queryDetailTableInfo(List<Map<String,String>> detailList,String detailid){
		DetailTableInfo dti = new DetailTableInfo();
		if("".equals(detailid)){
			return dti;
		}

		List<DetailTable> detailtables = new ArrayList<DetailTable>();
		DetailTable dt = new DetailTable();
		dt.setId(detailid);
		List<Row> rows = new ArrayList<Row>();

		for(int i=0;i<detailList.size();i++)
		{
			Map<String,String> detailMap = detailList.get(i);
			Row r = new Row();
			List<Cell> cells = new ArrayList<Cell>();
			for (Entry<String, String> entry : detailMap.entrySet())
			{
				String fieldname = Util.null2String(entry.getKey()).trim();
				String fieldvalue = Util.null2String(entry.getValue()).replace("'", "''").trim();
				Cell c = new Cell();
				c.setName(fieldname);
				c.setValue(fieldvalue);
				cells.add(c);
			}

			Cell[] ca = new Cell[cells.size()];
			cells.toArray(ca);
			r.setCell(ca);
			rows.add(r);
		}

		Row[] ra = new Row[rows.size()];
		rows.toArray(ra);
		dt.setRow(ra);
		detailtables.add(dt);

		DetailTable[] dta = new DetailTable[detailtables.size()];
		detailtables.toArray(dta);
		dti.setDetailTable(dta);

		return dti;
	}

	/***
	 *
	 * @param creatorId
	 * @param workflowId
	 * @param requestName
	 * @param IsNextFlow
	 * @param requestMainMap
	 * @param detailList
	 * @return
	 */
	public String WorkflowCreateByRequestMap2(String creatorId ,String workflowId ,String requestName ,String IsNextFlow,Map<String,String> requestMainMap,List<Map<String,String>> detailList)
	{
		writeLog("-----创建流程传递的参数个数--------");
		writeLog("creatorId:"+creatorId);
		writeLog("workflowId:"+workflowId);
		writeLog("requestName:"+requestName);
		writeLog("IsNextFlow:"+IsNextFlow);

		String requestid = "";
		RequestInfo requestInfo = new RequestInfo();
		requestInfo.setCreatorid(creatorId);//创建人Id
		requestInfo.setWorkflowid(workflowId);//工作流Id
		requestInfo.setDescription(requestName);//请求标题
		if(!"".equals(IsNextFlow))
		{
			requestInfo.setIsNextFlow(IsNextFlow);
		}

		//主表字段
		MainTableInfo mainTableInfo = new MainTableInfo();
		Property[] propertyArray = new Property[requestMainMap.size()];
		int p = 0;
		for (Entry<String, String> entry : requestMainMap.entrySet())
		{
			propertyArray[p] = new Property();
			propertyArray[p].setName(Util.null2String(entry.getKey()));
			propertyArray[p].setValue(Util.null2String(entry.getValue()));
			writeLog("\r\n---p="+p+"---Key="+entry.getKey()+"---Value="+entry.getValue());
			p++;
		}
		writeLog("-----创建流程传递的参数个数p="+p);
		mainTableInfo.setProperty(propertyArray);
		requestInfo.setMainTableInfo(mainTableInfo);

		if(detailList.size() >0){
			DetailTableInfo detailTableInfo = queryDetailTableInfo(detailList,"1");
			requestInfo.setDetailTableInfo(detailTableInfo);
		}

		RequestService service = new RequestService();
		try {
			//流程
			try {
				requestid = service.createRequest(requestInfo);//创建请求id

			} catch (Exception e) {
				writeLog("======="+e.getMessage());
			}
			//String userId = requestInfo.getLastoperator();//请求最后的操作者
			//记录日志
			StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始");
			WorkflowComInfo wfcif =new WorkflowComInfo();
			RequestComInfo rcif = new RequestComInfo();
			ResourceComInfo rscif = new ResourceComInfo();
			sbf.append("\r\n-----姓名:"+rscif.getLastname(rcif.getRequestCreater(requestid)));
			sbf.append("\r\n-----时间:"+rcif.getRequestCreateTime(requestid));
			sbf.append("\r\n-----创建流程:"+wfcif.getWorkflowname(workflowId));
			sbf.append("\r\n-----请求:"+rcif.getRequestname(requestid));
			sbf.append("\r\n-----请求:"+requestid);
			sbf.append("\r\n-----创建工作流记录日志结束");
			writeLog(sbf.toString());
			System.out.println(""+sbf.toString());
		} catch (Exception e) {
			writeLog("错误：" + e);
			System.out.println("错误：" + e);
		}
		return requestid;
	}

	/***
	 *
	 * @param requestid
	 * @param userid
	 * @return
	 */
	public boolean WorkflowNextNodeBySubmit(int requestid,int userid)
	{
		writeLog("-----创建流程传递的参数个数--------");
		writeLog("requestid:"+requestid);
		boolean istrue = false;

		RequestService service = new RequestService();
		RequestInfo requestInfo = service.getRequest(requestid);
		try {
			istrue = service.nextNodeBySubmit(requestInfo,requestid,userid, "");//创建请求id
		} catch (Exception e) {
			writeLog("======="+e.getMessage());
			istrue = false;
		}
		return istrue;
	}
}
