package weaver.interfaces.htxc.job;

import com.weaver.formmodel.util.DateHelper;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.interfaces.htsc.util.SqlUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class GWHistoryDataSynThread extends BaseCronJob {


    @Override
    public void execute() {
        doTableDataSyn();
    }


    //流程基础表
    public String wfBaseTables[] = {"workflow_form","workflow_requestbase","workflow_currentoperator","workflow_requestlog","workflow_nownode",
            "workflow_freenode","workflow_freenode_group","workflow_reqbrowextrainfo","workflow_autoflowlog",
            "workflow_requestoperatelog","record_formfield_history"};

    //文档基础表
    public String docBaseTables[] = {"docdetail","docimagefile","imagefile","docshare","shareinnerdoc"};





    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();
            StringBuffer sb2 =  new StringBuffer();
            StringBuffer sb3 =  new StringBuffer();

            String split ="";
            for (int i = 0; i <columnNames.length ; i++) {
                sb2.append(split).append(columnNames[i]);
                sb3.append(split).append("?");
                split=",";
            }
            String insertSql =  sb.append("insert into ").append(tableName)
                    .append("(").append(sb2.toString()).append(") ").append(" values(")
                    .append(sb3.toString()).append(")").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);

            }
        }
    }


    /**
     * 开启关闭表单触发器
     * @param isopen
     */
    public void controlTrigger(boolean isopen){
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        RecordSet rs3 = new RecordSet();
        String operation = isopen?"enable":"disable";
        for(int i=0;i<wfBaseTables.length;i++){
            String sql = " alter table "+wfBaseTables[i]+" "+operation+" all triggers ";
            System.out.println("修改table"+wfBaseTables[i]+"触发器sql===>"+sql);
            rs.executeUpdate(sql);
        }

        //流程表单触发器
        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);
            String maintableSql = " alter table "+maintable+" "+operation+" all triggers ";
            System.out.println("修改table"+maintable+"触发器sql===>"+maintableSql);
            rs2.execute(maintableSql);

            //明细表同步
            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"));
                String dttableSql = " alter table "+detailTable+" "+operation+" all triggers ";
                System.out.println("修改table"+detailTable+"触发器sql===>"+dttableSql);
                rs3.execute(dttableSql);

            }
        }



    }

    /**
     * 开启关闭表单触索引
     * @param isopen
     */
    public void controlIndex(boolean isopen){
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        String operation = isopen?"REBUILD":"UNUSABLE";
        for(int i=0;i<wfBaseTables.length;i++){
            String sql = " select * from user_indexes where table_name =? ";
            rs.executeQuery(sql,wfBaseTables[i].toUpperCase());
            while (rs.next()){
                String index_name = Util.null2String(rs.getString("index_name"));
                String indexSql = " ALTER INDEX "+index_name+" "+operation;
                System.out.println("修改table "+wfBaseTables[i]+"索引sql===>"+indexSql);
                rs2.execute(indexSql);
            }
        }


    }

    public void doBakAndClearData(String tableName){
        doBakAndClearData(tableName,false);
    }

    public void doBakAndClearData(String tableName,boolean isback){
        RecordSet rs = new RecordSet();
        if(isback){
            String timstamp = DateHelper.getTimestamp();
            System.out.println("备份table "+tableName+"数据");
            rs.execute(" create table "+tableName+"_"+timstamp+" as select * from "+tableName);

        }

        System.out.println("清空table "+tableName+"数据");
        rs.executeUpdate(" truncate table "+tableName);
    }


    /**
     * 备份清空表单数据
     */
    public void clearTableData(){
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        for(int i=0;i<wfBaseTables.length;i++){
            doBakAndClearData(wfBaseTables[i]);

        }

        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);
            doBakAndClearData(maintable);

            //清空备份明细数据
            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"));
                doBakAndClearData(detailTable);

            }

        }

    }







    public void doTableDataSyn(){

        controlTrigger(false);
        clearTableData();

        ExecutorService threadPool= Executors.newFixedThreadPool(5);


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

        String dataSql = " select requestid from oacodeprd.workflow_requestbase a,oacodeprd.workflow_base b where a.workflowid=b.id " +
                " and unnumber in('gsfw','dgtfw','zhfw','fzjgfw','zbggfb','ggfbfzjg','gssw','gsswldsy','gsswxbbm','gsswyz','gsswzbbm') and isvalid=1 ";
        rsd.execute(dataSql);
        while (rsd.next()){
            String requestid = Util.null2String(rsd.getString("requestid"));
            System.out.println("开始处理流程数据requestid="+requestid);
            //同步流程基础表单数据
            for(int i=0;i<wfBaseTables.length;i++){
                String synDataSql = " select * from oacodeprd."+wfBaseTables[i]+" where requestid="+requestid;
                threadPool.execute(new TableDataSynThead(wfBaseTables[i],synDataSql));
            }


            //同步具体流程表单数据
            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);
                String synDataSql = " select * from oacodeprd."+maintable+" where requestid="+requestid;
                threadPool.execute(new TableDataSynThead(maintable,synDataSql));

                //明细表同步
                rsd2.execute(synDataSql);
                if(rsd2.next()){
                    int mainid = rsd2.getInt("id");

                    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"));
                        String detailSynDataSql = " select * from oacodeprd."+detailTable+" where mainid="+mainid;
                        threadPool.execute(new TableDataSynThead(detailTable,detailSynDataSql));

                    }
                }

            }



        }

        controlTrigger(true);

    }


    public void gwkyDataSyn(){
        gwkyDataSyn(false);
    }


    /**
     * 同步公文看阅数据
     */
    public void gwkyDataSyn(boolean isbak){
        List<String> tableList = new ArrayList<String>();
        tableList.add("uf_gwky");

        RecordSet rs = new RecordSet();
        String dtTableSql = " select distinct detailtable  from workflow_billfield where detailtable like 'uf_gwky%' order by detailtable";
        rs.execute(dtTableSql);
        while(rs.next()){
            String dtTable = Util.null2String(rs.getString("detailtable"));
            tableList.add(dtTable);
        }

        for(int i=0;i<tableList.size();i++){
            String tmptable = tableList.get(i);
            String sql1 = " alter table "+tmptable+" disable all triggers ";
            System.out.println("修改table"+tmptable+"触发器sql===>"+sql1);
            rs.execute(sql1);

            doBakAndClearData(tmptable,isbak);



            String synDataSql = " select * from oacodeprd."+tmptable;
            syncTableData(synDataSql,tmptable);


            String sql2 = " alter table "+tmptable+" enable all triggers ";
            System.out.println("修改table"+tmptable+"触发器sql===>"+sql2);
            rs.execute(sql2);



        }


    }


    public class TableDataSynThead implements Runnable{
        public String tableName;
        public String synDataSql;

        TableDataSynThead(String tableName,String synDataSql){
            this.tableName = tableName;
            this.synDataSql = synDataSql;
        }

        @Override
        public void run() {
            RecordSet rs = new RecordSet();
            System.out.println("执行同步数据sql====>"+synDataSql);
            syncTableData(synDataSql,tableName);

        }
    }


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

        GWHistoryDataSynThread historyDataSyn = new GWHistoryDataSynThread();
        historyDataSyn.syncTableData("  select * from workflow_requestbase where requestid=618618 ","workflow_requestbase");

    }
}
