package com.customization.htsc.autonode;


import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.workflow.cmd.requestForm.RequestManager_FlowNextNodeCmd;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by dengjp
 * 自由节点，标题显示问题修改 #HTO-1520#
 *
 * 功能1： 自由节点，标题显示问题
 * 1.会签部门负责人审核、会签部门内部审核节点名称修改为会签部门
 * 2.跨公司会签负责人审核、跨公司会签内部审核节点名称修改为跨公司会签
 * 2020/12/18
 *
 * 功能2： 判斷自由节点是否生成成功，如果没有生成成功回滚
 */
@CommandDynamicProxy(target = RequestManager_FlowNextNodeCmd.class, desc = "自动节点扩展")
public class AutoNodeFlowNextNodeCmd extends AbstractCommandProxy<Boolean> {

    @Override
    public Boolean execute(Command<Boolean> targetCommand) {
        BaseBean beanBean = new BaseBean();
        PropBean propbean = new PropBean();
        try {
            beanBean.writeLog("进入拦截");
            HttpServletRequest request = ((RequestManager_FlowNextNodeCmd) targetCommand).getRequestManager().getRequest();
            String requestId = Util.null2String(request.getParameter("requestid"));
            String workflowid = Util.null2String(request.getParameter("workflowid"));
            String workflowunnumber = propbean.getWorkflowUnNumberByid(workflowid);
            beanBean.writeLog("流程的requestId： " + requestId);

            //执行标准的业务处理
            Boolean result = nextExecute(targetCommand);
            beanBean.writeLog("当前节点 result : " + result);

            // 判断自由节点是否插入成功

            try{
                if(Util.getIntValue(requestId) > 0)
                {
                    this.rollbackFreeNode(result, requestId);
                    // 修改自由节点标题显示问题
                    if(result)
                    {
                        RecordSet rs = new RecordSet();
                        String status = "";
                        String currentnodeid = "";
                        // 先获取原先status
                        String selectSql = "select status, currentnodeid from workflow_requestbase where requestid=?";
                        rs.executeQuery(selectSql, requestId);
                        if(rs.next()){
                            status = Util.null2String(rs.getString("status"));
                            currentnodeid = Util.null2String(rs.getString("currentnodeid"));
                        }
                        beanBean.writeLog("当前节点 status : " + status + " currentnodeid9999： " + currentnodeid);
                        // 如果当前节点是自由节点，修改workflow_requestbase的status字段该为当前节点的nodename
                        //   if ("~`~`7 自由节点`~`8 Free Nodes`~`~".equals(status)) {
                        if (Integer.parseInt(currentnodeid)<0)
                        {
                            String formid = getTableByRequestid(requestId);
                            beanBean.writeLog("formid:"+formid);

                            if(!"".equals(formid))
                            {
                                String table = "formtable_main_" ;
                                String tablename = table + formid;
                                beanBean.writeLog("查看sqltablename："+tablename);
                                String xybz = "";
                                String sqlsum = "select xybz  from "+tablename+" where requestid="+requestId+" and xybz in (0,1,6)";
                                beanBean.writeLog("sql999："+sqlsum);
                                rs.execute(sqlsum);
                                if(rs.next()){
                                    xybz = Util.null2String(rs.getString("xybz"));
                                }
                                beanBean.writeLog("xybz："+xybz);
                                String shq = propbean.getPropName("nodename_shq");
                                String kgshq = propbean.getPropName("nodename_kgshq");
                                String yzgsbm = propbean.getPropName("nodename_yzgsbm");
                                String nodeName = "";
                                if("0".equals(xybz))
                                {
                                    nodeName = shq;
                                }
                                if("1".equals(xybz))
                                {
                                    nodeName = kgshq;
                                }


//                                if("6".equals(xybz))
//                                {
//                                    nodeName = yzgsbm;
//                                }

                                if("itlxsq".equals(workflowunnumber))
                                {
                                    String ysxgbm = propbean.getPropName("nodename_ysxgbm");
                                    if("10".equals(xybz))
                                    {
                                        nodeName = ysxgbm;
                                    }
                                }
                                if("jgzxzysx".equals(workflowunnumber)||"fzjgzysx".equals(workflowunnumber)||"fzjgyy".equals(workflowunnumber)||"zbyy".equals(workflowunnumber)){
                                    String jdfl = "";
                                    String jdmc = "";
                                    String sql = "select jdfl,jdmc from uf_qzyjhqb where lcid = '"+requestId+"' and freenode like '%"+currentnodeid+"%'";
                                    beanBean.writeLog("sql："+sql);
                                    rs.execute(sql);
                                    if(rs.next()){
                                        jdfl = Util.null2String(rs.getString("jdfl"));
                                        jdmc = Util.null2String(rs.getString("jdmc"));
                                    }
                                    String yzgsbm_jdfl = propbean.getPropName("jdfl.yzgsbm");
                                    if(yzgsbm_jdfl.equals(jdfl)){
                                        sql = "select nodename from workflow_freenode where requestid = '"+requestId+"' and id = '"+currentnodeid+"'";
                                        beanBean.writeLog("sql："+sql);
                                        rs.execute(sql);
                                        if(rs.next()){
                                            nodeName = Util.null2String(rs.getString("nodename"));
                                        }
                                    }else if(StringUtils.isNotEmpty(jdmc)){
                                        nodeName = jdmc;
                                    }
                                }

                                if("itxqsq".equals(workflowunnumber))
                                {
                                    String ysxgbm = propbean.getPropName("itxqlc_xqjsrfs_nodename");
                                    nodeName = ysxgbm;
                                }
                                if("jgxtsq".equals(workflowunnumber))
                                {
                                    if("7".equals(xybz)){
                                        String ysxgbm = propbean.getPropName("jgxt_fs_zbnodename");
                                        nodeName = ysxgbm;
                                    }else if("6".equals(xybz)){
                                        String ysxgbm = propbean.getPropName("jgxt_fs_yybnodename");
                                        nodeName = ysxgbm;
                                    }

                                }
                                if("mbwj".equals(workflowunnumber))
                                {
                                    if("0".equals(xybz)){
                                        String ysxgbm = propbean.getPropName("wdzx.fs.xtfzrname");
                                        nodeName = ysxgbm;
                                    }else if("1".equals(xybz)){
                                        String ysxgbm = propbean.getPropName("wdzx.fs.xgbmname");
                                        nodeName = ysxgbm;
                                    }
                                }


                                if(nodeName!="")
                                {
                                    beanBean.writeLog("更新request base 的 status: " + status + ", 更新为 nodename: " + nodeName);
                                    beanBean.writeLog("更新操作");
                                    String updateFreeNode = " update workflow_requestbase set status = ? where requestid=?";
                                    boolean updated = rs.executeUpdate(updateFreeNode, nodeName, requestId);
                                    if (updated) {
                                        beanBean.writeLog("更新成功:"+updateFreeNode+"nodeName"+nodeName+"requestid"+requestId);
                                    } else {
                                        beanBean.writeLog("更新失败:"+updateFreeNode+"nodeName"+nodeName+"requestid"+requestId);
                                    }
                                }

                            }
                        }
                    }
                }
            }catch (Exception e){
                beanBean.writeLog("AutoNodeFlowNextNodeCmd-e:"+e);
            }
            return result;
        } catch (Exception e) {

            Boolean result = nextExecute(targetCommand);
            beanBean.writeLog("当前节点 result : " + result);

            e.printStackTrace();
            beanBean.writeLog("更新自由节点失败:" + e.getMessage());
            //执行标准的业务处理
            return result;
        }
    }

    /**
     * 判断自由节点是否生成成功，如果生成成功，讲uf_qzyjhqb表的zt字段该为1，
     * 如果失败讲uf_qzyjhqb表中zt为null且requestid对应的数据删除
     * @param resultStatus 原始cmd状态
     * @param requestid requestid
     */
    private boolean rollbackFreeNode(Boolean resultStatus, String requestid) {
        BaseBean baseBean = new BaseBean();
        try {
            RecordSet rs = new RecordSet();
            String id = "";
            String sql = " select id from uf_qzyjhqb where lcid=? and zt is null";
            rs.executeQuery(sql,new Object[]{requestid});
            if(rs.next()){
                id = Util.null2String(rs.getString("id"));
            }
            if(!"".equals(id))
            {
                if(resultStatus)
                {
                    // 插入自由节点成功，将zt字段设为1
                    String updateSql = "update uf_qzyjhqb set zt = '1' where LCID = ?";

                    rs.executeUpdate(updateSql, requestid);
                    baseBean.writeLog("requestid "+requestid+" : "+"插入自由节点成功，将zt字段设为1");
                }else {
                    // 回滚数据
                    String deletenodeflow=" delete from workflow_freenode where id in ( select freenode from uf_qzyjhqb where zt is null and LCID =? )";
                    rs.executeUpdate(deletenodeflow, requestid);
                    String deleteSql = " delete from uf_qzyjhqb where zt is null and LCID = ?";
                    rs.executeUpdate(deleteSql, requestid);
                    baseBean.writeLog("requestid "+requestid+" : "+"插入自由节点失败，回滚数据");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            baseBean.writeLog("回滚自由节点失败");
        }
        return resultStatus;
    }


    public String getTableByRequestid(String requestid){
        String formid = "";
        try{
            RecordSet rs = new RecordSet();
            String sql =" select abs(t.formid) as formid \n" +
                    " from workflow_base t\n" +
                    " inner join workflow_requestbase l on l.workflowid = t.id\n" +
                    " where l.requestid="+requestid+"" ;
            rs.execute(sql);
            if(rs.next()){
                formid = Util.null2String(rs.getString("formid"));
            }
        }catch (Exception e){
            new BaseBean().writeLog("getTableByRequestid-e:"+e);
        }
        return formid;
    }

}
