<%@ page import="ro.emid.Application" %>
<%@ page import="ro.emid.common.constants.AppConstants" %>
<%@ page import="ro.emid.common.constants.RoleConstants" %>
<%@ page import="ro.emid.common.types.*" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.common.utils.StringUtils" %>
<%@ page import="ro.emid.common.utils.UserUtils" %>
<%@ page import="ro.emid.lpod.LpodSessionUtils" %>
<%@ page import="ro.emid.lpod.action.dispecer.EditEvenimentDispecerAction" %>
<%@ page import="ro.emid.lpod.db.CategoryODAccessDB" %>
<%@ page import="java.util.*" %>


<%@ taglib prefix="emid" tagdir="/WEB-INF/tags" %>

<%
    /**
     * @see ro.emid.lpod.action.reports.RaportInformareZilnicaODAction
     */

    final User user = LpodSessionUtils.getUserLogat(session);
    final CategoryOD filiala = LpodSessionUtils.OD.getFiliala(session);
    final CategoryOD sucursala = LpodSessionUtils.OD.getSucursala(session);
    final CategoryOD centruExploatare = LpodSessionUtils.OD.getCentru(session);

    request.setAttribute("ctx", AppConstants.APP_NAME);
%>

<emid:template-od title="Raport informare zilnica">
    <jsp:attribute name="breadcrumb">
        <emid:localizare-od>
            <span class="slash">/</span>
            <a class="link" href="${ctx}?action=rapoarte-od">Rapoarte</a> <span class="slash">/</span> Raport informare zilnică
        </emid:localizare-od>
    </jsp:attribute>
    <jsp:attribute name="body">
        <%
            if (user.getOdLevel() > RoleConstants.NIVEL_FILIALA && ((sucursala == null || sucursala.getId() <= 0) && (centruExploatare == null || centruExploatare.getId() <= 0))) { %>
              <br>
                Va rugam sa selectati un DED / DED-L din
                <a class="link" href="<%=AppConstants.APP_NAME%>?action=homeDispecer">pagina principala.</a>
              <br/>
            <br/>
        <%  return; } %>

        <%
            if (Application.runAsFiliala()) {
                if (filiala == null || filiala.getId() < 0) { %>
                <br/>
                    Va rugam sa selectati o filiala din <a class="link" href="<%=AppConstants.APP_NAME%>?action=home">pagina principala.</a>
                <br/>
                <br/> <%
                return;
            }

        } else if (Application.runAsAparatCentral()) {
            // do nothing yet
        }

        List result = (List) request.getAttribute("result");
        Boolean error = (Boolean) request.getAttribute("error");
        Long idLocatie = (Long) request.getAttribute("idLocatie");
        Date dataStart = (Date) request.getAttribute("dataStart");
        Date dataStop = (Date) request.getAttribute("dataStop");
        Integer dataRevenireSN = (Integer) request.getAttribute("dataRevenireSN");


        final boolean checkBifaDedl = (sucursala != null && sucursala.getId() > 0) && (centruExploatare == null || centruExploatare.getId() <= 0);

        boolean faraDEDL = false;

        if (checkBifaDedl) {
            faraDEDL = 1 == ObjectUtils.getIntValue(request.getParameter("fara_dedl"), 0);
        } else {
            faraDEDL = true;
        }

        final CategoryCheckData checkData = LpodSessionUtils.getCategoriiSelectate(session);
%>

<style type="text/css">
    .bordered td {
        border: 1px solid #999999;
        background-color: white;
    }

</style>

<table border=0>

<tr>
    <td align="center" style="font-weight:bold;">INFORMARE ZILNICĂ</td>
</tr>

<tr>
<td>
<form name="zaforma" action="<%=AppConstants.APP_NAME%>?action=raport-informare-zilnica-od" method="post"
      style="margin-top: 10px">
      <input type="hidden" name="toExport" id="toExport" value="0">

<table>
    <tr valign="top">
        <td align="left">

            <A href="#" title="Click pentru a selecta mai multe categorii" onClick="openCheckCategorii(); return false"
               class="link"><IMG
                    alt="Click pentru a selecta mai multe sucursale/C.E." border=0 width=12 height=13 hspace=3
                    src="<%= AppConstants.WEB_RESOURCE_PATH + "/images/icon_mini_search.gif" %>"></A>
            &nbsp;

            Data :
            <emid:datetimefield name="data_start" value="<%=dataStart%>" hourFirst="true"/>
            -
            <emid:datetimefield name="data_stop" value="<%=dataStop%>" hourFirst="true"/>

            &nbsp;&nbsp;
            Data revenire SN:
            <select name="dataRevenireSN" id="dataRevenireSN">
                <option value="-1"></option>
                <option value="1" <%=dataRevenireSN == 1 ? "selected" : ""%>>Completat</option>
                <option value="0" <%=dataRevenireSN == 0 ? "selected" : ""%>>Necompletat</option>
            </select>


            <% if (checkBifaDedl) { %>

            &nbsp;

            <input type="checkbox" name="fara_dedl" value="1" <%=faraDEDL ? "checked" : "" %> id="fara_dedl">
            <label for="fara_dedl">Fara DED-L subordonate</label>

            <% } %>

        </td>
        <td align="right">
            &nbsp;<input type="submit" value="Ruleaza raport"/>
            &nbsp;<input type="button" value="Export" onclick="doExport()"/>

            <script type="text/javascript">
                function doExport(){
                    document.zaforma.toExport.value = '1';
                    document.zaforma.submit();
                    setTimeout(function(){
                        document.zaforma.toExport.value = '0';
                    }, 300);
                }
            </script>
        </td>
    </tr
    <% if (error.booleanValue()){%>
    <tr>
       <td>
           <span id="spanMaxPeriod" style="color: red;">
              Va rugam selectati o perioada de maxim 90 de zile.
           </span>
       </td>
    </tr>
    <%}%>

    <% if (checkData.someDataChecked()) {
        final StringBuffer strCategorii = new StringBuffer("");
        final long[] idCentre = checkData.getIdCentre();
        final Set sucursaleSelectate = new HashSet();
        final Set filialeSelectate = new HashSet();
        for (int i = 0; i < idCentre.length; i++) {
            final long id = idCentre[i];
            final CategoryOD c = CategoryODAccessDB.getById(id);
            if (c != null) {
                final CategoryOD s = CategoryODAccessDB.getById(c.getIdParent());
                if (s != null) {
                    final CategoryOD f = CategoryODAccessDB.getById(s.getIdParent());
                    if (f != null) {
                        if (strCategorii.length() > 0) strCategorii.append("<br>");
                        strCategorii.append(f.getName()).append(", ").append(s.getName()).append(", ").append(c.getName());

                        sucursaleSelectate.add(new Long(s.getId()));
                        filialeSelectate.add(new Long(f.getId()));
                    }
                }
            }
        }

        final long[] idSucursale = checkData.getIdSucursale();
        for (int i = 0; i < idSucursale.length; i++) {
            final long id = idSucursale[i];
            if (!sucursaleSelectate.contains(new Long(id))) {
                final CategoryOD s = CategoryODAccessDB.getById(id);
                if (s != null) {
                    final CategoryOD f = CategoryODAccessDB.getById(s.getIdParent());
                    if (f != null) {
                        if (strCategorii.length() > 0) strCategorii.append("<br>");
                        strCategorii.append(f.getName()).append(", ").append(s.getName());
                    }
                }
            }
        }

        final long[] idFiliale = checkData.getIdFiliale();
        for (int i = 0; i < idFiliale.length; i++) {
            final long id = idFiliale[i];
            if (!filialeSelectate.contains(new Long(id))) {
                final CategoryOD f = CategoryODAccessDB.getById(id);
                if (f != null) {
                    if (strCategorii.length() > 0) strCategorii.append("<br>");
                    strCategorii.append(f.getName());
                }
            }
        }
    %>
    <%=strCategorii%>
    <% } %>

</table>

<table border="0" style="margin-top: 10px; font-size:12px" cellspacing="1" cellpadding="3">


    <% if (filiala.getId() == idLocatie.longValue()) { %>
    <tr class="bordered">
        <td colspan="20"><b><%=filiala.getName().toUpperCase()%>
        </b></td>
    </tr>
    <% } %>

    <%
        String currentSucursala = "";

        int startIndex = 0;
        if (filiala.getId() == idLocatie.longValue()) {
            startIndex = 1;
        }
    %>

    <% for (int i = startIndex; i < result.size(); i++) {
        final RaportOdRow row = (RaportOdRow) result.get(i);

        final boolean isEmptyRow = row.getIdEveniment() <= 0;

        if (!currentSucursala.equals(row.getLocatie())) {
            currentSucursala = row.getLocatie();
    %>

    <% if (i > startIndex) { %>
    <tr style="">
        <td colspan="20">&nbsp;</td>
    </tr>
    <% } %>
    <tr class="bordered">
        <td colspan="20">
            <b><%=row.getLocatie()%>
            </b>

            <% if (isEmptyRow) { %>
            - fara evenimente
            <% } %>
        </td>
    </tr>

    <tr align="center" class="bordered">
        <td>Data</td>
        <td>Ora</td>
        <td>Min</td>
        <td>Data revenire SN</td>
        <td>Tip locatie</td>
        <td>U<br>[kV]</td>
        <td width="150px">Denumire locatie</td>
        <td width="150px">Descriere eveniment</td>
        <td width="150px">Defect</td>
        <td width="150px">Semnalizari</td>
        <td>Pi<br/>[MW]</td>
        <td>Ore</td>
        <td>min</td>
        <td>Consumatori <br/> intrerupti</td>
        <td>Gestionar</td>
        <td width="150px">Observatii suplimentare</td>
    </tr>
    <% } %>

    <% if (isEmptyRow) { %>
    <tr class="bordered">
        <td colspan="20">
            <span>&nbsp;</span>
        </td>
    </tr>
    <% } else {%>
    <tr class="bordered" valign="top">
        <td align="center">
            <nobr><%=AppConstants.formatx(row.getDataEveniment())%>
            </nobr>
            <br/>
            <% if (AppConstants.runAtFiliala() && UserUtils.hasRoleUtilizatorOperatiuniDispecer(user)) {%>
            <a class="link" href="<%=EditEvenimentDispecerAction.buildUrl( row.getIdEveniment())%>">Edit</a>
            <% } else {%>
            <a class="link" href="#" onclick="print( <%=row.getIdEveniment()%>)">View</a>
            <% } %>
        </td>
        <td nowrap><%=AppConstants.formatOra(row.getDataEveniment())%>
        </td>
        <td nowrap><%=AppConstants.formatMinute(row.getDataEveniment())%>
        </td>
        <td nowrap><%=AppConstants.formatDataTime(row.getDataRevenireSN())%>
        </td>
        <td nowrap>
            <nobr><%=AppConstants.format(row.getTipLocatie(), "&nbsp;")%>
            </nobr>
            <% if (!StringUtils.isZeroLength(row.getTipLocatie2())) { %>
            <br/>
            <nobr><%=AppConstants.format(row.getTipLocatie2(), "&nbsp;")%>
            </nobr>
            <% } %>
        </td>
        <td nowrap align="center">
            <nobr><%=AppConstants.format(row.getU(), "&nbsp;")%>
            </nobr>
            <% if (!StringUtils.isZeroLength(row.getU2())) {%>
            <br/>
            <nobr><%=AppConstants.format(row.getU2(), "&nbsp;")%>
            </nobr>
            <% } %>
        </td>
        <td nowrap>
            <nobr><%=AppConstants.format(row.getDenLocatie(), "&nbsp;")%>
            </nobr>
            <% if (!StringUtils.isZeroLength(row.getDenLocatie2())) {%>
            <br/>
            <nobr><%=AppConstants.format(row.getDenLocatie2())%>
            </nobr>
            <% } %>
        </td>
        <td>
            <%=row.getDescriereEveniment()%>&nbsp;
        </td>
        <td>
            <%=StringUtils.replace(row.getDefect(), '\n', "<br/>")%>
        </td>
        <td>
            <%=StringUtils.replace(row.getSemnalizari(), '\n', "<br/>")%>
        </td>
        <td nowrap title="Puterea originala : <%=AppConstants.format( row.getPi())%>">&nbsp;
            <% final double pi = ObjectUtils.getDoubleValue(row.getPi(), 0) / 1000; %>
            <%=AppConstants.format2(pi)%>
        </td>
        <td nowrap align="center"><%=row.getDurataEveniment() / 60%>
        </td>
        <td nowrap align="center"><%=row.getDurataEveniment() % 60%>
        </td>
        <td nowrap align="center"><%=row.getConsumatori()%>
        </td>
        <td nowrap><%=AppConstants.format(row.getGestionar(), "&nbsp;")%>
        </td>
        <td>
            <%=StringUtils.replace(row.getObservatii(), '\n', "<br/>")%>
        </td>
    </tr>
    <% } %>
    <% } %>
</table>
</form>
</td>
</tr>


</table>

    </jsp:attribute>
</emid:template-od>

<script type="text/javascript">
    var printWindow = null;
    function print(id) {
        if (printWindow != null) printWindow.close();
        printWindow = window.open('<%=AppConstants.APP_NAME%>?action=view-eveniment&id=' + id);
    }

    function categoriesChecked() {
        document.zaforma.submit();
    }
</script>


