<%@ page import="ro.emid.common.db.framework.ReportStatement" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="ro.emid.common.db.VolumInstalatiiAccessDB" %>
<%@ page import="ro.emid.common.constants.NomConstants" %>
<%@ page import="ro.emid.common.types.VolumInstalatii" %>
<%@ page import="java.sql.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page import="java.util.List" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.common.types.Category" %>
<%@ page import="ro.emid.common.constants.RoleConstants" %>

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

<%
    long sucursalaId = sucursala.getId();
    final long reqSucursala = ObjectUtils.getLongValue(request.getParameter("sucursalaId"), -1);
    if( reqSucursala != -1) sucursalaId = reqSucursala;

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


    Integer ani[] = VolumInstalatiiAccessDB.getAniVolumeInstalatii();
    ani = ro.emid.common.utils.Util.addCurrentYear(ani);

    int anRaport = ObjectUtils.getIntValue( request.getParameter("anRaport"), -1);
    if ( anRaport == -1) anRaport = ro.emid.common.utils.Util.getCurrentYear();
%>


<TABLE border=0 cellPading=0 cellSpacing=0 width="100%">
    <TR>
        <TD>
            <%@ include file="../header-localizare.jsp"%>
            <span class="slash">/</span> <A class="link" href="<%=AppConstants.APP_NAME%>?action=rapoarte">Rapoarte</A>
            <span class="slash">/</span> Indicatori Specifici de incident
        </TD>
    </TR>
</TABLE>

<%

    long centruId = centruExploatare.getId();
    final long reqCentruId = ObjectUtils.getLongValue(request.getParameter("centruId"), -1);
    if (reqCentruId != -1) centruId = reqCentruId;
    Category centruRaport = CategoryAccessDB.getById(centruId);
    if (centruRaport == null) centruRaport = new Category();

    final int currentYear = Calendar.getInstance().get(Calendar.YEAR);

    String localizareIncidentCondition = "";
    String localizareCentreCondition = "";
    String volumInstalatiiCondition = "";
    if (filiala.getId() > 0) {
        localizareIncidentCondition += " AND i.FILIALA_ID = " + filiala.getId();
        volumInstalatiiCondition = " AND FILIALA_ID=" + filiala.getId();

        final StringBuffer csv = new StringBuffer();
        final Category[] sucursale = CategoryAccessDB.getAllCategoriesByParentId(filiala.getId());
        for (int i = 0; i < sucursale.length; i++) {
            final Category s = sucursale[i];
            if (csv.length() > 0) csv.append(',');
            csv.append(s.getId());
        }

        localizareCentreCondition = " AND ID_PARENT IN (" + csv + ')';
    }

    if (sucursalaRaport.getId() > 0) {
        localizareIncidentCondition += " AND i.SUCURSALA_ID=" + sucursalaRaport.getId();
        localizareCentreCondition = " AND ID_PARENT=" + sucursalaRaport.getId();
        volumInstalatiiCondition = " AND SUCURSALA_ID=" + sucursalaRaport.getId();
    }

    if (centruRaport.getId() > 0) {
        localizareIncidentCondition += " AND i.SECTIE_ID = " + centruRaport.getId();
        localizareCentreCondition = " AND ID = " + centruRaport.getId();
        volumInstalatiiCondition = " AND SECTIE_ID=" + centruRaport.getId();
    }

    volumInstalatiiCondition += " AND AN="+anRaport;

    final Category[] centre = CategoryAccessDB.getAllCategories( localizareCentreCondition);
    final VolumInstalatii[] volumuriInstalatii = new VolumInstalatii[centre.length];

    final VolumInstalatii[] allVolumes = VolumInstalatiiAccessDB.getAll( volumInstalatiiCondition);


    for (int i = 0; i < allVolumes.length; i++) {
        final VolumInstalatii v = allVolumes[i];
    }

    int k = 0;
    Date dataRaport = null;
    int minimYear = 0;
    
    for (int i = 0; i < centre.length; i++) {
        VolumInstalatii volumForCentru = null;

        for (int j = 0; j < allVolumes.length; j++) {
            if( allVolumes[j].getSectieId() == centre[i].getId()) {
                volumForCentru = allVolumes[j];
                break;
            }
        }

        if( volumForCentru == null){
            //get Volum Instalatii din anul precedent
            volumForCentru = VolumInstalatiiAccessDB.getEntryByCentruIdAndLessThanYear( centre[ i].getId(), anRaport);
        }


        if (volumForCentru != null) {
            k++;
            volumuriInstalatii[i] = volumForCentru;

            //search ze minim date
            if (dataRaport != null) {
                if (volumForCentru.getDataSave() != null && volumForCentru.getDataSave().compareTo(dataRaport) < 0) {
                    dataRaport = volumForCentru.getDataSave();
                    minimYear  = volumForCentru.getAn();
                }
            } else {
                dataRaport = volumForCentru.getDataSave();
                minimYear  = volumForCentru.getAn();
            }
        }
    }

    //grupate dupa luna si centru
    final ReportStatement countIncidente = new ReportStatement(
            " SELECT TO_NUMBER(TO_CHAR(DATA, 'MM')), SECTIE_ID, COUNT(*) FROM incidente i, nomenclator n ",
            " GROUP BY TO_CHAR(DATA, 'MM'), SECTIE_ID ORDER BY TO_CHAR(DATA, 'MM') ASC, SECTIE_ID ASC"
    ).addStringCriteria( "AND i.ANSAMBLU_ID = n.ID")
     .addStringCriteria( localizareIncidentCondition)
     .addOrSetFilter( " AND ", " TO_CHAR(DATA, 'YYYY')", "=", new Integer( anRaport));


    final ReportStatement countIncidenteLinii = new ReportStatement(
            " SELECT TO_NUMBER(TO_CHAR(DATA, 'MM')), SECTIE_ID, COUNT(*) FROM incidente i, nomenclator n, LF l ",
            " GROUP BY TO_CHAR(DATA, 'MM'), SECTIE_ID ORDER BY TO_CHAR(DATA, 'MM') ASC, SECTIE_ID ASC"
    ).addStringCriteria( "AND i.ANSAMBLU_ID = n.ID AND i.LINIE_COD = l.COD_LF ")
     .addStringCriteria( localizareIncidentCondition)
     .addOrSetFilter( " AND ", " TO_CHAR(DATA, 'YYYY')", "=", new Integer( anRaport));

    final StringBuffer buffer = new StringBuffer();
    buffer.append("=").append(NomConstants.NOM_ANSAMBLURI ).append(
            " AND i.STATIE_ID > 0 AND " ).append(
            "  ( " ).append(
            "        (n.COD IN (13, 19, 22, 46, 47, 48, 49, 53, 57, 521, 542) AND i.PAPT_ID = -1) " ).append(
            "     OR (n.COD IN (21, 60, 62, 541)) " ).append(
            "     OR (n.COD IN (51) AND i.LINIE_ID=-1)    ").append(
            "     OR (n.COD IN (61) AND i.LINIE_ID=-1 AND i.PAPT_ID=-1)    ").append(
            "  )");

    final List resultStatii = countIncidente.addOrSetStringCriteria("AND", "n.TIP", buffer.toString()
    ).getListOfArrays("Get Numar Incidente pentru Statii");

    buffer.delete(0, buffer.length());
    buffer.append("=").append( NomConstants.NOM_ANSAMBLURI ).append(
            " AND i.PAPT_ID > 0 AND " ).append(
            " ( " ).append(
            "       (n.COD IN (13, 19, 22, 46, 47, 48, 49, 53, 57,  61, 521, 542) AND i.STATIE_ID = -1) " ).append(
            "    OR ( n.COD IN ( 58, 59 ))" ).append(
            "    OR ( n.COD IN ( 51) AND i.LINIE_ID=-1 AND i.STATIE_ID=-1)" ).append(
            " )");

    final List resultPaPt = countIncidente.addOrSetStringCriteria("AND", "n.TIP", buffer.toString()
    ).getListOfArrays("Get Numar Incidente pentru PA/PT");

    final List resultLea_110 = countIncidenteLinii.addOrSetStringCriteria("AND",  "n.TIP", "=" + NomConstants.NOM_ANSAMBLURI +
            " AND n.COD IN (50, 522) AND (i.TENSIUNE = 110 OR (i.TENSIUNE=0 AND getNumarFromText( l.DESC_LF) = 110 )) "
    ).getListOfArrays("Get Numar Incidente pentru Lea 110");

    final List resultLea_MT = countIncidenteLinii.addOrSetStringCriteria("AND", "n.TIP",  "=" + NomConstants.NOM_ANSAMBLURI +
            " AND n.COD IN (50, 522) AND (i.TENSIUNE < 110 OR (i.TENSIUNE=0 AND getNumarFromText( l.DESC_LF) < 110 )) "
    ).getListOfArrays("Get Numar Incidente pentru Lea MT");

    final List resultLes_110 = countIncidenteLinii.addOrSetStringCriteria("AND", "n.TIP", "=" + NomConstants.NOM_ANSAMBLURI +
            " AND n.COD = 51 AND (i.TENSIUNE = 110 OR (i.TENSIUNE=0 AND getNumarFromText( l.DESC_LF) = 110 ))"
    ).getListOfArrays("Get Numar Incidente pentru Les 110");

    final List resultLes_MT = countIncidenteLinii.addOrSetStringCriteria("AND", "n.TIP",  "=" + NomConstants.NOM_ANSAMBLURI +
            " AND n.COD = 51 AND (i.TENSIUNE < 110 OR (i.TENSIUNE=0 AND getNumarFromText( l.DESC_LF) < 110 ))"
    ).getListOfArrays("Get Numar Incidente pentru Les MT");

    final String[] luni = new String[]{"Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"};
    final String[] trimestre = new String[]{"Trimestrul I", "Trimestrul II", "Trimestrul III", "Trimestrul IV"};
%>

<table width="90%" align="center">
<% if( filiala.getId() == -1){ %>
<tr><td align="center">Selectati o filiala</td></tr>
<%}else{%>
<tr><td>
    <center>
        <span style="font-size: 18px; font-weight:bold;">Raport lunar/trimestrial/anual - Indicator specifici de incident - filiala <%=filiala.getName()%></span>
    </center>
</td></tr>

<% if( dataRaport != null) {
    if( minimYear < anRaport){%>
        <tr>
            <td align="center">
                <span style="color: red; font-size: 12px"> Atentie! Raportul ruleaza cu date din anul precedent</span>
            </td>
        </tr>
    <%}%>
<%}%>

<tr>
    <td>
        <table width="100%" cellspacing="0" cellpadding="0" class="gsaptd">
            <tr>
                <td>
                    <form name="zaforma" action="<%=AppConstants.APP_NAME%>" method="post" style="margin-bottom:5; margin-top:5">
                        <input type="hidden" name="action" value="raport-indici-specifici">
                        Sucursala:
                        <SELECT class="gSAPSelect" name="sucursalaId" onchange="document.zaforma.centruId.selectedIndex = 0; document.zaforma.submit()"  <%=user.getIeLevel() == RoleConstants.NIVEL_FULL || user.getIeLevel() == RoleConstants.NIVEL_FILIALA ? "" : "disabled"%> >
                            <option value="-1">Selectati:</option>
                            <%if( filiala.getId() > 0){ final Category [] sucursale = CategoryAccessDB.getAllCategoriesByParentId( filiala.getId());
                                if (sucursale != null) for(int i=0;i<sucursale.length;i++) {%>
                                <OPTION <%=(sucursale[i].getId() == sucursalaRaport.getId()) ? "selected=\"true\" " : ""%>value="<%=sucursale[i].getId()%>"><%=sucursale[i].getName()%></OPTION>
                            <%}}%>
                        </SELECT>&nbsp;&nbsp;
                        C.E:
                        <SELECT class="gSAPSelect" name="centruId" onchange="document.zaforma.submit()" <%=user.getIeLevel() == RoleConstants.NIVEL_CENTRU || user.getIeLevel() == RoleConstants.NIVEL_FORMATIE ? "disabled" : ""%>>
                            <option value="0">Selectati:</option>
                            <%if (sucursalaRaport.getId() > 0 ){ final Category [] ces = CategoryAccessDB.getAllCategoriesByParentId( sucursalaRaport.getId());
                                if(ces != null) for(int i=0;i<ces.length;i++) {%>
                                <OPTION <%=(ces[i].getId() == centruRaport.getId()) ? "selected=\"true\" " : ""%>value="<%=ces[i].getId()%>"><%=ces[i].getName()%></OPTION>
                            <%}}%>
                        </SELECT>

                        &nbsp;An:<select name="anRaport"  class="gSAPSelect" onchange="document.zaforma.submit()">
                            <% for (int i = 0; i < ani.length; i++) { %>
                                 <option value="<%=ani[i]%>" <%=ani[i].intValue() == anRaport ? "selected" : ""%> ><%=ani[i]%></option>
                            <% }%>
                        </select>
                    </form>
                </td>
                <td align="right">
                    <% if( dataRaport != null){ %>                        
                        <span style="font-size: 12">Data actualizare: <%=AppConstants.format(dataRaport)%></span>
                    <%}%>
                </td>
            </tr>
        </table>
    </td>
</tr>

<style>
    .explicatii{
        font-size: 10px;
    }
</style>

<tr>
    <td align="center">
        <table id="raportTable" border=0 width="100%" style="BACKGROUND-COLOR: white" cellspacing="1">
            <tr noSelect="true">
                <td class="gsapthead">&nbsp;</td>
                <TH class="gsapthead" noWrap >
                    Statii<br>
                    <span class="explicatii">(buc.)</span>
                </TH>
                <TH class="gsapthead" noWrap >
                    LEA 110KV<br>
                    <span class="explicatii">(nr. Km / 100)</span>
                </TH>
                <TH class="gsapthead" noWrap >
                    LES 110KV<br>
                    <span class="explicatii">(nr. Km / 100)</span>
                </TH>
                <TH class="gsapthead" noWrap >PA/PT</TH>
                <TH class="gsapthead" noWrap >
                    LEA MT<br>
                    <span class="explicatii">(nr. Km / 100)</span>
                </TH>
                <TH class="gsapthead" noWrap >
                    LES MT<br>
                    <span class="explicatii">(nr. Km / 100)</span>
                </TH>
            </tr>

<%! public long getCount(final List list, final int month, final long centruId) {
    for (int i = 0; i < list.size(); i++) {
        final Object[] o = (Object[])list.get(i);
        final long lMonth    = Long.parseLong ( o[0] != null ? o[0].toString() : "-1");
        final long lCentruId = Long.parseLong ( o[1] != null ? o[1].toString() : "-1");
        final long lCount = Long.parseLong ( o[2] != null ? o[2].toString() : "-1");

        if( lMonth == month && lCentruId == centruId){
            return lCount;
        }
    }
    return 0;
}%>
            <%
                double anual_statii  = 0, trimestrial_statii  = 0;
                double anual_lea_110 = 0, trimestrial_lea_110 = 0;
                double anual_les_110 = 0, trimestrial_les_110 = 0;
                double anual_pa_pt   = 0, trimestrial_pa_pt   = 0;
                double anual_lea_mt  = 0, trimestrial_lea_mt  = 0;
                double anual_les_mt  = 0, trimestrial_les_mt  = 0;


                for (int i = 0; i < luni.length; i++) {
                    //calcul indicator
                    double nr_incidente_statii  = 0;
                    double nr_incidente_lea_110 = 0;
                    double nr_incidente_les_110 = 0;
                    double nr_incidente_pa_pt   = 0;
                    double nr_incidente_lea_mt  = 0;
                    double nr_incidente_les_mt  = 0;

                    final VolumInstalatii totalVolumInstalatii = new VolumInstalatii();

                    boolean volumInstalatiiNedefinit = false;
                    for (int j = 0; j < centre.length; j++) {
                        final VolumInstalatii volumInstalatii = volumuriInstalatii[j];
                        if (volumInstalatii == null) {
                            volumInstalatiiNedefinit = true;
                            break; //nu mai are rost de continuat ...
                        }


                        nr_incidente_statii   += getCount( resultStatii, i+1, centre[j].getId());
                        nr_incidente_lea_110  += getCount( resultLea_110, i+1, centre[j].getId());
                        nr_incidente_les_110  += getCount( resultLes_110, i+1, centre[j].getId());
                        nr_incidente_pa_pt    += getCount( resultPaPt, i+1, centre[j].getId());
                        nr_incidente_lea_mt   += getCount( resultLea_MT, i+1, centre[j].getId());
                        nr_incidente_les_mt   += getCount( resultLes_MT, i+1, centre[j].getId());

                        totalVolumInstalatii.setStatii( totalVolumInstalatii.getStatii() + volumInstalatii.getStatii());
                        totalVolumInstalatii.setLea110( totalVolumInstalatii.getLea110() + volumInstalatii.getLea110());
                        totalVolumInstalatii.setLes110( totalVolumInstalatii.getLes110() + volumInstalatii.getLes110());
                        totalVolumInstalatii.setPa_pt(  totalVolumInstalatii.getPa_pt()  + volumInstalatii.getPa_pt());
                        totalVolumInstalatii.setLea_mt( totalVolumInstalatii.getLea_mt() + volumInstalatii.getLea_mt());
                        totalVolumInstalatii.setLes_mt( totalVolumInstalatii.getLes_mt() + volumInstalatii.getLes_mt());
                    }
                    final double indicator_statii  = totalVolumInstalatii.getStatii() != 0 ? nr_incidente_statii  / totalVolumInstalatii.getStatii() : 0;
                    final double indicator_lea_110 = totalVolumInstalatii.getLea110() != 0 ? nr_incidente_lea_110 / totalVolumInstalatii.getLea110() * 100 : 0;
                    final double indicator_les_110 = totalVolumInstalatii.getLes110() != 0 ? nr_incidente_les_110 / totalVolumInstalatii.getLes110() * 100 : 0;
                    final double indicator_pa_pt   = totalVolumInstalatii.getPa_pt()  != 0 ? nr_incidente_pa_pt   / totalVolumInstalatii.getPa_pt()  * 100 : 0;
                    final double indicator_lea_mt  = totalVolumInstalatii.getLea_mt() != 0 ? nr_incidente_lea_mt  / totalVolumInstalatii.getLea_mt() * 100 : 0;
                    final double indicator_les_mt  = totalVolumInstalatii.getLes_mt() != 0 ? nr_incidente_les_mt  / totalVolumInstalatii.getLes_mt() * 100 : 0;
            %>
                    <tr>
                        <td class="gsapthead"><%=luni[i]%></td>
                        <td align="right"><%=volumInstalatiiNedefinit ? "nedefinit" : AppConstants.format3(indicator_statii)%></td>
                        <td align="right"><%=volumInstalatiiNedefinit ? "nedefinit" : AppConstants.format3(indicator_lea_110)%></td>
                        <td align="right"><%=volumInstalatiiNedefinit ? "nedefinit" : AppConstants.format3(indicator_les_110)%></td>
                        <td align="right"><%=volumInstalatiiNedefinit ? "nedefinit" : AppConstants.format3(indicator_pa_pt)%></td>
                        <td align="right"><%=volumInstalatiiNedefinit ? "nedefinit" : AppConstants.format3(indicator_lea_mt)%></td>
                        <td align="right"><%=volumInstalatiiNedefinit ? "nedefinit" : AppConstants.format3(indicator_les_mt)%></td>
                    </tr>
                    <%
                        trimestrial_statii  +=  indicator_statii  ;
                        trimestrial_lea_110 +=  indicator_lea_110 ;
                        trimestrial_les_110 +=  indicator_les_110 ;
                        trimestrial_pa_pt   +=  indicator_pa_pt   ;
                        trimestrial_lea_mt  +=  indicator_lea_mt  ;
                        trimestrial_les_mt  +=  indicator_les_mt  ;
                    %>
                    <%if( (i + 1)%3 == 0){%>
                        <tr style="background-color:#f1f1ff;">
                            <td class="gsapthead" align="right"><b><%=trimestre[i/3]%></b></td>
                            <td align="right"><%=AppConstants.format03(trimestrial_statii)%></td>
                            <td align="right"><%=AppConstants.format03(trimestrial_lea_110)%></td>
                            <td align="right"><%=AppConstants.format03(trimestrial_les_110)%></td>
                            <td align="right"><%=AppConstants.format03(trimestrial_pa_pt)%></td>
                            <td align="right"><%=AppConstants.format03(trimestrial_lea_mt)%></td>
                            <td align="right"><%=AppConstants.format03(trimestrial_les_mt)%></td>

                            <%
                                anual_statii  += trimestrial_statii ;
                                anual_lea_110 += trimestrial_lea_110;
                                anual_les_110 += trimestrial_les_110;
                                anual_pa_pt   += trimestrial_pa_pt  ;
                                anual_lea_mt  += trimestrial_lea_mt ;
                                anual_les_mt  += trimestrial_les_mt ;

                                trimestrial_statii   = 0;
                                trimestrial_lea_110  = 0;
                                trimestrial_les_110  = 0;
                                trimestrial_pa_pt    = 0;
                                trimestrial_lea_mt   = 0;
                                trimestrial_les_mt   = 0;
                            %>
                        </tr>
                    <%}%>
                <%}%>
                <tr style="background-color:#f1f1ff;">
                    <td class="gsapthead" align="right"><b>Anul <%=anRaport%></b></td>
                    <td align="right"><%=AppConstants.format03(anual_statii)%></td>
                    <td align="right"><%=AppConstants.format03(anual_lea_110)%></td>
                    <td align="right"><%=AppConstants.format03(anual_les_110)%></td>
                    <td align="right"><%=AppConstants.format03(anual_pa_pt)%></td>
                    <td align="right"><%=AppConstants.format03(anual_lea_mt)%></td>
                    <td align="right"><%=AppConstants.format03(anual_les_mt)%></td>
                </tr>
        </table>
    </td>
</tr>
<%}%>
</table>
