<%@ 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="java.util.List" %>
<%@ page import="java.util.Calendar" %>
<%@ page import="java.sql.Date" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="ro.emid.common.types.Reclamatie" %>
<%@ page import="ro.emid.common.utils.*" %>
<%@ page import="ro.emid.callcenter.CallcenterSessionUtils" %>
<%@ page import="ro.emid.common.constants.*" %>
<%@ page import="ro.emid.common.types.User" %>
<%@ taglib prefix="emid" tagdir="/WEB-INF/tags" %>
<%
    final User user = SessionUtils.getUserLogat(session);
    final Category filiala = CallcenterSessionUtils.getFiliala(session);
    final long filialaId = CallcenterSessionUtils.getFilialaId(session);
    final long sucursalaId = CallcenterSessionUtils.getSucursalaId(session);
    final long centruId = CallcenterSessionUtils.getCentruId(session);

    long _zonaSelectata = ObjectUtils.getLongValue(request.getParameter("zonaSelectata"), -1);

    if( _zonaSelectata == -1){
        if( centruId > 0) _zonaSelectata = centruId;
        else if( sucursalaId > 0) _zonaSelectata = sucursalaId;
        else if( filialaId > 0) _zonaSelectata = filialaId;
    }


    Category zonaSelectata = null;
    if( _zonaSelectata > 0){
        zonaSelectata = CategoryAccessDB.getById( _zonaSelectata);
    }

    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 String localitate = ObjectUtils.getStringValue(request.getParameter(ReclamatieConstants.MUNICIPIU));
    final String reclamant = ObjectUtils.getStringValue(request.getParameter(ReclamatieConstants.NUME_CLIENT));

    final long objectType = ObjectUtils.getIntValue( request.getParameter(ReclamatieConstants.OBJECT_TYPE));
    final String objectId = ObjectUtils.getStringValue(request.getParameter(ReclamatieConstants.OBJECT_ID));

    FSC fscRaport = FSCUtils.getFsc(request);


    final StringBuffer buffer = new StringBuffer();
    buffer.append("SELECT * FROM (").append(
            " SELECT r.ID, c1.NAME AS SDEE, c2.NAME AS CE, TO_CHAR(r.DATA, 'DD.MM.YYYY HH24:MI'), r.NUME_CLIENT, r.LOCALITATE, r.TIP_ARTERA, r.STRADA, 'nr:'||r.NR||' bl:'||r.BLOC||' sc:'||r.SCARA||' ap:'||r.AP, " ).append(
            "r.FIX||' '||r.mobil, " ).append(
            "r.CONTINUT_SESIZARE1, r.CONTINUT_SESIZARE2, r.ALTA_SESIZARE, " ).append(
            "CASE " ).append(
            "   WHEN r.OBJECT_TYPE = " ).append( Reclamatie.LEGAT_LA_LUCRARE ).append( " THEN 'Lucrare ' " ).append(
            "   WHEN r.OBJECT_TYPE = " ).append( Reclamatie.LEGAT_LA_LUCRARE2 ).append( " THEN 'Lucrare '||lp2.NUMAR " ).append(
            "   WHEN r.OBJECT_TYPE = " ).append( Reclamatie.LEGAT_LA_DERANJAMENT ).append( " THEN 'Deranjament '||d.NUMAR " ).append(
            "   WHEN r.OBJECT_TYPE = " ).append( Reclamatie.LEGAT_LA_INCIDENT ).append( " THEN 'Incident '||li.ID " ).append(
            "ELSE '-' END " ).append(
            " FROM reclamatii r" ).append(
            "       LEFT JOIN deranjamente d ON (d.ID = r.LEGAT_OBJECT_ID) " ).append(
            "       LEFT JOIN LittleIncidente li ON (li.ID = r.LEGAT_OBJECT_ID) " ).append(
            "       LEFT JOIN LPD_LUCRARE_PROGRAMATA lp2 ON (lp2.ID = r.LEGAT_OBJECT_ID) " ).append(
            "       LEFT JOIN CATEGORIES c1 ON (c1.ID = r.ID_SUCURSALAR) " ).append(
            "       LEFT JOIN CATEGORIES C2 ON (c2.ID = r.ID_CENTRUR) " ).append(
            " WHERE 0=0 {filters} " ).append(
            " ORDER BY r.CONTINUT_SESIZARE1, r.CONTINUT_SESIZARE2, r.DATA ASC" ).append(
            " )t WHERE ROWNUM <= 1000 ");

    final ReportStatement raportReclamatii = new ReportStatement(
        buffer.toString()
    );

    buffer.delete(0, buffer.length());
    buffer.append(" SELECT r.ID, TO_CHAR(r.DATA, 'DD.MM.YYYY HH24:MI'), r.NUME_CLIENT, r.LOCALITATE, r.TIP_ARTERA, r.STRADA, 'nr:'||r.NR||' bl:'||r.BLOC||' sc:'||r.SCARA||' ap:'||r.AP, ").append(
            "r.FIX||' '||r.mobil, " ).append(
            "r.CONTINUT_SESIZARE1, r.CONTINUT_SESIZARE2, r.ALTA_SESIZARE, " ).append(
            "CASE " ).append(
            "  WHEN r.OBJECT_TYPE = " ).append( Reclamatie.LEGAT_LA_LUCRARE ).append( " THEN 'Lucrare ' " ).append(
            "  WHEN r.OBJECT_TYPE = " ).append( Reclamatie.LEGAT_LA_LUCRARE2 ).append( " THEN 'Lucrare '||lp2.NUMAR " ).append(
            "  WHEN r.OBJECT_TYPE = " ).append( Reclamatie.LEGAT_LA_DERANJAMENT ).append( " THEN 'Deranjament '||d.NUMAR " ).append(
            "  WHEN r.OBJECT_TYPE = " ).append( Reclamatie.LEGAT_LA_INCIDENT ).append( " THEN 'Incident '||li.ID " ).append(
            "ELSE '-' END " ).append(
            " FROM reclamatii r" ).append(
            "       LEFT JOIN deranjamente d ON (d.ID = r.LEGAT_OBJECT_ID) " ).append(
            "       LEFT JOIN LittleIncidente li ON (li.ID = r.LEGAT_OBJECT_ID) " ).append(
            "       LEFT JOIN LPD_LUCRARE_PROGRAMATA lp2 ON (lp2.ID = r.LEGAT_OBJECT_ID) " ).append(
            " WHERE 0=0 {filters} " ).append(
            " ORDER BY r.CONTINUT_SESIZARE1, r.CONTINUT_SESIZARE2, r.DATA ASC");

    final ReportStatement raportReclamatiiExcel = new ReportStatement(
        buffer.toString()
    );

    buffer.delete(0, buffer.length());
    buffer.append("SELECT COUNT(*) FROM reclamatii r ").append(
            "   LEFT JOIN deranjamente d ON (d.ID = r.LEGAT_OBJECT_ID) " ).append(
            "   LEFT JOIN LittleIncidente li ON (li.ID = r.LEGAT_OBJECT_ID) " ).append(
            "   LEFT JOIN LPD_LUCRARE_PROGRAMATA lp2 ON (lp2.ID = r.LEGAT_OBJECT_ID) " ).append(
            "  WHERE 0=0 {filters}");

    final ReportStatement countReclamatii = new ReportStatement(
        buffer.toString()
    );

    if (dataStartx != null) {
        raportReclamatii.addOrSetFilter("r.DATA", ">=", dataStartx);
    }

    if (dataStopx != null) {
        raportReclamatii.addOrSetFilter("r.DATA", "<=", dataStopx);
    }

    if( zonaSelectata != null){
        final String zonaColumn = (zonaSelectata.isFiliala() ? "ID_FILIALAR" : zonaSelectata.isSucursala() ? "ID_SUCURSALAR" : zonaSelectata.isCentru() ? "ID_CENTRUR" : null);
        if( zonaColumn == null){
            throw new RuntimeException("Nu s-a reusit stabilirea coloanei pentru zona reclamatie : " + zonaSelectata);
        }
        raportReclamatii.addOrSetFilter( zonaColumn, "=", new Long(zonaSelectata.getId()));
    }

    if (localitate != null && localitate.trim().length() > 0) {
        raportReclamatii.addOrSetFilter("UPPER(r.LOCALITATE)", "LIKE", '%' + localitate.trim().toUpperCase() + '%');
    }

    if (reclamant != null && reclamant.trim().length() > 0) {
        raportReclamatii.addOrSetFilter("UPPER(r.NUME_CLIENT)", "LIKE", '%' + reclamant.trim().replace(' ', '%').toUpperCase() + '%');
    }
    if (fscRaport.getFilialaId() != -1){
          raportReclamatii.addOrSetFilter("r.ID_FILIALAR", "=", new Long(fscRaport.getFilialaId()));
    }
    if (fscRaport.getSucursalaId() != -1){
        raportReclamatii.addOrSetFilter("r.ID_SUCURSALAR", "=", new Long(fscRaport.getSucursalaId()));
    }
    if (fscRaport.getCentruId() != -1){
       raportReclamatii.addOrSetFilter("r.ID_CENTRUR", "=", new Long(fscRaport.getCentruId()));
    }

    if( objectType > 0){

        if( objectType == Reclamatie.LEGAT_LA_LUCRARE){
            raportReclamatii.addStringCriteria("AND r.OBJECT_TYPE IN ("+objectType+ ',' +Reclamatie.LEGAT_LA_LUCRARE2+ ')');
        }else{
            raportReclamatii.addStringCriteria("AND r.OBJECT_TYPE="+objectType);
        }

        if( objectId != null && objectId.trim().length() > 0){

            if( objectType == Reclamatie.LEGAT_LA_DERANJAMENT){
                raportReclamatii.addStringCriteria(" AND d.NUMAR = " + objectId);
            }else if( objectType == Reclamatie.LEGAT_LA_INCIDENT){
                raportReclamatii.addStringCriteria(" AND li.ID = " + objectId);
            }else if( objectType == Reclamatie.LEGAT_LA_LUCRARE){
                raportReclamatii.addStringCriteria(" AND lp2.NUMAR = " + objectId);
            }
        }
    }

    countReclamatii.addFilters(raportReclamatii);
    raportReclamatiiExcel.addFilters(raportReclamatii);

    final long totalReclamatii = countReclamatii.getLongResult();

    final List rows = raportReclamatii.getListOfArrays("Get Reclamatii");

    String publicPath = null;

%>

<table>
    <tr>
        <td>
            <span style="font-size: 16px; font-weight:bold;">Raport reclamații</span>
            <div class="spacer"></div>
            <table class="gsaptd" width="100%">
                <tr>
                    <td nowrap>
                        <form id="zaforma" name="zaforma" action="<%=GlobalAppConstants.APP_NAME%>?action=raport-reclamatii" method="post">
                            <input type="hidden" name="toExport" value="0">
                            <input type="hidden" name="run_report" value="1"/>


                            <emid:filtru-localizare/>


                            <% if( filiala.isMunteniaNord()){ %>
                                <% Long []ids = UserUtils.getIdLocatiiFull(user); %>
                                <% if( ids != null && ids.length > 0){ %>
                                    <%--Zona:--%>
                                    <select id="zonaSelectata" name="zonaSelectata" class="gSAPSelect">
                                        <% if( ids.length > 1){ %>
                                            <option value="-1">Toate locatiile:</option>
                                        <% } %>
                                        <% for (int i = 0; i < ids.length; i++) {
                                            long idLocatie = ids[i].longValue();
                                            Category _c = CategoryAccessDB.getById( idLocatie);
                                            if( _c != null){%>
                                                <option value="<%=_c.getId()%>" <%=zonaSelectata != null && zonaSelectata.getId() == _c.getId() ? "selected" : ""%> ><%=_c.getName()%></option>
                                            <%}%>
                                        <%}%>
                                    </select>&nbsp;&nbsp;
                                <% } %>
                            <% } %>

                            Localitate:
                            <input type="hidden" id="<%=ReclamatieConstants.COD_MUNICIPIU%>"
                                   name="<%=ReclamatieConstants.COD_MUNICIPIU%>" value="">
                            <input style="width: 120px" id="<%=ReclamatieConstants.MUNICIPIU%>"
                                   name="<%=ReclamatieConstants.MUNICIPIU%>"
                                   value="<%=AppConstants.format( localitate)%>">

                            &nbsp;&nbsp;
                            Reclamant:
                            <input style="width: 120px" id="<%=ReclamatieConstants.NUME_CLIENT%>"
                                   name="<%=ReclamatieConstants.NUME_CLIENT%>"
                                   value="<%=AppConstants.format( reclamant)%>">

                            &nbsp;&nbsp;
                            <select id="<%=ReclamatieConstants.OBJECT_TYPE%>"
                                    name="<%=ReclamatieConstants.OBJECT_TYPE%>" onchange="enableObjectId(); $('<%=ReclamatieConstants.OBJECT_ID%>').focus();">
                                <option value="-1">Atasata la:</option>
                                <option value="<%=Reclamatie.LEGAT_LA_DERANJAMENT%>" <%=objectType == Reclamatie.LEGAT_LA_DERANJAMENT ? "selected" : ""%> >Deranjament</option>
                                <option value="<%=Reclamatie.LEGAT_LA_INCIDENT%>" <%=objectType == Reclamatie.LEGAT_LA_INCIDENT ? "selected" : ""%>>Incident</option>
                                <option value="<%=Reclamatie.LEGAT_LA_LUCRARE%>" <%=objectType == Reclamatie.LEGAT_LA_LUCRARE ? "selected" : ""%>>LP</option>
                            </select>
                            <input style="width: 100px" id="<%=ReclamatieConstants.OBJECT_ID%>"
                                   name="<%=ReclamatieConstants.OBJECT_ID%>"
                                   value="<%=AppConstants.format( objectId)%>">

                            &nbsp;&nbsp;
                            Data inregistrare: <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="Aplică">
                            &nbsp;<input type="button" id="btn-export-excel-recl"  value="Export"/>
                        </form>
                    </td>
                </tr>
            </table>
            <div class="spacer"></div>

            <TABLE id="table" frame="hsides" rules="groups" 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 noSelect="true">
                    <th class="gsapthead">ID</th>
                    <th class="gsapthead">SDEE</th>
                    <th class="gsapthead">C.E.</th>
                    <th class="gsapthead" nowrap>Data</th>
                    <th class="gsapthead" nowrap>Nume Reclamant</th>
                    <th class="gsapthead">Localitatea</th>
                    <th class="gsapthead" nowrap>Tip Artera</th>
                    <th class="gsapthead" nowrap>Denumire Artera</th>
                    <th class="gsapthead" nowrap>Descriere Adresa</th>
                    <th class="gsapthead">Telefon</th>
                    <th class="gsapthead" nowrap>Sesizare 1</th>
                    <th class="gsapthead" nowrap>Sesizare 2</th>
                    <th class="gsapthead" nowrap>Atasata la:</th>
                </tr>
                <%  if (rows == null || rows.size() == 0) {%>
                    <tr noSelect="true">
                        <td colspan="19">Nu exista date ...</td>
                    </tr>
                <% } else {
                    for (int i = 0; i < rows.size(); i++) {
                        final Object[] values = (Object[]) rows.get(i);
                        int continutSesizare1 = -1;
                        int continutSesizare2 = -1;

                        int k = 0;
                %>
                <tbody>
                <tr>
                    <td align="center"><%=values[k++]%>
                    </td>
                    <td><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <td><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <td nowrap><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <td><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <td><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <td><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <td nowrap><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <td nowrap><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <td nowrap><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                    <%--<td nowrap><%=GlobalAppConstants.format((String) values[k++])%>&nbsp;</td>--%>
                    <td>
                        <%
                            continutSesizare1 = ObjectUtils.getIntValue(values[k++], -1);
                            continutSesizare2 = ObjectUtils.getIntValue(values[k++], -1);
                            final String altaSesizare = (String) values[k++];

                            final Reclamatie r = new Reclamatie();
                            r.setContinutSesizare1(continutSesizare1);
                            r.setContinutSesizare2(continutSesizare2);
                            r.setAltaSesizare(altaSesizare);
                        %>
                        <%=ReclamatieConstants.getSesizare1(r)%>
                    </td>
                    <td><%=ReclamatieConstants.getSesizare2(r)%>
                    </td>
                    <td nowrap><%=AppConstants.format((String) values[k++])%>&nbsp;</td>
                </tr>
                </tbody>
                <%}%>
                <tr>
                    <td colspan="12" align="left">
                        <% final long count = rows.size(); %>
                        <% if (totalReclamatii > count) { %>
                        <b>Primele <%=count%> rezultate din  <%=totalReclamatii%>
                        </b>
                        <% } else { %>
                        <b>Total <%=count%> reclamatii</b>
                        <% } %>
                    </td>
                </tr>
                <%}%>
            </TABLE>
        </td>
    </tr>
</table>

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

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

    function setUpSuggesters(){
        var ac_localitate = new AutoAssist("<%=ReclamatieConstants.MUNICIPIU%>", function() {
            return "<%=GlobalAppConstants.APP_NAME%>?action=callcenter_cautLocalitate&q=" + this.txtBox.value;
        });
    }


    function enableObjectId(){
        $("<%=ReclamatieConstants.OBJECT_ID%>").disabled = $("<%=ReclamatieConstants.OBJECT_TYPE%>").selectedIndex == 0;
    }

    function setUpExportButton(){
        new JobButton({
                jobId: "callcenter-reclamatii",
                jobStartAction: "<%=AppConstants.APP_NAME%>?action=job-start-reclamatii",
                jobStatusAction: "<%=AppConstants.APP_NAME%>?action=job-status",
                downloadFileFromRepo: "<%=AppConstants.APP_NAME%>?action=download-file-from-repo",
                jobData: {
                      form: $('zaforma')
                }
        }, "btn-export-excel-recl");
    }

    enableObjectId();
    setUpExportButton();
    setTimeout(function(){
        setUpSuggesters();
    }, 200);
</script>
