package weaver.interfaces.htxc.job;

import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.docs.docs.DocComInfo;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.interfaces.htsc.util.SqlUtil;
import weaver.interfaces.htsc.util.WfUtil;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class WfDataSyn extends BaseCronJob {

    @Override
    public void execute() {
        String systime = LocalDateTime.now().minusHours(2).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        PropBean pb = new PropBean();
        String customSystime = pb.getPropName("datasyntime");
        if(!"".equals(customSystime)){
            systime = customSystime;
        }

        //关闭触发器
        controlTrigger(0);
        try {
            doWfDataSyn(systime);
            //doFileDataSyn(systime);

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //开启触发器
            controlTrigger(1);
        }

    }

    /**
     * 判断流程是否已存在
     * @param requestid
     * @return
     */
    public boolean hasWf(String requestid){
        String sql = " select 1 from workflow_requestbase where requestid=? ";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql,requestid);
        return rs.next();
    }

    /**
     * 查询主表
     * @param requestid
     * @return
     */
    public static String getWfMainTable(String requestid){
        String maintable = "";

        RecordSetDataSource rsd = new RecordSetDataSource("fromdb");
        String mainTableSql = " SELECT TABLENAME FROM OACODEPRD.WORKFLOW_REQUESTBASE T1,OACODEPRD.WORKFLOW_BASE T2," +
                "OACODEPRD.WORKFLOW_BILL T3\n" +
                "WHERE T1.WORKFLOWID=T2.ID AND T2.FORMID=T3.ID AND T1.REQUESTID="+requestid;
        rsd.execute(mainTableSql);
        if (rsd.next()){
            maintable = Util.null2String(rsd.getString("TABLENAME"));
        }
        return maintable;

    }

    /**
     * 查询所有明细表
     * @param requestid
     * @return
     */
    public static List<String> getWfAllDetailTables(String requestid){
        List<String> tables = new ArrayList<>();
        RecordSetDataSource rsd = new RecordSetDataSource("fromdb");
        String sql = " select distinct detailtable from oacodeprd.workflow_requestbase a,oacodeprd.workflow_base b, oacodeprd.workflow_billfield c  " +
                "where a.workflowid=b.id and b.formid=c.billid  and (detailtable is not null or detailtable='') " +
                "and a.requestid="+requestid+" order by detailtable ";
        rsd.execute(sql);
        while (rsd.next()){
            String detailTable = Util.null2String(rsd.getString("detailtable"));
            tables.add(detailTable);
        }
        return tables;

    }


    public int getSynMainid(String maintable,String requestid){
        int mainid = -1;
        RecordSetDataSource rsd = new RecordSetDataSource("fromdb");
        rsd.execute("select id from oacodeprd."+maintable+" where requestid="+requestid);
        if(rsd.next()){
            mainid = rsd.getInt("id");
        }
        return mainid;
    }


    public void doWfDataSyn(String systime){
        //查询所有需要同步的流程数据
        //String  sysdate  = LocalDate.now().minusDays(1l).toString();

        String sql = " select requestid from oacodeprd.workflow_requestbase a,oacodeprd.workflow_base b,oacodeprd.hrmresource c where a.workflowid=b.id and a.creater=c.id " +
                "and unnumber in('gsfw','dgtfw','zhfw','fzjgfw','zbggfb','ggfbfzjg','gssw','gsswldsy','gsswxbbm','gsswyz','gsswzbbm') " +
                "and isvalid=1 and c.departmentid=15 and (lastoperatedate || ' '||lastoperatetime)>= '"+systime+"' ";

        RecordSetDataSource rsd = new RecordSetDataSource("fromdb");
        RecordSetDataSource rsd2 = new RecordSetDataSource("fromdb");
        RecordSet rs = new RecordSet();
        rs.writeLog("WfDataSyn doWfDataSyn sql============>"+sql);
        try {
            rsd.execute(sql);
            while(rsd.next()) {
                String requestid = Util.null2String(rsd.getString("requestid"));
                String maintable = getWfMainTable(requestid);
                List<String> detailTables = getWfAllDetailTables(requestid);

                int synMainId = getSynMainid(maintable,requestid);
                boolean isExist = hasWf(requestid);
                //如果存在先删除历史数据再同步
                if(isExist){
                    //删除表单数据
                    int mainid = WfUtil.getMainId(requestid);
                    rs.executeUpdate(" delete from "+maintable+" where requestid=? ", requestid);

                    for(String dtable:detailTables){
                        rs.executeUpdate(" delete from "+dtable+" where mainid=? ", mainid);
                    }

                    //删除流程 workflow_requestbase 表数据
                    rs.executeUpdate(" delete from workflow_requestbase where requestid=? ", requestid);

                    //删除流程 workflow_form 表数据
                    rs.executeUpdate(" delete from workflow_form where requestid=? ", requestid);

                    //删除流程 workflow_currentoperator 表数据
                    rs.executeUpdate(" delete from workflow_currentoperator where requestid=? ", requestid);

                    //删除流程 workflow_requestlog 表数据
                    rs.executeUpdate(" delete from workflow_requestlog where requestid=? ", requestid);

                    //删除流程 workflow_nownode 表数据
                    rs.executeUpdate(" delete from workflow_nownode where requestid=? ", requestid);

                    //删除流程 workflow_freenode 表数据
                    rs.executeUpdate(" delete from workflow_freenode where requestid=? ", requestid);

                    //删除流程 workflow_freenode_group 表数据
                    rs.executeUpdate(" delete from workflow_freenode_group where requestid=? ", requestid);

                    //删除流程 workflow_reqbrowextrainfo 表数据
                    rs.executeUpdate(" delete from workflow_reqbrowextrainfo where requestid=? ", requestid);

                    //删除流程 workflow_requestviewlog 表数据
                    rs.executeUpdate(" delete from workflow_requestviewlog where id=? ", requestid);

                    //删除流程 workflow_autoflowlog 表数据
                    rs.executeUpdate(" delete from workflow_autoflowlog where requestid=? ", requestid);

                    //删除流程 workflow_requestoperatelog 表数据
                    rs.executeUpdate(" delete from workflow_requestoperatelog where requestid=? ", requestid);

                }

                //删除同id的数据
                rsd2.execute(" select id from oacodeprd."+maintable+" where requestid="+requestid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from "+maintable+" where id=? ",id);
                }

                for(String dtable:detailTables){
                    rsd2.execute(" select id from oacodeprd."+dtable+" where mainid="+synMainId);
                    while(rsd2.next()){
                        int id = rsd2.getInt("id");
                        rs.executeUpdate(" delete from "+dtable+" where id=? ",id);
                    }

                }

                rsd2.execute(" select id from oacodeprd.workflow_currentoperator where requestid="+requestid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from workflow_currentoperator where id=? ",id);
                }

                rsd2.execute(" select logid from oacodeprd.workflow_requestlog where requestid="+requestid);
                while(rsd2.next()){
                    int logid = rsd2.getInt("logid");
                    rs.executeUpdate(" delete from workflow_requestlog where logid=? ",logid);
                }

                rsd2.execute(" select id from oacodeprd.workflow_freenode where requestid="+requestid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from workflow_freenode where id=? ",id);
                }

                rsd2.execute(" select id from oacodeprd.workflow_freenode_group where requestid="+requestid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from workflow_freenode_group where id=? ",id);
                }

                rsd2.execute(" select id from oacodeprd.workflow_reqbrowextrainfo where requestid="+requestid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from workflow_reqbrowextrainfo where id=? ",id);
                }

                rsd2.execute(" select id from oacodeprd.workflow_requestoperatelog where requestid="+requestid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from workflow_requestoperatelog where id=? ",id);
                }

                //开始同步数据
                //同步表 workflow_requestbase
                syncTableData("select * from oacodeprd.workflow_requestbase where requestid="+requestid,"workflow_requestbase");

                //同步表 workflow_form
                syncTableData("select * from oacodeprd.workflow_form where requestid="+requestid,"workflow_form");

                //同步表 workflow_currentoperator
                syncTableData("select * from oacodeprd.workflow_currentoperator where requestid="+requestid,"workflow_currentoperator");

                //同步表 workflow_requestlog
                syncTableData("select * from oacodeprd.workflow_requestlog where requestid="+requestid,"workflow_requestlog");

                //同步表 workflow_nownode
                syncTableData("select * from oacodeprd.workflow_nownode where requestid="+requestid,"workflow_nownode");

                //同步表 workflow_freenode
                syncTableData("select * from oacodeprd.workflow_freenode where requestid="+requestid,"workflow_freenode");

                //同步表 workflow_freenode_group
                syncTableData("select * from oacodeprd.workflow_freenode_group where requestid="+requestid,"workflow_freenode_group");

                //同步表 workflow_reqbrowextrainfo
                syncTableData("select * from oacodeprd.workflow_reqbrowextrainfo where requestid="+requestid,"workflow_reqbrowextrainfo");

                //同步表 workflow_requestviewlog
                syncTableData("select * from oacodeprd.workflow_requestviewlog where id="+requestid,"workflow_requestviewlog");

                //同步表 workflow_autoflowlog
                syncTableData("select * from oacodeprd.workflow_autoflowlog where requestid="+requestid,"workflow_autoflowlog");

                //同步表 workflow_requestoperatelog
                syncTableData("select * from oacodeprd.workflow_requestoperatelog where requestid="+requestid,"workflow_requestoperatelog");


                //同步表单数据
                syncTableData("select * from oacodeprd."+maintable+" where requestid="+requestid,maintable);

                for(String dtable:detailTables){
                    syncTableData("select * from oacodeprd."+dtable+" where mainid="+synMainId,dtable);
                }

                //rst.commit();
//                WorkflowRequestComInfo wfReqComInfo = new WorkflowRequestComInfo();
//                wfReqComInfo.addRequestInfoCache(requestid);

            }
        }catch (Exception e) {
            //rst.rollback();;
            e.printStackTrace();
        }


    }




    public void syncTableData(String dataSql,String tableName){
        RecordSetDataSource rsd = new RecordSetDataSource("fromdb");
        rsd.execute(dataSql);
        String columnNames[] =  rsd.getColumnName();
        int count = rsd.getCounts();

        if(count>0){
            StringBuffer sb =  new StringBuffer();
            sb.append("insert into ").append(tableName).append(" values(");
            String split ="";
            for (int i = 0; i <columnNames.length ; i++) {
                sb.append(split).append("?");
                split=",";
            }
            sb.append(")");
            String insertSql = sb.toString();

            RecordSet rs = new RecordSet();
            while(rsd.next()){
                List<String> values = new ArrayList<>();
                for (String columnName:columnNames) {
                    String columnValue = rsd.getString(columnName);
                    values.add(columnValue);
                }
                rs.executeUpdate(insertSql,values);

            }
        }



    }


    public void doFileDataSyn(String systime){

        RecordSetDataSource rsd = new RecordSetDataSource("fromdb");
        RecordSetDataSource rsd2 = new RecordSetDataSource("fromdb");
        RecordSet rs = new RecordSet();
        try {

            rsd.execute(" select id from oacodeprd.docdetail where   (doclastmoddate || ' '||doclastmodtime)>= '"+systime+"' ");
            while(rsd.next()){
                int docid = rsd.getInt("id");

                //同步docdetail
                rs.executeUpdate(" delete from docdetail where id=? ",docid);
                syncTableData("select * from oacodeprd.docdetail where id="+docid,"docdetail");

                //同步 docimagefile
                rs.executeUpdate(" delete from docimagefile where docid=? ",docid);
                rsd2.execute(" select id from oacodeprd.docimagefile where docid="+docid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from docimagefile where id=? ",id);
                }
                syncTableData("select * from oacodeprd.docimagefile where docid="+docid,"docimagefile");

                //同步 imagefile
                rsd2.execute(" select * from oacodeprd.docimagefile where docid="+docid);
                while(rsd2.next()){
                    String imagefileid = Util.null2String(rsd2.getString("imagefileid"));
                    rs.executeUpdate(" delete from imagefile where imagefileid=? ",imagefileid);
                    syncTableData("select * from oacodeprd.imagefile where imagefileid="+imagefileid,"imagefile");

                }

                //同步 docshare
                rs.executeUpdate(" delete from docshare where docid=? ",docid);
                rsd2.execute(" select id from oacodeprd.docshare where docid="+docid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from docshare where id=? ",id);
                }
                syncTableData("select * from oacodeprd.docshare where docid="+docid,"docshare");

                //同步 shareinnerdoc
                rs.executeUpdate(" delete from shareinnerdoc where sourceid=? ",docid);
                rsd2.execute(" select id from oacodeprd.shareinnerdoc where sourceid="+docid);
                while(rsd2.next()){
                    int id = rsd2.getInt("id");
                    rs.executeUpdate(" delete from shareinnerdoc where id=? ",id);
                }
                syncTableData("select * from oacodeprd.shareinnerdoc where sourceid="+docid,"shareinnerdoc");

                DocComInfo docComInfo = new DocComInfo();
                docComInfo.addDocInfoCache(docid+"");
            }

            //rst.commit();

        }catch (Exception e) {
            //rst.rollback();;
            e.printStackTrace();
        }


    }


    /**
     * @param flag 0关闭触发器  1开启触发器
     */
    public void controlTrigger(int flag){
        String operation = "enable";
        if(flag==0){
            operation = "disable";
        }

        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        RecordSet rs3 = new RecordSet();

        //关闭开启流程基础表触发器
        String wfBaseTables[] = {"workflow_form","workflow_requestbase","workflow_currentoperator","workflow_requestlog","workflow_nownode",
                "workflow_freenode","workflow_freenode_group","workflow_reqbrowextrainfo","workflow_requestviewlog","workflow_autoflowlog",
                "workflow_requestoperatelog"};
        for(int i=0;i<wfBaseTables.length;i++){
            rs.executeUpdate(" alter table "+wfBaseTables[i]+" "+operation+" all triggers ");
        }

        //关闭打开表单触发器
        String wfSql = "select * from workflow_base where unnumber in('gsfw','dgtfw','zhfw','fzjgfw','zbggfb'," +
                "'ggfbfzjg','gssw','gsswldsy','gsswxbbm','gsswyz','gsswzbbm') and isvalid=1  ";
        rs.executeQuery(wfSql);
        while(rs.next()){
            int formid = rs.getInt("formid");
            String mainTableSql = " select tablename from workflow_bill where id=? ";
            String maintable = SqlUtil.querySingleField(mainTableSql,formid);
            rs2.executeUpdate(" alter table "+maintable+" "+operation+" all triggers ");


            String dtTableSql = " select distinct detailtable from workflow_billfield  " +
                    " where billid=? and (detailtable is not null or detailtable='')  order by detailtable ";
            rs2.executeQuery(dtTableSql,formid);
            while (rs2.next()){
                String detailTable = Util.null2String(rs2.getString("detailtable"));
                rs3.executeUpdate(" alter table "+detailTable+" "+operation+" all triggers ");

            }
        }

        //关闭打开文档表触发器
        String docBaseTables[] = {"docdetail","docimagefile","imagefile","docshare","shareinnerdoc"};
        for(int i=0;i<docBaseTables.length;i++){
            rs.executeUpdate(" alter table "+docBaseTables[i]+" "+operation+" all triggers ");
        }

    }


    public static void main(String[] args) {
        GCONST.setRootPath("./");
        GCONST.setServerName("ecology");

        WfDataSyn proDataSyn = new WfDataSyn();
        proDataSyn.execute();

        String  sysdate  = LocalDate.now().minusDays(1l).toString();
        System.out.println(sysdate);




    }
}
