<%@ page import="org.apache.log4j.helpers.LogLog" %>
<%@ page import="ro.emid.Application" %>
<%@ page import="ro.emid.common.db.IncidentAccessDB" %>
<%@ 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.incidente.action.DeleteIncidentAction" %>
<%@ page import="ro.emid.incidente.action.EditIncidentAction" %>
<%@ page import="ro.emid.incidente.obj.FiltruIncidenteConstants" %>
<%@ page import="java.util.List" %>
<%@ page import="ro.emid.common.constants.*" %>
<%@ page import="ro.emid.common.utils.*" %>

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

<%
    String sortColumn = ObjectUtils.getStringValue(request.getParameter("sortColumn"));
    if( sortColumn == null || sortColumn.length() == 0) sortColumn = "DATA";
    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);
    final FiltruIncidente filtru = IncidenteSessionUtils.getFiltruIncidente(session);
    if (filtru != null && (filtru.getNumarIncident() > 0 || filtru.getAnul() > 0 || filtru.hasCriteriiSelectate())) {
        filtru.buildFilterSql(condSql, SessionConstants.FILTER_TYPE_INCIDENTE);
    }

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

    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 = IncidentAccessDB.getIncidenteCount(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 Incident[] incidente = IncidentAccessDB.getAllIncidente(condSql.toString(), sortColumn, sortType, currentBeginIndex, currentBeginIndex + nrLines - 1);
    final int nrLinesSelected = incidente.length;
%>

<table border=0 cellpading=0 cellspacing=0 width="100%">
    <tr>
        <td>
            <%@ include file="../header-localizare.jsp"%> <span class="slash">/</span> Incidente
        </td>
        <td align="right" style="padding-right: 10px">
            <span style="font-size: 12px;">Mergi la:</span>
            <b>Incidente</b>&nbsp;
            <A title="Lista echipamente" href="<%=AppConstants.APP_NAME%>?action=showEchipamente" class="link">Echipamente</A>&nbsp;
            <A onclick="showFiltruIncidente(); return false;" title="Click pentru a configura filtru Incidente" href="javascript: void(null)" class="link">Filtru</A>
        </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=resetFiltruIncidente">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=cautaIncident" 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;

                <% final Integer[] ani = ro.emid.common.utils.Util.addCurrentYear(IncidentAccessDB.getAniProducereIncident(localizareCondition)); %>
                <% final int anSelectat = filtru != null && filtru.getAnul() > 0 ? filtru.getAnul() : -1; %>
                Produse î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 height=25 colspan="2" noWrap>&nbsp;Titlu incident:&nbsp;</th>
                    <th height=25 noWrap>&nbsp;Nr. Comanda:&nbsp;</th>
                    <th nowrap width=40>&nbsp;Echip.&nbsp;</th>
                    <th nowrap width=70>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showIncidente&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=showIncidente&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=130>&nbsp;<a href="<%=AppConstants.APP_NAME%>?action=showIncidente&sortColumn=DATA&sortType=<%=(sortColumn.equals("DATA") ? (sortType.equals("ASC") ? "DESC" : "ASC") : sortType)%>" style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;">Data producerii:</a>&nbsp;<% if(sortColumn.equals("DATA")) 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( incidente.length == 0){%>
                <tr>
                    <td class="no-data" colspan="5">
                        Nu exista date ...
                    </td>
                </tr>
                <%} else {

                    for (int i = 0; i < incidente.length; i++) {
                        final Incident incident = incidente[i];
                        final StringBuffer parametri_titlu_incident = new StringBuffer();

                        if (incident.getAnsambluId() != -1) {
                            Nomenclator ansamblu = null;
                            try {
                                ansamblu = NomAccessDB.getNom(incident.getAnsambluId());
                            } catch (DatabaseException e) {
                                LogLog.debug("Database exception: " + e.getMessage());
                            }
                            if (ansamblu != null) parametri_titlu_incident.append("<span title=\"Ansamblul Functional\">").append( ansamblu.getDescriere()).append("</span>, ");
                        }

                        if ( !StringUtils.isZeroLength( incident.getStatieDen())) {
                            parametri_titlu_incident.append("<span title=\"Statia\">").append(AppConstants.format(incident.getStatieDen(), "-")).append("</span>, ");
                        }

                        if ( !StringUtils.isZeroLength( incident.getCelulaDen())) {
                            parametri_titlu_incident.append("<span title=\"Celula\">").append(AppConstants.format(incident.getCelulaDen(), "-")).append("</span>, ");
                        }

                        if ( !StringUtils.isZeroLength(  incident.getBaraDen())) {
                            parametri_titlu_incident.append("<span title=\"Bara\">").append(AppConstants.format(incident.getBaraDen(), "-")).append("</span>, ");
                        }

                        if ( !StringUtils.isZeroLength(  incident.getBobinaDen())) {
                            parametri_titlu_incident.append("<span title=\"Bobina\">").append(AppConstants.format(incident.getBobinaDen(), "-")).append("</span>, ");
                        }

                        if ( !StringUtils.isZeroLength(  incident.getLinieDen())) {
                            parametri_titlu_incident.append("<span title=\"Linia\">").append(AppConstants.format(incident.getLinieDen(), "-")).append("</span>, ");
                        }

                        if ( !StringUtils.isZeroLength(  incident.getPaptDen())) {
                            parametri_titlu_incident.append("<span title=\"PA/PT\">").append(AppConstants.format(incident.getPaptDen(), "-")).append("</span>, ");
                        }

                        if ( !StringUtils.isZeroLength( incident.getTrafoDen())) {
                            parametri_titlu_incident.append("<span title=\"Trafo\">") .append( AppConstants.format( incident.getTrafoDen())).append("</span>, ");
                        }%>
                        <tr ondblclick=" printIncident(<%=incident.getId()%>)" valign="top">
                            <td align="center" width="15" title="Numar Fisa Incident"><%=incident.getNumarIncident()%></td>
                            <td><%=parametri_titlu_incident%></td>
                            <%--<td align="center" ><span title="Numar Comanda SAP"><%=AppConstants.format( EvenimentAccessDB.getNumarComandaByResultIdAndResultType(incident.getId(), Eveniment.STATUS_TRECUT_INCIDENT))%></span></td>--%>
                            <td align="center" ><span title="Numar Comanda SAP"><%=incident.getNumarComandaSap() > 0 ? String.valueOf( incident.getNumarComandaSap()) : ""%></span></td>
                            <td align="center" title="Numar Fise Echipament atasate"><%=IncidentAccessDB.getNumarEchipamente( incident.getId())%></td>
                            <td title="Autor" <%if(sortColumn.equals("AUTOR")){%> class="sortColumn" <%}%>   ><%=ObjectUtils.getStringValue( incident.getUserInsert())%></td>
                            <td title="Actualizata de" <%if(sortColumn.equals("ACTUALIZAT_DE")){%> class="sortColumn" <%}%>   ><%=ObjectUtils.getStringValue( incident.getUserUpdate())%></td>
                            <td title="Data producerii incidentului" align="center" <%if(sortColumn.equals("DATA")){%> class="sortColumn" <%}%> ><%=AppConstants.format(incident.getDataProducere())%></td>

                            <% if( UserUtils.hasRoleAdminIncidente( user) || UserUtils.hasRoleUtilizatorIncidente( user)){%>
                                <td align="left" nowrap >
                                    <% if( GlobalAppConstants.APP_SERVER == GlobalAppConstants.APP_SERVER_FILIALA){%>
                                        <% if ( EditIncidentAction.hasRightEditIncident( user, incident)) { %>
                                            <a class="link" title="Modifica Fisa Incident" href="<%=AppConstants.APP_NAME%>?action=editIncident&id=<%=incident.getId()%>">Modifică</a>
                                        <% } %>

                                        <% if ( DeleteIncidentAction.hasRightDeleteIncident(user, incident)){ %>
                                            <a class="link" title="Sterge Fisa Incident" onclick="return confirm('Stergeti incidentul ?')" href="<%=AppConstants.APP_NAME%>?action=deleteIncident&id=<%=incident.getId()%>">Şterge</a>
                                        <% } %>

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

