package weaver.interfaces.htsc.GlobatTools.workflow;

import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.MessageDetailLog;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * @ClassName: WorkflowCreateHandler
 * @Description: TODO
 * {异构系统创建ecology工作流的辅助类,
 * 支持ecology7.x-ecology8.1所有版本的ecology的创建工作流
 * }
 * @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);

        String DatetimeStr=new SimpleDateFormat("yyyyMMdd").format(new Date());
        workflowtitle.append(findWorkflowName(""+workflowid)+"--"+DatetimeStr);
        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("-----创建流程传递的参数个数--------");
        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);

        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;
    }


    public String WorkflowCreateByRequestMap(String creatorId ,
                                             String workflowId ,
                                             String requestName ,
                                             String IsNextFlow,
                                             Map<String,String> requestMainMap,
                                             String DetailNo,
                                             List< Map<String,String>> detailist)
    {
     String requestid= WorkflowCreateByRequestMap(creatorId,workflowId,requestName,IsNextFlow,requestMainMap);
        if("".equals(DetailNo)||detailist==null||detailist.size()<0){
            return "";
        }
       String detailname= JAVATools.getdetailtable(requestid,DetailNo);
        String mainid= JAVATools.getMaintableid(requestid);
        for ( Map<String,String> detailmap:detailist) {
            excetesqlvoid(detailmap,detailname,mainid);
        }
        return requestid;
    }

        private void excetesqlvoid(  Map<String,String> mapvalue,String table,String mainid){

        String dttablename="";
        String dttablenvalue="";
          List<String> list=new ArrayList<>();
        for (Map.Entry<String, String> entry : mapvalue.entrySet())
        {
            String fieldname = Util.null2String(entry.getKey());
            String fieldvalue = Util.null2String(entry.getValue());
            dttablename += dttablename == "" ? fieldname : "," + fieldname;
            dttablenvalue += dttablenvalue == "" ? "?" : ",?";
            list.add(lengthmax(fieldvalue.replace("\r\n","")));
        }
            dttablename += dttablename == "" ? "mainid" : "," + "mainid";
            dttablenvalue += dttablenvalue == "" ? "?" : ",?";
            list.add(mainid);
            String sql = "insert into "+table+"("+dttablename+") values("+dttablenvalue+")";
            System.out.println(sql);
            RecordSet rs = new RecordSet();
        try {
            rs.executeUpdate(sql,new Object[]{list});
        }catch (Exception exo){

            exo.printStackTrace();
            new BaseBean().writeLog("存入明细表数数据报错:"+exo.getMessage());
        }

    }

    public String lengthmax(String value){
        if("".equals(value)) return "";
        if(value.length()>4000){
            value=value.substring(0,3999);
        }
        return  value;
    }

}
