<%@ page import="org.apache.log4j.helpers.LogLog" %>
<%@ page import="ro.emid.common.constants.SessionConstants" %>
<%@ page import="ro.emid.common.db.EchipamentAccessDB" %>
<%@ page import="ro.emid.common.db.NomAccessDB" %>
<%@ page import="ro.emid.common.db.framework.DatabaseException" %>
<%@ page import="ro.emid.common.types.*" %>
<%@ page import="ro.emid.common.utils.StringUtils" %>
<%@ page import="ro.emid.common.utils.UserUtils" %>
<%@ page import="ro.emid.incidente.action.DeleteEchipamentAction" %>
<%@ page import="ro.emid.incidente.action.EditEchipamentAction" %>
<%@ page import="ro.emid.incidente.obj.FiltruIncidenteConstants" %>
<%@ page import="java.util.List" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.Application" %>

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

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


    String localizareCondition = "";
    if (user.getIeLevel() == RoleConstants.NIVEL_FORMATIE) {
        localizareCondition = " AND FORMATIA_DE_LUCRU_ID = " + formatiaDeLucru.getId();
    } else {
        localizareCondition = " AND SECTIE_ID = " + centruExploatare.getId();
    }

    final StringBuffer condSql = new StringBuffer( localizareCondition);
    //for pagination{
    if (!"echipamente".equals(IncidenteSessionUtils.getPaginationJsp(session))) {
        IncidenteSessionUtils.resetPaginationData(session, "echipamente");
    }

    final FiltruIncidente filtru = IncidenteSessionUtils.getFiltruEchipamente(session);

    if (filtru != null && (filtru.getNumarIncident() > 0 || filtru.getNumarEchipament() > 0 || filtru.getAnul() > 0 || filtru.hasCriteriiSelectate())) {
        filtru.buildFilterSql(condSql, SessionConstants.FILTER_TYPE_ECHIPAMENTE);
    }


    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 = EchipamentAccessDB.getEchipamenteCount(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 Echipament[] echipamente = EchipamentAccessDB.getAllEchipamente(condSql.toString(), sortColumn, sortType, currentBeginIndex, currentBeginIndex + nrLines - 1);
    final int nrLinesSelected = echipamente.length;
%>

<table border=0 cellpading=0 cellspacing=0 width="100%">
    <tr>
        <td>
            <%@ include file="../header-localizare.jsp"%> <span class="slash">/</span> Echipamente
        </td>
        <td align="RIGHT" style="padding-right: 10px">
            <span style="font-size: 12px;">Mergi la:</span>
            <A title="Lista incidente" href="<%=AppConstants.APP_NAME%>?action=showIncidente" class="link">Incidente</A>&nbsp;
            <b>Echipamente</b>&nbsp;

            <A onclick="showFiltruEchipamente(); return false;" title="Click pentru a configura filtru Echipamente" href="javascript: void(null)" class="link">Filtru</A>&nbsp;
        </td>
    </tr>
</table>

<%@ include file="../layout/messages.jspf"%>

<table width="100%" border=0>
    <tr><td>
        <%  if( filtru != null && filtru.hasCriteriiSelectate()){%>
            <table width="100%" cellspacing="0" class="gsaptd" border=0>
                <tr valign="top">
                    <td width="10"><b>Filtru:</b></td>
                    <td>
                        <% boolean newLine = false;%>
                        <%if( filtru.getDataStart() != null){ newLine = true;%>
                            De la data: <b><%=AppConstants.format(filtru.getDataStart())%></b>
                        <%}%>
                        <%if( filtru.getDataStop() != null){ newLine = true;%>
                            pana la data: <b><%=AppConstants.format(filtru.getDataStop())%></b>
                        <%}%>

                        <%if(newLine){ %><br><%}%>
                        <%
                            final List criterii = filtru.getCriteriiFiltru();
                            for (int i = 0; i < criterii.size(); i++) {
                                final CriteriuFiltruIncidente criteriu = (CriteriuFiltruIncidente) criterii.get(i); %>
                                <%=criteriu.getText()%>
                                <%if( i < criterii.size() - 1 ){%><br><%}%>
                        <%}%>
                    </td>
                    <td align="right" width="80" nowrap>
                        <a title="Click pentru a reseta filtrul" class="link" href="<%=AppConstants.APP_NAME%>?action=resetFiltruEchipamente">Reset Filtru</a>
                    </td>
                </tr>
            </table>
            <div class="spacer"></div>
            <div class="sqlNumarConsumatori" style="display: none"><%=condSql%></div>
        <%}%>
        <div id="divFiltru">
            <form name="searchForm" action="<%=AppConstants.APP_NAME%>?action=cautaEchipament" method="post"  >
                Număr F.I.: <input class="gsapinputtext" name="<%=FiltruIncidenteConstants.NUMAR_INCIDENT%>" type="text" value="<%=(filtru != null && filtru.getNumarIncident() > 0 ? String.valueOf(filtru.getNumarIncident()) : "")%>"/>&nbsp;
                Număr F.E.: <input class="gsapinputtext" name="<%=FiltruIncidenteConstants.NUMAR_ECHIPAMENT%>" type="text" value="<%=(filtru != null && filtru.getNumarEchipament() > 0 ? String.valueOf(filtru.getNumarEchipament()) : "")%>"/>&nbsp;

                <% final Integer[] ani = ro.emid.common.utils.Util.addCurrentYear(EchipamentAccessDB.getAniDeteriorareEchipamente(localizareCondition)); %>
                <% final int anSelectat = filtru != null && filtru.getAnul() > 0 ? filtru.getAnul() : -1; %>
                Deteriorate în anul: <select name="<%=FiltruIncidenteConstants.AN%>" class="gSAPSelect">
                <option value="-1">&nbsp;</option>
                <% for (int i = 0; i < ani.length; i++) {
                        final Integer an = ani[i]; %>
                        <option value="<%=an%>" <%=anSelectat == an.intValue() ? "selected" : ""%> ><%=an%></option>
                <% }%>
                </select>&nbsp;

                <input type="submit" style="font-size:10px" value="Caută" />
            </form>
        </div>
        <div class="spacer"></div>

        <table border=0 cellpadding=2 cellspacing=1 width="100%" class="table">
            <thead>
                <tr>
                    <th colspan=2 height=25 nowrap>&nbsp;Titlu echipament:&nbsp;</th>
                    <th height=25 nowrap>&nbsp;Nr. Comanda:&nbsp;</th>
                    <th nowrap width=70>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showEchipamente&sortColumn=AUTOR&sortType=<%=(sortColumn.equals("AUTOR") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;">Autor:</a>&nbsp;<% if(sortColumn.equals("AUTOR")) 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 nowrap width=70>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showEchipamente&sortColumn=ACTUALIZAT_DE&sortType=<%=(sortColumn.equals("ACTUALIZAT_DE") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;">Modificat:</a>&nbsp;<% if(sortColumn.equals("ACTUALIZAT_DE")) 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 nowrap width=140>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showEchipamente&sortColumn=DATA_DETERIORARE&sortType=<%=(sortColumn.equals("DATA_DETERIORARE") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;">Data deteriorare:</a>&nbsp;<% if(sortColumn.equals("DATA_DETERIORARE")) 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>
                    <% if( UserUtils.hasRoleAdminIncidente( user) || UserUtils.hasRoleUtilizatorIncidente(user)){%>
                    <th nowrap width="1%">&nbsp;Operatie:&nbsp;</th>
                    <% }%>
                </tr>
            </thead>
            <tbody>
            <% if( echipamente.length == 0){%>
                <tr>
                    <td colspan="5" class="no-data">
                        Nu exista date ...
                    </td>
                </tr>
            <%} else {
                for (int i = 0; i < echipamente.length; i++) {

                    final Echipament echipament = echipamente[i];
                    final StringBuffer parametri_titlu_echipament = new StringBuffer();

                    if (echipament.getComponentaId() != -1) {
                        Nomenclator componenta = null;
                        try {
                            componenta = NomAccessDB.getNom(echipament.getComponentaId());
                        } catch (DatabaseException e) {
                            LogLog.debug("Database Exception: " + e.getMessage());
                        }
                        if (componenta != null) parametri_titlu_echipament.append(componenta.getDescriere()).append(", ");
                    }

                    if ( !StringUtils.isZeroLength(echipament.getStatieDen())) {
                        parametri_titlu_echipament.append(AppConstants.format(echipament.getStatieDen(), "-")).append(',');
                    }

                    if ( !StringUtils.isZeroLength(echipament.getCelulaDen())) {
                        parametri_titlu_echipament.append(AppConstants.format(echipament.getCelulaDen(), "-")).append(',');
                    }

                    if ( !StringUtils.isZeroLength( echipament.getLinieDen())) {
                        parametri_titlu_echipament.append(AppConstants.format(echipament.getLinieDen(), "-")).append(',');
                    }

                    if ( !StringUtils.isZeroLength( echipament.getPaptDen())) {
                        parametri_titlu_echipament.append(AppConstants.format(echipament.getPaptDen(), "-")).append(',');
                    }

                    if ( !StringUtils.isZeroLength( echipament.getTrafoDen())) {
                        parametri_titlu_echipament.append( AppConstants.format(echipament.getTrafoDen())).append(',');
                    }
            %>
                    <tr ondblclick="printEchipament(<%=echipament.getId()%>)" valign="top">
                        <td align="center" width="15" title="Numar Fisa Echipament"><%=echipament.getNumarFI_FE()%></td>
                        <td><%=parametri_titlu_echipament%></td>
                        <td>
                            <%=echipament.getNumarComandaSap() > 0 ? String.valueOf(echipament.getNumarComandaSap()) : ""%>
                        </td>
                        <td title="Autor <%=echipament.getNumarComandaSap() > 0 ? "Nr. comanda SAP:" + echipament.getNumarComandaSap() : ""%>"  <%if(sortColumn.equals("AUTOR")){%> class="sortColumn" <%}%>   ><%=ObjectUtils.getStringValue( echipament.getUserInsert())%></td>
                        <td title="Actualizat de" <%if(sortColumn.equals("ACTUALIZAT_DE")){%> class="sortColumn" <%}%>   ><%=ObjectUtils.getStringValue(echipament.getUserUpdate())%></td>
                        <td align="center" <%if(sortColumn.equals("DATA_DETERIORARE")){%> class="sortColumn" <%}%>   ><%=AppConstants.format(echipament.getDataDeterioarare())%></td>

                        <% if( UserUtils.hasRoleAdminIncidente( user) || UserUtils.hasRoleUtilizatorIncidente( user)){%>
                            <td align="left" nowrap >
                                <% if( Application.runAsFiliala()){%>
                                    <% if ( EditEchipamentAction.hasRightEditEchipament(user, echipament)){%>
                                        <a class="link" title="Editeaza Fisa Echipament" href="<%=AppConstants.APP_NAME%>?action=editEchipament&id=<%=echipament.getId()%>">Modifică</a>
                                    <% } %>

                                    <% if ( DeleteEchipamentAction.hasRightDeleteEchipament( user, echipament)){ %>
                                        <a class="link" title="Sterge Fisa Echipament" onclick="return confirm('Stergeti echipamentul ?')" href="<%=AppConstants.APP_NAME%>?action=deleteEchipament&id=<%=echipament.getId()%>">Şterge</a>
                                    <% } %>

                                <% } %>
                                <a class="link" title="Printeaza Fisa Echipament" href="#" onclick="printEchipament(<%=echipament.getId()%>)"><%=UserUtils.hasRoleViewIncidente( user) ? "Deschide": "Printează"%></a>
                            </td>
                        <% }%>
                    </tr>
                <%}%>
            <%}%>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="7">
                        <div class="pull-left">
                            <% if( Application.runAsFiliala() && (UserUtils.hasRoleAdminIncidente(user) || UserUtils.hasRoleUtilizatorIncidente(user))){%>
                            &nbsp;<input type="button" class="btn" data-href="<%=AppConstants.APP_NAME%>?action=editEchipament" value="Adaugă echipament"/>
                            <%}%>
                        </div>
                        <div class="pull-right">
                            <form action="<%=AppConstants.APP_NAME%>" method="post">
                                <input type="hidden" name="action" value="showEchipamente">
                                <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>
                        </div>
                    </td>
                </tr>
            </tfoot>
        </table>
    </td></tr>
</table>


<script type="text/javascript">
    function reloadData(){
        window.location = "<%=AppConstants.APP_NAME%>?action=showEchipamente";
    }
</script>
