package weaver.interfaces.zjrb.mode;

import oracle.sql.CLOB;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.RequestInfo;

import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.*;

public class MicroExaminationUserModeExpand2 extends AbstractModeExpandJavaCodeNew {
    /**
     * 执行模块扩展动作
     * @param param
     *  param包含(但不限于)以下数据
     *  user 当前用户
     *  importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加，2覆盖,3更新，获取方式(int)param.get("importtype")
     *  导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输)，比如a=1，可通过param.get("a")获取参数值
     *  页面链接拼接的参数，比如b=2,可以通过param.get("b")来获取参数
     * @return
     */
    public Map<String, String> doModeExpand(Map<String, Object> param) {
        Map<String, String> result = new HashMap<String, String>();
        try {
            User user = (User)param.get("user");
            int billid = -1;//数据id
            int modeid = -1;//模块id
            RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo");
            if(requestInfo!=null){
                billid = Util.getIntValue(requestInfo.getRequestid());
                modeid = Util.getIntValue(requestInfo.getWorkflowid());
                if(billid>0&&modeid>0){
                    //------请在下面编写业务逻辑代码------
                    saveUserData(billid+"",user);
                }
            }
        } catch (Exception e) {
            result.put("errmsg","自定义出错信息");
            result.put("flag", "false");
        }
        return result;
    }


    /***
     *
     * @param billid
     */
    public void saveUserData(String billid,User user){
        BaseBean bb = new BaseBean();
        long start = System.currentTimeMillis();
        bb.writeLog("ExaminationPaperModeExpand-"+billid+":"+start);
        ResourceComInfo resourceComInfo = null;
        try{
            RecordSet rs = new RecordSet();
            boolean isTrue2 = false;
            resourceComInfo = new ResourceComInfo();

            String uf_table = "uf_ksks" ;
            String formmodeid = "" ;
            String tableSql=" select k.id from modeinfo k  \n" +
                            " inner join workflow_bill l on formid = l.id\n" +
                            " where l.tablename = '"+uf_table+"' " ;
            rs.execute(tableSql);
            if(rs.next()){
                formmodeid = Util.null2String(rs.getString("id"));
            }

            String modedatacreater = user.getUID()+"";
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");//设置日期格式
            String modedatacreatedate = sdfDate.format(new Date());
            String modedatacreatetime = sdfTime.format(new Date());
            String modedatacreatertype = "0";
            String uuid = UUID.randomUUID().toString();

            if(StringUtils.isNotBlank(billid)){

                if(("oracle").equals(rs.getDBType())){
                    bb.writeLog("oracle");
                    String sfqtygks = "" ;
                    String sql = " select sfqtygks from uf_ks_kjb where id = "+billid ;
                    rs.executeQuery(sql);
                    if(rs.next()){
                        sfqtygks = Util.null2String(rs.getString("sfqtygks"));
                    }
                    bb.writeLog("sfqtygks:"+sfqtygks);

                    Map<String,Map<String,String>> userMap = new HashMap<String,Map<String,String>>();
                    sql = " select id,zgs,fgs,sgs from picc_hrm_org_path_view";
                    rs.executeQuery(sql);
                    while (rs.next()){
                        String id = Util.null2String(rs.getString("id"));
                        String zgs = Util.null2String(rs.getString("zgs"));
                        String fgs = Util.null2String(rs.getString("fgs"));
                        String sgs = Util.null2String(rs.getString("sgs"));
                        Map<String,String> gsMap = new HashMap<String,String>();
                        gsMap.put("zgs",zgs);
                        gsMap.put("fgs",fgs);
                        gsMap.put("sgs",sgs);
                        userMap.put(id,gsMap);
                    }

                    if("0".equals(sfqtygks)){
                        List<String> khryList = new ArrayList<String>();
                        sql = " select id from hrmresource where status in(0,1,2,3) and loginid is not null and password is not null ";
                        bb.writeLog("sql:"+sql);
                        rs.executeQuery(sql);
                        while (rs.next()){
                            String id = Util.null2String(rs.getString("id"));
                            khryList.add(id);
                        }
                        bb.writeLog("khryList:"+khryList.size());
                        sql = " delete from "+uf_table+" where mainid = "+billid ;
                        boolean isTrue = rs.executeUpdate(sql);
                        bb.writeLog("isTrue:"+isTrue);
                        if(isTrue){
                            List<List> batchList = new ArrayList<>(); //存放每条数据更新时需要的参数

                            for(int i=0;i<khryList.size();i++){
                                String userid = khryList.get(i);
                                String deptid = "" ;
                                if(StringUtils.isNotBlank(userid)){
                                    deptid = resourceComInfo.getDepartmentID(userid);
                                }

                                String zgs = "";
                                String fgs = "";
                                String sgs = "";
                                if(userMap.containsKey(userid)){
                                    Map<String,String> gsMap =userMap.get(userid);
                                    if(gsMap.containsKey("zgs")){
                                        zgs = gsMap.get("zgs");
                                    }
                                    if(gsMap.containsKey("fgs")){
                                        fgs = gsMap.get("fgs");
                                    }
                                    if(gsMap.containsKey("sgs")){
                                        sgs = gsMap.get("sgs");
                                    }
                                }

                                List<String> userList = new ArrayList<String>();
                                userList.add(billid);
                                userList.add(userid);
                                userList.add(deptid);
                                userList.add("0");
                                userList.add(zgs);
                                userList.add(fgs);
                                userList.add(sgs);

                                userList.add(formmodeid);
                                userList.add(modedatacreater);
                                userList.add(modedatacreatertype);
                                userList.add(modedatacreatedate);
                                userList.add(modedatacreatetime);

                                batchList.add(userList);
                            }

                            bb.writeLog("batchList:"+batchList.size());
                            if(batchList.size()>0){
                                sql = " insert into "+uf_table+"(mainid,ks,ksssbm,zt,kssszgs,ksssfgs,kssssgs,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime) values(?,?,?,?,?,?,?,?,?,?,?,?)";
                                isTrue2 = rs.executeBatchSql(sql,batchList);
                                bb.writeLog("isTrue2:"+isTrue2);
                            }
                        }
                    }else if("1".equals(sfqtygks)){
                        String ksfw = "";
                        ConnStatement statement = null;
                        try{
                            statement = new ConnStatement();
                            sql = "select ksfw from uf_ks_kjb where id = " + billid;
                            statement.setStatementSql(sql, false);
                            statement.executeQuery();
                            if (statement.next()) {
                                CLOB clob = statement.getClob("ksfw");
                                String readline = "";
                                StringBuffer clobStrBuff = new StringBuffer("");
                                BufferedReader clobin = new BufferedReader(clob.getCharacterStream());
                                while ((readline = clobin.readLine()) != null)
                                    clobStrBuff = clobStrBuff.append(readline);
                                clobin.close();
                                ksfw = clobStrBuff.toString();
                            }
                        }catch(Exception e){
                            bb.writeLog("saveUserData2-e:"+e);
                        }finally {
                            statement.close();
                        }


                        long start2 = System.currentTimeMillis();
                        bb.writeLog("ExaminationPaperModeExpand-"+billid+":"+start2);
                        if(StringUtils.isNotBlank(ksfw)){

                            sql = " delete from "+uf_table+" where mainid = "+billid ;
                            boolean isTrue = rs.executeUpdate(sql);
                            if(isTrue){
                                String[] userids = ksfw.split(",");

                                bb.writeLog("userids:"+userids.length);

                                List<List> batchList = new ArrayList<>(); //存放每条数据更新时需要的参数
                                for(int i=0;i<userids.length;i++){
                                    String userid = userids[i];
                                    String deptid = "" ;
                                    if(StringUtils.isNotBlank(userid)){
                                        deptid = resourceComInfo.getDepartmentID(userid);
                                    }

                                    String zgs = "";
                                    String fgs = "";
                                    String sgs = "";
                                    if(userMap.containsKey(userid)){
                                        Map<String,String> gsMap =userMap.get(userid);
                                        if(gsMap.containsKey("zgs")){
                                            zgs = gsMap.get("zgs");
                                        }
                                        if(gsMap.containsKey("fgs")){
                                            fgs = gsMap.get("fgs");
                                        }
                                        if(gsMap.containsKey("sgs")){
                                            sgs = gsMap.get("sgs");
                                        }
                                    }

                                    List<String> userList = new ArrayList<String>();
                                    userList.add(billid);
                                    userList.add(userid);
                                    userList.add(deptid);
                                    userList.add("0");
                                    userList.add(zgs);
                                    userList.add(fgs);
                                    userList.add(sgs);

                                    userList.add(formmodeid);
                                    userList.add(modedatacreater);
                                    userList.add(modedatacreatertype);
                                    userList.add(modedatacreatedate);
                                    userList.add(modedatacreatetime);

                                    batchList.add(userList);
                                }

                                bb.writeLog("batchList:"+batchList.size());
                                if(batchList.size()>0){
                                    sql = " insert into "+uf_table+"(mainid,ks,ksssbm,zt,kssszgs,ksssfgs,kssssgs,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime) values(?,?,?,?,?,?,?,?,?,?,?,?)";
                                    isTrue2 = rs.executeBatchSql(sql,batchList);
                                    bb.writeLog("isTrue2:"+isTrue2);
                                }
                            }
                        }
                    }
                    bb.writeLog("isTrue2:"+isTrue2);
//                    if(isTrue2){
//                        try{
//                            sql = " update uf_ks_kjb set ksfw = empty_clob() where id = " + billid;
//                            bb.writeLog("sql:"+sql);
//                            isTrue2 = rs.executeUpdate(sql);
//                            bb.writeLog("isTrue22:"+isTrue2);
//                        }catch(Exception e){
//                            bb.writeLog("saveUserData2-e:"+e);
//                        }
//                    }
                }
                long end = System.currentTimeMillis();
                bb.writeLog("ExaminationPaperModeExpand-"+billid+":"+end);
            }
        }catch (Exception e){
           bb.writeLog("e:"+e+"</br>");
        }
    }
}
