<%@ page import="ro.emid.common.types.Category" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="ro.emid.common.db.framework.AppConnManager" %>
<%@ page import="ro.emid.common.constants.GlobalAppConstants" %>
<%@ page import="java.util.Vector" %>
<%@ page import="ro.emid.common.db.framework.ReportStatement" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="java.util.List" %>
<%@ page import="ro.emid.common.db.DeranjamentAccessDB" %>
<%@ page import="ro.emid.callcenter.CallcenterSessionUtils" %>
<%@ page import="ro.emid.common.constants.RoleConstants" %>

<%@ include file="../callcenter/declaratii.jsp"%>
<%
    long filialaId = CallcenterSessionUtils.getFilialaId(session);
    long sucursalaId = CallcenterSessionUtils.getSucursalaId(session);
    long centruId = CallcenterSessionUtils.getCentruId(session);

    if( 0 < ObjectUtils.getLongValue( request.getParameter( "filiala"), -2)){
        filialaId = ObjectUtils.getLongValue( request.getParameter( "filiala"));
    }

    if( 0 < ObjectUtils.getLongValue( request.getParameter( "sucursala"), -2)){
        sucursalaId = ObjectUtils.getLongValue( request.getParameter( "sucursala"));
    }

    if( 0 < ObjectUtils.getLongValue( request.getParameter( "centruId"), -2)){
        centruId = ObjectUtils.getLongValue( request.getParameter( "centruId"));
    }

    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 Vector vani = DeranjamentAccessDB.getAniProducereDeranjament();
        
    Long anSelectat = new Long(ObjectUtils.getLongValue(request.getParameter("an"), -1));
    if (anSelectat.longValue() == -1) anSelectat = (Long) (vani.size() > 0 ? vani.firstElement() : new Long(0));
%>

<TABLE border=0 cellPading=0 cellSpacing=0 width="100%">
    <TR>
        <TD>
            <SPAN style="FONT-SIZE: 12px; FONT-WEIGHT: bold">
                <A class="link" href="<%=GlobalAppConstants.APP_NAME%>?action=rapoarte">Rapoarte</A> - Raport indicatori performanta furnizare
            </span>
        </TD>
    </TR>
</TABLE>

<center>
    <br />
    Realizarea indicatorilor de performanta pentru serviciul de furnizare a energiei electrice <br />
    <span style="font-size: 14; font-weight: bold;" >RAPORT ANUAL</span>
</center>

<div class="spacer"></div>
<table width="100%" class="gsaptd"><tr><td>
<form name="zaforma" action="<%=GlobalAppConstants.APP_NAME%>" method="post">
    <input type="hidden" name="action" value="raport-deranjamente-anual2">
    Filiala:
    <SELECT name="filiala" onchange="fill_sucursala_select()" class="gSAPSelect" <%=user.getIeLevel() == RoleConstants.NIVEL_FULL ? "" : "disabled"%> >
        <OPTION value="-1">ELECTRICA SA:</OPTION>
        <%  final Category [] filiale = CategoryAccessDB.getAllCategoriesByParentId(-1);
          if (filiale != null) for(int i=0;i<filiale.length;i++) {%>
          <OPTION <%=(filiale[i].getId() == filialaRaport.getId()) ? "selected=\"true\" " : ""%>value="<%=filiale[i].getId()%>"><%=filiale[i].getName()%></OPTION>
        <%} %>
    </SELECT>&nbsp;&nbsp;

    Sucursala:
    <span id="sucursalaDiv">
    <SELECT name="sucursala" class="gSAPSelect" onchange="fill_centru_select()" >
          <option value="-1">Selectati:</option>
    </SELECT></span>&nbsp;&nbsp;

    C.E.:
    <span id="centruDiv">
        <SELECT name="centruId" class="gSAPSelect">
         <OPTION value="-1">Selectati:</OPTION>
        </SELECT>
    </span>&nbsp;&nbsp;

    &nbsp;&nbsp;&nbsp;Anul:
    <select name="an" >
        <% for (int i = 0; i < vani.size(); i++) {
            final Long an = (Long)vani.get( i);%>
            <option value="<%=an%>" <%=anSelectat.equals(an) ? "selected" : ""%> ><%=an%></option>
        <% } %>
    </select>
    &nbsp;
    <input type="submit" value="Aplica">
</form>


    <script type="text/javascript">
        function fill_sucursala_select(selectedValue, disabled, firstShow){
            resetComboLeaveFirstOption( document.zaforma.sucursala);
            resetComboLeaveFirstOption( document.zaforma.centruId);

            var filialaId = document.zaforma.filiala[ document.zaforma.filiala.selectedIndex].value;
            if( filialaId > -1){
                var params = "parentId="+filialaId + "&selectName=sucursala&disabled=" + disabled + (selectedValue ? "&selectedValue=" + selectedValue : "");
                //alert( params);

                getCategoriesFromServer(params, function(originalRequest){
                    //alert( getResponseMesg (originalRequest.responseText));
                    $( 'sucursalaDiv').innerHTML = getResponseMesg (originalRequest.responseText);

                    document.zaforma.sucursala.onchange=fill_centru_select;

                    if( firstShow){
                        fill_centru_select(<%=centruRaport.getId()%>, <%=user.getIeLevel() == RoleConstants.NIVEL_CENTRU || user.getIeLevel() == RoleConstants.NIVEL_FORMATIE%>);
                    }
                });
            }
        }

        function fill_centru_select(selectedValue, disabled){
            resetComboLeaveFirstOption( document.zaforma.centruId);

            var sucursalaId = document.zaforma.sucursala[ document.zaforma.sucursala.selectedIndex].value;
            if( sucursalaId > -1){
                var params = "parentId="+sucursalaId + "&selectName=centruId&disabled=" + disabled + (selectedValue ? "&selectedValue=" + selectedValue : "");
                //alert( params);

                getCategoriesFromServer(params,function(originalRequest){
                    //alert( getResponseMesg (originalRequest.responseText));
                    $( 'centruDiv').innerHTML = getResponseMesg (originalRequest.responseText);
                });
            }
        }


        fill_sucursala_select(<%=sucursalaRaport.getId()%>, <%=user.getIeLevel() == RoleConstants.NIVEL_SUCURSALA || user.getIeLevel() == RoleConstants.NIVEL_CENTRU || user.getIeLevel() == RoleConstants.NIVEL_FORMATIE%>, true);
   </script>                 
</td></tr></table>
<div class="spacer"></div>
<%
    String condition = "";
    String columnTitle = "";
    if( centruRaport.getId() > 0){
        condition = " AND ID = " + centruRaport.getId();
    }else if( sucursalaRaport.getId() > 0){
        condition = " AND id_parent = " + sucursalaRaport.getId();
    }else if( filialaRaport.getId() > 0){
        condition = " AND id_parent = " + filialaRaport.getId();
        columnTitle = "SDFEE";
    }else{
        condition = " AND id_parent = -1";
        columnTitle = "FDFEE";
    }
//    Category[] sucursale_sectii = new Category[0];
    final Category[] sucursale_sectii = CategoryAccessDB.getAllCategories( condition);
%>

<TABLE id="table" border=1 cellPadding=2 cellSpacing=1 width="100%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white">
    <colgroup align="left">
    <tr noSelect="true">
        <th class="gsapthead" rowspan="2">&nbsp;</th>
        <th class="gsapthead" rowspan="2" width="100">Denumire</th>
        <th class="gsapthead" rowspan="2">&nbsp;</th>
        <th class="gsapthead" colspan="19">Valoare Realizata lunar/anual</th>        
    </tr>
    <tr noSelect="true">
        <th class="gsapthead">1</th>
        <th class="gsapthead">2</th>
        <th class="gsapthead">3</th>
        <th class="gsapthead">Trim. I</th>
        <th class="gsapthead">4</th>
        <th class="gsapthead">5</th>
        <th class="gsapthead">6</th>
        <th class="gsapthead">Trim. II</th>
        <th class="gsapthead">Sem. I</th>
        <th class="gsapthead">7</th>
        <th class="gsapthead">8</th>
        <th class="gsapthead">9</th>
        <th class="gsapthead">Trim. III</th>
        <th class="gsapthead">10</th>
        <th class="gsapthead">11</th>
        <th class="gsapthead">12</th>
        <th class="gsapthead">Trim. IV</th>
        <th class="gsapthead">Sem. II</th>
        <th class="gsapthead">Anual</th>
    </tr>    
        <%
            final ReportStatement raportNrDeranjamente = new ReportStatement("SELECT /*+ INDEX(RAPORT_ANUAL_CC_IDX) */ TO_CHAR(data_anuntare, 'MM'), COUNT(*) FROM deranjamente", "GROUP BY TO_CHAR(data_anuntare, 'MM')")
                .addOrSetFilter("TO_CHAR(data_anuntare, 'YYYY')", "=", anSelectat);

            final ReportStatement raportNrConsumatoriAfectati = new ReportStatement("SELECT /*+ INDEX(RAPORT_ANUAL_CC_IDX) */ se seteaza functie de (casnici, mici, mari) FROM deranjamente", "GROUP BY TO_CHAR(data_anuntare, 'MM')")
                .addOrSetFilter("TO_CHAR(data_anuntare, 'YYYY')", "=", anSelectat);

            final ReportStatement raportNrConsumatoriReconectati4 = new ReportStatement("SELECT /*+ INDEX(RAPORT_ANUAL_CC_IDX) */ se seteaza functie de (casnici, mici, mari) FROM deranjamente", "GROUP BY TO_CHAR(data_anuntare, 'MM')")
                .addOrSetFilter("TO_CHAR(data_anuntare, 'YYYY')","=", anSelectat)
                .addOrSetFilter("floor((data_rezolvare - data_anuntare)*24)", "<", new Long(4));

            final ReportStatement raportNrConsumatoriReconectati24 = new ReportStatement("SELECT /*+ INDEX(RAPORT_ANUAL_CC_IDX) */ se seteaza functie de (casnici, mici, mari) FROM deranjamente", "GROUP BY TO_CHAR(data_anuntare, 'MM')")
                .addOrSetFilter("TO_CHAR(data_anuntare, 'YYYY')","=", anSelectat)
                .addOrSetFilter("floor((data_rezolvare - data_anuntare)*24)", "<", new Long(24));



            final String[] denumiri = new String[]{
                    "Nr. deranjamente",
                    "Nr. de consumatori afectati de intreruperile cauzate de deranjament",
                    "Nr. de consumatori reconectati intr-un interval mai mic de 4 ore",
                    "Nr. de consumatori reconectati intr-un interval mai mic de 24 ore"
            };

            final long[][] totaluri = new long[ 1 + (denumiri.length - 1)*3][19];
            for (int i = 0; i < sucursale_sectii.length; i++) {
                final Category category = sucursale_sectii[i];
                boolean categoryShown = false;

                if (sucursalaRaport.getId() > 0 || centruRaport.getId() > 0){
                    raportNrDeranjamente.addOrSetFilter("SECTIE_ID","=", new Long(category.getId()));
                    raportNrConsumatoriAfectati.addOrSetFilter("SECTIE_ID","=", new Long( category.getId()));
                    raportNrConsumatoriReconectati4.addOrSetFilter("SECTIE_ID","=", new Long( category.getId()));
                    raportNrConsumatoriReconectati24.addOrSetFilter("SECTIE_ID","=", new Long( category.getId()));
                }else if( filialaRaport.getId() > 0){
                    raportNrDeranjamente.addOrSetFilter("SUCURSALA_ID","=", new Long(category.getId()));
                    raportNrConsumatoriAfectati.addOrSetFilter("SUCURSALA_ID","=", new Long( category.getId()));
                    raportNrConsumatoriReconectati4.addOrSetFilter("SUCURSALA_ID","=", new Long( category.getId()));
                    raportNrConsumatoriReconectati24.addOrSetFilter("SUCURSALA_ID","=", new Long( category.getId()));
                }else{
                    raportNrDeranjamente.addOrSetFilter("FILIALA_ID","=", new Long( category.getId()));
                    raportNrConsumatoriAfectati.addOrSetFilter("FILIALA_ID","=", new Long( category.getId()));
                    raportNrConsumatoriReconectati4.addOrSetFilter("FILIALA_ID","=", new Long( category.getId()));
                    raportNrConsumatoriReconectati24.addOrSetFilter("FILIALA_ID","=", new Long( category.getId()));
                }

                for( int j = 0; j < denumiri.length; j++){
                    ReportStatement datas = null;
                    switch (j){
                        case 0 : datas = raportNrDeranjamente; break;
                        case 1 : datas = raportNrConsumatoriAfectati; break;
                        case 2 : datas = raportNrConsumatoriReconectati4; break;
                        case 3 : datas = raportNrConsumatoriReconectati24; break;
                    }

                    final int n = ( j == 0 ? 1 : 3);
                    for( int k = 0; k < n ; k++){
                         long valoareSemestriala = 0;
                         long valoareAnuala = 0;
                         long v1 = 0, v2 = 0, v3 = 0;
                    
                         final int index = (j == 0 ? 0 : (j-1)*3 + 1 + k);
                         String tip = "nedefinit";
                         if( n == 1) {
                            tip = "JT";
                         }else switch( k){
                                 case 0 : tip = "casnici"; datas.setSelectStatement( "SELECT /*+ INDEX(RAPORT_ANUAL_CC_IDX) */ TO_CHAR(data_anuntare, 'MM'), SUM( NR_AP + NR_CASE) FROM deranjamente");  break;
                                 case 1 : tip = "mici";    datas.setSelectStatement( "SELECT /*+ INDEX(RAPORT_ANUAL_CC_IDX) */ TO_CHAR(data_anuntare, 'MM'), SUM( NR_MICI) FROM deranjamente"); break;
                                 case 2 : tip = "mari";    datas.setSelectStatement( "SELECT /*+ INDEX(RAPORT_ANUAL_CC_IDX) */ TO_CHAR(data_anuntare, 'MM'), SUM( NR_MARI) FROM deranjamente"); break;
                              }

                          final List matrix = datas.getListOfArrays("Get M"); %>
                          <tr>
                            <% if( k == 0){
                                if ( !categoryShown){
                                    categoryShown = true;%>
                                    <td rowspan="<%=totaluri.length%>" valign="middle"><b><%=columnTitle%> <%=category.getName()%></b></td>
                                <%}%>
                                <td rowspan="<%=(j==0 ? "1" : "3" )%>"><%=denumiri[j]%></td>
                            <%}%>
                            <td><%=tip%></td>
                            <% v1 = DeranjamentAccessDB.getLongByMonth(matrix, 1); %>
                            <% v2 = DeranjamentAccessDB.getLongByMonth(matrix, 2); %>
                            <% v3 = DeranjamentAccessDB.getLongByMonth(matrix, 3); %>
                            <% valoareSemestriala   += v1 + v2 + v3; %>
                            <td align="right"><%=v1%></td>
                            <td align="right"><%=v2%></td>
                            <td align="right"><%=v3%></td>
                            <td align="right"><%=v1 + v2 + v3%></td>
                            <% totaluri[index][0] += v1; %>
                            <% totaluri[index][1] += v2; %>
                            <% totaluri[index][2] += v3; %>
                            <% totaluri[index][3] += v1 + v2 + v3; %>

                            <% v1 = DeranjamentAccessDB.getLongByMonth(matrix, 4); %>
                            <% v2 = DeranjamentAccessDB.getLongByMonth(matrix, 5); %>
                            <% v3 = DeranjamentAccessDB.getLongByMonth(matrix, 6); %>
                            <% valoareSemestriala   += v1 + v2 + v3; %>
                            <td align="right"><%=v1%></td>
                            <td align="right"><%=v2%></td>
                            <td align="right"><%=v3%></td>
                            <td align="right"><%=v1 + v2 + v3%></td>
                            <td align="right"><%=valoareSemestriala%></td>
                            <% totaluri[index][4] += v1; %>
                            <% totaluri[index][5] += v2; %>
                            <% totaluri[index][6] += v3; %>
                            <% totaluri[index][7] += v1 + v2 + v3; %>
                            <% totaluri[index][8] += valoareSemestriala; %>

                            <% valoareAnuala += valoareSemestriala; %>
                            <% valoareSemestriala = 0;%>

                            <% v1 = DeranjamentAccessDB.getLongByMonth(matrix, 7); %>
                            <% v2 = DeranjamentAccessDB.getLongByMonth(matrix, 8); %>
                            <% v3 = DeranjamentAccessDB.getLongByMonth(matrix, 9); %>
                            <% valoareSemestriala += v1 + v2 + v3; %>
                            <td align="right"><%=v1%></td>
                            <td align="right"><%=v2%></td>
                            <td align="right"><%=v3%></td>
                            <td align="right"><%=v1 + v2 + v3%></td>
                            <% totaluri[index][9]  += v1; %>
                            <% totaluri[index][10] += v2; %>
                            <% totaluri[index][11] += v3; %>
                            <% totaluri[index][12] += v1 + v2 + v3; %>

                            <% v1 = DeranjamentAccessDB.getLongByMonth(matrix, 10); %>
                            <% v2 = DeranjamentAccessDB.getLongByMonth(matrix, 11); %>
                            <% v3 = DeranjamentAccessDB.getLongByMonth(matrix, 12); %>
                            <% valoareSemestriala += v1 + v2 + v3; %>
                            <% valoareAnuala += valoareSemestriala; %>
                            <td align="right"><%=v1%></td>
                            <td align="right"><%=v2%></td>
                            <td align="right"><%=v3%></td>
                            <td align="right"><%=v1 + v2 + v3%></td>
                            <td align="right"><%=valoareSemestriala%></td>
                            <td align="right"><%=valoareAnuala%></td>
                            <% totaluri[index][13] += v1; %>
                            <% totaluri[index][14] += v2; %>
                            <% totaluri[index][15] += v3; %>
                            <% totaluri[index][16] += v1 + v2 + v3; %>
                            <% totaluri[index][17] += valoareSemestriala; %>
                            <% totaluri[index][18] += valoareAnuala; %>
                        </tr>
                    <%}%>
            <%  }%>
        <%}%>

        <tr>
            <td rowspan="10"><b>Total</b></td>
            <td><%=denumiri[0]%></td>
            <td>JT</td>
            <%for (int i = 0; i < totaluri[0].length; i++) {
                final long value = totaluri[0][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>
        <tr>
            <td rowspan="3"><%=denumiri[1]%></td>
            <td>casnici</td>
            <%for (int i = 0; i < totaluri[1].length; i++) {
                final long value = totaluri[1][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>
        <tr>
            <td>mici</td>
            <%for (int i = 0; i < totaluri[2].length; i++) {
                final long value = totaluri[2][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>
        <tr>
            <td>mari</td>
            <%for (int i = 0; i < totaluri[3].length; i++) {
                final long value = totaluri[3][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>

        <tr>
            <td rowspan="3"><%=denumiri[2]%></td>
            <td>casnici</td>
            <%for (int i = 0; i < totaluri[4].length; i++) {
                final long value = totaluri[4][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>
        <tr>
            <td>mici</td>
            <%for (int i = 0; i < totaluri[5].length; i++) {
                final long value = totaluri[5][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>
        <tr>
            <td>mari</td>
            <%for (int i = 0; i < totaluri[6].length; i++) {
                final long value = totaluri[6][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>

        <tr>
            <td rowspan="3"><%=denumiri[3]%></td>
            <td>casnici</td>
            <%for (int i = 0; i < totaluri[7].length; i++) {
                final long value = totaluri[7][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>
        <tr>
            <td>mici</td>
            <%for (int i = 0; i < totaluri[8].length; i++) {
                final long value = totaluri[8][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>
        <tr>
            <td>mari</td>
            <%for (int i = 0; i < totaluri[9].length; i++) {
                final long value = totaluri[9][i];%>
                <td align="right"><%=value%></td>
            <%}%>
        </tr>
</TABLE>

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