package zr.zrpower.anqueryflow.action;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

import zr.zrpower.common.util.SysPreperty;
import zr.zrpower.ejb.sys.UIService;
import zr.zrpower.entity.sys.SessionUser;

import zr.zrpower.anqueryflow.service.QueryService;
import zr.zrpower.queryengine.Request;
import zr.zrpower.queryengine.mode.QUERY_CONFIG_TABLE;


public class QueryPageSer
    extends HttpServlet {

  public void init() throws ServletException {
  }

  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    response.setContentType("text/html; charset=GBK");
    request.setCharacterEncoding("GBK");

    QueryService queryControl = new QueryService();
    UIService  userUI = new UIService();


    String TITLENAME = request.getParameter("TITLENAME");
    if (TITLENAME == null) {TITLENAME = "";}

    String ISCODE = request.getParameter("ISCODE");
    if (ISCODE == null) {ISCODE = "1";}
    if (ISCODE.length()==0) {ISCODE = "1";}

    if (TITLENAME.length()>0 && ISCODE.equals("1"))
    {
          TITLENAME = new String(TITLENAME.getBytes("iso-8859-1"),"gbk");
    }

    try {

      HttpSession session = request.getSession(true);
      SessionUser user = (SessionUser) session.getAttribute("userinfo");

      Request rq=null;
     try {
       rq = new Request();
       rq.fullItem(request);
     }
     catch (Exception ex) {

     }

      String strResult = "";
      strResult = GetTemplateStr(user,request,rq,userUI,queryControl,TITLENAME);
      response.getWriter().print(strResult);

    }
    catch (Exception ex) {
      response.getWriter().print(
          "<p>发生异常！</p><p>详细错误信息:</p><p>" +
          ex.toString() + "</p>");
    }

  }

  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    doGet(request, response);
  }

  //Clean up resources
  public void destroy() {
  }

  private String GetTemplateStr(SessionUser user,HttpServletRequest _request,Request rq,UIService userUI,QueryService queryControl,String TITLENAME) {


    StringBuffer sb = new StringBuffer();
    String strRe ="";
    String sumROW = "0";


    String ID = _request.getParameter("ID");
    if (ID == null) {ID = "";}
    String SHOWTITLE = _request.getParameter("SHOWTITLE");
    if (SHOWTITLE == null) {SHOWTITLE = "";}
    String ISCODE = _request.getParameter("ISCODE");
    if (ISCODE == null) {ISCODE = "1";}
    if (ISCODE.length()==0) {ISCODE = "1";}

    String ISNULL = _request.getParameter("ISNULL");
    if (ISNULL == null) {ISNULL = "1";}

    String BUTTONIDS = _request.getParameter("BUTTONIDS");
    if (BUTTONIDS == null) {BUTTONIDS = "";}

    String ifFirstData = _request.getParameter("ifFirstData");
    String strWhere = _request.getParameter("strWhere");
    if(strWhere == null){strWhere = "";}

    String queryFlag =_request.getParameter("queryFlag");
    if(queryFlag == null){queryFlag = "0";}

    String swidth =_request.getParameter("SWIDTH");
    if(swidth == null){swidth = "0";}

    String sheight =_request.getParameter("SHEIGHT");
    if(sheight == null){sheight = "0";}


    int currentPage=1;
    int height;
    try {
      currentPage = Integer.parseInt(_request.getParameter("page"));
    }
    catch (Exception ex) {
      currentPage = 1;
    }


    try {

      QUERY_CONFIG_TABLE queryConfigEntity = queryControl.GetConfigTable(ID);

      if(ifFirstData == null)
      {ifFirstData = queryConfigEntity.getIFFIRSTDATA();}

      String queryHidDis = _request.getParameter("queryDisHid");

      if (queryHidDis != null) {
        if (queryHidDis.trim().length() > 0) {
          queryHidDis = "none";
        }
        else {
          queryHidDis = "";
        }
      }
      else {
        if (queryConfigEntity.getTYPE().equals("2")) {
          queryHidDis = "none";
        }
        else {
          queryHidDis = "";

        }
      }

      sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n");
      sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
      sb.append("<head>\r\n");
      sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=GBK\" />  \r\n");
      sb.append("<meta http-equiv=\"Cache-Control\" content=\"no-cache\"/>  \r\n");
      sb.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\" /> \r\n");
      sb.append("<meta http-equiv=\"Cache-Control\" content=\"max-age=0\" />\r\n");
      sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\""+SysPreperty.getProperty().AppUrl+"/ZrPhoneEngine/css/style.css\" media=\"screen\" />\r\n");
      sb.append("<script type=\"text/javascript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrPhoneEngine/js/jquery.min.js\"></script>\r\n");
      sb.append("<script type=\"text/javascript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrQueryEngine/Js/QueryEngine.js\"></script>\r\n");
      sb.append("<SCRIPT LANGUAGE=Javascript TYPE=\"text/javascript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrQueryEngine/Res/coll.js\"></SCRIPT>");
      sb.append("<SCRIPT LANGUAGE=\"JavaScript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrQueryEngine/DatePicker/WdatePicker.js\"  type=\"text/jscript\" ></SCRIPT>");
      sb.append("<SCRIPT LANGUAGE=\"JavaScript\" src=\"zrsysmanage/script/Public.js\"  type=\"text/jscript\" ></SCRIPT>");
      
      sb.append("<script type=\"text/javascript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrwebGui/sigma_grid/grid/calendar/calendar.js\"></script>");
      sb.append("<script type=\"text/javascript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrwebGui/sigma_grid/grid/calendar/calendar-setup.js\"></script>");
      sb.append("<script type=\"text/javascript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrwebGui/sigma_grid/grid/gt_msg_en.js\"></script>");
      sb.append("<script type=\"text/javascript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrwebGui/sigma_grid/grid/gt_const.js\"></script>");
      sb.append("<script type=\"text/javascript\" src=\""+SysPreperty.getProperty().AppUrl+"/ZrwebGui/sigma_grid/grid/gt_grid_all.js\"></script>");
      //sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\""+SysPreperty.getProperty().AppUrl+"/zrsysmanage/css/Blue.css\" media=\"screen\" />\r\n");
      sb.append("<script type=\"text/javascript\">\r\n");
      sb.append("var $ = jQuery.noConflict();\r\n");
      sb.append("$(function() {\r\n");
      sb.append("$('#activator').click(function(){\r\n");
      sb.append("$('#box').animate({'top':'65px'},500);\r\n");
      sb.append("});\r\n");
      sb.append("$('#boxclose').click(function(){\r\n");
      sb.append("$('#box').animate({'top':'-1000px'},500);\r\n");
      sb.append("});\r\n");
      sb.append("$('#activator_share').click(function(){\r\n");
      sb.append("$('#box_share').animate({'top':'65px'},500);\r\n");
      sb.append("});\r\n");
      sb.append("$('#boxclose_share').click(function(){\r\n");
      sb.append("$('#box_share').animate({'top':'-1000px'},500);\r\n");
      sb.append("});\r\n");
      sb.append("});\r\n");
      sb.append("$(document).ready(function(){\r\n");
      sb.append("$(\".toggle_container\").hide(); \r\n");
      sb.append("$(\".trigger\").click(function(){\r\n");
      sb.append("$(this).toggleClass(\"active\").next().slideToggle(\"slow\");\r\n");
      sb.append("return false;\r\n");
      sb.append("});\r\n");
      sb.append("});\r\n");
      sb.append("</script>\r\n");
      sb.append("<script type=\"text/javascript\">\r\n");
      sb.append("window.addEventListener(\"load\",function() {\r\n");
      sb.append("setTimeout(function(){\r\n");
      sb.append("window.scrollTo(0, 1);\r\n");
      sb.append("}, 0);\r\n");
      sb.append("});\r\n");
      sb.append("</script>\r\n");
      sb.append("</head>\r\n");
      sb.append("<body>\r\n");
      sb.append("<div  id=\"main_container\" class=\"divForm\" align=\"center\" style=\"width: 100%;height: 100%\">\r\n");
      //上面是头部
      sb.append(
      "<FORM name=\"recordfrm\" method=\"post\" Action=\"QueryPageSerPhone.do?ID=").append(
      ID).append("&SHOWTITLE="+SHOWTITLE+"&TITLENAME="+TITLENAME+"&ISCODE="+ISCODE+"&BUTTONIDS="+BUTTONIDS+"&ISNULL="+ISNULL+"\">\r\n");
      //查询是否有配置按钮
      String buttow=queryControl.CreateButtonNavigate(ID,queryConfigEntity.getQTABLETYPE(),user,BUTTONIDS);
    //下面是菜单栏
      sb.append("<div class=\"header\">\r\n");
      sb.append("<a href=javaScript:history.go(-1) class=\"left_bt\">返回</a>\r\n");
      if(buttow.length()>5){
    	  //有按钮
    	  sb.append(buttow);
      }else{
    	  //没有按钮
      }
      //下面是菜单栏
     
      sb.append("<a href=\"#\" class=\"right_bt\" id=\"activator\"><img src=\"ZrPhoneEngine/css/images/search.png\" alt=\"\" title=\"\" border=\"0\" /></a>\r\n");
      sb.append("</div>\r\n");
    
     
      //页面传递的参数
      String P1, P2, P3, P4, P5;
      P1 = _request.getParameter("P1");
      if (P1 != null) {
        sb.append("<input type=\"hidden\" name=\"P1\" value=\"" ).append(P1).append("\">\r\n");
      }

      P2 = _request.getParameter("P2");
      if (P2 != null) {
        sb.append("<input type=\"hidden\" name=\"P2\" value=\"").append(P2).append("\">\r\n");
      }

      P3 = _request.getParameter("P3");
      if (P3 != null) {
        sb.append("<input type=\"hidden\" name=\"P3\" value=\"").append(P3).append("\">\r\n");
      }

      P4 = _request.getParameter("P4");
      if (P4 != null) {
        sb.append("<input type=\"hidden\" name=\"P4\" value=\"").append(P4).append("\">\r\n");
      }

      P5 = _request.getParameter("P5");
      if (P5 != null) {
        sb.append("<input type=\"hidden\" name=\"P5\" value=\"").append(P5).append("\">\r\n");
      }


      sb.append("<input type=\"hidden\" name=\"page\" value=\"\">\r\n");
      sb.append("<input type=\"hidden\" name=\"setall\" value=\"0\">\r\n");
      sb.append("<input type=\"hidden\" name=\"queryDisHid\" value=\"").append(
                queryHidDis).append("\">");
      sb.append("<input type=hidden name=ifFirstData value="+ifFirstData+">\r\n");
      sb.append("<input type=hidden name=strWhere value="+strWhere+">\r\n");
      sb.append("<input type=hidden name=queryFlag value="+queryFlag+">\r\n");
      sb.append("<input type=hidden name=SWIDTH value="+swidth+">\r\n");
      sb.append("<input type=hidden name=SHEIGHT value="+sheight+">\r\n");

      String getQTABLETYPE = "";
      if (queryConfigEntity.getQTABLETYPE()==null)
      {
        getQTABLETYPE = "1";
      }
      else
      {
        getQTABLETYPE = queryConfigEntity.getQTABLETYPE();
      }
      if (getQTABLETYPE.equals("2"))
      {
        sb.append("<input type=hidden id=selectrow name=selectrow value=0>\r\n");
      }else
      {
        sb.append("<input type=hidden id=selectrow  name=selectrow value=x>\r\n");
      }

      
  

      //1 一般查询     2 操作查询     3 显示列表    4 嵌入Iframe  5 查询录入项和结果分离
      String queryType = queryConfigEntity.getTYPE();
      String queryItemDis = "";
        String queryItemStr = queryControl.CreateQueryItem(ID,queryConfigEntity.getQITEMTYPE(),user,rq);
        String align = "left";
        int ItemRowNum = queryControl.GetQueryItemRowNum(ID,queryConfigEntity.getQITEMTYPE());
        if (ItemRowNum > 0) {
          align = "center";
          if (ItemRowNum < 9) {
            height = ItemRowNum * 23 + 7;
          }
          else {
            height = 8 * 23 + 7;
          }
          sb.append("<!-- 条件页面 -->");
          sb.append("<div class=\"box\" id=\"box\">\r\n");
          sb.append("<div class=\"box_content\">\r\n");
          sb.append("<div class=\"box_content_tab\">搜索</div>\r\n");
          sb.append(" <div class=\"box_content_center\">\r\n");
          sb.append("<div class=\"form_content\">\r\n");
          //查询条件呢内容
          sb.append("<TABLE border='0' width='100%' cellspacing=\"0\" cellpadding=\"0\" valign=center>\r\n");
          sb.append(queryItemStr);
          sb.append("</TABLE>\r\n");
          sb.append("<a class=\"boxclose\" id=\"boxclose\">关闭</a>\r\n");
          sb.append("<input type=\"button\" class=\"form_submit\" onclick=\"JavaScript:submitquery();\" value=\"查询\" />\r\n");
          sb.append("</div> <div class=\"clear\"></div> </div> </div> </div>\r\n");
        }
        //查询结果数据
        sb.append("<div class=\"corner_wrap\">\r\n");
//      //得到数据
        sb.append(queryControl.GetQueryResultTable(ID,queryConfigEntity.getQTABLETYPE(),queryType,user,rq,P1,P2,P3,P4,P5,ifFirstData,currentPage,swidth,sheight));
       
        
        //分页显示
        sb.append("<table align=\"left\" class=\"bordered\">\r\n");
        sb.append("<tr><td colspan=\"5\">\r\n");
        String Navigate1[] = queryControl.CreatePageNavigate(ID,user,P1,P2,P3,P4,P5,currentPage);
        sumROW = Navigate1[1];
        sb.append(Navigate1[0]);
        sb.append("</td></tr>\r\n");
        sb.append("</table>\r\n");
        sb.append("</div>\r\n");
        
      sb.append("</FORM></div>");
      sb.append("<script language=\"javascript\">");


      //输出必填项js
      String outJS = queryControl.GetIsmustJs(ID,ISNULL);

      sb.append(outJS+"\r\n");

      sb.append("function showquery(){\r\n");

      sb.append("var isshow = document.all.queryItem.style.display;\r\n");
      sb.append("if (isshow=='none'){document.all.queryItem.style.display='';document.all.showquery.style.display='';}else{document.all.queryItem.style.display='none';document.all.showquery.style.display='none';} \r\n");
      sb.append("document.recordfrm.queryDisHid.value=document.all.queryItem.style.display;\r\n");

      sb.append("}\r\n");

      sb.append("function SetSelectValue(SelectId, DictTable){\r\n");
      //网页形式字典选择----------------
      sb.append("var mFileUrl =\"ZrQueryEngine/selectDictPage.jsp?DictTable=\"+DictTable+\"&SelectId=\"+SelectId;\r\n");
      sb.append("var strValue=window.showModalDialog(mFileUrl,window,'status:no;help:no;dialogHeight:312px;dialogWidth:382px');\r\n");
      sb.append("if (strValue!=null){var arrTmp = strValue.split('/');\r\n");
      sb.append("document.getElementById(SelectId).options.length = 0;\r\n");
      sb.append("document.getElementById(SelectId).options[0] = new Option(arrTmp[1],arrTmp[0]);\r\n");
      sb.append("document.getElementById(SelectId).options[0].selected = true;\r\n");
      sb.append("document.getElementById(SelectId).options[0].className = 'selectlist';}\r\n");
       //网页形式-----------------
      sb.append("}\r\n");

      sb.append("function TableOndblclick()");
      sb.append("{");
      String scriptStr = "";
      try {
        scriptStr = queryControl.CreateButtonScript(queryControl.getButtonByID(
            queryConfigEntity.getBID()),ID);
      }
      catch (Exception ex) {
      }
      if (scriptStr.trim().length() > 0) {
        sb.append("parseButtonJs(\"").append(scriptStr).append("\");");
      }
      sb.append("}\r\n");

      sb.append("function TableOnclick()");
      sb.append("{");
      scriptStr = "";
      try {
        scriptStr = queryControl.CreateButtonScript(queryControl.getButtonByID(
            queryConfigEntity.getCID()),ID);
      }
      catch (Exception ex) {
      }
      if (scriptStr.trim().length() > 0) {
        sb.append("parseButtonJs(\"").append(scriptStr).append("\");");
      }
      sb.append("}\r\n");

      sb.append("function ExeOndblclick(id)");
      sb.append("{");
      scriptStr = "";
      try {
        scriptStr = queryControl.CreateButtonScript(queryControl.getButtonByID(
            queryConfigEntity.getBID()),ID);
      }
      catch (Exception ex) {
      }
      if (scriptStr.trim().length() > 0) {
        sb.append("parseButtonJs_B(\"").append(scriptStr).append("\",id);");
      }
      sb.append("}\r\n");

      sb.append("function ExeOnclick(id)");
      sb.append("{");
      scriptStr = "";
      try {

        scriptStr = queryControl.CreateButtonScript(queryControl.getButtonByID(
            queryConfigEntity.getCID()),ID);
      }
      catch (Exception ex) {

      }
      if (scriptStr.trim().length() > 0) {
        sb.append("parseButtonJs_B(\"").append(scriptStr).append("\",id);");
      }
      sb.append("}\r\n");
      
      
      sb.append("function expexcel(url){\r\n");
      sb.append("url=url+'&crow="+sumROW+"';\r\n");
      sb.append("var name='PopWindow';\r\n");
      sb.append("var ShowPopWindow = null;");
      sb.append("var status='toolbar=no,location=no,directories=no,menubar=no,resizable=yes,scrollbars=yes,width=400,height=250';");
      sb.append("ShowPopWindow = window.open(url,name,status);");
      sb.append("ShowPopWindow.moveTo(280,200);");
      sb.append("ShowPopWindow.focus();");
      sb.append("}\r\n");
      sb.append("function submitquery(){\r\n");
      sb.append("var isnull='0';\r\n");
      sb.append("document.recordfrm.submit();}\r\n");

      sb.append(" </script>");

      sb.append("</BODY>");
      sb.append("</HTML>");

        strRe = sb.toString();
        //将按钮带有参数的替换成实际的参数值
        if (P1 == null) {P1="";}
        if (P2 == null) {P2="";}
        if (P3 == null) {P3="";}
        if (P4 == null) {P4="";}
        if (P5 == null) {P5="";}
        strRe=strRe.replaceAll("\\{P1\\}",P1);
        strRe=strRe.replaceAll("\\{P2\\}",P2);
        strRe=strRe.replaceAll("\\{P3\\}",P3);
        strRe=strRe.replaceAll("\\{P4\\}",P4);
        strRe=strRe.replaceAll("\\{P5\\}",P5);
        //--------------

      HttpSession session = _request.getSession(true);
      session.setAttribute("queryControl", queryControl);

    }
    catch (Exception ex) {
      return "";
    }

    user = null;
    userUI = null;
    queryControl = null;
    _request = null;

    return strRe;
  }
}
