package weaver.workflow.request;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.api.doc.search.service.OperateService;
import com.api.workflow.util.ServiceUtil;
import com.cloudstore.dev.api.util.Util_TableMap;
import com.engine.kq.biz.KQFlowActiontBiz;
import com.engine.workflow.biz.requestForm.RequestFlowRemindBiz;
import com.engine.workflow.biz.requestList.RequestAttentionBiz;
import com.engine.workflow.biz.workflowCore.WorkflowBaseBiz;
import com.engine.workflow.entity.core.NodeInfoEntity;
import net.freeutils.tnef.msg.Msg;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.conn.constant.DBConstant;
import weaver.cpt.util.CptWfUtil;
import weaver.docs.docs.util.DocumentDeleteSecurityUtil;
import weaver.docs.docs.util.DocumentDeleteStatusMould;
import weaver.docs.docs.util.MouldStatus;
import weaver.fna.general.FnaCommon;
import weaver.general.BaseBean;
import weaver.general.DBColumnTypeUtils;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.attendance.manager.HrmAttVacationManager;
import weaver.hrm.attendance.manager.HrmPaidLeaveManager;
import weaver.systeminfo.SysMaintenanceLog;
import weaver.workflow.monitor.Monitor;
import weaver.workflow.monitor.MonitorDTO;
import weaver.workflow.msg.MsgPushUtil;
import weaver.workflow.msg.PoppupRemindInfoUtil;
import weaver.workflow.msg.entity.MsgEntity;
import weaver.workflow.report.RequestDeleteLog;
import weaver.workflow.workflow.WfFunctionManageUtil;
import weaver.workflow.workflow.WorkflowConfigComInfo;

import java.util.*;
/**
 * 流程删除
 * @ClassName:RequestDeleteUtils
 * @Description:TODO
 * @author wuser0326
 * @date Nov 15, 2016 5:44:09 PM
 *
 */
public class RequestDeleteUtils extends BaseBean {

    private Map<String, RequestDeleteInfo> deleteTableMap;

    private int requestid;
    private RecordSetTrans rst;
    private RequestDeleteLog log;
    private JSONObject delDataInfo;

    private int isbill;
    private int formid;
    private int workflowid;

    private User user;
    private DocumentDeleteSecurityUtil docDeleteUtil = new DocumentDeleteSecurityUtil();
    private String message;
    private String messageContent;

    private void init() {
        RecordSet   rs = new RecordSet();
        delDataInfo = new JSONObject();
        boolean isoracle = rs.getDBType().equals("oracle");
        // 需要复制数据的相关表
        deleteTableMap = new HashMap<String, RequestDeleteInfo>();
        RequestDeleteInfo rdi = new RequestDeleteInfo();
        List<String> clobColumns = new ArrayList<String>();

        // workflow_requestbase
        String queryWhere = " where requestid = " + requestid;
        if (isoracle) {
            clobColumns.add("HRMIDS");
            rdi.setClobColumn(clobColumns);
        }
        rdi.setCopytablename("workflow_requestbase_dellog");
        rdi.setPrimarykey("requestid");
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_requestbase", rdi);

        // workflow_currentoperator
        rdi = new RequestDeleteInfo();
        rdi.setCopytablename("workflow_curroperator_dellog");
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_currentoperator", rdi);

        // workflow_requestLog
        rdi = new RequestDeleteInfo();
        if (isoracle) {
            clobColumns = new ArrayList<String>();
            clobColumns.add("REMARK");
            clobColumns.add("RECEIVEDPERSONS");
            clobColumns.add("RECEIVEDPERSONIDS");
            rdi.setClobColumn(clobColumns);
        }
        rdi.setCopytablename("workflow_requestLog_dellog");
        rdi.setPrimarykey("logid");
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_requestLog", rdi);

        // workflow_nownode
        rdi = new RequestDeleteInfo();
        rdi.setCopytablename("workflow_nownode_dellog");
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_nownode", rdi);

        //删除数据的相关表
        queryWhere = " where exists (select 1 from workflow_requestLog where workflow_requestLog.requestid = " + requestid + " and workflow_requestLog.logid = workflow_logviewusers.logid)";
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_logviewusers", rdi);

        queryWhere = " where id = " + requestid;
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_requestViewLog", rdi);

        queryWhere = " where requestid = " + requestid;
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("Workflow_SharedScope", rdi);

        queryWhere = "where id in (select a.id from (select wgt.id from workflow_groupdetail wgt, workflow_nodegroup wng , workflow_nodebase wnb where wgt.groupid = wng.id and wng.nodeid = wnb.id and wnb.IsFreeNode = '1' and wnb.requestid = " + requestid + ") a)";
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_groupdetail", rdi);

        queryWhere = " where EXISTS(select 1 from workflow_nodebase b where workflow_nodegroup.nodeid=b.id and b.IsFreeNode='1' and b.requestid=" + requestid + ")";
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_nodegroup", rdi);

        queryWhere = " where EXISTS(select 1 from workflow_nodebase b where workflow_nodemode.nodeid=b.id and b.IsFreeNode='1' and b.requestid= " + requestid + ")";
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_nodemode", rdi);

        //queryWhere = " where EXISTS(select 1 from workflow_nodebase b where workflow_nodeform.nodeid=b.id and b.IsFreeNode='1' and b.requestid= " + requestid + ")";
        queryWhere = " join workflow_nodebase b on a.nodeid=b.id  where b.IsFreeNode='1' and b.requestid= " + requestid ;
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_nodeform", rdi);

        queryWhere = " where EXISTS(select 1 from workflow_nodebase b where workflow_flownode.nodeid=b.id and b.IsFreeNode='1' and b.requestid=" + requestid + ")";
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_flownode", rdi);

        queryWhere = " where EXISTS(select 1 from workflow_nodebase b where workflow_nodelink.nodeid=b.id and b.IsFreeNode='1' and b.requestid=" + requestid + ") or EXISTS(select 1 from workflow_nodebase b where workflow_nodelink.destnodeid=b.id and b.IsFreeNode='1' and b.requestid=" + requestid
                + ") or wfrequestid=" + requestid;
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_nodelink", rdi);

        queryWhere = " where IsFreeNode='1' and requestid=" + requestid;
        rdi = new RequestDeleteInfo();
        rdi.setQueryWhere(queryWhere);
        deleteTableMap.put("workflow_nodebase", rdi);

        //获取路径id
        rs.executeQuery("select workflowid from workflow_requestbase where requestid = ? ", requestid);
        if(rs.next()){
            workflowid = rs.getInt(1);
            log.setWorkflowId(String.valueOf(workflowid));
        }

        //初始化表单信息
        rs.executeQuery("select isbill,formid from workflow_base where id = ? ", workflowid);
        if(rs.next()){
            isbill = rs.getInt(1);
            formid  = rs.getInt(2);
        }
    }

    public RequestDeleteUtils() {}


    public RequestDeleteUtils(int requestid, RecordSetTrans rst,RequestDeleteLog log) {
        this.requestid = requestid;
        this.rst = rst;
        this.log = log;
    }

    public RequestDeleteUtils(int requestid, RecordSetTrans rst,RequestDeleteLog log, User user) {
        this.requestid = requestid;
        this.rst = rst;
        this.log = log;
        this.user = user;
    }

    public void executeDeleteRequest() throws Exception{
        RequestOperationMsgManager romm = new RequestOperationMsgManager();
        List<MsgEntity> deleteMsg = romm.requestDeletMsg(String.valueOf(requestid));

        init();
        new RequestFlowRemindBiz().deleteFlowMsgByRequestid(requestid +"");
        executeDeleteAddinOperate();
        updateCodeseqReserved();
        checkAndDeleteAcc();
        deleteBaseTableInfo();
        deleteFormData();
        deletePoppupRemindInfo();
        deleteSubWFRequestInfo();
        //删除表单数据
        log.save(rst);
        String updatesql = "update workflow_requestdeletelog set deletetabledata = ?,isold='0' where request_id = ?";
        rst.executeUpdate(updatesql, delDataInfo.toString(),requestid);
        this.deleteSuperviseByRequestId();//删除督办数据

        new RequestAttentionBiz().cancelAttention(requestid,"delete",this.rst);
        new MsgPushUtil().pushMsg(deleteMsg);
        executeDeleteOdocLogs(requestid);
    }

    public List<MsgEntity> executeDeleteRequestAndMsg() throws Exception{
        RequestOperationMsgManager romm = new RequestOperationMsgManager();
        List<MsgEntity> deleteMsg = romm.requestDeletMsg(String.valueOf(requestid));

        init();
        new RequestFlowRemindBiz().deleteFlowMsgByRequestid(requestid +"");
        executeDeleteAddinOperate();
        updateCodeseqReserved();
        checkAndDeleteAcc();
        deleteBaseTableInfo();
        deleteFormData();
        deletePoppupRemindInfo();
        deleteSubWFRequestInfo();
        //删除表单数据
        log.save(rst);
        String updatesql = "update workflow_requestdeletelog set deletetabledata = ?,isold='0' where request_id = ?";
        rst.executeUpdate(updatesql, delDataInfo.toString(),requestid);
        this.deleteSuperviseByRequestId();//删除督办数据

        new RequestAttentionBiz().cancelAttention(requestid,"delete",this.rst);
        executeDeleteOdocLogs(requestid);

        return deleteMsg;
    }

    public void executeDeleteOdocLogs(int requestid) throws Exception{
        RecordSet rs = new RecordSet();
        rs.executeQuery("select 1 from odoc_requestdoc where requestid = ?",requestid);
        if (rs.next()){
            rs.executeUpdate("delete from odoc_requestdoc where requestid = ?",requestid);
        }
    }



    //执行流程删除附加操作
    private void executeDeleteAddinOperate() throws Exception{
        RequestCheckAddinRules requestCheckAddinRules = new RequestCheckAddinRules();
        try {
            requestCheckAddinRules.setTrack(false);
            requestCheckAddinRules.setStart(false);
            requestCheckAddinRules.setNodeid(-3);
            requestCheckAddinRules.setRequestid(requestid);
            requestCheckAddinRules.setWorkflowid(workflowid);
            requestCheckAddinRules.setObjid(-3);
            requestCheckAddinRules.setObjtype(1);
            requestCheckAddinRules.setIsbill(isbill);
            requestCheckAddinRules.setFormid(formid);
            requestCheckAddinRules.setIspreadd("0");
            requestCheckAddinRules.setUser(this.user);
            requestCheckAddinRules.setSpecialOperate(true);
            requestCheckAddinRules.checkAddinRules();
        } catch (Exception e) {
            this.message = requestCheckAddinRules.getRequestManager().getMessage();
            this.messageContent = requestCheckAddinRules.getRequestManager().getMessagecontent();
            e.printStackTrace();
            throw new Exception("workflow interface action error:"+e.getMessage());
        }
    }

    /**
     * 删除主流程中的子流程流转意见信息
     */
    public void deleteSubWFRequestInfo(){

        List<List> params = new ArrayList<>();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from workflow_subwfrequest where subrequestid = ?", requestid);
        while (rs.next()) {
            List param = new ArrayList();
            param.add(rs.getInt(1));
            param.add(rs.getInt(2));
            param.add(rs.getInt(3));
            param.add(rs.getString(4));
            param.add(rs.getInt(5));
            param.add(rs.getInt(6));
            param.add(rs.getString(7));
            params.add(param);
        }
        rs.executeBatchSql("insert into Workflow_SubwfRequest_dellog values (?,?,?,?,?,?,?)", params);
        rs.executeUpdate("delete from workflow_subwfrequest where subrequestid = ?", requestid);
    }
    /**
     * 督办数据删除
     * @throws Exception
     */
    private void deleteSuperviseByRequestId() throws Exception{
        rst.executeUpdate("delete from WORKFLOW_SUPERVISEOPERATOR where requestid = ?",requestid);
    }

    /**
     * 根据是否开启删除流程时同时删除附件，来删除附件
     */
    public void checkAndDeleteAcc() {
        ArrayList checkids = new ArrayList();
        RecordSet checkrs = new RecordSet();
        checkrs.execute("select isneeddelacc from workflow_base where id in (select workflowid from workflow_requestbase where requestid ="+requestid+")");
        if(checkrs.next()){
            String isneeddelacc = checkrs.getString("isneeddelacc");
            if("1".equals(isneeddelacc)){
                this.delWfFormAcc(requestid, checkids);
                this.delWfSignAcc(requestid, checkids);
            }
        }

    }

    /**
     * 删除流程表单中所带的附件
     * @param requestid 流程ID
     * @param checkids  不需要删除的文档ID
     */
    private void delWfFormAcc(int requestid,ArrayList checkids){
        RecordSet rs=new RecordSet();
        RecordSet rs1=new RecordSet();
        RecordSet rsDelRq=new RecordSet();
        RecordSet rsDelDoc=new RecordSet();
        OperateService docExtUtil = new OperateService();

        String sql = "";
        String delDocid = "";
        String delRqid = "";
        String uploadfieldname ;
        String[] deleteDocIds;
        rs.executeSql("select b.formid, b.isbill from workflow_requestbase a, workflow_base b where requestid = "+requestid+" and a.workflowid = b.id");
        if(rs.next()){
            int formid_tmp = Util.getIntValue(rs.getString("formid"));
            int isbill_tmp = Util.getIntValue(rs.getString("isbill"));
            if(isbill_tmp == 1){
                String tablename_tmp="";
                String detailtablename="";
                String detailkeyfield="";
                rs.execute("select tablename,detailtablename,detailkeyfield from workflow_bill where id="+formid_tmp);
                if(rs.next()){
                    tablename_tmp=Util.null2String(rs.getString(1));
                    detailtablename=Util.null2String(rs.getString(2)).trim();
                    detailkeyfield=Util.null2String(rs.getString(3));
                    String tempdetail="";
                    boolean temphasreqeustid=false;
                    if(!"".equals(tablename_tmp)){
                        rsDelRq.executeSql("select fieldname,viewtype,detailtable from workflow_billfield where billid= "+formid_tmp+" and fieldhtmltype = '6'");
                        while(rsDelRq.next()){
                            uploadfieldname=Util.null2String(rsDelRq.getString(1));
                            int tviewtype=Util.getIntValue(rsDelRq.getString(2),0);
                            String tdetailtable=Util.null2String(rsDelRq.getString(3));
                            if(!uploadfieldname.trim().equals("")){
                                if(tviewtype==0){
                                    sql="select "+uploadfieldname+" from "+tablename_tmp+" where requestid="+requestid;
                                }else{
                                    if(tdetailtable.trim().equals("")) tdetailtable=detailtablename;
                                    boolean hasrequestid=false;
                                    if(tempdetail.equals(tdetailtable)){
                                        hasrequestid=temphasreqeustid;
                                    }else{
                                        if(rs.getDBType().toUpperCase().equals("ORACLE")){
                                            sql="select * from "+tdetailtable+" where rownum<2";
                                        }else{
                                            sql="select top 1 * from "+tdetailtable;
                                        }
                                        if(rs1.executeSql(sql)){
                                            String[] colnames=rs1.getColumnName();
                                            if(colnames!=null){
                                                for (int m=0;m<colnames.length;m++){
                                                    if(colnames[m].toUpperCase().equals("REQUESTID")){
                                                        hasrequestid=true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        temphasreqeustid=hasrequestid;
                                        tempdetail=tdetailtable;
                                    }
                                    if(hasrequestid)
                                        sql="select "+uploadfieldname+" from "+tdetailtable+" where requestid="+requestid;
                                    else
                                        sql="select a."+uploadfieldname+" from "+tdetailtable+" a,"+tablename_tmp+" b where a."+detailkeyfield+"=b.id and b.requestid="+requestid;
                                }
                                //System.out.println(sql);
                                rsDelDoc.executeSql(sql);
                                while(rsDelDoc.next()){
                                    delDocid = rsDelDoc.getString(uploadfieldname);
                                    if(delDocid!=null && !"".equals(delDocid)){
                                        deleteDocIds = Util.TokenizerString2(delDocid, ",");
                                        for(int d=0; d <deleteDocIds.length; d++){
                                            if(isCanDel(Util.getIntValue(deleteDocIds[d],0))){
                                                try{
                                                    securityDeleteDoc(deleteDocIds[d]);
                                                } catch (Exception e){
                                                    e.printStackTrace();
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }else{
                rsDelRq.executeSql("select fieldname from workflow_formfield a,workflow_formdict b where a.formid = "+formid_tmp+" and a.fieldid = b.id and b.fieldhtmltype = '6' and (a.isdetail is null or a.isdetail<>'1')");
                while(rsDelRq.next()){
                    uploadfieldname  = rsDelRq.getString("fieldname");
                    rsDelDoc.executeSql("select "+uploadfieldname+" from workflow_form where requestid = " + requestid);
                    if(rsDelDoc.next()){
                        delDocid = rsDelDoc.getString(uploadfieldname);
                        if(delDocid!=null && !"".equals(delDocid)){
                            deleteDocIds = Util.TokenizerString2(delDocid, ",");
                            for(int d=0; d <deleteDocIds.length; d++){
                                if(isCanDel(Util.getIntValue(deleteDocIds[d],0))){
                                    //删除表中该文档的相关记录及物理删除
                                    try{
                                        securityDeleteDoc(deleteDocIds[d]);
                                    } catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }

                sql="select a.fieldname from workflow_formdictdetail a,workflow_formfield b where a.id=b.fieldid and a.fieldhtmltype='6' and b.isdetail='1' and b.formid="+formid_tmp;
                rsDelRq.executeSql(sql);
                while(rsDelRq.next()){
                    uploadfieldname  = rsDelRq.getString("fieldname");
                    rsDelDoc.executeSql("select "+uploadfieldname+" from workflow_formdetail where requestid = " + requestid);
                    while(rsDelDoc.next()){
                        delDocid = rsDelDoc.getString(uploadfieldname);
                        if(delDocid!=null && !"".equals(delDocid)){
                            deleteDocIds = Util.TokenizerString2(delDocid, ",");
                            for(int d=0; d <deleteDocIds.length; d++){
                                if(isCanDel(Util.getIntValue(deleteDocIds[d],0))){
                                    //删除表中该文档的相关记录及物理删除
                                    try{
                                        securityDeleteDoc(deleteDocIds[d]);
                                    } catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * * 删除流程签字意见中所带的附件
     * @param requestid 流程ID
     * @param checkids  不需要删除的文档ID
     */
    private  void delWfSignAcc(int requestid,ArrayList checkids){
        OperateService docExtUtil = new OperateService();
        String sql="select annexdocids from workflow_requestLog where requestid="+requestid;
        RecordSet rs=new RecordSet();
        rs.executeSql(sql);
        while(rs.next()){
            String  annexdocids = Util.null2String(rs.getString("annexdocids"));
            String[] docIdstr = Util.TokenizerString2(annexdocids, ",");
            for(int b=0; b <docIdstr.length; b++){
                if(isCanDel(Util.getIntValue(docIdstr[b],0))){
                    try{
                        securityDeleteDoc(docIdstr[b]);
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    //文档是否能删除
    private boolean isCanDel(int docid){
        RecordSet noDelRs = new RecordSet();
        String noDelSql = "";
        if("mysql".equals(noDelRs.getDBType())){
            noDelSql = "SELECT 1 FROM workflow_requestbase WHERE  FIND_IN_SET("+docid+",docids)  AND (deleted = 0 OR deleted IS NULL)";
        }else if("oracle".equals(noDelRs.getDBType())){
            noDelSql = "select 1 from workflow_requestbase where ','||docids||',' like '%,"+docid+",%'  and (deleted = 0 or deleted is null)";
        }
        else if("postgresql".equals(noDelRs.getDBType())){
            noDelSql = "select 1 from workflow_requestbase where ','||docids||',' like '%,"+docid+",%'  and (deleted = 0 or deleted is null)";
        }
        else{
            noDelSql = "select 1 from workflow_requestbase where ','+cast(docids AS varchar(4000))+',' like '%,"+docid+",%'  and (deleted = 0 or deleted is null)";
        }
        noDelRs.executeSql(noDelSql);

        if(noDelRs.next()){
            return false;
        }else{
            return true;
        }
    }

    private void securityDeleteDoc(String docids){
        docDeleteUtil.deleteDocids(docids, DocumentDeleteStatusMould.WORKFLOW.getMouldCode(), this.user, requestid+"", MouldStatus.WF_DELETE_REQUEST.getItemCode());
    }


    /**
     * 流程监控删除流程
     * @param deleteRequestIds
     * @param user
     * @param clientIp
     */
    public String executeMonitorDelete(String deleteRequestIds,User user,String clientIp){
        RecordSetTrans mrst = new RecordSetTrans();
        List<MsgEntity> delMsg = null;
        try{
            if(deleteRequestIds == null || "".equals(deleteRequestIds)) return "fail";
            if(deleteRequestIds.endsWith(",")) deleteRequestIds = deleteRequestIds.substring(0,deleteRequestIds.length() - 1);
            RecordSet temprs = new RecordSet();
            mrst.setAutoCommit(false);
            Monitor monitor = new Monitor();
            String[] deleteRequestIdAarray = Util.TokenizerString2(deleteRequestIds, ",");
            String tempDeleteRequestIds = "";
            SysMaintenanceLog SysMaintenanceLog = new SysMaintenanceLog();
            RecordSet rscpt = new RecordSet();
            boolean isRefCpt = false;
            List<String> deleteIngRequestList;
            for (String deleteRequestId : deleteRequestIdAarray) {
                synchronized (RequestDeleteUtils.class) {
                    Object obj = Util_TableMap.getObjVal("deleteIngRequestList");
                    if (obj == null) {
                        obj = new LinkedList<String>();
                        Util_TableMap.setObjVal("deleteIngRequestList", obj);
                    }
                    deleteIngRequestList = (List<String>) obj;
                    temprs.writeLog("lyy=====>deleteIngRequestList: " + deleteIngRequestList);
                    if (deleteIngRequestList.contains(deleteRequestId)) {
                        continue;
                    } else {
                        deleteIngRequestList.add(deleteRequestId);
                        temprs.writeLog("lyy=====>deleteIngRequestList1: " + deleteIngRequestList);
                    }
                }
                String workflowid_kq = "";
                temprs.execute("select creater,workflowid from workflow_requestbase where requestid = " + deleteRequestId);
                if(temprs.next()){
                    String creater = temprs.getString(1);
                    String workflowid = temprs.getString(2);
                    workflowid_kq = workflowid;
                    MonitorDTO dto = monitor.getMonitorInfo(String.valueOf(user.getUID()),creater,workflowid);

                    //判断流程是否关联了资产模块
                    rscpt.executeSql("select wfid from cpt_cptwfconf where wfid="+workflowid);
                    if(rscpt.next()){
                        isRefCpt = true;
                    }
                    rscpt.executeSql("select formid from workflow_base where id="+workflowid);
                    if(rscpt.next()){
                        int formid = rscpt.getInt(1);
                        if(formid==18||formid==19||formid==201||formid==220||formid==221||formid==222||formid==224){
                            isRefCpt = true;
                        }
                    }

                    boolean isdelete = dto.getIsdelete();
                    if(isdelete){
                        tempDeleteRequestIds +=  deleteRequestId+",";
                    }else{
                        continue;
                    }
                }

                try {
                    FnaCommon fnaCommon = new FnaCommon();
                    fnaCommon.doWfForceOver(Util.getIntValue(deleteRequestId, 0), 0, true);
                }catch(Exception easi) {
                    new BaseBean().writeLog(easi);
                }

                //E9 新考勤，删除流程后删除流程数据
                try {
                    new KQFlowActiontBiz().delTest(Util.getIntValue(deleteRequestId, 0),workflowid_kq,"RequestDeleteUtils");
                }catch(Exception e) {
                    new BaseBean().writeLog(e);
                }

                temprs.executeSql("select requestname,workflowid from workflow_requestbase where requestid="+deleteRequestId);
                temprs.next();
                String temprequestname = temprs.getString("requestname");
                String tempworkflowid = temprs.getString("workflowid");

                SysMaintenanceLog.resetParameter();
                SysMaintenanceLog.setRelatedId(Util.getIntValue(deleteRequestId));
                SysMaintenanceLog.setRelatedName(temprequestname);
                SysMaintenanceLog.setOperateType("3");
                SysMaintenanceLog.setOperateDesc("delete workflow_currentoperator where requestid="+deleteRequestId+
                        ";delete workflow_form where requestid="+deleteRequestId+
                        ";delete workflow_formdetail where requestid="+deleteRequestId+
                        ";delete workflow_requestLog where requestid="+deleteRequestId+
                        ";delete workflow_requestViewLog where id="+deleteRequestId+
                        ";delete workflow_requestbase where requestid="+deleteRequestId);
                SysMaintenanceLog.setOperateItem("85");
                SysMaintenanceLog.setOperateUserid(user.getUID());
                SysMaintenanceLog.setClientAddress(clientIp);
                SysMaintenanceLog.setOperatesmalltype(1);
                SysMaintenanceLog.setSysLogInfo();

                //1:请求

                try{
                    RequestDeleteLog log = initRequestDeleteLog(user, clientIp, deleteRequestId);

                    this.requestid =Util.getIntValue(deleteRequestId);
                    this.rst = mrst;
                    this.log = log;
                    this.user = user;
                    delMsg = this.executeDeleteRequestAndMsg();
                }catch (Exception exception){
                    exception.printStackTrace();
                    writeLog(exception);
                    if(exception.getMessage().indexOf("workflow interface action error")>-1){
                        return "actionfail";
                    }
                } finally {
                    deleteIngRequestList.remove(deleteRequestId);
                }
            }

            if(tempDeleteRequestIds.length() > 0){
                tempDeleteRequestIds = tempDeleteRequestIds.substring(0,tempDeleteRequestIds.length() - 1);

                String[] tempDeleteRequestIdArray = Util.TokenizerString2(tempDeleteRequestIds, ",");

                if(isRefCpt){
                    temprs.executeSql("update cptcapital set frozennum=0 where isdata='2' and frozennum > 0");
                    CptWfUtil cwu = new CptWfUtil();
                    cwu.DoFrozenCpt_new();
                }

                //删除费用信息表中的相应数据-----begin
//                for(int i=0;i<tempDeleteRequestIdArray.length;i++){
//                    String temprequestid = tempDeleteRequestIdArray[i];
//                    try {
//                        FnaCommon fnaCommon = new FnaCommon();
//                        fnaCommon.doWfForceOver(Util.getIntValue(temprequestid, 0), 0, true);
//                    }catch(Exception easi) {
//                        new BaseBean().writeLog(easi);
//                    }
//                }

                /*删除流程，如果是请假申请单，则在删除流程后解冻请假信息*/
                temprs.executeSql(" select r.requestid,r.workflowid,r.currentnodetype from workflow_requestbase r,workflow_base b where requestid in ( " + tempDeleteRequestIds + " ) and r.workflowid=b.id and b.isbill=1" ) ;
                while(temprs.next()){
                    String workflowid=temprs.getString("workflowid"); //流程id
                    String requestid=temprs.getString("requestid");   //流程请求id
                    String currentnodetype=temprs.getString("currentnodetype"); //当前节点状态
                    //申请流程 不为 3归档节点 0 创建节点

                    if(!"0".equals(currentnodetype)&&!"3".equals(currentnodetype)){
                        HrmAttVacationManager vacationManager = new HrmAttVacationManager();
                        vacationManager.handle(Util.getIntValue(requestid,0),Util.getIntValue(workflowid,0),3);
                        //加班强制归档要生成调休
                        new HrmPaidLeaveManager().handle(StringUtil.parseToLong(requestid), Util.getIntValue(workflowid,0), 3);
                    }
                    //
                }

                mrst.commit();
                new MsgPushUtil().pushMsg(delMsg);
                if (!"".equals(tempDeleteRequestIds) && isRefCpt) {
                    new Thread(new CptWfUtil(tempDeleteRequestIds,"releaseFrozenCptnum")).start();
                }
            }

        }catch (Exception e) {
            mrst.rollback();
            writeLog(e);
            return "fail";
        }
        return "success";
    }

    /**
     * 外部接口调用流程删除通用方法
     * @param user
     * @param clientipOrFrom
     * @param requestid
     * @return
     */
    public boolean requestDelete(User user,String clientipOrFrom,int requestid){
        WorkflowConfigComInfo configComInfo = new WorkflowConfigComInfo();
        boolean verifyRight = "1".equals(Util.null2String(configComInfo.getValue("wbservice_delreq_verify_right")));
        if(verifyRight && !(verifyDelRight(requestid,user,false) || verifyDelRight(requestid,user,true))) {
            writeLog("用户" + user.getUID()+"无" + requestid + "删除权限!");
            return false;
        }

        RecordSetTrans trst = new RecordSetTrans();
        trst.setAutoCommit(false);
        RequestDeleteLog log = initRequestDeleteLog(user, clientipOrFrom, String.valueOf(requestid));

        this.log = log;
        this.rst = trst;
        this.requestid = requestid;
        this.user = user;

        try {
            List<MsgEntity> delMsg = executeDeleteRequestAndMsg();
            trst.commit();

            new MsgPushUtil().pushMsg(delMsg);
        } catch (Exception e) {
            writeLog(e);
            trst.rollback();
            return false;
        }
        return true;
    }

    /**
     * 公文内部交换删除流程方法
     * @param user
     * @param clientipOrFrom
     * @param requestid
     * @return
     */
    public boolean requestDeleteForOdoc(User user,String clientipOrFrom,int requestid){
        RecordSetTrans trst = new RecordSetTrans();
        trst.setAutoCommit(false);
        RequestDeleteLog log = initRequestDeleteLog(user, clientipOrFrom, String.valueOf(requestid));

        this.log = log;
        this.rst = trst;
        this.requestid = requestid;
        this.user = user;

        try {
            List<MsgEntity> delMsg = executeDeleteRequestAndMsg();
            trst.commit();
            new MsgPushUtil().pushMsg(delMsg);
        } catch (Exception e) {
            writeLog(e);
            trst.rollback();
            return false;
        }
        return true;
    }


    /**
     * 创建log对象
     * @param user
     * @param clientIp
     * @param deleteRequestId
     * @return
     */
    public RequestDeleteLog initRequestDeleteLog(User user, String clientIp, String deleteRequestId) {
        Calendar today = Calendar.getInstance();
        String formatdate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + Util.add0(today.get(Calendar.MONTH)+1,2) + "-" + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        String formattime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + Util.add0(today.get(Calendar.MINUTE), 2) + ":" +Util.add0(today.get(Calendar.SECOND), 2);

        RecordSet rs1 = new RecordSet();
        RequestDeleteLog log = new RequestDeleteLog();
        rs1.executeQuery("select requestname,workflowid from workflow_requestbase where requestid  = ?", deleteRequestId);
        if(rs1.next()){
            log.setRequestName(Util.fromScreen2(rs1.getString(1), user.getLanguage()));
            log.setWorkflowId(rs1.getString(2));
        }
        log.setRequestId(String.valueOf(deleteRequestId));
        log.setOperateUserId(String.valueOf(user.getUID()));
        log.setOperateUserType("2".equals(user.getLogintype())?"1":"0");
        log.setOperateDate(formatdate);
        log.setOperateTime(formattime);
        log.setClientAddress(Util.null2String(clientIp));

        return log;
    }

    /**
     * 复制流程基础表数据
     * @throws Exception
     */
    private void deleteBaseTableInfo() throws Exception {
        Iterator<String> it = deleteTableMap.keySet().iterator();
        while (it.hasNext()) {
            String tablename = it.next();
            RequestDeleteInfo rdi  = deleteTableMap.get(tablename);
            String copytablename  = Util.null2String(rdi.getCopytablename());
            if("".equals(copytablename)){
                deleteTableData(tablename,rdi.getQueryWhere(),null);
            }else{
                String columnStr="";
                if(rdi.getClobColumn()!=null){
                    columnStr = getTableColumn(tablename, rdi.getClobColumn());
                }else{
                    columnStr = getTableColumn(tablename, null);
                }
                //先查一下
                if("st".equalsIgnoreCase(rst.getOrgindbtype())||"postgresql".equalsIgnoreCase(rst.getDBType())){
                    DBColumnTypeUtils.syncLogTableField(tablename, copytablename,rst);
                }
                String dellogsql = "insert into " + copytablename + "(" + columnStr + ") select " + columnStr + " from " + tablename + rdi.getQueryWhere();
                try{
                    rst.executeSql(dellogsql);
                }catch (Exception e) {
                    boolean flag  = DBColumnTypeUtils.syncLogTableField(tablename, copytablename,rst);
                    if(flag){
                        rst.executeSql(dellogsql);
                    }else{
                        throw e;
                    }
                }
                //更新clob字段
                updateClobColumn(tablename,rdi);
                rst.executeSql("delete from " + tablename + rdi.getQueryWhere());

            }

        }
    }

    /**
     * 删除消息
     */
    private void deletePoppupRemindInfo(){
        PoppupRemindInfoUtil poppupRemindInfoUtil = new PoppupRemindInfoUtil();
        poppupRemindInfoUtil.deletePoppupRemindInfo(requestid,0);
        poppupRemindInfoUtil.deletePoppupRemindInfo(requestid,1);
        poppupRemindInfoUtil.deletePoppupRemindInfo(requestid,10);
    }


    /**
     * 更新clob字段
     * @param tablename
     * @param rdi
     * @throws Exception
     */
    private void updateClobColumn(String tablename,RequestDeleteInfo rdi) throws Exception{
        String clobcolumns = rdi.toClobColumString();
        RecordSet   rs = new RecordSet();
        if(clobcolumns == null) return;
        String querysqlString = "select " + clobcolumns + ","+rdi.getPrimarykey()+" from " + tablename + rdi.getQueryWhere();
        rs.executeSql(querysqlString);
        while(rs.next()){
            for(String column:rdi.getClobColumn()){
                String updatesqlString = "update " + rdi.getCopytablename() + " set "+column+" = ? where " + rdi.getPrimarykey() + " = ? ";
                rst.executeUpdate(updatesqlString, rs.getString(column),rs.getString(rdi.getPrimarykey()));
            }
        }
    }

    /**
     * 记录请求相关表数据，并记录数据
     * @param tablename
     * @param querywhere
     * @param columnStr
     */
    private void deleteTableData(String tablename,String querywhere,String columnStr) {
        JSONObject colunInfo;
        RecordSet   rs = new RecordSet();
        if("".equals(Util.null2String(columnStr))){
            columnStr = getTableColumn(tablename, null);
        }
        String[] columnArray = columnStr.split(",");
        String querysql = "";
        if(tablename.equals("workflow_nodeform")){
            querysql = "select " + columnStr + " from " + tablename +" a "+ querywhere;
        }else {
            querysql = "select " + columnStr + " from " + tablename + " " + querywhere;
        }
        rs.executeSql(querysql);
        rs.isReturnDecryptData(true);
        JSONArray array = new JSONArray();
        while (rs.next()) {
            colunInfo = new JSONObject();
            for (int i = 0; i < columnArray.length; i++) {
                colunInfo.put(columnArray[i], rs.getString(columnArray[i]));
            }
            array.add(colunInfo);
        }
        String deleteSql = "delete from " + tablename + " " + querywhere;
        if(DBConstant.DB_TYPE_MYSQL.equals(rs.getDBType())) {
            switch (tablename){
                case "workflow_logviewusers":
                    deleteSql = "delete t1 from workflow_logviewusers t1,workflow_requestlog t2 where t1.logid=t2.logid and t2.requestid= " + requestid;
                    break;
                case "workflow_nodeform":
                    deleteSql = "delete t1 from workflow_nodeform t1,workflow_nodebase t2 where t1.nodeid=t2.id and  t2.isfreenode='1' and t2.requestid= " + requestid;
                    break;
                default:
                    break;

            }
        }
        rs.executeUpdate(deleteSql);
        delDataInfo.put(tablename, array);
    }

    /**
     * 删除请求表单数据(自定义、系统表单、老表单)
     */
    private void deleteFormData(){
        RecordSet temprs = new RecordSet();
        if(isbill == 1){
            temprs.executeQuery("select tablename,detailkeyfield from workflow_bill where id  = ?", formid);
            String maintablename  = "";
            String detailkeyfield="";
            String querywhere = "where requestid= " + requestid;
            if(temprs.next()){
                maintablename  = temprs.getString("tablename");
                detailkeyfield = temprs.getString("detailkeyfield");
                //deleteTableData(maintablename,"where requestid = " + requestid,null);
            }
            if("".equals(detailkeyfield)){//如果为空时默认赋值【特殊表单不一定是按照mainid进行关联】
                detailkeyfield="mainid";
            }
            temprs.executeQuery("select tablename from workflow_billdetailtable where billid = ?",formid);
            while(temprs.next()){
                String detailtablename  = temprs.getString(1);
                querywhere = "where exists (select 1 from "+maintablename+" b where b.id  = "+detailtablename+"."+detailkeyfield+" and b.requestid  = "+requestid+")";
                deleteTableData(detailtablename,querywhere,null);
            }
            //先删除明细而后删除主表QC250286,增加判断在maintablename不为空时执行。
            if (!"".equals(maintablename)) {
                deleteTableData(maintablename,"where requestid = " + requestid,null);
            }
            querywhere = "where requestid= " + requestid;
            String column = "REQUESTID,BILLFORMID,BILLID";
            deleteTableData("workflow_form",querywhere,column);
        }else{
            deleteOldFormData(temprs);
        }
    }
    /**
     * 删除老表单数据
     * @param temprs
     */
    private void deleteOldFormData(RecordSet temprs){
        //老表单主表
        String maintablefieldquerysql = "select b.fieldname from workflow_formfield a left join workflow_formdict b on a.fieldid = b.id where (a.isdetail<>'1' or a.isdetail is null) and  a.formid  = ?";
        temprs.executeQuery(maintablefieldquerysql, formid);
        String column = "";
        while(temprs.next()){
            String columnname  = Util.null2String(temprs.getString(1));
            if("".equals(columnname)){
                continue;
            }
            column += columnname+",";
        }
        if(column.length() > 0) {
            column += "requestid,billformid,billid";
        }
        String querywhere  = "where requestid  = " +requestid;
        deleteTableData("workflow_form",querywhere,column);

        //老表单明细表
        String detailtablefieldquerysql ="select b.fieldname from workflow_formfield a left join workflow_formdictdetail b on a.fieldid = b.id and a.isdetail = '1' and a.formid  = ?";
        temprs.executeQuery(detailtablefieldquerysql, formid);
        column = "";
        while(temprs.next()){
            String columnname  = Util.null2String(temprs.getString(1));
            if("".equals(columnname)){
                continue;
            }
            column += columnname+",";
        }
        if(column.length() > 0) {
            column += "id,requestid,groupid";
        }
        deleteTableData("workflow_formdetail",querywhere,column);
    }


    /**
     *
     *    删除流程的时候,将流程编号预留号表中的是否已使用/是否已删除置为0
     */

    private void updateCodeseqReserved(){
        if(requestid <= 0){
            return;
        }

        //1.用requestid 去workflow_codeseqrecord表中查出codeSeqId和codeSeqReservedId
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        String sql = "select codeSeqId,sequenceId,workflowcode from workflow_codeseqrecord where requestId = " + requestid;
        rs.executeSql(sql);
        RecordSet rsz=new RecordSet();
        while (rs.next()) {
            String codeSeqId = rs.getString(1);
            String sequenceId = rs.getString(2);
            String RESERVEDCODE = rs.getString(3);
            //更新workflow_codeseqreserved流程编号预留号表的hasUsed=0,hasDeleted=0
            rs1.executeSql("update workflow_codeseqreserved set hasUsed=0,hasDeleted=0 where codeSeqId=" + codeSeqId + " and reservedId=" + sequenceId);
            rsz.executeQuery("select  count(1) from workflow_codeseqreserved where codeSeqId=? and reservedId=? and RESERVEDCODE=? ",codeSeqId,sequenceId,RESERVEDCODE);
            rsz.next();
            int count = rsz.getInt(1);
            if(count==0){
                //没有预留号 所以需要
                String sql2 = "insert into workflow_codeSeqReserved(codeSeqId,reservedId,reservedCode,reservedDesc,hasUsed,hasDeleted) values(?,?,?,?,?,?)";
                new RecordSet().executeUpdate(sql2, codeSeqId,sequenceId,RESERVEDCODE,"","0","0");
            }
            //删除记录表里的数据
            rsz.executeUpdate("delete  workflow_codeseqrecord where requestid = ? " , requestid );
        }

    }

    /**
     * 查询表字段
     * @param tablename
     * @param clobcolumns
     * @return
     */
    public static String getTableColumn(String tablename, List<String> clobcolumns) {
        RecordSet rs = new RecordSet();
        String sqltemp = "select column_name from user_tab_columns  where table_name = upper(?)";
        if ("sqlserver".equalsIgnoreCase(rs.getDBType())) {
            sqltemp = "select name from syscolumns b where id = OBJECT_ID(?)";
        }else if(rs.getDBType().equals("mysql")){
            String currentDB = DBColumnTypeUtils.getMysqlCurrentDBName();
            sqltemp = "select DISTINCT column_name from Information_schema.columns  where table_schema = database() and table_name = upper(?)";
            if(!"".equalsIgnoreCase(currentDB)) sqltemp += " and table_schema = '" + currentDB + "' ";
        }else if(rs.getDBType().equals("postgresql")){
            sqltemp = "select DISTINCT column_name from Information_schema.columns  where table_schema = 'public' and lower(table_name) = lower(?)";
        }

        rs.executeQuery(sqltemp, tablename);
        StringBuffer column = new StringBuffer();
        while (rs.next()) {
            String columnname ="";
            if(tablename.equals("workflow_nodeform")){
                columnname = "a." + rs.getString(1).toUpperCase();
            }else {
                columnname = rs.getString(1).toUpperCase();
            }
            // clob字段特殊处理
            if (clobcolumns != null && clobcolumns.size() > 0 && clobcolumns.contains(columnname)) {
                continue;
            }
            if(rs.getDBType().equals("mysql") && "CONDITION".equals(columnname)){
                columnname = "`CONDITION`";
            }
            column.append(columnname).append(",");
        }
        String coumntemp = "";
        if (column.length() > 0) {
            coumntemp = column.substring(0, column.length() - 1);
        }
        column = null;
        return coumntemp;
    }

    /**
     * 校验流程删除权限
     * @param requestid
     * @param user
     * @param isMonitor
     * @return
     */
    public static boolean verifyDelRight(int requestid,User user,boolean isMonitor) {
        int userType = "2".equals(user.getLogintype()) ? 1 : 0;
        RecordSet rs = new RecordSet();
        if(isMonitor) {
            rs.executeQuery("select creater,workflowId from workflow_requestbase where requestid  = ?",requestid);
            if(rs.next()) {
                String workflowId = rs.getString("workflowId");
                String creater = rs.getString("creater");
                Monitor monitor = new Monitor();
                MonitorDTO monitorInfo = monitor.getMonitorInfo(String.valueOf(user.getUID()),creater,workflowId);
                return monitorInfo.getIsdelete();
            }
        } else {
            String querySql = ServiceUtil.calculateCurrentNodeSql(String.valueOf(requestid),user.getUID(),userType);
            rs.executeQuery(querySql);
            if(rs.next()) {
                int nodeid  = rs.getInt("nodeid");
                int isremark  = rs.getInt("isremark");
                int workflowid = rs.getInt("workflowid");
                NodeInfoEntity nodeInfoEntity = WorkflowBaseBiz.getNodeInfo(nodeid);
                if(nodeInfoEntity == null) return false;
                WfFunctionManageUtil wfFunctionManageUtil = new WfFunctionManageUtil();
                return (nodeInfoEntity.getNodetype() == 0 && isremark == 0 && wfFunctionManageUtil.IsShowDelButtonByReject(requestid, workflowid));
            }
        }
        return false;
    }

    public void setRequestid(int requestid) {
        this.requestid = requestid;
    }

    public String getMessage() {
        return this.message;
    }

    public String getMessagecontent() {
        return this.messageContent;
    }

    public void setMessageContent(String messageContent) {
        this.messageContent = messageContent;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    private class RequestDeleteInfo{
        private String queryWhere;
        private String copytablename;
        private String primarykey;
        private List<String> clobColumn;

        public String getQueryWhere() {
            return queryWhere;
        }
        public void setQueryWhere(String queryWhere) {
            this.queryWhere = queryWhere;
        }
        public String getCopytablename() {
            return copytablename;
        }
        public void setCopytablename(String copytablename) {
            this.copytablename = copytablename;
        }
        public String getPrimarykey() {
            return primarykey;
        }
        public void setPrimarykey(String primarykey) {
            this.primarykey = primarykey;
        }
        public List<String> getClobColumn() {
            return clobColumn;
        }
        public void setClobColumn(List<String> clobColumn) {
            this.clobColumn = clobColumn;
        }

        public String toClobColumString(){
            if(clobColumn == null) return null;
            String columnString  = "";
            for(String column:clobColumn){
                columnString += column+",";
            }
            return  ((columnString.length() > 0)?(columnString.substring(0, columnString.length() - 1)):null);

        }
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
