package kr.co.kihyun.tree;

import java.io.IOException;
import java.sql.ResultSet;
//import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.co.kihyun.beans.entity.SysAuth;
//import kr.co.kihyun.lang.Encoder;
//import kr.co.kihyun.lang.MInteger;
//import kr.co.kihyun.lang.MLong;
//import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.db.DBManager;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.beans.user.HttpSSOLogin;
//import java.util.Calendar;

public class MakeJSon3 extends DBManager {

    public int dataCnt = 0, sysAuth;
    public String userId, sql = null;
    public PrintWriter out = null;
    public StringBuffer sbuf = new StringBuffer();

    public MakeJSon3(HttpServletRequest req, HttpServletResponse res) {
        try {
            res.setContentType("text/html;charset=UTF-8");
            sysAuth = HttpSSOLogin.getSysAuth(req);
            userId = HttpSSOLogin.getLoginID(req);
            out = res.getWriter();
            String id = req.getParameter("id");
            String rootId = req.getParameter("rootId");
            String rel = req.getParameter("rel");

            //String userYN=MString.checkNull(req.getParameter("userYN"),"N");
            String userYN = MString.checkNull(req.getParameter("userYN"), "Y");
            String gubun = MString.checkNull(req.getParameter("gubun"), "ORGAN");
            if (rootId == null || rootId.equals("null") || rootId.equals("ROOT")) {
                rootId = null;
            }
            sbuf.append("[");
            if (gubun.equals("GROUP")) {
                makeGroupSql(id, userId);
                group2JSon();
            } else {
                makeTreeSql(id, rootId, rel);
                dept2JSon();
                if (userYN.equals("Y")) //user2JSon(id);
                {
                    user2JSon(rel);
                }
            }
            sbuf.append("]");
            if (dataCnt > 0) {
                sbuf.deleteCharAt(sbuf.lastIndexOf(","));
            }
            out.println(sbuf.toString());
            //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
        } catch (IOException ioex) {
            ioex.printStackTrace();
            //++++++++++++++++++++++++++++++++++++++++++++++++    
        } catch (Exception ex) {
            //System.out.println("error exception1:"+ex); 
            ex.printStackTrace();
        }
    }

    public void makeTreeSql(String id, String rootId, String rel) {

        sql = null;
        if (rootId != null) {
            //System.out.println("::makeTreeSql:::rootId!=null:id::::"+id+"::::::::rootId::::::::"+rootId+"::rel:"+rel);
            sql = "SELECT ID,NAME,UPPER_DEPT,ORGAN, ";
            sql += "CASE WHEN SEL_TYPE='Y' AND SEL_TYPE<>'0' THEN 1 ELSE 0 END SEL_TYPE, ";
            //sql+="PRIORITY FROM MOUMI_DEPT WHERE ORGAN IS NOT NULL AND ID='"+rootId+"' ";
            sql += "PRIORITY FROM MOUMI_DEPT WHERE ORGAN IS NOT NULL AND ID='" + rel + "' ";
            //sql+="OR (UPPER_DEPT='"+rootId+"' AND ID=ORGAN) ORDER BY NAME";
            sql += "OR (UPPER_DEPT='" + id + "' AND ID=ORGAN) ORDER BY NAME";

            return;
        }
        if (id.equals("ROOT")) {
            //System.out.println("::makeTreeSql:::id.equals(ROOT):::id::::"+id+"::::::::rootId::::::::"+rootId+"::rel:"+rel);
            sql = "SELECT ID,NAME,UPPER_DEPT,ORGAN,";
            sql += "CASE WHEN SEL_TYPE='Y' AND SEL_TYPE<>'0' THEN 1 ELSE 0 END SEL_TYPE,";
            sql += "PRIORITY FROM MOUMI_DEPT WHERE ORGAN IS NOT NULL AND UPPER_DEPT IS NULL ";
            sql += "AND SYS_AUTH<3 ORDER BY NAME";

            return;
        }
        sql = "SELECT ID,NAME,UPPER_DEPT,ORGAN,";
        sql += "CASE WHEN SEL_TYPE='Y' AND SEL_TYPE<>'0' THEN 1 ELSE 0 END SEL_TYPE,";
        //sql+="PRIORITY FROM MOUMI_DEPT WHERE UPPER_DEPT='"+id+"' AND ID<>UPPER_DEPT AND SYS_AUTH<6 ";
        sql += "PRIORITY FROM MOUMI_DEPT WHERE UPPER_DEPT='" + id + "' AND ID<>UPPER_DEPT AND SYS_AUTH<6 ";
        sql += "ORDER BY NAME";

        return;

    }

    public void makeGroupSql(String id, String userId) {
        sql = null;
        if (id.equals("ROOT")) {
            sql = "SELECT UP.ID PART_ID,UP.NAME DEPT_NAME,UP.USER_ID,UP.ID DEPT_ID,'closed' STATE ";
            sql += "FROM MOUMI_MUSER US,MOUMI_DEPT DT,MOUMI_USER_PART UP LEFT JOIN MOUMI_USER_USER UU ON (UU.PART_ID = UP.ID) ";
            sql += "WHERE DT.ORGAN IS NOT NULL AND US.ID='" + userId + "' AND US.DEPT_ID=DT.ID ";
            sql += "AND (UP.USER_ID=US.ID OR UP.USER_ID IN (SELECT ID FROM MOUMI_MUSER WHERE SYS_AUTH=9) ";
            if (sysAuth != 2) {
                sql += "OR UP.USER_ID IN (SELECT ID FROM MOUMI_MUSER WHERE SYS_AUTH=2)";
            }
            sql += ") ORDER BY UP.NAME";

            return;
        } else {
            sql = "SELECT PART_ID,NAME DEPT_NAME,'' USER_ID,ID DEPT_ID,'opened' STATE FROM MOUMI_USER_DEPT WHERE PART_ID='" + id + "' ORDER BY NAME";

            return;
        }
    }

    public void group2JSon() {
        int ii = 0;
        ResultSet rs = null;
        String partId, deptName, userId, deptId, upper, organ, seltype, pri, state = "closed";
        partId = deptName = userId = deptId = upper = organ = seltype = pri = "";
        try {
            rs = execQuery(sql);

            if (rs == null) {
                return;
            }
            while (rs.next()) {
                partId = MString.checkNull(rs.getString(1));
                deptName = MString.checkNull(rs.getString(2));
                deptName = new GroupCount().getCount(partId, deptName);
                userId = MString.checkNull(rs.getString(3));
                deptId = MString.checkNull(rs.getString(4));
                state = MString.checkNull(rs.getString(5));
                sbuf.append("{ \"data\":\"" + deptName + "\",\"attr\": { \"ID\":\"" + deptId + "\", ");
                sbuf.append("\"UPPER\":\"" + upper + "\",\"ORGAN\":\"" + organ + "\", \"SELTYPE\":\"" + seltype + "\", ");
                sbuf.append("\"PRI\":\"" + pri + "\",\"rel\":\"GROUP\"},\"state\" : \"" + state + "\"}");
                sbuf.append(",");
                dataCnt++;

            }
            close(rs);
            rs = null;
            //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
        } catch (SQLException sqlex) {
            sqlex.printStackTrace();
            //++++++++++++++++++++++++++++++++++++++++++++++++    
        } catch (Exception ex) {
            //System.out.println("error exception2:"+ex); 
            ex.printStackTrace();
        } finally {
            if (rs != null) {
                close(rs);
            }
            execClose();
        }
    }

    public void dept2JSon() {
        int ii = 0;
        ResultSet rs = null;
        String deptId, name, upper, organ, seltype, pri;
        deptId = name = upper = organ = seltype = pri = null;
        try {
            rs = execQuery(sql);

            if (rs == null) {
                return;
            }
            while (rs.next()) {
                deptId = MString.checkNull(rs.getString(1));
                name = MString.checkNull(rs.getString(2));
                upper = MString.checkNull(rs.getString(3));
                organ = MString.checkNull(rs.getString(4));
                seltype = MString.checkNull(rs.getString(5));
                pri = MString.checkNull(rs.getString(6));
                sbuf.append("{ \"data\":\"" + name + "\",\"attr\": { \"ID\":\"" + deptId + "\", ");
                sbuf.append("\"UPPER\":\"" + upper + "\",\"ORGAN\":\"" + organ + "\", \"SELTYPE\":\"" + seltype + "\", ");
                sbuf.append("\"PRI\":\"" + pri + "\",\"rel\":\"DEPT\"},\"state\" : \"closed\"}");
                sbuf.append(",");
                dataCnt++;

            }
            close(rs);
            rs = null;
            //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
        } catch (SQLException sqlex) {
            sqlex.printStackTrace();
            //++++++++++++++++++++++++++++++++++++++++++++++++
        } catch (Exception ex) {
            //System.out.println("error exception2:"+ex); 
            ex.printStackTrace();
        } finally {
            if (rs != null) {
                close(rs);
            }
            execClose();
        }
    }

    public void user2JSon(String rel) {
        int ii = 0;
        ResultSet rs = null;
        String userId, name, sysAuth;
        String subSysadm = Integer.toString(SysAuth.SUB_SYSADM.ordinal());
        String deptName;              //2014.08.26 Add by KWON,HAN 
        
        sql = "SELECT ID,sp_cm_dec_fu(NAME),sys_auth, (SELECT X.NAME FROM MOUMI_DEPT X WHERE X.ID = DEPT_ID AND ROWNUM = 1) FROM MOUMI_MUSER WHERE DEL_TYPE='N' AND DEPT_ID='" + rel + "'";
        sql += " ORDER BY NAME_GENCPT ";
//System.out.println("user2JSon:::::"+sql);
        try {
            rs = execQuery(sql);
            if (rs == null) {
                return;
            }
            while (rs.next()) {
                userId = MString.checkNull(rs.getString(1));
                name = MString.checkNull(rs.getString(2));
                sysAuth = MString.checkNull(rs.getString(3));
                deptName = MString.checkNull(rs.getString(4));    //2014.08.26 Add by KWON,HAN 

//System.out.println("SysAuth.SUB_SYSADM.ordinal():::::"+subSysadm);                                
//System.out.println("sysAuth:::::"+sysAuth); 
                //2014.10.15 Update by KWON,HAN 
                sbuf.append("{ \"data\":\"" + name + "(" + userId + ")");
                if (sysAuth.equals(subSysadm)) {
                    sbuf.append(" [관리자]");
                }
                sbuf.append("\",");
                //==============================
                sbuf.append("\"attr\": { \"ID\":\"" + userId + "\", \"SYSAUTH\":\"" + sysAuth + "\",");
                sbuf.append("\"name\":\"" + name + "\",");         //2014.08.26 Add by KWON,HAN 
                sbuf.append("\"deptid\":\"" + rel + "\",");         //2014.08.26 Add by KWON,HAN 
                sbuf.append("\"deptname\":\"" + deptName + "\","); //2014.08.26 Add by KWON,HAN                 
                sbuf.append("\"rel\":\"USER\"},\"state\" : \"opened\"}");
                sbuf.append(",");
                dataCnt++;

            }
            close(rs);
            rs = null;
            //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
        } catch (SQLException sqlex) {
            sqlex.printStackTrace();
            //++++++++++++++++++++++++++++++++++++++++++++++++
        } catch (Exception ex) {
            //System.out.println("error exception2:"+ex); 
            ex.printStackTrace();
        } finally {
            if (rs != null) {
                close(rs);
            }
            execClose();
        }
    }
}
