<%@ page import="ro.emid.common.constants.AppConstants" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="ro.emid.common.db.EchipamentAccessDB" %>
<%@ page import="ro.emid.common.db.IncidentAccessDB" %>
<%@ page import="ro.emid.common.db.UserAccessDB" %>
<%@ page import="ro.emid.common.types.Eveniment" %>
<%@ page import="ro.emid.common.types.FiltruEvenimente" %>
<%@ page import="ro.emid.incidente.db.EvenimentAccessDB" %>
<%@ page import="ro.emid.incidente.obj.FiltruEvenimentConstants" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.common.utils.UserUtils" %>
<%@ page import="ro.emid.Application" %>

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

<TABLE border=0 cellPading=0 cellSpacing=0 width="100%">
    <TR>
        <TD>
            <%@ include file="../header-localizare.jsp"%> <span class="slash">/</span> Arhiva evenimente
        </TD>

        <TD align="RIGHT">
            <span style="font-size: 12px;">Mergi la:</span>
            <A title="Lista incidente" href="<%=AppConstants.APP_NAME%>?action=showIncidente" class="link">Incidente</A>&nbsp;
            <A title="Lista echipamente" href="<%=AppConstants.APP_NAME%>?action=showEchipamente" class="link">Echipamente</A>&nbsp;
            <A title="Lista evenimente" class="link" href="<%=AppConstants.APP_NAME%>?action=showEvenimente">Evenimente</A>
        </TD>
    </TR>
</TABLE>

<%
    String sortColumn = ObjectUtils.getStringValue(request.getParameter("sortColumn"));
    if (sortColumn == null || sortColumn.length() == 0) sortColumn = "NR_COMANDA";
    String sortType = ObjectUtils.getStringValue(request.getParameter("sortType"));
    if (sortType == null || sortType.length() == 0) sortType = "DESC";
%>

<%
    final StringBuffer condSql = new StringBuffer();


    final FiltruEvenimente filtruCautare = IncidenteSessionUtils.getFiltruEvenimente(session);
    if ( filtruCautare != null && filtruCautare.hasCriterii() ){
        filtruCautare.buildFilterSql( condSql);
    }


    Category[] formatii = null;
    final StringBuffer coduriFormatii = new StringBuffer();
    final StringBuffer condSqlFormatii = new StringBuffer();
    if (user.getIeLevel() == RoleConstants.NIVEL_FORMATIE) {
        formatii = new Category[1];
        formatii[0] = formatiaDeLucru;
    } else {
        formatii = CategoryAccessDB.getAllCategoriesByParentId((centruExploatare.getId() > 0 ? centruExploatare.getId() : -2));
    }

    if( formatii != null && formatii.length > 0){
        for (int i = 0; i < formatii.length; i++) {
            coduriFormatii.append(formatii[i].getCodSap()).append(i < formatii.length - 1 ? ";" : "");
        }
        condSqlFormatii.append(" AND (( INSTR('").append(ro.emid.common.utils.Util.escapeToSql(coduriFormatii.toString())).append("', ev.ID_OBIECT)>0 "); // unele formatii au mai multe coduri (le-am pus in acelasi cimp separate prin ";")
    }else{
        condSqlFormatii.append(" AND (( ev.ULPI = '").append(ro.emid.common.utils.Util.escapeToSql(sucursala.getCodSap())).append("' ");
    }

    condSql.append(condSqlFormatii)
            .append(" AND ev.COD_FORMATIE IS NULL) OR (ev.COD_FORMATIE IS NOT NULL AND INSTR('")
            .append(ro.emid.common.utils.Util.escapeToSql(coduriFormatii.toString()))
            .append("', ev.COD_FORMATIE)>0 )) " + " AND ev.STATUS > " + Eveniment.STATUS_NEW);

    //for pagination{
    if (!"evenimenteArhiva".equals(IncidenteSessionUtils.getPaginationJsp(session))) {
        IncidenteSessionUtils.resetPaginationData(session, "evenimenteArhiva");
    }

    long nrLines = ObjectUtils.getLongValue(request.getParameter("nrLines"), -1);
    if (nrLines == -1) nrLines = IncidenteSessionUtils.getNrLines(session);

    long currentBeginIndex = ObjectUtils.getLongValue(request.getParameter("currentBeginIndex"), -1);
    if (currentBeginIndex == -1) currentBeginIndex = IncidenteSessionUtils.getBeginIndex(session);

    final long nrLinesTotal = EvenimentAccessDB.getCount (condSql.toString());
    final String direction = ObjectUtils.getStringValue(request.getParameter("direction"));
    if ("backward".equals(direction)) {
        currentBeginIndex -= nrLines;
    } else if ("forward".equals(direction)) {
        currentBeginIndex += nrLines;
    } else if( "first".equals( direction)){
        currentBeginIndex = 1;
    } else if( "last".equals( direction)){
        currentBeginIndex =  nrLines * nrLinesTotal/nrLines + 1;
    }

    if (currentBeginIndex > nrLinesTotal && nrLinesTotal > 1)
        currentBeginIndex -= nrLines; //cazul cind se sterge ultimul element de pe ultima pagina si este singurul pe pagina
    if (currentBeginIndex < 1) currentBeginIndex = 1;

    IncidenteSessionUtils.setNrLines(session, nrLines);
    IncidenteSessionUtils.setBeginIndex(session, currentBeginIndex);
    //}for pagination
%>

<%
    final Eveniment[] evenimente = EvenimentAccessDB.getAllPaginat( condSql.toString(), sortColumn, sortType, currentBeginIndex, currentBeginIndex + nrLines - 1);
    final int nrLinesSelected = evenimente.length;
%>


<table width="100%" border=0>
    <tr><td>
        <div id="divFiltru">
            <form name="searchForm" action="<%=AppConstants.APP_NAME%>?action=cautaEvenimentArhiva" method="post"  >
                Numar comanda: <input class="gsapinputtext" name="<%=FiltruEvenimentConstants.NUMAR_COMANDA%>" type="text" value="<%=( filtruCautare != null ? ObjectUtils.getStringValue( filtruCautare.getNumarComanda()): "")%>"/>&nbsp;

                &nbsp;
                <input type="submit" style="font-size:10px" value="Cauta" />
            </form>
        </div>
        <div class="spacer"></div>
        <TABLE id="table" border=0 cellPadding=2 cellSpacing=1 width="100%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white">
            <TR noSelect="true">
                <TH class="gsapthead" height=25 noWrap>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showEvenimenteArhiva&sortColumn=NR_COMANDA&sortType=<%=(sortColumn.equals("NR_COMANDA") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;">Nr Comanda:</a>&nbsp; <% if(sortColumn.equals("NR_COMANDA")) if( sortType.equals("ASC")){%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_up_1.gif" border=0> <%}else{%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_dn_1.gif" border=0> <%}%></TH>
                <TH class="gsapthead" height=25 noWrap>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showEvenimenteArhiva&sortColumn=TEXT&sortType=<%=(sortColumn.equals("TEXT") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;">Text:</a>&nbsp; <% if(sortColumn.equals("TEXT")) if( sortType.equals("ASC")){%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_up_1.gif" border=0> <%}else{%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_dn_1.gif" border=0> <%}%></TH>
                <TH class="gsapthead" height=25 noWrap>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showEvenimenteArhiva&sortColumn=ID_OBIECT&sortType=<%=(sortColumn.equals("ID_OBIECT") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;"><%=sucursala.isCuSectiiSiCentre() ? "C.E." : "F.L."%></a>&nbsp; <% if(sortColumn.equals("ID_OBIECT")) if( sortType.equals("ASC")){%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_up_1.gif" border=0> <%}else{%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_dn_1.gif" border=0> <%}%></TH>
                <TH class="gsapthead" noWrap width=1%>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showEvenimenteArhiva&sortColumn=ev.STATUS&sortType=<%=(sortColumn.equals("ev.STATUS") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;">Status:</a>&nbsp; <% if(sortColumn.equals("ev.STATUS")) if( sortType.equals("ASC")){%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_up_1.gif" border=0> <%}else{%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_dn_1.gif" border=0> <%}%></TH>
                <TH class="gsapthead" noWrap width=2%>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showEvenimenteArhiva&sortColumn=DATA_COM || TIME_COM&sortType=<%=(sortColumn.equals("DATA_COM || TIME_COM") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;">Data comanda:</a>&nbsp; <% if(sortColumn.equals("DATA_COM || TIME_COM")) if( sortType.equals("ASC")){%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_up_1.gif" border=0> <%}else{%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_dn_1.gif" border=0> <%}%></TH>
                <!--<TH class="gsapthead" noWrap width=2%>&nbsp;Data PIF:&nbsp;</TH>-->
                <% if( UserUtils.hasRoleAdminIncidente(user) || UserUtils.hasRoleUtilizatorIncidente( user)){%>
                    <TH class="gsapthead" noWrap>&nbsp;Operatie:&nbsp;</TH>
                <%}%>
            </TR>
            <% if( evenimente.length == 0){%>
                    <TR noSelect="true">
                        <TD>
                            Nu sunt evenimente ...
                        </TD>
                    </TR>
            <%} else for (int i = 0; i < evenimente.length; i++) {
                    final Eveniment eveniment = evenimente[i];
                    final String parametri_titlu = eveniment.getText();%>
                    <tr>
                        <td title="Tip <%=eveniment.getTip()%>" nowrap <%if(sortColumn.equals("NR_COMANDA")){%> class="sortColumn" <%}%>>
                            <label for="check<%=eveniment.getNrComanda()%>"><%=eveniment.getNrComanda()%></label>
                        </td>
                        <td nowrap <%if(sortColumn.equals("TEXT")){%> class="sortColumn"  <%}%> ><label for="check<%=eveniment.getNrComanda()%>"><%=parametri_titlu%></label></td>
                        <td nowrap <%if(sortColumn.equals("ID_OBIECT")){%> class="sortColumn" <%}%>>
                            <%--<%=eveniment.getLocFunctional()%>--%>
                            <%--<% Category formatia = CategoryAccessDB.getFormatieByCodSAP(eveniment.getIdObiect());%>--%>
                            <% Category formatia = null;
                             for (int j = 0; j < formatii.length; j++) {
                                 final Category f = formatii[j];
                                 final String codFormatie = eveniment.getCodSapFormatie() != null ? eveniment.getCodSapFormatie() : eveniment.getIdObiect();
                                 if( f.getCodSap() != null && f.getCodSap().indexOf( codFormatie) >= 0){
                                    formatia = f;
                                    break;
                                }
                             } %>
                            <%=formatia != null ? formatia.getName() : "-"%>
                        </td>
                        <td nowrap <%if(sortColumn.equals("ev.STATUS")){%> class="sortColumn" <%}%>>
                            <%
                                final StringBuffer nrResult = new StringBuffer();
                                if (eveniment.getStatus() == Eveniment.STATUS_TRECUT_INCIDENT && eveniment.getResultId() > 0) {
                                    nrResult.append(IncidentAccessDB.getNRIncident(eveniment.getResultId()));
                                } else
                                if (eveniment.getStatus() == Eveniment.STATUS_TRECUT_ECHIPAMENT && eveniment.getResultId() > 0) {
                                    nrResult.append(EchipamentAccessDB.getNREchipament(eveniment.getResultId()));
                                }

                                if( nrResult == null) {
                                    nrResult.delete(0, nrResult.length());
                                    nrResult.append(" - nu exista");
                                }
                                else{
                                    nrResult.delete(0, nrResult.length());
                                    nrResult.append(" - nr. ").append(nrResult);}
                            %>
                            <%=Eveniment.getNiceStatus( eveniment.getStatus(), nrResult.toString())%>
                        </td>
                        <td align="center" <%if(sortColumn.equals("DATA_COM || TIME_COM")){%> class="sortColumn"   <%}%>><%=AppConstants.format(eveniment.getDataComanda())%></td>
                        <%--<td align="center"><%=AppConstants.format(eveniment.getDataPIF())%></td>--%>
                            <td nowrap align="center" nowrap style="<%=UserUtils.hasRoleViewIncidente( user) ? "display: none" : ""%>">
                                <% if( !Application.runAsAparatCentral() && ( UserUtils.hasRoleAdminIncidente( user) || UserUtils.hasRoleUtilizatorIncidente( user))){%>
                                <% if( UserUtils.hasRoleAdminIncidente( user) || eveniment.getAutor().equals( user.getUsername()) || UserAccessDB.isNivelSuperior(user, eveniment.getAutor())){ %>
                                <% final String mesaj = eveniment.getStatus() == Eveniment.STATUS_ARHIVAT ? "Dezarhivati evenimentul ?" : "In urma acestei actiuni vor fi sterse si Fisa(le) de Incident/Echipament\nContinuati actiunea ?"; %>
                                    <a style="color: #3300ff;" href="<%=AppConstants.APP_NAME%>?action=dezarhivareEveniment&id=<%=eveniment.getNrComanda()%>" onclick="return confirm('<%=ro.emid.common.utils.Util.escapeToJs( mesaj)%>');">Back</a>&nbsp;&nbsp;
                                <%}%>
                            </td>
                        <%}%>
                    </tr>
            <%}%>
            <tr class="paginationRow" noSelect="true">
                <td colspan="8" >
                    <table width="100%" cellspacing="0" cellpadding="0">
                        <tr noSelect="true">
                            <td align="right">
                                <form action="<%=AppConstants.APP_NAME%>" method="post">
                                    <input type="hidden" name="action" value="showEvenimenteArhiva">
                                    <input type="hidden" name="currentBeginIndex" value="<%=currentBeginIndex%>">
                                    <input type="hidden" name="direction" value="">
                                    <input type="hidden" name="sortColumn" value="<%=sortColumn%>">
                                    <input type="hidden" name="sortType" value="<%=sortType%>">
                                    Nr. linii:
                                    <select name="nrLines" onchange="this.form.submit()" style="font-size: 10px">
                                        <option value="10"  <%=nrLines == 10 ? "selected" : ""%> >10</option>
                                        <option value="15"  <%=nrLines == 15 ? "selected" : ""%> >15</option>
                                        <option value="20"  <%=nrLines == 20 ? "selected" : ""%> >20</option>
                                        <option value="30"  <%=nrLines == 30 ? "selected" : ""%> >30</option>
                                        <option value="40"  <%=nrLines == 40 ? "selected" : ""%> >40</option>
                                        <option value="50"  <%=nrLines == 50 ? "selected" : ""%> >50</option>
                                    </select>&nbsp;&nbsp;
                                    <%=currentBeginIndex%> - <%=currentBeginIndex + nrLinesSelected - 1%> din <%=nrLinesTotal%>&nbsp;&nbsp;&nbsp;
                                    <input <%=currentBeginIndex == 1 ? "disabled" : ""%>  title="Primele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='first'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&lt&lt" />
                                    <input <%=currentBeginIndex == 1 ? "disabled" : ""%>  title="Precedentele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='backward'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&lt" />
                                    <input <%=currentBeginIndex + nrLinesSelected - 1 >= nrLinesTotal ? "disabled" : ""%> title="Urmatoarele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='forward'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&gt" />
                                    <input <%=currentBeginIndex + nrLinesSelected - 1 >= nrLinesTotal ? "disabled" : ""%> title="Ultimele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='last'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&gt&gt" />
                                </form>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </TABLE>
    </td></tr>
</table>

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



