<%@ page import="ro.emid.common.types.Category" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="ro.emid.common.db.framework.ReportStatement" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Calendar" %>
<%@ page import="java.sql.Date" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="ro.emid.common.types.Reclamatie" %>
<%@ page import="ro.emid.callcenter.CallcenterSessionUtils" %>
<%@ page import="ro.emid.common.constants.*" %>

<%@ include file="../callcenter/declaratii.jsp"%>

<%! private boolean isProvizorat( final String tip){ return tip != null && "p".equalsIgnoreCase(tip); }%>
<%! private boolean isComandaAise( final String tip){ return tip != null && "aise".equalsIgnoreCase(tip); }%>
<%! private boolean isReferat( final String tip){ return tip != null && "referat".equalsIgnoreCase(tip); }%>

<%
    long filialaId = CallcenterSessionUtils.getFilialaId(session);
    long sucursalaId = CallcenterSessionUtils.getSucursalaId(session);
    long centruId = CallcenterSessionUtils.getCentruId(session);

    String tip = ObjectUtils.getStringValue( request.getParameter("tip"));
    if( !isProvizorat(tip) && !isComandaAise(tip) && !isReferat( tip)){
        tip = "p";  //provizorate default
    }

    if (0 < ObjectUtils.getLongValue(request.getParameter("filiala"), -2)) {
        filialaId = ObjectUtils.getLongValue(request.getParameter("filiala"));
    }

    if (0 < ObjectUtils.getLongValue(request.getParameter("sucursala"), -2)) {
        sucursalaId = ObjectUtils.getLongValue(request.getParameter("sucursala"));
    }

    if (0 < ObjectUtils.getLongValue(request.getParameter("centruId"), -2)) {
        centruId = ObjectUtils.getLongValue(request.getParameter("centruId"));
    }

    Category filialaRaport = CategoryAccessDB.getById(filialaId);
    if (filialaRaport == null) filialaRaport = new Category();

    Category sucursalaRaport = CategoryAccessDB.getById(sucursalaId);
    if (sucursalaRaport == null) sucursalaRaport = new Category();

    Category centruRaport = CategoryAccessDB.getById(centruId);
    if (centruRaport == null) centruRaport = new Category();

    Date dataStart = ObjectUtils.getDateValue(request.getParameter("data_start"), AppConstants.FORMAT_DATA_TIME);
    Date dataStop = ObjectUtils.getDateValue(request.getParameter("data_stop"), AppConstants.FORMAT_DATA_TIME);

    final Calendar c = Calendar.getInstance();
    c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 7, 0, 0);
    if (dataStart == null) dataStart = new Date(c.getTime().getTime());

    if (dataStop == null) {
        c.add(Calendar.DATE, 1);
        dataStop = new Date(c.getTime().getTime());
    }

    final String value_data_start = AppConstants.formatx(dataStart);
    final String value_data_stop = AppConstants.formatx(dataStop);

    final Timestamp dataStartx = new Timestamp(dataStart.getTime());
    final Timestamp dataStopx = new Timestamp(dataStop.getTime());

    final StringBuffer buffer = new StringBuffer();
    buffer.append(" SELECT /*+ INDEX_ASC(d EMID_DER_DATA_ANUNTARE) */d.NUMAR, c1.NAME AS SDEE, c2.NAME AS CE, r.NUME_CLIENT, r.LOCALITATE, r.TIP_ARTERA||' '||r.STRADA, r.NR, r.BLOC, r.SCARA, r.AP, ").append(
            "r.CONTINUT_SESIZARE1, r.CONTINUT_SESIZARE2, r.ALTA_SESIZARE, " ).append(
            " TO_CHAR(d.DATA_ANUNTARE, 'DD.MM.YYYY HH24:MI'), TO_CHAR(d.DATA_REZOLVARE, 'DD.MM.YYYY HH24:MI'), d.ECHIPA, d.DESCRIERE, d.MOD_REZOLVARE, d.OBSERVATII" ).append(
            " FROM deranjamente d, reclamatii r, categories c1, categories c2 ");
    final ReportStatement raport = new ReportStatement(
         buffer.toString()
         ,
        "ORDER BY d.DATA_ANUNTARE ASC"
        )
        .addStringCriteria("AND d.ID_PRIMA_RECLAMATIE = r.ID AND d.ID = r.LEGAT_OBJECT_ID AND r.OBJECT_TYPE = " + Reclamatie.LEGAT_LA_DERANJAMENT)
        .addStringCriteria("AND d.SUCURSALA_ID = c1.ID")
        .addStringCriteria("AND d.SECTIE_ID = c2.ID")
        .addOrSetFilter("DATA_ANUNTARE", ">=", dataStartx)
        .addOrSetFilter("DATA_ANUNTARE", "<=", dataStopx);

    String title = "n/a";
    if( isProvizorat( tip)){
        title = "Raport provizorate";
        raport.addOrSetFilter("PROVIZORAT", "=", new Integer(1));
    } else if( isComandaAise( tip)){
        title = "Deranjamente cu emitere comanda catre AISE";
        raport.addOrSetFilter("MASURI_LUATE", "=", new Integer( DeranjamentConstants.MASURI_LUATE_EMID_C_DA_AISE));
    } else if( isReferat( tip)){
        title = "Deranjamente cu referat catre S.O CEMTJT";
        raport.addOrSetFilter("MASURI_LUATE", "=", new Integer( DeranjamentConstants.MASURI_LUATE_REFERAT_SO_CEMTJT));
    } else {
        throw new RuntimeException("Tip raport necunoscut : " + tip);
    }


    if (centruRaport.getId() > 0) {
        raport.addOrSetFilter("SECTIE_ID", "=", new Long(centruRaport.getId()));
    } else if (sucursalaRaport.getId() > 0) {
        raport.addOrSetFilter("SUCURSALA_ID", "=", new Long(sucursalaRaport.getId()));
    } else if (filialaRaport.getId() > 0) {
        raport.addOrSetFilter("FILIALA_ID", "=", new Long(filialaRaport.getId()));
    }
%>

<TABLE border=0 cellPading=0 cellSpacing=0 width="100%">
    <TR>
        <TD>
            <SPAN style="FONT-SIZE: 12px; FONT-WEIGHT: bold">

                <A class="link" href="<%=GlobalAppConstants.APP_NAME%>?action=rapoarte">Rapoarte</A> - <%=title%>
            </span>
        </TD>
    </TR>
</TABLE>

<table><tr><td>
    <center>
        <br />
        <span style="font-size: 14px"><%=title%></span>
    </center>
<div class="spacer"></div>
<table class="gsaptd" width="100%"><tr><td>
<form name="zaforma" action="<%=GlobalAppConstants.APP_NAME%>" method="post">
    <input type="hidden" name="action" value="raport-provizorate">
    <input type="hidden" name="tip" value="<%=tip%>">
    Filiala:
    <SELECT name="filiala" onchange="fill_sucursala_select()" class="gSAPSelect" <%=user.getIeLevel() == ro.emid.common.constants.RoleConstants.NIVEL_FULL ? "" : "disabled"%> >
        <OPTION value="-1">ELECTRICA SA:</OPTION>
        <%  final Category [] filiale = CategoryAccessDB.getAllCategoriesByParentId(-1);
          if (filiale != null) for(int i=0;i<filiale.length;i++) {%>
          <OPTION <%=(filiale[i].getId() == filialaRaport.getId()) ? "selected=\"true\" " : ""%>value="<%=filiale[i].getId()%>"><%=filiale[i].getName()%></OPTION>
        <%} %>
    </SELECT>&nbsp;&nbsp;

    Sucursala:
    <span id="sucursalaDiv">
    <SELECT name="sucursala" class="gSAPSelect" onchange="fill_centru_select()" >
          <option value="-1">Selectati:</option>
    </SELECT></span>&nbsp;&nbsp;

    C.E.:
    <span id="centruDiv">
        <SELECT name="centruId" class="gSAPSelect">
         <OPTION value="-1">Selectati:</OPTION>
        </SELECT>
    </span>

    &nbsp;&nbsp;<input type="text" id="data_start" name="data_start" size="14" value="<%=value_data_start%>" /> <a href="#" id="trigger_data_start" ><img src="<%=AppConstants.WEB_RESOURCE_PATH + "/images/cal.gif"%>" width="16" height="16" border="0" alt="Apasa pt. a selecta data."></a> -
    <input type="text" id="data_stop" name="data_stop" size="14" value="<%=value_data_stop%>" /> <a href="#" id="trigger_data_stop" ><img src="<%=AppConstants.WEB_RESOURCE_PATH + "/images/cal.gif"%>" width="16" height="16" border="0" alt="Apasa pt. a selecta data."></a>
    <input type="submit" value="Aplica">
</form>
</td></tr></table>
<div class="spacer"></div>

<TABLE id="table" frame="hsides" rules="groups" border=1 cellPadding=3 cellSpacing=1 width="100%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white">
    <col>
    <col>
    <col style="padding-right: 10px">
    <col style="padding-right: 10px; padding-left: 10px">
    <tr noSelect="true">
        <th class="gsapthead">Crt.</th>
        <th class="gsapthead">COD</th>
        <th class="gsapthead">SDEE</th>
        <th class="gsapthead">C.E.</th>
        <th class="gsapthead">Nume</th>
        <th class="gsapthead">Localit.</th>
        <th class="gsapthead">Strada</th>
        <th class="gsapthead">Nr.</th>
        <th class="gsapthead">Bl.</th>
        <th class="gsapthead">Sc.</th>
        <th class="gsapthead">Ap.</th>
        <th class="gsapthead" nowrap>Continut Sesizare</th>
        <th class="gsapthead" nowrap>Data anuntare</th>
        <th class="gsapthead" nowrap>Data realimentare</th>
        <th class="gsapthead">Echipa</th>
    </tr>
    <%
        final List rows = raport.getListOfArrays("Get Provizorate");
        if( rows == null || rows.size() == 0){%>
        <tr noSelect="true">
            <td>Nu exista informatii...</td>
        </tr>
       <%} else for (int i = 0; i < rows.size(); i++) {
            final Object[] values = (Object[]) rows.get(i);
            int continutSesizare1 = -1; 
            int continutSesizare2 = -1; %>
            <tbody>
            <tr>
               <td align="center"><%=(i+1)%></td>
               <td align="center"><%=values[0]%></td>
               <td><%=AppConstants.format((String) values[1])%>&nbsp;</td>
               <td><%=AppConstants.format((String) values[2])%>&nbsp;</td>
               <td><%=AppConstants.format((String) values[3])%>&nbsp;</td>
               <td><%=AppConstants.format((String) values[4])%>&nbsp;</td>
               <td><%=AppConstants.format((String) values[5])%>&nbsp;</td>
               <td><%=AppConstants.format((String) values[6])%>&nbsp;</td>
               <td nowrap><%=AppConstants.format((String) values[7])%>&nbsp;</td>
               <td nowrap><%=AppConstants.format((String) values[8])%>&nbsp;</td>
               <td nowrap><%=AppConstants.format((String) values[9])%>&nbsp;</td>
               <td>
                   <%
                      continutSesizare1 = ObjectUtils.getIntValue( values[10], -1 );
                      continutSesizare2 = ObjectUtils.getIntValue( values[11], -1 );
                      final String altaSesizare = (String )values[12];

                       final Reclamatie r = new Reclamatie();
                       r.setContinutSesizare1( continutSesizare1);
                       r.setContinutSesizare2( continutSesizare2);
                       r.setAltaSesizare( altaSesizare);
                   %>
                   <%=ReclamatieConstants.getContinutSesizare( r, " ")%>
               </td>
               <td nowrap align="center"><%=AppConstants.format((String) values[13])%>&nbsp;</td>
               <td nowrap align="center"><%=AppConstants.format((String) values[14])%>&nbsp;</td>
               <td ><%=AppConstants.format((String) values[15])%>&nbsp;</td>
            </tr>
            <tr valign="top" noSelect="true">
                <td colspan="2"><b>Descriere:</b></td>
                <td colspan="3">&nbsp;<%=AppConstants.format((String) values[16])%></td>
                <td colspan="3" nowrap><b>Mod Rezolvare:</b></td>
                <td colspan="2">&nbsp;<%=AppConstants.format((String) values[17])%></td>
                <td colspan="1"><b>Observatii:</b></td>
                <td colspan="2">&nbsp;<%=AppConstants.format((String) values[18])%></td>
            </tr>
            </tbody>
            <%
        }%>
</TABLE>
</td></tr></table>

<script type="text/javascript">
    var table = new Table("table", "table");
</script>

<script type="text/javascript">
        function fill_sucursala_select(selectedValue, disabled, firstShow){
            resetComboLeaveFirstOption( document.zaforma.sucursala);
            resetComboLeaveFirstOption( document.zaforma.centruId);

            var filialaId = document.zaforma.filiala[ document.zaforma.filiala.selectedIndex].value;
            if( filialaId > -1){
                var params = "parentId="+filialaId + "&selectName=sucursala&disabled=" + disabled + (selectedValue ? "&selectedValue=" + selectedValue : "");
                //alert( params);

                getCategoriesFromServer(params, function(originalRequest){
                    //alert( getResponseMesg (originalRequest.responseText));
                    $( 'sucursalaDiv').innerHTML = getResponseMesg (originalRequest.responseText);

                    document.zaforma.sucursala.onchange=fill_centru_select;

                    if( firstShow){
                        fill_centru_select(<%=centruRaport.getId()%>, <%=user.getIeLevel() == RoleConstants.NIVEL_CENTRU || user.getIeLevel() == RoleConstants.NIVEL_FORMATIE%>);
                    }
                });
            }
        }

        function fill_centru_select(selectedValue, disabled){
            resetComboLeaveFirstOption( document.zaforma.centruId);

            var sucursalaId = document.zaforma.sucursala[ document.zaforma.sucursala.selectedIndex].value;
            if( sucursalaId > -1){
                var params = "parentId="+sucursalaId + "&selectName=centruId&disabled=" + disabled + (selectedValue ? "&selectedValue=" + selectedValue : "");
                //alert( params);

                getCategoriesFromServer(params,function(originalRequest){
                    //alert( getResponseMesg (originalRequest.responseText));
                    $( 'centruDiv').innerHTML = getResponseMesg (originalRequest.responseText);
                });
            }
        }


        fill_sucursala_select(<%=sucursalaRaport.getId()%>, <%=user.getIeLevel() == RoleConstants.NIVEL_SUCURSALA || user.getIeLevel() == RoleConstants.NIVEL_CENTRU || user.getIeLevel() == RoleConstants.NIVEL_FORMATIE%>, true);
   </script>         
<script type="text/javascript">
      Calendar.setup(
        {
          inputField  : "data_start",         // ID of the input field
          ifFormat    : "%d.%m.%Y %H:%M",    // the date format
          button      : "trigger_data_start"       // ID of the button
        }
      );

      Calendar.setup(
        {
          inputField  : "data_stop",         // ID of the input field
          ifFormat    : "%d.%m.%Y %H:%M",    // the date format
          button      : "trigger_data_stop"       // ID of the button
        }
      );
</script>
