<%@ page import="ro.emid.callcenter.obj.Lucrare" %>
<%@ page import="ro.emid.callcenter.db.LucrareAccessDB" %>
<%@ page import="ro.emid.common.constants.GlobalAppConstants" %>
<%@ page import="ro.emid.common.types.Reclamatie" %>
<%@ page import="ro.emid.common.db.ReclamatieAccessDB" %>
<%@ page import="ro.emid.common.utils.ObjectUtils" %>
<%@ page import="ro.emid.callcenter.db.AdresaAccesDB" %>
<%@ page import="java.sql.Date" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="ro.emid.common.db.framework.Filter" %>
<%@ page import="ro.emid.common.db.framework.IFilter" %>
<%@ page import="ro.emid.common.constants.RoleConstants" %>
<%@ page import="ro.emid.common.types.Adresa" %>
<%@ page import="ro.emid.common.constants.AppConstants" %>
<%@ page import="ro.emid.common.utils.UserUtils" %>

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

<%
    String sortColumn = ObjectUtils.getStringValue(request.getParameter("sortColumn"));
    if (sortColumn == null || sortColumn.length() == 0) sortColumn = "ID";
    String sortType = ObjectUtils.getStringValue(request.getParameter("sortType"));
    if (sortType == null || sortType.length() == 0) sortType = "ASC";


    IFilter filter = (Filter)session.getAttribute("showLucrariArhivate.session.filter");
    if( filter == null){
        filter = new Filter();
        session.setAttribute("showLucrariArhivate.session.filter", filter);
    }

    //daca avem ceva parametri in request ii aplicam filtrului{
    Date dataStart = ObjectUtils.getDateValue( request.getParameter("dataStart"), AppConstants.FORMAT_DATA_TIME);
    Date dataStop  = ObjectUtils.getDateValue( request.getParameter("dataStop"), AppConstants.FORMAT_DATA_TIME);

    if( dataStart == null) dataStart = (Date) session.getAttribute("showLucrariArhivare.session.dataStart");
    if( dataStop  == null) dataStop  = (Date) session.getAttribute("showLucrariArhivare.session.dataStop");

    if( dataStart != null){
        filter.addOrSetCriteria("AND", "DATA_START", ">=", new Timestamp( dataStart.getTime()));
        session.setAttribute("showLucrariArhivare.session.dataStart", dataStart);
    }

    if( dataStop != null){
        filter.addOrSetCriteria("AND", "DATA_START", "<=", new Timestamp( dataStop.getTime()));
        session.setAttribute("showLucrariArhivare.session.dataStop", dataStart);
    }

    if (user.getIeLevel() == RoleConstants.NIVEL_FILIALA) {
        filter.addOrSetCriteria("AND", "FILIALA_ID", "=", new Long(filiala.getId()));
    } else if (user.getIeLevel() == RoleConstants.NIVEL_SUCURSALA) {
        filter.addOrSetCriteria("AND", "SUCURSALA_ID", "=", new Long(sucursala.getId()));
    } else if (user.getIeLevel() == RoleConstants.NIVEL_CENTRU) {
        filter.addOrSetCriteria("AND", "SECTIE_ID", "=", new Long(centruExploatare.getId()));
    }

    //}

    //for pagination{
    if (!"lucrariProgramateArhivate".equals(CallcenterSessionUtils.getPaginationJsp( session))) {
        CallcenterSessionUtils.resetPaginationData(session, "lucrariProgramateArhivate");
    }

    long nrLines = ObjectUtils.getLongValue(request.getParameter("nrLines"), -1);
    if (nrLines == -1) nrLines = CallcenterSessionUtils.getNrLines( session);

    long currentBeginIndex = ObjectUtils.getLongValue(request.getParameter("currentBeginIndex"), -1);
    if (currentBeginIndex == -1) currentBeginIndex = CallcenterSessionUtils.getBeginIndex( session);

    final long nrLinesTotal = LucrareAccessDB.getCountLucrariArhivate( filter);
    final String direction = ObjectUtils.getStringValue(request.getParameter("direction"));
    if ("backward".equals(direction)) {
        currentBeginIndex -= nrLines;
    } else if ("forward".equals(direction)) {
        currentBeginIndex += nrLines;
    } else if( "first".equals( direction)){
        currentBeginIndex = 1;
    } else if( "last".equals( direction)){
        currentBeginIndex =  nrLines * nrLinesTotal/nrLines + 1;
    }


    if (currentBeginIndex > nrLinesTotal && nrLinesTotal > 1)
        currentBeginIndex -= nrLines; //cazul cind se sterge ultimul element de pe ultima pagina si este singurul pe pagina
    if (currentBeginIndex < 1) currentBeginIndex = 1;

    CallcenterSessionUtils.setNrLines(session, nrLines);
    CallcenterSessionUtils.setBeginIndex(session, currentBeginIndex);
    //}for pagination
    

    final Lucrare[] lucrariArhivate = LucrareAccessDB.getAllArhivate( filter, sortColumn, sortType, currentBeginIndex, currentBeginIndex + nrLines - 1);
    final int nrLinesSelected = lucrariArhivate.length;
%>


<%@ include file="../layout/messages.jspf"%>

<form action="<%=GlobalAppConstants.APP_NAME%>" method="post">
    <input type="hidden" name="action" value="showLucrariArhivate"/>
    <input type="hidden" name="apllyNewFilter" value="true"/>

     Data start: <input type="text" class="gsapinputtext" name="dataStart" id="data_start" value="<%=AppConstants.formatx( dataStart)%>" /><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" class="gsapinputtext" name="dataStop"  id="data_stop"  value="<%=AppConstants.formatx( dataStop)%>" /><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" />
</form>


<table width="100%" border=0 cellspacing="0" cellpadding="0">
<tr>
<td>
<TABLE id="lucrariArhivate" border=0 cellPadding=2 cellSpacing=1 width="100%" class="gSAPTHEAD" style="BACKGROUND-COLOR: white;">
<TR noSelect="true">
    <th class="gsapthead" width="40" nowrap>
        <a style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;" href="#" onclick="sort('ID', '<%=(sortType.equals("ASC") ? "DESC" : "ASC")%>')">Nr.</a> <% if(sortColumn.equals("ID")) if( sortType.equals("ASC")){%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_up_1.gif" border=0> <%}else{%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_dn_1.gif" border=0> <%}%>
    </th>
    <th class="gsapthead"  nowrap>
        <a style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;" href="#" onclick="sort('NUME', '<%=(sortType.equals("ASC") ? "DESC" : "ASC")%>')">Nume:</a> <% if(sortColumn.equals("NUME")) if( sortType.equals("ASC")){%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_up_1.gif" border=0> <%}else{%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_dn_1.gif" border=0> <%}%>
    </th>
    <TH class="gsapthead" height=25 noWrap width="300">Adresa:</TH>
    <TH class="gsapthead" noWrap >Descriere:</TH>
    <TH class="gsapthead" noWrap >
        <a style="COLOR: #000000; FONT-SIZE: 13px; text-decoration: none;" href="#" onclick="sort('DATA_START', '<%=(sortType.equals("ASC") ? "DESC" : "ASC")%>')">Data start:</a> <% if(sortColumn.equals("DATA_START")) if( sortType.equals("ASC")){%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_up_1.gif" border=0> <%}else{%> <img src="<%=AppConstants.WEB_RESOURCE_PATH%>/images/sort_dn_1.gif" border=0> <%}%>
    </TH>
    <TH class="gsapthead" noWrap >Durata:<br><span style="font-size:10px">(ore)</span></TH>
    <% if( UserUtils.hasRoleAdminCallcenter(user) || UserUtils.hasCcRightEditareLucrariProgramate(user)){%>
    <TH class="gsapthead" noWrap width="1%">Operatii:</TH>
    <% }%>
</TR>
<%if( lucrariArhivate.length == 0){%>
<tr noSelect="true">
    <td colspan="5">Nu exista informatii...</td>
</tr>
<%} else for (int i = 0; i < lucrariArhivate.length; i++) {
    final Lucrare lucrare = lucrariArhivate[i];
    lucrare.setAdrese(AdresaAccesDB.getAdreseLucrare( lucrare.getId()));
    final Reclamatie[] reclamatii = ReclamatieAccessDB.getAll(" AND OBJECT_TYPE =" + Reclamatie.LEGAT_LA_LUCRARE + " AND LEGAT_OBJECT_ID = " + lucrare.getId(), "DATA", "ASC");

    final StringBuffer adresa = new StringBuffer();
    for (int j = 0; j < lucrare.getAdrese().length; j++) {
        final Adresa adresaLucrare = lucrare.getAdrese()[j];
        adresa
                .append("<label title='Judet'>").append(ro.emid.common.utils.StringUtils.isZeroLength( adresaLucrare.getJudet()) ? "" : "j." + adresaLucrare.getJudet() + ", ").append("</label>")
                .append(" <label title='Municipiu/Comuna'>").append( adresaLucrare.getLocalitate()).append("</label>")
                .append(", <label title='Localitate/Sat'>").append(ro.emid.common.utils.StringUtils.isZeroLength( adresaLucrare.getLocalitate2()) ? "" : adresaLucrare.getLocalitate2()).append("</label>")
                .append(", ").append(adresaLucrare.getTipArtera())
                .append(' ').append(adresaLucrare.getDenStrada())
                .append(adresaLucrare.getNr() != null ? ", Nr. " + ObjectUtils.getStringValue(adresaLucrare.getNr()) : "")
                .append(adresaLucrare.getBloc() != null ? ", Bl. " + ObjectUtils.getStringValue(adresaLucrare.getBloc()) : "")
                .append("<br>");
    }
%>

<tr valign="top">
    <td align="left" <%if(sortColumn.equals("ID")){%> class="sortColumn"<%}%>>
        &nbsp;<%=lucrare.getId()%>
        <img style="cursor:pointer; <% if(reclamatii.length == 0){%> visibility: hidden;<%}%>" id="img<%=i%>" src="<%=AppConstants.WEB_RESOURCE_PATH + "/images/plus.bmp"%>" border="0" alt="Click pentru a vizualiza reclamatiile" onclick="toggleReclamatii(<%=i%>)">&nbsp;
    </td>
    <td <%if(sortColumn.equals("NUME")){%> class="sortColumn"<%}%>>
        <%=AppConstants.format(lucrare.getNume())%>
    </td>
    <td <%if(sortColumn.equals("ADRESA")){%> class="sortColumn" <%}%>>
        <%=adresa%>
    </td>
    <td >
        <%=AppConstants.format(lucrare.getDescriere())%>
    </td>
    <td align="center" <%if(sortColumn.equals("DATA_START")){%> class="sortColumn" <%}%>>
        <%=AppConstants.format(lucrare.getDataStart())%>
    </td>
    <td align="center">
        <%=AppConstants.format(lucrare.getDurata())%>
    </td>
    <% if( UserUtils.hasRoleAdminCallcenter(user) || UserUtils.hasCcRightEditareLucrariProgramate(user)){%>
    <td nowrap>
        <%--<a class="link" title="Editeaza Lucrare" href="<%=GlobalAppConstants.APP_NAME%>?action=editLucrare&id=<%=lucrare.getId()%>">Edit</a>--%>
        <%--<% if( reclamatii.length == 0){ %>--%>
        <%--<a title="Sterge Lucrare" class="link" href="<%=GlobalAppConstants.APP_NAME%>?action=deleteLucrare&id=<%=lucrare.getId()%>" onclick="return confirm('Sugur ?')">Delete</a>--%>
        <%--<%}%>--%>
        <%--<a class="link" title="Arhiveaza Lucrare" href="<%=GlobalAppConstants.APP_NAME%>?action=arhivareLucrare&id=<%=lucrare.getId()%>" onclick="return confirm('Sugur ?')">Arhivare</a>--%>
    </td>
    <% }%>
</tr>
<tr id="reclamatii<%=i%>" style="display: none;" noSelect="true">
    <td colspan="7" nowrap>
        <table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td width="1%">&nbsp;&nbsp;&nbsp;</td>
                <td>
                    <table class="gsapthead" width="100%" cellpadding="0" cellspacing="1" id="tablereclamatii<%=i%>">
                        <%if( reclamatii.length == 0 ){%>
                        <tr><td> Nu sunt reclamatii atasate ...</td></tr>
                        <%} else{%>
                        <%for (int j = 0; j < reclamatii.length; j++) {
                            final Reclamatie reclamatie = reclamatii[j];%>
                        <tr ondblclick="showDateReclamatie(<%=reclamatie.getId()%>)">
                            <td>
                                <label><%=reclamatie.getTitlu()%></label>
                            </td>
                            <td width="1%" nowrap>

                            </td>
                        </tr>
                        <%}%>
                        <%}%>
                    </table>
                </td>
            </tr>
        </table>
    </td>
</tr>

<script type="text/javascript">
    var table<%=i%> = new Table('tablereclamatii<%=i%>', "table<%=i%>");
    table<%=i%>.setSelectedClassName('checked');
</script>
<%}%>
    <tr class="paginationRow" noSelect="true">
                    <td colspan="8" >
                        <table width="100%" cellspacing="0" cellpadding="0">
                            <tr noSelect="true">
                                <td align="right">
                                    <form action="<%=GlobalAppConstants.APP_NAME%>" method="post">
                                        <input type="hidden" name="action" value="showLucrariArhivate">
                                        <input type="hidden" name="currentBeginIndex" value="<%=currentBeginIndex%>">
                                        <input type="hidden" name="direction" value="">
                                        <input type="hidden" name="sortColumn" value="<%=sortColumn%>">
                                        <input type="hidden" name="sortType" value="<%=sortType%>">
                                        Nr. linii:
                                        <select name="nrLines" onchange="this.form.submit()" style="font-size: 10px">
                                            <option value="10"  <%=nrLines == 10 ? "selected" : ""%> >10</option>
                                            <option value="15"  <%=nrLines == 15 ? "selected" : ""%> >15</option>
                                            <option value="20"  <%=nrLines == 20 ? "selected" : ""%> >20</option>
                                            <option value="30"  <%=nrLines == 30 ? "selected" : ""%> >30</option>
                                            <option value="40"  <%=nrLines == 40 ? "selected" : ""%> >40</option>
                                            <option value="50"  <%=nrLines == 50 ? "selected" : ""%> >50</option>
                                        </select>&nbsp;&nbsp;
                                        <%=currentBeginIndex%> - <%=currentBeginIndex + nrLinesSelected - 1%> din <%=nrLinesTotal%>&nbsp;&nbsp;&nbsp;
                                        <input <%=currentBeginIndex == 1 ? "disabled" : ""%>  title="Primele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='first'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&lt&lt" />
                                        <input <%=currentBeginIndex == 1 ? "disabled" : ""%>  title="Precedentele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='backward'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&lt" />
                                        <input <%=currentBeginIndex + nrLinesSelected - 1 >= nrLinesTotal ? "disabled" : ""%> title="Urmatoarele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='forward'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&gt" />
                                        <input <%=currentBeginIndex + nrLinesSelected - 1 >= nrLinesTotal ? "disabled" : ""%> title="Ultimele <%=nrLines%> linii" type="button" onclick="this.form.direction.value='last'; this.form.submit()" style="font-size: 8px; cursor: pointer" value="&gt&gt" />
                                    </form>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
</TABLE>
</td>
</tr>
</table>

<script type="text/javascript">
    function toggleReclamatii(index){
        if( $('reclamatii' + index).style.display == 'none'){
            $('img' +index).src = '<%=AppConstants.WEB_RESOURCE_PATH + "/images/minus.bmp"%>';
            Element.show('reclamatii' + index);
        }else{
            $('img' +index).src = '<%=AppConstants.WEB_RESOURCE_PATH + "/images/plus.bmp"%>';
            Element.hide('reclamatii' + index);
        }
    }

    function sort( column, type){
        window.location = "<%=GlobalAppConstants.APP_NAME%>?action=showLucrariArhivate&sortColumn="+column+"&sortType="+type;
    }


    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
    }
  );

    

    var tableLucrariArhivate = new Table('lucrariArhivate', "tableLucrariArhivate");
</script>