<%@ page import="ro.emid.common.db.AccessDB" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ 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.db.framework.Filter" %>
<%@ page import="ro.emid.common.db.framework.IFilter" %>
<%@ page import="ro.emid.common.types.Category" %>
<%@ page import="ro.emid.common.types.Echipament" %>
<%@ page import="ro.emid.common.types.Nomenclator" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.common.utils.pagination.PaginationController" %>
<%@ page import="ro.emid.common.utils.pagination.PaginationData" %>
<%@ page import="ro.emid.incidente.IncidenteSessionUtils" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="java.text.MessageFormat" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>

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

<%

    final long idAnsamblu = ObjectUtils.getLongValue( request.getParameter("idAnsamblu"), -2);
    final long idComponenta = ObjectUtils.getLongValue( request.getParameter("idComponenta"), -2);
    final long idCauzaGrupa = ObjectUtils.getLongValue(request.getParameter("idCauzaGrupa"), -2);
    final long idCauza = ObjectUtils.getLongValue( request.getParameter("idCauza"), -2);


    long filialaId = IncidenteSessionUtils.getFilialaId(session);
    long sucursalaId = IncidenteSessionUtils.getSucursalaId(session);
    long centruId = IncidenteSessionUtils.getCentruId(session);

    final Category sFiliala = (Category) session.getAttribute("filiala");
    final Category sSucursala = (Category) session.getAttribute("sucursala");
    final Category sCentru = (Category) session.getAttribute("centru");

    if (sFiliala != null && sFiliala.getId() > 0) filialaId = sFiliala.getId();
    if (sSucursala != null && sSucursala.getId() > 0) sucursalaId = sSucursala.getId();
    if (sCentru != null && sCentru.getId() > 0) centruId = sCentru.getId();

    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();


    final String append_to = (String )session.getAttribute("rapoarteEchipamenteFiltru.append_to");
    final Long sData_start = (Long )session.getAttribute("rapoarteEchipamenteFiltru.data_start");
    final Long sData_stop = (Long )session.getAttribute("rapoarteEchipamenteFiltru.data_stop");

    final StringBuffer condSql = new StringBuffer( append_to != null ? append_to : "");

    if( filialaRaport.getId() > 0){
        condSql.append(" AND FILIALA_ID = ").append( filialaRaport.getId());
    }

    if( sucursalaRaport.getId() > 0){
        condSql.append(" AND SUCURSALA_ID = ").append( sucursalaRaport.getId());
    }

    if( centruRaport.getId() > 0){
        condSql.append(" AND SECTIE_ID = ").append( centruRaport.getId());
    }

    if( idAnsamblu > 0 || idAnsamblu == -1){
        condSql.append( " AND ANSAMBLU_ID=").append( idAnsamblu);

        if( idComponenta > 0 || idComponenta == -1){
            condSql.append( " AND COMPONENTA_ID=").append( idComponenta);
        }
    }else {
        if( idCauzaGrupa > 0 || idCauzaGrupa == -1){
            condSql.append( " AND CAUZA_GR_ID=").append( idCauzaGrupa);
        }

        if( idCauza > 0 || idCauza == -1){
            condSql.append( " AND CAUZA_ID=").append( idCauza);
        }
    }

    final IFilter filtru = new Filter().addStringCriteria( condSql.toString());
    if( sData_start != null && sData_start.longValue() > 0){
        filtru.addOrSetCriteria(" AND ", "DATA_DETERIORARE", ">=", new Timestamp( sData_start.longValue()));
    }

    if( sData_stop != null && sData_stop.longValue() > 0){
        filtru.addOrSetCriteria(" AND ", "DATA_DETERIORARE", "<=", new Timestamp( sData_stop.longValue()));
    }


    final PaginationData pd = PaginationController.getPaginationData(request, 500);

    final Echipament[] echipamente = EchipamentAccessDB.getAllEchipamente( filtru, "FILIALA_ID ASC, SUCURSALA_ID ASC, SECTIE_ID", "ASC", pd.getStartIndex(), pd.getQueryEndIndex());

    final Integer tc = (Integer) AccessDB.executeSQL(new AccessDB("Get Incidente count") {
        protected Object doWork() throws SQLException, DatabaseException {
            Integer obj = new Integer(0);
            createStatementFromString(MessageFormat.format("SELECT count(*) CNT FROM echipamente e WHERE 0=0 {0} ", new String[]{filtru.getSqlFilterCondition()}));
            filtru.bindStatement(this.statement);
            getResultSetFromQuery();
            if (resultSet.next()) {
                obj = new Integer(resultSet.getInt("CNT"));
            }

            return obj;
        }
    });

    pd.setResultRowCount( echipamente != null ? echipamente.length : 0 );
    pd.setTotalRowsCount( tc != null ? tc.intValue() : 0 );
%>

<form method="post" action="">
    <TABLE id="echipamente" border=0 cellPadding=2 cellSpacing=1 width="97%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white;margin: 10px">
        <col align="right" style="padding-right:5px">
        <col align="right" style="padding-right:5px">
        <tr noSelect="true">
            <TH class="gsapthead" height=25 width="100px" align="center">&nbsp;Nr. Fisa<br/>Echipament:&nbsp;</TH>
            <TH class="gsapthead" height=25 width="3%" align="center" style="font-size:12px" noWrap>&nbsp;Nr. Echipamente<br>Identice deteriorate:&nbsp;</TH>
            <TH class="gsapthead" height=25 noWrap align="left">&nbsp;Localizare:&nbsp;</TH>
            <TH class="gsapthead" height=25 noWrap align="left">&nbsp;Ansamblu:&nbsp;</TH>
            <TH class="gsapthead" height=25 width="1%" noWrap align="left">&nbsp;Op.:&nbsp;</TH>
        </tr>

        <% if( echipamente.length == 0){%>
            <tr>
                <td>No data ...</td>
            </tr>
        <% }else {%>
        <%  long totalEchipamente = 0; %>
        <%  long centruCurentId = -1;%>
        <%  final Map cacheAnsamblu = new HashMap(); %>
        <%  for (int i = 0; i < echipamente.length; i++) {
            final Echipament echipament = echipamente[i];
            totalEchipamente += echipamente[ i].getNumarEchipIdenticeDet();

            Category f = CategoryAccessDB.getById( echipament.getFilialaId());
            if( f == null) f =  new Category();

            Category s = CategoryAccessDB.getById( echipament.getSucursalaId());
            if( s == null) s = new Category();

            Category c = CategoryAccessDB.getById( echipament.getCentruId());
            if( c == null) c = new Category();

            Nomenclator ansamblu = (Nomenclator) cacheAnsamblu.get(String.valueOf(echipament.getAnsambluId()));
            if( ansamblu == null){
                ansamblu = NomAccessDB.getNom(echipament.getAnsambluId());
                if( ansamblu != null){
                    cacheAnsamblu.put(String.valueOf(echipament.getAnsambluId()), ansamblu);
                }
            }

            String className = "";
            if( centruCurentId != c.getId()){
                centruCurentId = c.getId();
                className = "underlined";
            }
        %>

            <tr ondblclick="printEchipament( <%=echipament.getId()%>)" title="Dubluclick pentru a vizualiza Fisa de Echipament">
                <td align="" class="<%=className%>">
                    <%=echipament.getNumarFI_FE()%>
                </td>
                <td align="center">
                    <%=echipament.getNumarEchipIdenticeDet()%>
                </td>
                <td class="<%=className%>">
                    <%=f.getName()%> - <%=s.getName()%> - <%=c.getName()%>
                </td>
                <td><nobr>
                    <%=ansamblu != null ? ansamblu.getDescriere() : "-" %>
                </nobr></td>
                <td>
                    <a class="link" href="javascript: void( null)" onclick="printEchipament( <%=echipament.getId()%>); return false;" title="Click pentru a vizualiza Fisa de Echipament">Vizualizare</a>
                </td>
            </tr>
            <%}%>
            <tr noSelect="true" style="font-weight:bold;">
                <td class="gsapthead">&nbsp;</td>
                <td class="gsapthead" title="Numarul total de Echipamente" align="center"><%=totalEchipamente%></td>
                <td colspan="3" align="right" class="gsapthead" >
                    <%=PaginationController.printPaginationData(pd)%>
                </td>
            </tr>
        <%}%>
    </TABLE>
</form>
<br>

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

</span>