<%@ 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="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="ro.emid.common.db.framework.ReportStatement" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="java.util.List" %>
<%@ page import="ro.emid.callcenter.CallcenterSessionUtils" %>
<%@ page import="ro.emid.common.constants.RoleConstants" %>
<%@ page import="ro.emid.common.constants.AppConstants" %>


<%@ 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 Connection con = AppConnManager.getInstance().getConnection();
    final Vector vani = new Vector();
    final PreparedStatement ps = con.prepareStatement("SELECT DISTINCT TO_CHAR(data_anuntare, 'YYYY') FROM deranjamente ORDER BY TO_CHAR(data_anuntare, 'YYYY') ASC");
    final ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        vani.add(new Long(rs.getLong(1)));
    }
    rs.close();
    ps.close();
    con.close();

    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> - Energia electrica nelivrata consumatorilor datorita producerii deranjamentelor
            </span>
        </TD>
    </TR>
</TABLE>

<center>
    <br>
    Energia electrica nelivrata consumatorilor datorita producerii deranjamentelor <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-enc">
    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.getAllCategories(" AND id_parent=-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;&nbsp;&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">
    <tr noSelect="true">
        <th class="gsapthead" rowspan="2">&nbsp;</th>
        <th class="gsapthead" rowspan="2" colspan="2" width="200">Energie nelivrata</th>
        <th class="gsapthead" >&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 raportConsumatoriCasnici = new ReportStatement("SELECT TO_CHAR(data_anuntare, 'MM'), SUM( ENC_CASNICI) FROM deranjamente", "GROUP BY TO_CHAR(data_anuntare, 'MM')")
                    .addOrSetFilter("TO_CHAR(data_anuntare, 'YYYY')","=", anSelectat);

            final ReportStatement raportAltiConsumatori = new ReportStatement("SELECT TO_CHAR(data_anuntare, 'MM'), SUM( ENC_MICI + ENC_MARI) FROM deranjamente", "GROUP BY TO_CHAR(data_anuntare, 'MM')")
                    .addOrSetFilter("TO_CHAR(data_anuntare, 'YYYY')","=", anSelectat);

            final String[] denumiri = new String[]{
                    "Consumatori casnici",
                    "Alti consumatori",
            };

            final double[][] totaluri = new double[denumiri.length][19];
            for (int i = 0; i < sucursale_sectii.length; i++) {
                final Category category = sucursale_sectii[i];
                final double[] totalCategory = new double[19];

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

                for (int j = 0; j < denumiri.length; j++) {
                    double valoareSemestriala = 0;
                    double valoareAnuala = 0;
                    double v1 = 0, v2 = 0, v3 = 0;

                    ReportStatement datas = null;
                    switch (j) {
                        case 0:
                            datas = raportConsumatoriCasnici;
                            break;
                        case 1:
                            datas = raportAltiConsumatori;
                            break;
                    }
                    final List matrix = datas.getListOfArrays("Get M"); %>
                    <tr>
                        <% if( j == 0){ %>
                            <td rowspan="<%=denumiri.length + 1%>" valign="middle"><b><%=columnTitle%> <%=category.getName()%></b></td>
                        <%}%>
                        <td><%=denumiri[j]%></td>
                        <td>kWh</td>
                        <% v1 = getValueByMonth(matrix, 1); %>
                        <% v2 = getValueByMonth(matrix, 2); %>
                        <% v3 = getValueByMonth(matrix, 3); %>
                        <% valoareSemestriala   += v1 + v2 + v3; %>
                        <td align="right"><%=formatValue( v1)%></td>
                        <td align="right"><%=formatValue( v2)%></td>
                        <td align="right"><%=formatValue( v3)%></td>
                        <td align="right"><%=formatValue( v1 + v2 + v3)%></td>
                        <% totaluri[j][0] += v1; totalCategory[0] += v1; %>
                        <% totaluri[j][1] += v2; totalCategory[1] += v2; %>
                        <% totaluri[j][2] += v3; totalCategory[2] += v3; %>
                        <% totaluri[j][3] += v1 + v2 + v3; totalCategory[3] += v1 + v2 + v3; %>


                        <% v1 = getValueByMonth(matrix, 4); %>
                        <% v2 = getValueByMonth(matrix, 5); %>
                        <% v3 = getValueByMonth(matrix, 6); %>
                        <% valoareSemestriala   += v1 + v2 + v3; %>
                        <td align="right"><%=formatValue( v1)%></td>
                        <td align="right"><%=formatValue( v2)%></td>
                        <td align="right"><%=formatValue( v3)%></td>
                        <td align="right"><%=formatValue( v1 + v2 + v3)%></td>
                        <td align="right"><%=formatValue( valoareSemestriala)%></td>
                        <% totaluri[j][4] += v1; totalCategory[4] += v1; %>
                        <% totaluri[j][5] += v2; totalCategory[5] += v2; %>
                        <% totaluri[j][6] += v3; totalCategory[6] += v3; %>
                        <% totaluri[j][7] += v1 + v2 + v3; totalCategory[7] += v1 + v2 + v3; %>
                        <% totaluri[j][8] += valoareSemestriala; totalCategory[8] += valoareSemestriala; %>

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

                        <% v1 = getValueByMonth(matrix, 7); %>
                        <% v2 = getValueByMonth(matrix, 8); %>
                        <% v3 = getValueByMonth(matrix, 9); %>
                        <% valoareSemestriala += v1 + v2 + v3; %>
                        <td align="right"><%=formatValue( v1)%></td>
                        <td align="right"><%=formatValue( v2)%></td>
                        <td align="right"><%=formatValue( v3)%></td>
                        <td align="right"><%=formatValue( v1 + v2 + v3)%></td>
                        <% totaluri[j][9]  +=v1; totalCategory[9]  += v1; %>
                        <% totaluri[j][10] +=v2; totalCategory[10] += v2; %>
                        <% totaluri[j][11] +=v3; totalCategory[11] += v3; %>
                        <% totaluri[j][12] +=v1 + v2 + v3; totalCategory[12] += v1 + v2 + v3; %>
            
                        <% v1 = getValueByMonth(matrix, 10); %>
                        <% v2 = getValueByMonth(matrix, 11); %>
                        <% v3 = getValueByMonth(matrix, 12); %>
                        <% valoareSemestriala += v1 + v2 + v3; %>
                        <% valoareAnuala += valoareSemestriala; %>
                        <td align="right"><%=formatValue( v1)%></td>
                        <td align="right"><%=formatValue( v2)%></td>
                        <td align="right"><%=formatValue( v3)%></td>
                        <td align="right"><%=formatValue( v1 + v2 + v3)%></td>
                        <td align="right"><%=formatValue( valoareSemestriala)%></td>
                        <td align="right"><%=formatValue( valoareAnuala)%></td>
                        <% totaluri[j][13] += v1; totalCategory[13] += v1; %>
                        <% totaluri[j][14] += v2; totalCategory[14] += v2; %>
                        <% totaluri[j][15] += v3; totalCategory[15] += v3; %>
                        <% totaluri[j][16] +=v1 + v2 + v3; totalCategory[16] += v1 + v2 + v3; %>
                        <% totaluri[j][17] +=valoareSemestriala; totalCategory[17] += valoareSemestriala; %>
                        <% totaluri[j][18] +=valoareAnuala; totalCategory[18] += valoareAnuala; %>
                    </tr>
            <%} %>
            <tr class="gsapthead">
                <td> <b>TOTAL</b></td>
                <td> kWh</td>
                <% for (int k = 0; k < totalCategory.length; k++) { %>
                    <td align="right"><%=formatValue( totalCategory[k])%></td>
                <%}%>
            </tr>
    <%}%>
    <tr class="gsapthead">
        <td rowspan="3"><b>TOTAL</b></td>
        <td><%=denumiri[0]%></td>
        <td>kWh</td>
        <% for (int i = 0; i < totaluri[0].length; i++) {
                final double value = totaluri[0][i];%>
                <td align="right"><%=formatValue( value)%></td>
        <% }%>
    </tr>
    <tr class="gsapthead">
        <td><%=denumiri[1]%></td>
        <td>kWh</td>
        <% for (int i = 0; i < totaluri[1].length; i++) {
                final double value = totaluri[1][i];%>
                <td align="right"><%=formatValue( value)%></td>
        <% }%>
    </tr>
    <tr class="gsapthead">
        <td><b>TOTAL</b></td>
        <td>kWh</td>
        <% for (int i = 0; i < totaluri[0].length; i++) {
                final double value = totaluri[0][i] + totaluri[1][i];%>
                <td align="right"><%=formatValue( value)%></td>
        <% }%>
    </tr>

</TABLE>

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

<%!
    public static double getValueByMonth(final List matrix, final int month){
        double result = 0;
        for (int i = 0; i < matrix.size(); i++) {
            final Object[] o = (Object[]) matrix.get(i);
            final int m = Integer.parseInt( o[0].toString());
            if( m == month){
                result = Double.parseDouble( o[1].toString());
                break;
            }
        }

        return result;
    }

    public static String formatValue( final double d){
        return AppConstants.format3(d);
    }
%>