<%@ page import="ro.emid.common.types.Category" %>
<%@ page import="ro.emid.common.db.CategoryAccessDB" %>
<%@ page import="ro.emid.common.db.framework.ReportStatement" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.common.types.Deranjament" %>
<%@ page import="java.util.List" %>
<%@ page import="java.sql.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="java.io.File" %>
<%@ page import="ro.emid.common.utils.*" %>
<%@ page import="ro.emid.callcenter.CallcenterSessionUtils" %>
<%@ page import="ro.emid.common.constants.*" %>

<%!
    private static final java.text.SimpleDateFormat _df = new java.text.SimpleDateFormat("yyyyMMdd");
%>

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

    Date dataStart = ObjectUtils.getDateValue(request.getParameter("data_start"), AppConstants.FORMAT_DATA_TIME);
    Date dataStop = ObjectUtils.getDateValue(request.getParameter("data_stop"), AppConstants.FORMAT_DATA_TIME);

    final Calendar c = Calendar.getInstance();
    c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 7, 0, 0);
    if (dataStart == null) dataStart = new Date(c.getTime().getTime());

    if (dataStop == null) {
        c.add(Calendar.DATE, 1);
        dataStop = new Date(c.getTime().getTime());
    }

    final String value_data_start = AppConstants.formatx(dataStart);
    final String value_data_stop = AppConstants.formatx(dataStop);

    final Timestamp dataStartx = new Timestamp(dataStart.getTime());
    final Timestamp dataStopx = new Timestamp(dataStop.getTime());


    final ReportStatement countDeranjamente = new ReportStatement("SELECT /*+ INDEX(DERANJAMENTE  EMID_SHOW_DERANJAMENTE) */ COUNT(*) FROM deranjamente")
            .addStringCriteria("AND CAT_INSTALATII IN (" + Deranjament.INDEX_PA + ", " + Deranjament.INDEX_PT + ')')
            .addOrSetFilter("DATA_ANUNTARE", ">=", dataStartx)
            .addOrSetFilter("DATA_ANUNTARE", "<=", dataStopx);


    final ReportStatement countDeranjamenteByCategorie = new ReportStatement("SELECT /*+ INDEX(DERANJAMENTE  EMID_SHOW_DERANJAMENTE) */ COUNT(*) FROM deranjamente")
            .addOrSetFilter("DATA_ANUNTARE", ">=", dataStartx)
            .addOrSetFilter("DATA_ANUNTARE", "<=", dataStopx);

    final ReportStatement countDeranjamente2 = new ReportStatement(
            "SELECT /*+ INDEX(DERANJAMENTE  EMID_SHOW_DERANJAMENTE) */ CAT_INSTALATII, EL_DEFECT, COUNT(*) FROM deranjamente",
            "GROUP BY CAT_INSTALATII, EL_DEFECT ORDER BY CAT_INSTALATII ASC, EL_DEFECT ASC"
    ).addOrSetFilter("DATA_ANUNTARE", ">=", dataStartx)
            .addOrSetFilter("DATA_ANUNTARE", "<=", dataStopx);


    if (centruRaport.getId() > 0) {
        countDeranjamente.addOrSetFilter("SECTIE_ID", "=", new Long(centruRaport.getId()));
        countDeranjamente2.addOrSetFilter("SECTIE_ID", "=", new Long(centruRaport.getId()));
        countDeranjamenteByCategorie.addOrSetFilter("SECTIE_ID", "=", new Long(centruRaport.getId()));
    } else if (sucursalaRaport.getId() > 0) {
        countDeranjamente.addOrSetFilter("SUCURSALA_ID", "=", new Long(sucursalaRaport.getId()));
        countDeranjamente2.addOrSetFilter("SUCURSALA_ID", "=", new Long(sucursalaRaport.getId()));
        countDeranjamenteByCategorie.addOrSetFilter("SUCURSALA_ID", "=", new Long(sucursalaRaport.getId()));
    } else if (filialaRaport.getId() > 0) {
        countDeranjamente.addOrSetFilter("FILIALA_ID", "=", new Long(filialaRaport.getId()));
        countDeranjamente2.addOrSetFilter("FILIALA_ID", "=", new Long(filialaRaport.getId()));
        countDeranjamenteByCategorie.addOrSetFilter("FILIALA_ID", "=", new Long(filialaRaport.getId()));
    }

    String publicPath = null;
    if (ObjectUtils.getIntValue(request.getParameter("toExport"), 0) == 1) {
        final String root = AppConstants.PUBLIC_RESOURCE_PATH + File.separator + "raport";

        final String folder = _df.format(new java.util.Date());
        //cleanup...
        final File[] folders = new File(root).listFiles();
        if (folders != null) for (int i = 0; i < folders.length; i++) {
            final File file = folders[i];
            if (!file.getName().equals(folder)) {
                final File[] d = file.listFiles();
                if (d != null) for (int j = 0; j < d.length; j++) {
                    final File file1 = d[j];
                    file1.delete();
                }
                file.delete();  //cleanup
            }
        }

        File f = new File(root, folder);
        if (!f.exists()) f.mkdir();

        final String strDataStart = AppConstants.format(dataStart);
        final String strDataStop = AppConstants.format(dataStop);

        final String fileName = "Raport Evenimente Cauze " + strDataStart + " - " + strDataStop + '_' + System.currentTimeMillis() + ".xls";
        final String privatePath = root + File.separator + folder + File.separator + fileName;

        publicPath = AppConstants.WEB_RESOURCE_PATH + "/raport/" + folder + '/' + fileName;

        f = new File(privatePath);
        if (f.exists()) {
            f.delete();
        }

        final String templatePath = GlobalAppConstants.PRIVATE_PATH + File.separator + "template" + File.separator + "Raport Evenimente Cauze.xls";

        final RaportEvenimenteCauzeExcelExporter exporter = new RaportEvenimenteCauzeExcelExporter();
        exporter.begin(templatePath, privatePath);

        final List rowss = countDeranjamente2.getListOfArrays("Get Grupe Categorii Instalatii");

        exporter.export(filialaId, sucursalaId, centruId, rowss, dataStartx, dataStopx);

        exporter.end();
    }
%>

<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 evenimente cauze
            </span>
        </TD>
    </TR>
</TABLE>

<table>
<tr>
<td>
<center>
    <br/>
    <span style="font-size: 14px">Raport Evenimente cauze</span>
</center>
<div class="spacer"></div>
<table class="gsaptd" width="100%">
    <tr>
        <td>
            <form name="zaforma" action="<%=AppConstants.APP_NAME%>?action=raport-evenimente-cauze" method="post">
                <input type="hidden" name="toExport" value="0">
                Filiala:
                <SELECT name="filiala" onchange="fill_sucursala_select()"
                        class="gSAPSelect" <%=user.getIeLevel() == ro.emid.common.constants.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;<input type="text" id="data_start" name="data_start" size="14"
                                   value="<%=value_data_start%>"/> <a href="#" id="trigger_data_start"><img
                    src="<%=AppConstants.WEB_RESOURCE_PATH + "/images/cal.gif"%>" width="16" height="16" border="0"
                    alt="Apasa pt. a selecta data."></a> -
                <input type="text" id="data_stop" name="data_stop" size="14" value="<%=value_data_stop%>"/> <a href="#"
                                                                                                               id="trigger_data_stop"><img
                    src="<%=AppConstants.WEB_RESOURCE_PATH + "/images/cal.gif"%>" width="16" height="16" border="0"
                    alt="Apasa pt. a selecta data."></a>
                <input type="submit" value="Aplica">
                &nbsp;<input type="button" value="Export"
                             onclick="document.zaforma.toExport.value = '1'; document.zaforma.submit();"/>
            </form>
        </td>
    </tr>
</table>
<div class="spacer"></div>

<% long totalDeranjamente = 0; %>
<% long currentValue = 0; %>
<TABLE id="table" border=1 cellPadding=3 cellSpacing=1 width="100%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white">
    <col>
    <col>
    <col style="padding-right: 10px">
    <col style="padding-right: 10px; padding-left: 10px">
    <tr>
        <td rowspan="16">PA sau PT</td>
        <td rowspan="5">Elementul</td>
        <td>Intreruptor JT</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("EL_DEFECT", "=", new Integer(Deranjament.INDEX_INTRERUPTOARE_JT)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Tablouri de JT</td>
        <td>
            <%
                currentValue = countDeranjamente.addOrSetFilter("EL_DEFECT", "=", new Integer(Deranjament.INDEX_TABLOU_JT)).getLongResult();
                currentValue += countDeranjamente.addOrSetFilter("EL_DEFECT", "=", new Integer(Deranjament.INDEX_TABLOU_JT_ILUMINAT_PUBLIC)).getLongResult();
            %>
            <%=currentValue%>
            <% totalDeranjamente += currentValue; %>
        </td>
    </tr>
    <tr>
        <td>Circuite de JT</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("EL_DEFECT", "=", new Integer(Deranjament.INDEX_CIRCUITE_DE_JT)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Siguranta MT/(declansare) de I de MT [Neselectivitate]</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("EL_DEFECT", "=", new Integer(Deranjament.INDEX_SIGURANTE_MT)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td align="right"><b>TOTAL:</b></td>
        <td><%=totalDeranjamente%>
        </td>
    </tr>

    <%
        countDeranjamente.removeFilter("EL_DEFECT");
        totalDeranjamente = 0;
    %>
    <tr>
        <td rowspan="11">Cauza</td>
        <td>Suprasarcina electrica</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("CAUZA", "=", new Integer(Deranjament.INDEX_CAUZA_SUPRASARCINA_ELECTRICA)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Depasirea conditiilor de dimensionare dpdv mecanic</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("CAUZA", "=", new Integer(Deranjament.INDEX_CAUZA_UZURA)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Neselectivitate</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("CAUZA", "=", new Integer(Deranjament.INDEX_CAUZA_NESELECTIVITATE)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Inreruperea unei faze</td>
        <td></td>
    </tr>
    <tr>
        <td>Intrerupere nul</td>
        <td></td>
    </tr>
    <tr>
        <td>Contact necorespunzator</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("CAUZA", "=", new Integer(Deranjament.INDEX_CAUZA_CONTACT_NECORESPUNZATOR)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Inundarea instalatiilor</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("CAUZA", "=", new Integer(Deranjament.INDEX_CAUZA_INUNDAREA_INSTALATIILOR)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Actiuni ale unor persoane straine</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("CAUZA", "=", new Integer(Deranjament.INDEX_CAUZA_ACTIUNI_STRAINI)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Actiuni ale pasarilor sau animalelor mici</td>
        <td><%=currentValue = countDeranjamente.addOrSetFilter("CAUZA", "=", new Integer(Deranjament.INDEX_CAUZA_ACTIUNI_PASARI_ANIMALE)).getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td>Altele</td>
        <%
            countDeranjamente.removeFilter("CAUZA");
            countDeranjamente.addStringCriteria(" AND CAUZA NOT IN(" +
                    Deranjament.INDEX_CAUZA_SUPRASARCINA_ELECTRICA + ',' +
                    Deranjament.INDEX_CAUZA_UZURA + ',' +
                    Deranjament.INDEX_CAUZA_NESELECTIVITATE + ',' +
                    Deranjament.INDEX_CAUZA_CONTACT_NECORESPUNZATOR + ',' +
                    Deranjament.INDEX_CAUZA_INUNDAREA_INSTALATIILOR + ',' +
                    Deranjament.INDEX_CAUZA_ACTIUNI_STRAINI + ',' +
                    Deranjament.INDEX_CAUZA_ACTIUNI_PASARI_ANIMALE + ')'
            );
        %>

        <td><%=currentValue = countDeranjamente.getLongResult()%>
        </td>
        <% totalDeranjamente += currentValue; %>
    </tr>
    <tr>
        <td align="right"><b>TOTAL:</b></td>
        <td><%=totalDeranjamente%>
        </td>
    </tr>
</TABLE>


<%
    long total = 0;

%>

<br>
<TABLE id="table2" border=1 cellPadding=3 cellSpacing=1 width="100%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white">
    <col>
    <col>
    <col align="right">
    <TR noSelect="true">
        <TH class="gsapthead" noWrap>Cat. instalatii</TH>
        <TH class="gsapthead" noWrap>Elementul</TH>
        <TH class="gsapthead" noWrap>Nr. deranjamente</TH>
    </TR>
    <%
        final List matrix = countDeranjamente2.getListOfArrays("Get Grupe Categorii Instalatii");
        if (matrix == null || matrix.size() == 0) {
    %>
    <tr noSelect="true">
        <td>Nu exista informatii...</td>
    </tr>
    <%
    } else {
        String currentCategory = "nedefinit";
        for (int i = 0; i < matrix.size(); i++) {
            final Object[] arr = (Object[]) matrix.get(i);
            final int indexCategoriaInstalatii = Integer.parseInt(arr[0].toString());
            final int indexElementulDefect = Integer.parseInt(arr[1].toString());
            final int count = Integer.parseInt(arr[2].toString());

            total += count;
            String strCatInstalatii = "unknown";
            String strElementulDefect = "unknown";

            if (indexCategoriaInstalatii == -1) {
                strCatInstalatii = "neselectata";
                strElementulDefect = "neselectat";
            } else if (indexCategoriaInstalatii >= 0 && indexCategoriaInstalatii < DeranjamentConstants.ARR_CAT_INSTALATII.length) {
                strCatInstalatii = DeranjamentConstants.ARR_CAT_INSTALATII[indexCategoriaInstalatii];

                if (indexElementulDefect == -1) {
                    strElementulDefect = "neselectat";
                } else if (indexCategoriaInstalatii < DeranjamentConstants.ARR_ELEMENTE_DEFECTE.length &&
                        indexElementulDefect >= 0 && indexElementulDefect < DeranjamentConstants.ARR_ELEMENTE_DEFECTE[indexCategoriaInstalatii].length) {
                    strElementulDefect = DeranjamentConstants.ARR_ELEMENTE_DEFECTE[indexCategoriaInstalatii][indexElementulDefect];
                }
            }

            if (!currentCategory.equalsIgnoreCase(strCatInstalatii)) {
                currentCategory = strCatInstalatii;
    %>
    <tr style="font-weight: bold">
        <td><%=currentCategory%>
        </td>
        <td>&nbsp;</td>
        <td><%=countDeranjamenteByCategorie.addOrSetFilter("CAT_INSTALATII", "=", new Integer(indexCategoriaInstalatii)).getLongResult()%>
        </td>
    </tr>
    <%}%>
    <tr>
        <td>&nbsp;</td>
        <td><%=strElementulDefect%>
        </td>
        <td><%=count%>
        </td>
    </tr>
    <%}%>
    <tr style="font-weight: bold">
        <td colspan="2" align="right">TOTAL:</td>
        <td><%=total%>
        </td>
    </tr>
    <%}%>
</TABLE>

</td>
</tr>
</table>

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

<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>

<script type="text/javascript">
    Calendar.setup(
            {
                inputField  : "data_start",         // ID of the input field
                ifFormat    : "%d.%m.%Y %H:%M",    // the date format
                button      : "trigger_data_start"       // ID of the button
            }
    );

    Calendar.setup(
            {
                inputField  : "data_stop",         // ID of the input field
                ifFormat    : "%d.%m.%Y %H:%M",    // the date format
                button      : "trigger_data_stop"       // ID of the button
            }
    );
</script>

<script type="text/javascript">
    <% if ( publicPath != null){ %>

    setTimeout(function() {
        window.location = '<%=publicPath%>';
    }, 500);

    <% } %>
</script>