package weaver.interfaces.htsc.workflowdoc;

import com.weaver.general.Util;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.interfaces.schedule.BaseCronJob;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


public class Workflowdoc2ModeJob extends BaseCronJob {
    @Override
    public void execute() {
        runWorkflowdoc2Mode();
    }

    public void runWorkflowdoc2Mode(){
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        try{
            //System.out.println();
            bb.infoLog("进入--runWorkflowdoc2Mode--定时器","");
            try{
                String delsql = "  delete from uf_processfile where id in( \n" +
                                "  select l.id\n" +
                                "  from (select id,\n" +
                                "               ROW_NUMBER() OVER(PARTITION BY lcid, docid, imagefileid ORDER BY id) as px\n" +
                                "          from uf_processfile\n" +
                                "       ) l\n" +
                                "  where l.px > 1\n" +
                                " ) ";
                rs.execute(delsql);
            }catch (Exception e){

            }

            List<Map<String,String>> list = new ArrayList<Map<String,String>>();
            Map<String,String> map = null;
            String sql = " select lcxz,fjzd from uf_lcfjzdcx where sfqy = 0";
            rs.execute(sql);
            while (rs.next()){
                String lcxz = Util.null2String(rs.getString("lcxz"));
                String fjzd = Util.null2String(rs.getString("fjzd"));
                map = new HashMap<String,String>();
                map.put("lcxz",lcxz);
                map.put("fjzd",fjzd);
                list.add(map);
            }

            String formmodeid = "";
            rs.executeQuery( "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = 'uf_processfile'" );
            if(rs.next()){
                formmodeid = Util.null2String( rs.getString( "id" ) );
            }

            SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss");
            String modedatacreatedate = formatter1.format(new Date());
            String modedatacreatetime = formatter2.format(new Date());
            String modedatacreater = "1";
            String modedatacreatertype = "0";

            for(int i=0;i<list.size();i++)
            {
                Map<String,String> datamap = list.get(i);
                String lcxz = Util.null2String(datamap.get("lcxz"));
                String fjzd = Util.null2String(datamap.get("fjzd"));
                if(!"".equals(lcxz)){
                    String fromtable = "" ;
                    sql = " select 'formtable_main_'||abs(formid) as fromtable from workflow_base where id= "+lcxz;
                    rs.execute(sql);
                    if(rs.next()){
                        fromtable = Util.null2String(rs.getString("fromtable"));
                    }

                    if(!"".equals(fromtable))
                    {
                        if(!"".equals(fjzd))
                        {
                            String fjzdnew = "" ;
                            String[] fj_zds = fjzd.split(",");
                            for(int n=0;n<fj_zds.length;n++){
                                if(n == 0){
                                    fjzdnew += " (case when to_char("+fj_zds[n]+") is not null then to_char("+fj_zds[n]+") else '' end)" ;
                                }else{
                                    fjzdnew += "||(case when to_char("+fj_zds[n]+") is not null then ','||to_char("+fj_zds[n]+") else '' end)" ;
                                }
                            }

                            List<Map<String,String>> fjList = new ArrayList<Map<String,String>>();
                            Map<String,String> fjmap = null;
                            sql = " select "+fjzdnew+" as fjzd,h.requestid from "+fromtable+" t \n" +
                                  " inner join workflow_requestbase h on h.requestid = t.requestid\n" +
                                  " where h.workflowid= "+lcxz +" and h.currentnodetype in(1,2,3) " +
                                  " and lastoperatedate >= to_char(sysdate-1,'yyyy-mm-dd')" ;
                            rs.execute(sql);
                            bb.infoLog("sql:",sql);
                            while (rs.next()){
                                String fjvalue = Util.null2String(rs.getString("fjzd"));
                                String requestid = Util.null2String(rs.getString("requestid"));

                                fjmap = new HashMap<String,String>();
                                fjmap.put("fjvalue",fjvalue);
                                fjmap.put("lcid",requestid);
                                fjList.add(fjmap);
                            }

                            List<Map<String,String>> docinfoList = new ArrayList<Map<String,String>>();
                            Map<String,String> docmap = null;
                            if(fjList !=null && fjList.size() > 0){
                                for(int k=0;k<fjList.size();k++){

                                    Map<String,String> fj_map = fjList.get(k);
                                    String fj =  fj_map.get("fjvalue");
                                    String lcid =  fj_map.get("lcid");

                                    String uf_fjids = "" ;
                                    sql = " select docid from uf_processfile where lcid="+lcid;

                                    rs.execute(sql);
                                    while (rs.next()){
                                        uf_fjids += uf_fjids == "" ? Util.null2String(rs.getString("docid")) : ","+Util.null2String(rs.getString("docid"));
                                    }
                                    boolean isequal  = isEqualData(uf_fjids,fj);
                                    if(!isequal)
                                    {
                                        sql = " delete from uf_processfile where lcid="+lcid  ;
                                        boolean flag = rs.execute(sql);
                                        if(flag){
                                            if(!"".equals(fj))
                                            {
                                                if(fj.startsWith(",")){
                                                    fj = fj.substring(1);
                                                }
                                                List<String> fjlist = new ArrayList<>(Arrays.asList(fj.split(",")));
                                                List<String> qclist = fjlist.stream().distinct().collect(Collectors.toList());
                                                String fjnew = String.join(",", qclist);
                                                sql = " select d.id,k.imagefileid,k.fileid,h.imagefilename,d.doccreatedate||' '||d.doccreatetime as doccreatedate\n" +
                                                        "from docdetail d \n" +
                                                        "inner join docimagefile h on h.docid = d.id\n" +
                                                        "inner join imagefile k on k.imagefileid = h.imagefileid\n" +
                                                        "where docid in("+fjnew+")" ;

                                                bb.infoLog("sql:",sql);
                                                rs.execute(sql);
                                                while (rs.next()){
                                                    String docid = Util.null2String(rs.getString("id"));
                                                    String imagefileid = Util.null2String(rs.getString("imagefileid"));
                                                    String fileid = Util.null2String(rs.getString("fileid"));
                                                    String imagefilename = Util.null2String(rs.getString("imagefilename"));
                                                    String doccreatedate = Util.null2String(rs.getString("doccreatedate"));
                                                    docmap = new HashMap<String,String>();

                                                    docmap.put("formmodeid",formmodeid+"");
                                                    docmap.put("modedatacreater",modedatacreater+"");
                                                    docmap.put("modedatacreatertype",modedatacreatertype+"");
                                                    docmap.put("modedatacreatedate",modedatacreatedate+"");
                                                    docmap.put("modedatacreatetime",modedatacreatetime+"");

                                                    docmap.put("workflowid",lcxz);

                                                    docmap.put("lcid",lcid);
                                                    docmap.put("docid",docid);
                                                    docmap.put("imagefileid",imagefileid);
                                                    docmap.put("fileid",fileid);
                                                    docmap.put("attachname",imagefilename);
                                                    docmap.put("updatetime",modedatacreatedate+" "+modedatacreatetime);
                                                    docinfoList.add(docmap);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //System.out.println("docinfoList:"+docinfoList.size());

                            for(int p=0;p<docinfoList.size();p++ )
                            {
                                Map<String,String> doc_map = docinfoList.get(p);

                                String dttablename = "" ;
                                String dttablenvalue = "" ;
                                for (Map.Entry<String, String> entry : doc_map.entrySet())
                                {
                                    String fieldname = Util.null2String(entry.getKey());
                                    String fieldvalue = Util.null2String(entry.getValue());
                                    dttablename += dttablename==""? fieldname :","+fieldname ;
                                    dttablenvalue += dttablenvalue=="" ? "'"+fieldvalue+"'" :",'"+fieldvalue+"'" ;
                                }
                                if(dttablename !="" && dttablenvalue !="")
                                {
                                    sql = "insert into uf_processfile("+dttablename+") values ("+dttablenvalue+")";

                                    rs.execute(sql);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){

        }
    }

    /***
     *
     * @param modedocid
     * @param workflowdocid
     * @return
     */
    public boolean isEqualData(String modedocid,String workflowdocid){
        boolean flag = false ;
        BaseBean bb = new BaseBean();

        //bb.writeLog("modedocid:"+modedocid);
        //bb.writeLog("workflowdocid:"+workflowdocid);

        try{
            if(workflowdocid.equals(modedocid)){
                flag = true;
            }else{
                if(workflowdocid.length() == modedocid.length())
                {
                    List<String> modelist = new ArrayList<>(Arrays.asList(modedocid.split(",")));
                    List<String> workflowlist = new ArrayList<>(Arrays.asList(workflowdocid.split(",")));
                    Collections.sort(modelist);
                    Collections.sort(workflowlist);

                    String modedocids = String.join(",", modelist);
                    //System.out.println(modedocids);
                    String workflowdocids = String.join(",", workflowlist);
                    //System.out.println(workflowdocids);

                    if(workflowdocids.equals(modedocids)){
                        flag = true;
                    }else{
                        flag = false;
                    }
                }else{
                    flag = false;
                }


//            try{
//                if(!"".equals(modedocid) && !"".equals(workflowdocid)){
//                    List<String> modelist = new ArrayList<>(Arrays.asList(modedocid.split(",")));
//                    List<String> workflowlist = new ArrayList<>(Arrays.asList(workflowdocid.split(",")));
//                    List<String> qclist = workflowlist.stream().distinct().collect(Collectors.toList());
//                    Iterator<String> it1 = qclist.iterator();
//                    while(it1.hasNext()){
//                        String workflow_docid = it1.next();
//                        System.out.println("workflow_docid:"+workflow_docid);
//                        Iterator<String> it2 = modelist.iterator();
//                        while(it2.hasNext()){
//                            String mode_docid = it2.next();
//                            //System.out.println("mode_docid:"+mode_docid);
//                            if(workflow_docid.equals(mode_docid)){
//                                it2.remove();
//                                it1.remove();
//
//                                //System.out.println("modelist:"+modelist.size());
//                                //System.out.println("workflowlist:"+workflowlist.size());
//                            }
//                        }
//                    }
//
//                    System.out.println("modelist:"+modelist.size());
//                    System.out.println("workflowlist:"+workflowlist.size());
//
//                    if(qclist.size() ==0 && modelist.size() ==0 ){
//                        flag = true;
//                    }
//                }
//            }catch (Exception e){
//                bb.writeLog("ee2:"+e);
//                System.out.println(e);
//                flag = false;
//            }
            }
        }catch (Exception e){
            bb.writeLog("e:"+e);
            flag = false;
        }

        return flag;
    }


    /***
     *
     */
    public void runInitWorkflowdoc2Mode(){

        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();

        try{
            String delsql = "  delete from uf_processfile where id in( \n" +
                    "  select l.id\n" +
                    "  from (select id,\n" +
                    "               ROW_NUMBER() OVER(PARTITION BY lcid, docid, imagefileid ORDER BY id) as px\n" +
                    "          from uf_processfile\n" +
                    "       ) l\n" +
                    "  where l.px > 1\n" +
                    " ) ";
            bb.infoLog("delsql:",delsql);
            boolean flag = rs.execute(delsql);

        }catch (Exception e){

        }

        try{
            bb.infoLog("进入--runWorkflowdoc2Mode--INIT","");
            List<Map<String,String>> list = new ArrayList<Map<String,String>>();
            Map<String,String> map = null;
            String sql = " select lcxz,fjzd from uf_lcfjzdcx where sfqy = 0";
            rs.execute(sql);
            while (rs.next()){
                String lcxz = Util.null2String(rs.getString("lcxz"));
                String fjzd = Util.null2String(rs.getString("fjzd"));
                map = new HashMap<String,String>();
                map.put("lcxz",lcxz);
                map.put("fjzd",fjzd);
                list.add(map);
            }

            String formmodeid = "";
            rs.executeQuery( "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = 'uf_processfile'" );
            if(rs.next()){
                formmodeid = Util.null2String( rs.getString( "id" ) );
            }

            SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss");
            String modedatacreatedate = formatter1.format(new Date());
            String modedatacreatetime = formatter2.format(new Date());
            String modedatacreater = "1";
            String modedatacreatertype = "0";

            for(int i=0;i<list.size();i++)
            {
                Map<String,String> datamap = list.get(i);
                String lcxz = Util.null2String(datamap.get("lcxz"));
                String fjzd = Util.null2String(datamap.get("fjzd"));
                if(!"".equals(lcxz)){
                    String fromtable = "" ;
                    sql = " select 'formtable_main_'||abs(formid) as fromtable from workflow_base where id= "+lcxz;
                    rs.execute(sql);
                    if(rs.next()){
                        fromtable = Util.null2String(rs.getString("fromtable"));
                    }

                    if(!"".equals(fromtable))
                    {
                        if(!"".equals(fjzd))
                        {
                            String fjzdnew = "" ;
                            String[] fj_zds = fjzd.split(",");
                            for(int n=0;n<fj_zds.length;n++){
                                if(n == 0){
                                    fjzdnew += " (case when to_char("+fj_zds[n]+") is not null then to_char("+fj_zds[n]+") else '' end)" ;
                                }else{
                                    fjzdnew += "||(case when to_char("+fj_zds[n]+") is not null then ','||to_char("+fj_zds[n]+") else '' end)" ;
                                }
                            }

                            List<Map<String,String>> fjList = new ArrayList<Map<String,String>>();
                            Map<String,String> fjmap = null;
                            sql = " select "+fjzdnew+" as fjzd,h.requestid from "+fromtable+" t \n" +
                                    " inner join workflow_requestbase h on h.requestid = t.requestid\n" +
                                    " where h.workflowid= "+lcxz +" and h.currentnodetype in(1,2,3) " ;
                            rs.execute(sql);
                            bb.infoLog("sql:",sql);
                            while (rs.next()){
                                String fjvalue = Util.null2String(rs.getString("fjzd"));
                                String requestid = Util.null2String(rs.getString("requestid"));

                                fjmap = new HashMap<String,String>();
                                fjmap.put("fjvalue",fjvalue);
                                fjmap.put("lcid",requestid);
                                fjList.add(fjmap);
                            }

                            List<Map<String,String>> docinfoList = new ArrayList<Map<String,String>>();
                            Map<String,String> docmap = null;
                            if(fjList !=null && fjList.size() > 0){
                                for(int k=0;k<fjList.size();k++){

                                    Map<String,String> fj_map = fjList.get(k);
                                    String fj =  fj_map.get("fjvalue");
                                    String lcid =  fj_map.get("lcid");

                                    String uf_fjids = "" ;
                                    sql = " select distinct docid from uf_processfile where lcid="+lcid;
                                    rs.execute(sql);
                                    while (rs.next()){
                                        uf_fjids += uf_fjids == "" ? Util.null2String(rs.getString("docid")) : ","+Util.null2String(rs.getString("docid"));
                                    }
                                    boolean isequal  = isEqualData(uf_fjids,fj);
                                    if(!isequal)
                                    {
                                        sql = " delete from uf_processfile where lcid="+lcid  ;
                                        bb.infoLog("sql:",sql);
                                        boolean flag = rs.execute(sql);
                                        if(flag){
                                            if(fj.startsWith(",")){
                                                fj = fj.substring(1);
                                            }
                                            sql =   " select * from (\n" +
                                                    "  select d.id,k.imagefileid,k.fileid,h.imagefilename,\n" +
                                                    "  d.doccreatedate||' '||d.doccreatetime as doccreatedate,h.versionid,\n" +
                                                    "  row_number() over(partition by d.id order by h.versionid desc)  as px\n" +
                                                    "  from docdetail d \n" +
                                                    "  inner join docimagefile h on h.docid = d.id\n" +
                                                    "  inner join imagefile k on k.imagefileid = h.imagefileid\n" +
                                                    "  where docid in("+fj+")\n" +
                                                    " ) l where l.px=1" ;
                                            bb.infoLog("sql:",sql);
                                            rs.execute(sql);
                                            while (rs.next()){
                                                String docid = Util.null2String(rs.getString("id"));
                                                String imagefileid = Util.null2String(rs.getString("imagefileid"));
                                                String fileid = Util.null2String(rs.getString("fileid"));
                                                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                                                docmap = new HashMap<String,String>();


                                                docmap.put("formmodeid",formmodeid+"");
                                                docmap.put("modedatacreater",modedatacreater+"");
                                                docmap.put("modedatacreatertype",modedatacreatertype+"");
                                                docmap.put("modedatacreatedate",modedatacreatedate+"");
                                                docmap.put("modedatacreatetime",modedatacreatetime+"");

                                                docmap.put("workflowid",lcxz);

                                                docmap.put("lcid",lcid);
                                                docmap.put("docid",docid);
                                                docmap.put("imagefileid",imagefileid);
                                                docmap.put("fileid",fileid);
                                                docmap.put("attachname",imagefilename);
                                                docmap.put("updatetime",modedatacreatedate+" "+modedatacreatetime);
                                                docinfoList.add(docmap);
                                            }

                                        }

                                    }
                                }
                            }

                            for(int p=0;p<docinfoList.size();p++ )
                            {
                                Map<String,String> doc_map = docinfoList.get(p);
                                String lcid = doc_map.get("lcid");
                                String docid = doc_map.get("docid");
                                String imagefileid = doc_map.get("imagefileid");
                                int flag = 0;
                                sql = " select id from uf_processfile where lcid= "+lcid+" and docid="+docid+" and imagefileid="+imagefileid ;
                                rs.execute(sql);
                                if(rs.next()){
                                    flag++;
                                }

                                if(flag == 0)
                                {
                                    String dttablename = "" ;
                                    String dttablenvalue = "" ;
                                    for (Map.Entry<String, String> entry : doc_map.entrySet())
                                    {
                                        String fieldname = Util.null2String(entry.getKey());
                                        String fieldvalue = Util.null2String(entry.getValue());
                                        dttablename += dttablename == ""? fieldname :","+fieldname ;
                                        dttablenvalue += dttablenvalue =="" ? "'"+fieldvalue+"'" :",'"+fieldvalue+"'" ;
                                    }
                                    if(dttablename !="" && dttablenvalue !="")
                                    {
                                        sql = "insert into uf_processfile("+dttablename+") values ("+dttablenvalue+")";
                                        rs.execute(sql);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
        }

    }
    public static void main(String[] args) {

//        String data1 ="3491,3492,3490";
//        String data2 ="3491,3490,3492";
//        Workflowdoc2ModeJob Workflowdoc2ModeJob = new Workflowdoc2ModeJob();
//        boolean flag = Workflowdoc2ModeJob.isEqualData(data1,data2);
//        System.out.println(flag);


        GCONST.setRootPath("WEB-INF/");
        GCONST.setServerName("ecology");
        Workflowdoc2ModeJob Workflowdoc2ModeJob = new Workflowdoc2ModeJob();
        Workflowdoc2ModeJob.runInitWorkflowdoc2Mode();

    }


}