<%@language = "javascript" %>
<% /*
     $Revision$
     $Id$

     File:               mld_reject.asp
     Description:        Afwijzen van een melding. Opmerking moet ingevuld worden.
     Parameters:         mld_melding_key

     Context:
     Note:

*/
%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/disciplineselector.inc" -->
<!-- #include file="../Shared/stdmeldingselector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/save2db.inc" -->
<!-- #include file="../ins/ins.inc" -->
<!-- #include file="mld_flexkenmerk.inc" -->
<!-- #include file="mld.inc" -->
<%

FCLTHeader.Requires({ plugins: ["suggest", "jQuery", "kenmerk"] });

var mld_key_arr = getQParamIntArray("mld_key");
var opmerk = getFParam("opmerk", "");

var result = {};
var toberejected = 0;
var ingesloten = [];  // mld_key.
var reqStatusEmptyMelding = [];
var object_ontbreekt = false;
// Bepaal de meldingen in de selectie die
// ook echt afgewezen kunnen of mogen worden.
for (var i = 0; i < mld_key_arr.length; i++)
{
  var this_mld = mld.func_enabled_melding(mld_key_arr[i]); // Wat heb ik zoal aan rechten op deze specifieke melding
  var mld_info = mld.mld_melding_info(mld_key_arr[i]);
  lcl.set_dialect(mld_info.srtdisc_key, "MLD_SRTDISCIPLINE_KEY");
  if (this_mld.canReject && !mld_info.parent_key) // Geen child melding
  {
    ingesloten.push({ mld_key: mld_key_arr[i] });
    toberejected++;
  }
  // Zijn er nog kenmerken die nu wel verplicht zijn?
  var afwezig = mld.hasRequiredStatusEmptyMelding(mld_key_arr[i], 1); // Melding status "Afgemeld(5)"
  if (afwezig.kenm_ontbreekt.length || afwezig.obj_ontbreekt)
  {
    var mldnr = mld.mld_prefix(mld_key_arr[i]) + mld_key_arr[i];
    if (afwezig.kenm_ontbreekt.length)
      reqStatusEmptyMelding.push(L("lcl_mld_req_status_empty").format(afwezig.kenm_ontbreekt.join(", "), mldnr));
    if (afwezig.obj_ontbreekt)
    {
      reqStatusEmptyMelding.push(L("lcl_mld_req_obj").format(mldnr));
      object_ontbreekt = true;
    }
  }
}
// De laatst gebruikte set_dialect uit de for-lus geldt nu voor de onderstaande code.
// abort with required status message only with multi-action. 1 call can continue with required status message.
user.anything_todo_or_abort(!(reqStatusEmptyMelding.length && toberejected > 1) && !object_ontbreekt, reqStatusEmptyMelding.join("<br />"));
user.anything_todo_or_abort(toberejected > 0); // We klagen niet over enkele wel en enkele niet

var mldKeyArray = "";
for (var i = 0; i < ingesloten.length; i++)
{
  mldKeyArray += (i > 0? "," : "") + ingesloten[i].mld_key;
}

var canCloseCtr = 0;
var controleModeArray = [-1, -1, -1]; // De drie controlemoden zijn niet aanwezig (-1);
for (var i = 0; i < ingesloten.length; i++)
{
  var mld_melding = mld.mld_melding_info(ingesloten[i].mld_key);
  var stdm_info = mld.mld_stdmeldinginfo(mld_melding.stdm_key);

  var sql = "SELECT dsc.ins_deel_key"
          + "     , dsc.ins_srtcontrole_key"
          + "     , cdp.ctr_disc_params_controle_type"
          + "     , mo.ins_deelsrtcontrole_key"
          + "  FROM ins_deelsrtcontrole dsc"
          + "     , ins_srtcontrole isc"
          + "     , ctr_disc_params cdp"
          + "     , mld_melding_object mo"
          + " WHERE dsc.ins_srtcontrole_key = isc.ins_srtcontrole_key"
          + "   AND isc.ctr_discipline_key = cdp.ctr_ins_discipline_key"
          + "   AND mo.ins_deelsrtcontrole_key = dsc.ins_deelsrtcontrole_key"
          + "   AND mo.mld_melding_key = " + ingesloten[i].mld_key;
  var oRs = Oracle.Execute(sql);
  while (!oRs.eof)
  {
    // De controle moet aanwezig zijn. Maar een inspectie kan ook verwijderd zijn!
    var this_ins = ins.func_enabled_deel(oRs("ins_deel_key").Value,
                                         {srtcont_key: oRs("ins_srtcontrole_key").Value,
                                          deelsrtcont_key: oRs("ins_deelsrtcontrole_key").Value,
                                          scen_key: 1
                                         });
    if (this_ins.canInspFinishMjb)
    {
      canCloseCtr++;
      controleModeArray[oRs("ctr_disc_params_controle_type").Value - 1] = oRs("ctr_disc_params_controle_type").Value; // Controlemode 2 op de 2de plek van de Array invullen [-1, 2, -1].
    }
    oRs.MoveNext();
  }
  oRs.Close();
}

// De -1 waarden in de controlemode Array verwijderen
for (var i = 2; i >= 0; i--)
{
  if (controleModeArray[i] == -1) controleModeArray.splice(i, 1);
}
%>

<html>
  <head>
<%  FCLTHeader.Generate(); %>

    <script type="text/javascript">

        $(function()
        {
            $('textarea').resize(function () { FcltMgr.resized(window) } );
            $('textarea').autogrow();
            PasteFromSelectbox();
<%  if (canCloseCtr > 0 && S("mld_close_ctr_default"))
    { %>
            $("#ctr_close").trigger("change");
<%  } %>
        });

        async function mld_reject()
        {
            // Standaard checks op verplichte velden, datum formaat, numeriek en float formaat, currency formaat.
            if (!await validateForm("rejectform"))
                return false;

            $.post( $("form[name=rejectform]")[0].action
                  , $("[name=rejectform]").serialize()
                  , FcltCallbackAndThenAlways(mld_reject_callback)
                  , "json"
                  );

            return true; // disable button
        }

        function mld_reject_callback(data)
        {
            for (var i=0; i< data.reject_arr.length; i++)
            {
                if (data.reject_arr[i].inspect)
                {
                    var insdata = data.reject_arr[i].inspect;
                    protectRequest.dataToken(insdata);

                    //jQuery.ajaxSetup({async: false});
                    $.post( "../ins/ins_inspect_save.asp"
                          , insdata
                          , null // we gaan er vanuit dat er niets fout gaat :)
                          , "json"
                          );
                    //jQuery.ajaxSetup({async: true});
                }
            }
            mld_reject_close(data);
        }

        function mld_reject_close(data)
        {
            FcltMgr.closeDetail( window
                               , { key: data.mld_key
                                 , warning: data.warning
                                 , success: data.success
                                 });
        }

        function mld_cancel()
        {
          FcltMgr.closeDetail(window, { cancel: true } );
        }

        function PasteFromSelectbox()
        {
          if ($("#stdopmerk :selected").val() > -1)
          {
            $("#opmerk").focus();
            var PastedText = $("#stdopmerk :selected")[0].getAttribute("afmeldtekstoms");
            $("#opmerk").val($("#opmerk").val() + ($("#opmerk").val() != ""? "\n" : "") + PastedText);
          }
        }

        function ctrcloseToggler(deze)
        {
            var ctrclose = $(deze).prop('checked');
            if (ctrclose)
            {
<%              for (var i = 0; i < controleModeArray.length; i++) { %>
                    $("#sel_controlemode" + <%=controleModeArray[i]%>).addClass("required");
<%              } %>
                $("#inscontrolemode").show();
                FcltMgr.resized(window);
            }
            else
            {
                $("#inscontrolemode").hide();
<%              for (var i = 0; i < controleModeArray.length; i++) { %>
                    $("#sel_controlemode" + <%=controleModeArray[i]%>).removeClass("required");
<%              } %>
            }
        }
    </script>
  </head>

  <body class="fclt-modal" id="mod_rejectbody">
    <% MODAL_START(); %>
      <form id="rejectform" name="rejectform" action="mld_reject_save.asp?mld_key=<%=mldKeyArray%>" method="post">
<%
      if (ingesloten.length == 1)
      {
        sql = "SELECT mm.mld_melding_opmerking"
          + "     , " + lcl.xsqla('md.ins_discipline_omschrijving', 'md.ins_discipline_key')
            + "   , " + lcl.xsqla('std.mld_stdmelding_omschrijving', 'std.mld_stdmelding_key')
            + "     , sd.ins_srtdiscipline_prefix"
            + "     , mm.mld_melding_status"
            + "  FROM mld_melding mm"
            + "     , mld_stdmelding std"
            + "     , mld_discipline md"
            + "     , ins_srtdiscipline sd"
            + " WHERE mld_melding_key = " + ingesloten[0].mld_key
            + "   AND mm.mld_stdmelding_key = std.mld_stdmelding_key"
            + "   AND std.mld_ins_discipline_key = md.ins_discipline_key"
            + "   AND md.ins_srtdiscipline_key = sd.ins_srtdiscipline_key";
        oRs = Oracle.Execute(sql);

        var stdmelding_omschrijving = oRs("mld_stdmelding_omschrijving").value;
        var melding_opmerking = oRs("mld_melding_opmerking").value;
        var prefix = oRs("ins_srtdiscipline_prefix").value || "";
        var ins_discipline_omschrijving = oRs("ins_discipline_omschrijving").value;
        var mld_status = oRs("mld_melding_status").value;
        oRs.close();
      }

        MODAL_BLOCK_START("mldReject",
                         (ingesloten.length == 1
                          ? ((mld_status == 2 || mld_status == 0) ? L("lcl_mld_reject") : L("lcl_mld_cancel")) + " " + prefix + ingesloten[0].mld_key
                          : L("lcl_forward_mld_1") + mldKeyArray),
                         { icon: (mld_status == 2 || mld_status == 0) ? "fa-times" : "fa-trash-can-xmark"});

        if (ingesloten.length == 1)
        {
          ROFIELDTR("fld", L("lcl_complain"), stdmelding_omschrijving, {suppressEmpty: true});
          ROFIELDTR("fld", L("lcl_vakgroup"), (prefix ? prefix + "-" : "") + ins_discipline_omschrijving, {suppressEmpty: true})
        }
        // Afwijstekst
        var stdmld_arr = [];
        var disc_arr = [];

        sql = "SELECT DISTINCT mld_stdmelding_afmeldtext"
            + "     , mld_melding_opmerking"
            + "     , ins_srtdiscipline_prefix"
            + "     , std.mld_stdmelding_key"
            + "     , md.ins_discipline_key"
            + "  FROM mld_melding mm"
            + "     , mld_stdmelding std"
            + "     , mld_discipline md"
            + "     , ins_srtdiscipline sd"
            + " WHERE mld_melding_key IN (" + mldKeyArray + ")"
            + "   AND mm.mld_stdmelding_key = std.mld_stdmelding_key"
            + "   AND std.mld_ins_discipline_key = md.ins_discipline_key"
            + "   AND md.ins_srtdiscipline_key = sd.ins_srtdiscipline_key";
        oRs = Oracle.Execute(sql);
        while (!oRs.eof)
        {
          stdmld_arr[stdmld_arr.length] = oRs("mld_stdmelding_key").Value;
          disc_arr[disc_arr.length] = oRs("ins_discipline_key").Value;
          oRs.MoveNext();
        }

        var sql_from_t = "  FROM mld_afmeldtekst"
                       + " WHERE ((mld_stdmelding_key IN (" + stdmld_arr.join(",") + ") )"
                       + "    OR (mld_stdmelding_key IS NULL AND mld_ins_discipline_key IN (" + disc_arr.join(",") + ") )"
                       + "    OR (mld_stdmelding_key IS NULL AND mld_ins_discipline_key IS NULL))"
                       + "   AND BITAND(mld_afmeldtekst_usefor, 2) = 2";

        var sql_from_o = "  FROM mld_opdr mo"
                       + " WHERE mo.mld_melding_key = " + ingesloten[0].mld_key
                       + "   AND mo.mld_statusopdr_key = 6" // status=afgemeld
                       + "   AND mo.mld_opdr_opmerking IS NOT NULL";

        var sql = "SELECT SUM(aantal) aantal"
                + "  FROM ( SELECT COUNT(*) aantal" + sql_from_t
                        + (ingesloten.length == 1
                          ? " UNION SELECT COUNT(*)" + sql_from_o
                          : ""
                          )
                        + ")";
        oRs = Oracle.Execute(sql);
        var aantal_teksten = oRs("aantal").Value;
        oRs.Close();
        if (aantal_teksten > 0)
        {
          sql = "SELECT mld_afmeldtekst_key"
              + "     , " + lcl.xsqla('mld_afmeldtekst_naam', 'mld_afmeldtekst_key')
              + "     , " + lcl.xsql('mld_afmeldtekst_omschrijving', 'mld_afmeldtekst_key') + " afmeldtekstoms"
              + "     , 2 src"
              + sql_from_t;
          if (ingesloten.length == 1)
          {
            sql += " UNION "
                 + "SELECT mo.mld_opdr_key"
                 + "     ," + safe.quoted_sql(L("lcl_opdr_closeremark") + " /") +"|| mo.mld_opdr_bedrijfopdr_volgnr"
                 + "     , mo.mld_opdr_opmerking"
                 + "     , 1"
                 + sql_from_o
          }
          sql += " ORDER BY 4,2";
          FCLTselector("stdopmerk",
                       sql,
                       { label: L("lcl_mld_inf_std_opm"),
                         initKey: -1,
                         emptyOption: (S("mld_sel_single_closingtext")==2 && aantal_teksten==1 ? null : ""),
                         extraParamValue: "afmeldtekstoms",
                         onChange: "PasteFromSelectbox()"});
        }

        RWTEXTAREATR("opmerk",
                     "fldtxt required",
                     L("lcl_mld_inf_Opmerking"),
                     melding_opmerking,
                     {html: "rows='8'"});
        if (canCloseCtr > 0)
        { %>
          <tr>
            <td colspan="2">
              <% CHECKBOX("fldctrclose", "ctr_close", S("mld_close_ctr_default"), { html: "onChange='ctrcloseToggler(this)'" }); %>
              <label for="ctr_close"><%=canCloseCtr > 1? canCloseCtr + L("lcl_mld_ctr_close_all_n") : L("lcl_mld_ctr_close_all_1")%></label>
            </td>
          </tr>
          <tr>
            <td colspan="2">
              <div id="inscontrolemode" style="display: none">
                <table>
<%                for (var i = 0; i < controleModeArray.length; i++)
                  { // Maximaal 3 types.
                    var sctype;
                    switch (controleModeArray[i])
                    {
                      case 1:  sctype = L("lcl_ins_srtcontrole_insp"); break;
                      case 2:  sctype = L("lcl_ins_srtcontrole_repl"); break;
                      case 3:  sctype = L("lcl_ins_srtcontrole_cert"); break;
                    }

                    sql = "SELECT ins_controlemode_key"
                        + "     , " + lcl.xsqla('ins_controlemode_oms', 'ins_controlemode_key')
                        + "  FROM ins_controlemode"
                        + "  WHERE ins_srtcontrole_type = " + controleModeArray[i]
                        + "    AND ins_controlemode_success = 0"
                        + "  ORDER BY 2";

                    // Methode is voor de status Afgemeld(5) en Historie/Verwerkt(6) altijd ingevuld.
                    // Required wordt gezet als de selectbox zichtbaar wordt.
                    FCLTselector("sel_controlemode" + controleModeArray[i],
                                 sql,
                                 { label: L("lcl_ins_controle_mode") + " " + sctype,
                                   initKey: -1,
                                   emptyOption: L("lcl_select_controlemode"),
                                   selectjustone: true
                                 });
                  }
%>              </table>
              </div>
            </td>
          </tr>
<%      }
        MODAL_BLOCK_END();

        // De verplichte afwijs (cancel) kenmerken tonen bij het afmelden. Vooralsnog worden de andere verplichte kenmerken niet getoond.
        generateFlexKenmerkBlock({stdm_arr         : [mld_melding.stdm_key],
                                  mld_key          : mld_melding.mld_key,
                                  prs_key          : user_key,
                                  cancel           : true,
                                  canFlexChange    : this_mld.canFlexChange,
                                  showConfidential : this_mld.canViewConfidential,
                                  melder_key       : mld_melding.melder_key,
                                  srtdisc          : S("mld_processing_group_all")? [] : [mld_melding.srtdisc_key],
                                  disc             : mld_melding.disc_key,                                                                            // Initiele waarde primaire Vakgroep/Behandelteam.
                                  //prsautlevel      : prsautlevel, // Blokbehandelteam, blokbehandelaar en afgemeld niet te wijzigen. Voor de prsautlevel wordt dan wel 9 genomen.
                                  show_alg         : mld_melding.show_alg,
                                  loc_key          : mld_melding.loc_key,
                                  this_mld         : this_mld
                                });

        var buttons =  [ {title: L("lcl_reject"), icon: "fa-fclt-save", action: "mld_reject()", singlepress: true, id: "btn_reject_submit", importance: 1 },
                         {title: L("lcl_cancel"), icon: "fa-fclt-cancel", action: "mld_cancel()", importance: 3 }];
        SIMPLE_BLOCK_START();
        CreateButtons(buttons);
        SIMPLE_BLOCK_END();
        IFACE.FORM_END(); %>
      </form>
    <% MODAL_END(); %>
  </body>
</html>
<% ASPPAGE_END(); %>
