/***********************************************************************************
 * @@ Program Name : HttpDeptList.java Description : 기관에속한 부서들의 목록 Author : 강원중 Create Date : 2003-12-16 History :
 * @@
 ***********************************************************************************/

package kr.co.kihyun.beans.user;

import java.io.IOException;
import java.io.PrintWriter;
//import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import kr.co.kihyun.beans.entity.MDept;
import kr.co.kihyun.beans.entity.MUser;
import kr.co.kihyun.beans.entity.UserPart;
import kr.co.kihyun.beans.entity.util.MPersistenceManager;
import kr.co.kihyun.beans.entity.util.PMF;

import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.lang.MString;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.user.HttpDeptListApprove")
public class HttpDeptListApprove extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpDeptListApprove.class);

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException,
			NumberFormatException {
		doPost(req, res);
		return;
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException,
			NumberFormatException {
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();

		String idList = Encoder.toJava(req.getParameter("idList"));
		String typeList = Encoder.toJava(req.getParameter("typeList"));
     	LOG.debug("typeList: {}", typeList);
		String selectType = Encoder.toJava(req.getParameter("selectType"));
		String num = Encoder.toJava(req.getParameter("num"));
		String usID = Encoder.toJava(req.getParameter("usID"));
		String validList = Encoder.toJava(MString.checkNull(req.getParameter("validList")));
		//LOG.debug("idList, typeList, selectType, num, usID, validList, {}, {}, {}, {}, {}, {}"
        //,new Object[] {idList, typeList, selectType, num, usID, validList});

		if (!MString.isNull(idList)) { // 파라메터에 dept_list.jsp에서 불러온 idList가 있다면
                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//			out.println(getRightCheckList(idList, typeList, validList));
                        
                        // 수정 : 외부 입력값 필터링
                        String filtered_idList = idList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        String filtered_typeList = typeList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        String filtered_validList = validList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDeptListApprove.doPost() filtered_idList={}, Not Test", filtered_idList);
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDeptListApprove.doPost() filtered_typeList={}, Not Test", filtered_typeList);
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDeptListApprove.doPost() filtered_validList={}, Not Test", filtered_validList);
                        out.println(getRightCheckList(filtered_idList, filtered_typeList, filtered_validList));      
                        //========================================                         
                        
//           getRightCheckList 메서드로 이동 (선택된 부서를  		     // deptFrame에 보냄)
//		   } else if (!MString.isNull(usID) && !MString.isNull(num)) {// 파라메터에 사용자그룹ID와 사용자그룹번호가 있다면
//			 out.println(getUserLeftTreeList(usID, num, selectType));// getUserLeftTreeList 메서드로 이동 (사용자그룹 부서를
//																	// leftFrame에 보냄)
		}
	}

	private String getOutputHTML(int change, String resultIDString, String resultNameString, String typeList, String validList, int count, String[] showName, boolean[] arrayValidType, String[] arrayID, String[] arrayTID, String[] arrayValid) {
		StringBuilder strbuf = new StringBuilder(8192);
		strbuf.append("<script language=\"javascript\">\n\n");
		if (change == 1) {
			strbuf.append("	alert(").append(MoumiConfig.getMessageBundle().getString("moumi.message.popup.selectDeptInclude")).append(");\n");
			strbuf.append("	\n");
		}
		strbuf.append("	function setList() {\n");
		strbuf.append("		parent.idList = \"").append(resultIDString).append("\";\n");
		strbuf.append("		parent.nameList = \"").append(resultNameString).append("\";\n");
		strbuf.append("		parent.typeList = \"").append(typeList).append("\";\n");
		strbuf.append("		orgidList = \"").append(resultIDString).append("\";\n");
		strbuf.append("		orgnameList = \"").append(resultNameString).append("\";\n");
		strbuf.append("		selidList=orgidList+',';\n");
		strbuf.append("		selnameList=orgnameList+',';\n");
		strbuf.append("	}\n\n");
		strbuf.append("	function movelist(){\n");
		strbuf.append("		var name = '';\n");
		strbuf.append("		var id = '';\n");
		strbuf.append("		var type = '';\n");
		if (!MString.isNull(validList)) {
			strbuf.append("		var valid = '';\n");
		}
		strbuf.append("		var addForm = document.AddrList;\n");
		for (int i = 0; i < count; i++) {
			strbuf.append("		if(addForm.name");
			strbuf.append(i);
			strbuf.append(".checked == false){\n");
			strbuf.append("			id += addForm.id");
			strbuf.append(i);
			strbuf.append(".value+',';\n");
			strbuf.append("			name += addForm.name");
			strbuf.append(i);
			strbuf.append(".value+',';\n");
			strbuf.append("			type += addForm.type");
			strbuf.append(i);
			strbuf.append(".value+',';\n");
			if (!MString.isNull(validList)) {
				strbuf.append("			valid += addForm.valid");
				strbuf.append(i);
				strbuf.append(".value+',';\n");
			}
			strbuf.append("		}\n\n");
		}
		if (!MString.isNull(validList)) {
			strbuf.append("		parent.leftFrameDel(name, id, type, valid);\n");
		} else {
			strbuf.append("		parent.leftFrameDel(name, id, type);\n");
		}
		strbuf.append("	}\n\n");
		strbuf.append("	function AllSelect() {\n");
		strbuf.append("		var addForm = document.AddrList;\n");
		for (int i = 0; i < count; i++) {
			strbuf.append("		addForm.name");
			strbuf.append(i);
			strbuf.append(".checked = true;\n");
		}
		strbuf.append("	}\n\n");
		strbuf.append("	function AllCancel() {\n");
		strbuf.append("		var addForm = document.AddrList;\n");
		for (int i = 0; i < count; i++) {
			strbuf.append("		addForm.name");
			strbuf.append(i);
			strbuf.append(".checked = false;\n");
		}
		strbuf.append("	}\n\n");
		strbuf.append("</script>\n");
		/******************** HTML 생성 ********************/ strbuf.append("<html>\n");
		strbuf.append("	<head></head>\n");
		strbuf.append("<link rel='stylesheet' href='/totsys/common/css/text.css' type='text/css'>\n");
		strbuf.append("	<body bgcolor=\"#FFFFFF\" text=\"#000000\" leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\" onload=\"setList()\">\n");
		strbuf.append("		<form name=AddrList method=Post>\n");
		strbuf.append("		<table border=0 cellpadding=5 cellspacing=2 width=100%>\n");
		strbuf.append("			<tr><td><font size=2 face=\"돋움\">").append(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.submit")).append(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.request")).append(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.devision")).append("(").append(count).append(")</font></td></tr>\n");
		strbuf.append("			<tr><td><font size=2 face=\"돋움\"><span style='cursor:hand' onclick='AllSelect()'>").append(MoumiConfig.getMessageBundle().getString("moumi.message.button_small.selectAll")).append("</span> | <span style='cursor:hand' onclick='AllCancel()'>").append(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.all")).append(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.cancel")).append("</span></font></td></tr>\n");
		strbuf.append("			<tr>\n");
		strbuf.append("				<td>\n");
		for (int i = 0; i < count; i++) {
            int tmpNum = i+1; //mjh추가 
			strbuf.append("		"+tmpNum+".			<input type=checkbox name=name");
			strbuf.append(i);
			strbuf.append(" value=\"");
			strbuf.append(showName[i]);
			if (!MString.isNull(validList)) {
				if (arrayValidType[i] == true && showName[i].indexOf("/") > 0) {
					strbuf.append("\" checked onclick=\"\"><font size=2 face=\"돋움\">");
				} else {
					strbuf.append("\" onclick=\"\"><font size=2 color=\"red\" face=\"돋움\">");
				}
			} else {
				strbuf.append("\" onclick=\"\"><font size=2 color=\"red\" face=\"돋움\">");
			}
			strbuf.append(showName[i]);
			strbuf.append("</font><br>\n");
			strbuf.append("					<input type=hidden name=id");
			strbuf.append(i);
			strbuf.append(" value=\"");
			strbuf.append(arrayID[i]);
			strbuf.append("\">\n");
			strbuf.append("					<input type=hidden name=type");
			strbuf.append(i);
			strbuf.append(" value=\"");
			strbuf.append(arrayTID[i]);
			strbuf.append("\">\n");
			if (!MString.isNull(validList)) {
				strbuf.append("					<input type=hidden name=valid");
				strbuf.append(i);
				strbuf.append(" value=\"");
				strbuf.append(arrayValid[i]);
				strbuf.append("\">\n");
			}
		}
		strbuf.append("				</td>\n");
		strbuf.append("			</tr>\n");
		strbuf.append("		</table>\n");
		strbuf.append("		</form>\n");
		strbuf.append("	</body>\n");
		strbuf.append("</html>\n");
        
		return strbuf.toString();
	}

	private String getPartID(String id) {
		String partID;
		if (id.indexOf("/") == -1) {
			partID = id;
		} else {
			partID = id.split("/")[1];
		}
		return partID;
	}

	private String getRightCheckList(String idList, String typeList, String validList) {
//     System.out.println("idlist====================================================================>"+idList);
//     System.out.println("typeList====================================================================>"+typeList);
//     System.out.println("validList====================================================================>"+validList);
  		String[] arrayID = idList.split(","); // 선택된부서 아이디리스트
		String[] arrayName = new String[arrayID.length];
		String[] showName = null;
		String[] arrayTID = typeList.split(",");
		String[] arrayDID;
		String[] arrayDTID;
		String[] arrayValid;
		boolean[] arrayValidType = null;
		String[] arrayValidId = null;
		int count = 0;
		int change = 0;
		String resultIDString, resultNameString;

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			for (int i = 0; i < arrayID.length; i++) { 

                    arrayName[i] = pm.getObjectById(MUser.class, arrayID[i]).getName(pm);    //User Type
                    //System.out.println(":::기타일때::::부서명"+arrayTID[i]+":::ID::"+arrayID[i]+"::유저 이름:::"+arrayName[i]);
       
			}
			tx.rollback();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
		}

		if (arrayID.length > 0) {
			count = arrayID.length;
			if (idList.length() == 0)
				count = 0;

			if (count != 0) {
				arrayDID = new String[count];
				arrayDTID = new String[count];

				int isEquals = 0;
				int newSize = 0;

				// 사용자추가 후 같은소속부서를 추가할수없도록 수정
				String[] tmp = null;
				for (int i = 0; i < count; i++) {
					isEquals = 0;
					if (arrayTID[i].equals("dept")) {
						for (int j = i + 1; j < count; j++) {
							if (arrayTID[j].equals("user")) {
								if (arrayID[j].length() > 0)
									tmp = arrayID[j].split("/");

								if (tmp.length > 1) { // tmp[1]의 ArrayOutOfBoundsException 방지
									if (tmp[1].equals(arrayID[i])) { // 선택된 사용자의 부서와 선택된 부서 중 같은게 있는지 검사
										isEquals = 1;
										change = 1;
										break;
									}
								}
							}
						}
					} else if (arrayTID[i].equals("user")) {
						if (arrayID[i].length() > 0)
							tmp = arrayID[i].split("/");

						for (int j = i + 1; j < count; j++) {
							if (arrayTID[j].equals("dept")) {
								if (tmp.length > 1) { // tmp[1]의 ArrayOutOfBoundsException 방지
									if (tmp[1].equals(arrayID[j])) { // 선택된 사용자의 부서와 선택된 부서 중 같은게 있는지 검사
										isEquals = 1;
										change = 1;
										break;
									}
								}
							}
						}
					}

					if (isEquals == 0) {
						arrayDID[newSize] = arrayID[i];
						arrayDTID[newSize] = arrayTID[i];
						newSize = newSize + 1;
					}
				}

				if (newSize == 0) {
					arrayID = new String[1];
					arrayID[0] = "";
					arrayTID = new String[1];
					arrayTID[0] = "";
					count = 0;
				} else {
					arrayID = new String[newSize];
					arrayTID = new String[newSize];
					for (int a = 0; a < newSize; a++) {
						arrayID[a] = arrayDID[a];
						arrayTID[a] = arrayDTID[a];
					}
					count = newSize;
				}
			}

			if (count == 0) {
				resultIDString = "";
				resultNameString = "";
			} else {

				Dept dept = new Dept();
				showName = new String[count];

				if (arrayName[0].indexOf("-") != -1) {
					// showName[0] = arrayName[0];
					showName[0] = (arrayName[0].split("-"))[(arrayName[0].split("-")).length - 1];
				} else {
					showName[0] = arrayName[0];
				}


				pm = new MPersistenceManager(PMF.get().getPersistenceManager());
				tx = pm.currentTransaction();
				try {
					tx.begin();

					String deptListName, upperDeptName, partID;
					typeList = arrayTID[0];
					if (!arrayTID[0].equals("group")) {
						partID = getPartID(arrayID[0]);
						deptListName = dept.getPartName(partID);
						upperDeptName = dept.getUpperDeptName(partID);
						if (!deptListName.equals(upperDeptName)) {
							deptListName += "" + upperDeptName;
						}
						showName[0] = deptListName + "" + showName[0];
					} else {
						showName[0] = pm.getObjectById(UserPart.class, arrayID[0]).getName();
					}

					resultIDString = arrayID[0];
					resultNameString = showName[0];

					for (int i = 1; i < count; i++) {
						typeList = typeList + "," + arrayTID[i];
						if (arrayName[i].indexOf("-") != -1) {
							showName[i] = (arrayName[i].split("-"))[(arrayName[i].split("-")).length - 1];
						} else {
							showName[i] = arrayName[i];
						}

						/*if (!arrayTID[i].equals("group")) {
							partID = getPartID(arrayID[i]);
							MDept mDept = pm.getObjectById(MDept.class, partID);
							MDept upperDept = mDept.getUpperDept(pm);
							MDept organ = mDept.getOrgan(pm);
							deptListName = organ == null ? "" : organ.getName();
							upperDeptName = upperDept == null ? "" : upperDept.getName();
							if (!deptListName.equals(upperDeptName)) {
								deptListName += "-" + upperDeptName;
							}
							showName[i] = deptListName + "-" + showName[i];
						} else {
							showName[i] = pm.getObjectById(UserPart.class, arrayID[i]).getName();
						}*/

						resultIDString = resultIDString + "," + arrayID[i];
						resultNameString = resultNameString + "," + showName[i];
					}

					tx.rollback();
				} catch (Exception e) {
					throw new RuntimeException(e);
				} finally {
					if (tx.isActive())
						tx.rollback();
					pm.close();
				}
			}
		} else {
			throw new NullPointerException();
		}

		arrayValid = validList.split(",");
		arrayValidType = new boolean[arrayValid.length];
		arrayValidId = new String[arrayValid.length];

		if (!MString.isNull(validList)) {
			for (int i = 0; i < arrayValid.length; i++) {
				arrayValidType[i] = "1".equals(arrayValid[i].substring(0, 1));
				arrayValidId[i] = arrayValid[i].substring(arrayValid[i].indexOf("@@@@") + 4, arrayValid[i].length());
			}
		}

		return getOutputHTML(change, resultIDString, resultNameString, typeList, validList, count, showName, arrayValidType, arrayID, arrayTID, arrayValid);
	}
}
