{% extends "admin/base_site_grid.html" %}
{% load i18n %}
{% load static %}

{% block extrastyle %}{{block.super}}
<style>
#attributes-supplyinformation thead tr td,
#attributes-networkstatus thead tr td,
#attributes-downstreamoperationplans thead tr td,
#attributes-upstreamoperationplans thead tr td,
#attributes-operationproblems thead tr td,
#attributes-operationresources thead tr td,
#attributes-operationflowplans thead tr td,
#attributes-operationdemandpegging thead tr td,
#attributes-inventorydata thead tr td {
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: #bbb;
}

rect.opplan {
  vector-effect: non-scaling-stroke;
  stroke-width: 1px;
  stroke: rgb(0,0,0);
}

/* Button group icons */
.btn-primary.active:disabled {
  background-color: var(--bs-btn-active-bg);
}
</style>
{% endblock %}

{% block extrahead %}{{block.super}}
<script src="{{STATIC_URL}}js/d3.min.js"></script>
<script src="{{STATIC_URL}}js/angular.min.js"></script>
<script src="{{STATIC_URL}}js/angular-cookies.min.js"></script>
<script src="{{STATIC_URL}}js/angular-gettext.min.js"></script>
<script src="{{STATIC_URL}}js/angular-websocket.js"></script>
<script src="{{STATIC_URL}}js/i18n/angular-freppletranslations.js"></script>

{% if debug_js %}
<script src="{{STATIC_URL}}common/src/module.js"></script>
<script src="{{STATIC_URL}}common/src/preferences.js"></script>
<script src="{{STATIC_URL}}common/src/webfactory.js"></script>

<script src="{{STATIC_URL}}input/src/module.js"></script>
<script src="{{STATIC_URL}}input/src/customer.js"></script>
<script src="{{STATIC_URL}}input/src/demand.js"></script>
<script src="{{STATIC_URL}}input/src/location.js"></script>
<script src="{{STATIC_URL}}input/src/buffer.js"></script>
<script src="{{STATIC_URL}}input/src/resource.js"></script>
<script src="{{STATIC_URL}}input/src/item.js"></script>
<script src="{{STATIC_URL}}input/src/operation.js"></script>
<script src="{{STATIC_URL}}input/src/operationplan.js"></script>
<script src="{{STATIC_URL}}input/src/model.js"></script>

<script src="{{STATIC_URL}}operationplandetail/src/calendar.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/d3service.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/module.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/operationplandetailCtrl.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/problemspanelDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/resourcespanelDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/bufferspanelDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/demandpeggingpanelDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/operationplanpanelDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/networkstatusDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/downstreamoperationplansDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/upstreamoperationplansDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/supplyinformationDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/inventorydataDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/inventorygraphDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/kanbanDrv.js"></script>
<script src="{{STATIC_URL}}operationplandetail/src/ganttDrv.js"></script>
{% else %}
<script src="{{STATIC_URL}}js/frepple-common.min.js"></script>
<script src="{{STATIC_URL}}js/frepple-input.min.js"></script>
<script src="{{STATIC_URL}}js/frepple-operationplandetail.min.js"></script>
{% endif %}
<script>

  var urlParams = new URLSearchParams(window.location.search);
  var mode = preferences && preferences.mode || "table";
  var calendarmode = preferences && preferences.calendarmode || "{{reportclass.calendarmode}}";
  var grouping = preferences && preferences.grouping || null;
  var groupingdir = preferences && preferences.groupingdir || "asc";
  var editable = {% if reportclass.editable and haschangeperm %}true{% else %}false{% endif %};
  var service_url = {% if proxied %}'/svc/{{request.database}}/'{% else %}document.location.protocol + "//{{port}}/"{% endif %};
  var service_token = '{{token}}';
  var showChildren = (!urlParams.has("noautofilter") && preferences && "showChildren" in preferences) ? preferences.showChildren : true;
  var showTop = (!urlParams.has("noautofilter") && preferences && "showTop" in preferences) ? preferences.showTop : true;

  function saveData(rows, ok_callback) {
      $.ajax({
        url: service_url + 'operationplan/',
        data: JSON.stringify(rows),
        type: "POST",
        headers: { "Authorization": "Bearer " + service_token },
        contentType: "application/json",
        success: function () {
          upload.undo();
          $("#save i").addClass('hidden');
          $(".ng-dirty").removeClass('ng-dirty');
          if (typeof ok_callback !== 'undefined') ok_callback();
        },
        error: ajaxerror
    });
  }

  function extraPreference() {
    var tmp = {
      "height": Math.floor($("#content-main").height()),
      "width": Math.floor($("#fields").width()),
      "mode": mode,
      "calendarmode": calendarmode,
      "columns": angular.element('#controller').scope().kanbancolumns,
      "grouping": grouping,
      "groupingdir": groupingdir,
      "detailwidth": Math.floor($("#detailspanel").width() || 0),
      "widgets": widget.getConfig()
    };
    if (!urlParams.has("noautofilter")){
      tmp["showTop"] = showTop;
      tmp["showChildren"] = showChildren;
    }
    return tmp;
  }

  function extraSearchUpdate(filter) {
    thefilter = filter;
  	if (preferences && preferences.mode == "kanban") {
      initialfilter = filter;
  	  angular.element('#controller').scope().loadKanbanData(filter);
  	  return true;
  	}
  	else if (preferences && preferences.mode == "gantt") {
      initialfilter = filter;
  	  angular.element('#controller').scope().loadGanttData(filter);
  	  return true;
  	}
    else if (preferences && preferences.mode && preferences.mode.startsWith("calendar")) {
      initialfilter = filter;
      angular.element('#controller').scope().loadCalendarData(filter);
      return true;
    }
    return false;
  }

  function setHeights() {
    var h = $('#content-main').height();
    $('#grid').setGridWidth($('#content-main').width());
    $("#grid").setGridHeight(h - 52);
    $(".column-body").css("height", h - 25);
    $("#scrolldayview").css("height", h - 25);
    $("#scrollweekview").css("height", h - 60);
    $("#scrollmonthview").css("height", h - 45);
  }

  function setWidths() {
    var w = $("#workarea").width() - $('#detailspanel').width() - $("#resize-handle").parent().width();
    $('#grid').setGridWidth(w);
    $("#grid").setGridHeight($('#content-main').height() - 52);
    $("#kanban").css("width", w - 25);
    $("#scrolldayview").css("width", w - 25);
    $("#scrollweekview").css("width", w - 60);
    $("#scrollmonthview").css("width", w - 45);
  }

  function getDirtyData() {
  	if (preferences && preferences.mode && (preferences.mode == "kanban" || preferences.mode == "gantt" || preferences.mode.startsWith("calendar"))) {
      initialfilter = thefilter;
      return angular.element('#controller').scope().getDirtyCards();
    }
  	else {
      var dirty = $("#grid").getChangedCells('dirty');
      for (var c of dirty) {
        var ref = $("#grid").jqGrid('getCell', c.id, "operationplan__reference");
        if (ref) c.operationplan__reference = ref;
      }
      return dirty;
    }
  }

  var language = "{{LANGUAGE_CODE}}";
  var version = '{% version_short %}';
  var lastid = '';
  var preferences = {{ preferences | json }};
  var default_operationplan_type = "{{ default_operationplan_type }}";
  var groupBy = "{{ groupBy }}";
  var thefilter = initialfilter;
  var groupingcfg = {{ groupingcfg | json }};
  var currentdate = new Date("{{ currentdate|date:'Y-m-d' }}");

  var horizonstart = new Date({{request.report_startdate|date:"Y"}},{{request.report_startdate|date:"n"}}-1,{{request.report_startdate|date:"j"}});
  var horizonend = new Date({{request.report_enddate|date:"Y"}},{{request.report_enddate|date:"n"}}-1,{{request.report_enddate|date:"j"}});
  var viewstart = new Date(horizonstart.getTime());
  var viewend = new Date(horizonend.getTime());

  function zoom(factor) {
    gantt.zoom(factor, "#ganttheader");
    angular.element('#controller').scope().zoom();
  }

  $(function() {
    $("#workarea").css('overflow-x','visible');
    $("#content-main").resizable({
      handleSelector: "#resize-handle",
      resizeWidth: false,
      resizeHeight: true,
      onDrag: setHeights,
      onDragEnd: function (e, $el, opt) {
        grid.saveColumnConfiguration();
      }
    });
    $("#save").on('click', function() {
      $(window).off('beforeunload', upload.warnUnsavedChanges);
      });
    $("#undo").on('click', function() {
      $(window).off('beforeunload', upload.warnUnsavedChanges);
      });
    $("#actionsul li, button#actions1").on('click', function() {
      angular.element('#controller').scope().refreshstatus($("#actions").val());
    });
    $("#gridmode").on('click', function() {
      angular.element('#controller').scope().setMode("table");
    });
    $("#kanbanmode").on('click', function() {
      angular.element('#controller').scope().setMode("kanban");
    });
    $("#calendarmonth").on('click', function() {
      angular.element('#controller').scope().setMode("calendarmonth");
    });
    $("#calendarweek").on('click', function() {
      angular.element('#controller').scope().setMode("calendarweek");
    });
    $("#calendarday").on('click', function() {
      angular.element('#controller').scope().setMode("calendarday");
    });
    $("#showTop").on('click', function() {
      angular.element('#controller').scope().toggleShowTop();
    });
    $("#showChildren").on('click', function() {
      angular.element('#controller').scope().toggleShowChildren();
    });
    $('#zoomin').on("click", function() { zoom(0.5); });
    $('#zoomout').on("click", function() { zoom(2); });
    {% if showGantt %}
    $("#ganttmode").on('click', function() {
      angular.element('#controller').scope().setMode("gantt");
    });
    $("#zoomin, #zoomout").removeClass("d-none");
    {% endif %}
  });
  // frepple.js will call this function to alert angular that the grid has changed
  function checkrows(grid, selection) {
    var selectiondata = [];
    jQuery.each(selection , function(index,item){
      selectiondata.push(grid.getRowData(item));
    });
    if (selectiondata.length > 1) {
      angular.element('#controller').scope().processAggregatedInfo(selectiondata, jQuery("#grid").jqGrid ('getGridParam', 'colModel'));
    } else if (selectiondata.length === 1) {
      angular.element('#controller').scope().displayInfo(selectiondata[0]);
    } else {
      angular.element('#controller').scope().displayInfo(undefined);
    }
  }

  // Controller will call this function to pass values to the grid
  function displayongrid(id, columnid, value) {
    angular.element(document).find(document.getElementById(id)).removeClass("edited").addClass("edited");
    if (
      columnid === "startdate" ||
      columnid === "enddate" ||
      columnid === "quantity" ||
      columnid === "quantity_completed" ||
      columnid === "remark" ||
      (columnid === "status" && ['proposed', 'approved', 'confirmed', 'completed', 'closed'].indexOf(value) > -1)
    ) {
      angular.element(document).find("#grid").jqGrid("setCell", id, columnid, value, "dirty-cell");
      $("#save, #undo").removeClass("btn-primary btn-danger").addClass("btn-danger").prop("disabled", false);
      $(window).off('beforeunload', upload.warnUnsavedChanges);
      $(window).on('beforeunload', upload.warnUnsavedChanges);
    }
  }
</script>
{% endblock %}

{% block extracontainer %}data-ng-app="operationplandetailapp"{% endblock %}

{% block tools %}{% if args %}{% include "common/snippet_follow.html" %}{% endif %}{% endblock %}

{% block tabs %}{% if args %}{% tabs model %}{% endif %}{% endblock %}

{% block actions %}
  <div class="btn-group" role="group">
    <button data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans "display table"|capfirst|force_escape %}"
      class="btn btn-sm btn-primary{% if preferences.mode != 'kanban' and preferences.mode != 'gantt' and preferences.mode != 'calendarday' and preferences.mode != 'calendarweek' and preferences.mode != 'calendarmonth' or not preferences.mode %} active{% endif %}"
      type="button" id="gridmode" name="mode">
      <span class="fa fa-table fa-lg" style="margin: 2px 0 3px 0;"></span>
    </button>
    <button data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans "display kanban cards"|capfirst|force_escape %}" class="btn btn-sm btn-primary{% if preferences.mode == 'kanban' %} active{% endif %}" type="button" id="kanbanmode" name="mode">
      <span class="fa fa-columns fa-lg fa-lg" style="margin: 2px 0 3px 0;"></span>
    </button>
    <div class="btn-group dropdown" data-bs-toggle="tooltip" data-bs-toggle="tooltip"
      data-bs-placement="top" title="{% trans "display calendar"|capfirst|force_escape %}">
      <button type="button" id="calendarmode" name="mode"
        class="btn btn-sm btn-primary dropdown-toggle{% if preferences.mode == 'calendarday' or preferences.mode == 'calendarweek' or preferences.mode == 'calendarmonth' %} active{% endif %}"
        data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        <span class="fa fa-calendar-o"></span>
        <span class="caret"></span>
      </button>
      <ul class="dropdown-menu">
        <li class="dropdown-item" id="calendarmonth"><a href="#">{% trans "month"|capfirst %}</a></li>
        <li class="dropdown-item" id="calendarweek"><a href="#">{% trans "week"|capfirst %}</a></li>
        <li class="dropdown-item" id="calendarday"><a href="#">{% trans "day"|capfirst %}</a></li>
      </ul>
    </div>
    {% if showGantt %}
    <button data-bs-toggle="tooltip" data-bs-placement="top" title="{% trans "display Gantt chart"|capfirst|force_escape %}" class="btn btn-sm btn-primary{% if preferences.mode == 'gantt' %} active{% endif %}" type="button" id="ganttmode" name="mode">
      <span class="fa fa-align-left fa-lg fa-lg" style="margin: 2px 0 3px 0;"></span>
    </button>
    {% endif %}
  </div>
{% if hasaddperm %}<button class="btn btn-sm btn-primary" onclick="location.href='{{request.prefix}}/data/{{model|app_label}}/{{model|object_name|lower}}/add/{% if is_popup %}?_popup=1{% endif %}'" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Create new object"|escape %}" ><span class="fa fa-plus"></span></button>
{% endif %}{% if hasaddperm and not is_popup and reportclass.canDuplicate %}<button class="btn btn-sm btn-primary"  disabled id="copy_selected" onclick="grid.showCopy()" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Copy selected objects'|capfirst|escape %}" ><span class="fa fa-copy"></span></button>
{% endif %}
<!--{% if haschangeperm and not is_popup %}<button class="btn btn-sm btn-primary" id="edit_selected" disabled onclick="grid.update('{{request.prefix}}/data/{{model|app_label}}/{{model|object_name|lower}}/')" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Update objects"|escape %}" ><span class="fa fa-edit"></span></button>
{% endif %}-->
{% if hasdeleteperm and not is_popup %}<button class="btn btn-sm btn-primary" id="delete_selected" disabled data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Delete selected objects'|capfirst|escape %}" onclick="grid.showDelete('{{request.prefix}}/data/{{model|app_label}}/{{model|object_name|lower}}/')" ><span class="fa fa-minus"></span></button>
{% endif %}{% if reportclass.hasTimeBuckets %}<button class="btn btn-sm btn-primary" onclick="grid.showBucket()" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'set time horizon'|capfirst|force_escape %}" id="bucketconfig"><span class="fa fa-clock-o"></span></button>
{% endif %}<button class="btn d-none btn-sm btn-primary" id="zoomin" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Zoom in'|capfirst|force_escape %}"><span class="fa fa-search-plus"></span></button>
<button class="btn d-none btn-sm btn-primary" id="zoomout" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Zoom out'|capfirst|force_escape %}"><span class="fa fa-search-minus"></span></button>
{% if hasaddperm %}<button class="btn btn-sm d-none d-md-inline-block btn-primary" id="csvimport" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Import CSV or Excel file'|capfirst|force_escape %}" onclick="import_show('', undefined, true)"><span class="fa fa-arrow-up"></span></button>
{% endif %}<button class="btn btn-sm btn-primary" onclick="grid.showExport(true,{{ scenario_permissions }})" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'export as CSV or Excel file'|capfirst|force_escape %}"><span class="fa fa-arrow-down"></span></button>
<button id="customize" class="btn btn-sm btn-primary" onclick="grid.showCustomize(false);" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'customize'|capfirst|force_escape %}"><span class="fa fa-wrench"></span></button>
{% endblock %}

{% block afterPageLoad %}
displayGrid({% if preferences.mode != "kanban" and preferences.mode != "gantt" and preferences.mode != "calendarday" and preferences.mode != "calendarweek" and preferences.mode != "calendarmonth" %}true{% else %}false{% endif %});
{% endblock %}

{% block extra_grid %}

onSelectAll: function(aRowids,status){
  var selection = $(this).jqGrid('getGridParam','selarrrow');
  var selectiondata = [];
  jQuery.each(selection , function(index,item) {
    selectiondata.push(jQuery("#grid").getRowData(item));
  });
  if (status === true)
    angular.element('#controller').scope().processAggregatedInfo(selectiondata, jQuery("#grid").jqGrid ('getGridParam', 'colModel'));
  else
    angular.element('#controller').scope().displayInfo(undefined);
  if ($("#actions").length) $("#actions1").prop('disabled', !status);
},
beforeSaveCell: function(rowid, cellname, value, iRow, iCol) {
  var selection = $(this).jqGrid('getGridParam','selarrrow');
  var selectiondata = [];
  var rowdata = {};
  var temprow = jQuery("#grid").getRowData(rowid);

  jQuery.each(selection , function(index,item){
    if (item === rowid) {
      //update temprow
      temprow[cellname] = value;

      selectiondata.push(temprow);
    } else {
      rowdata = jQuery("#grid").getRowData(item);

      //if is being edited
      var el = $(document.getElementById(item));
      if (typeof el.find("input").attr('cm','[Object Object]').not('.cbox').val() !== 'undefined') {
        if (el.hasClass('success')) {
          if (typeof el.find("input").attr('cm','[Object Object]').not('.cbox').attr("id") !== 'undefined') {
            colname=el.find("input").attr('cm','[Object Object]').not('.cbox').attr("id").split("_")[1];
            if (typeof colname !== 'undefined') {
              rowdata[colname] = el.find("input").attr('cm','[Object Object]').not('.cbox').val();
            }
          }
        }
      }
      selectiondata.push(rowdata);
    }
  });
  upload.select();
  if (selection.length > 1)
    angular.element('#controller').scope().processAggregatedInfo(selectiondata, jQuery("#grid").jqGrid ('getGridParam', 'colModel'));
  else
    angular.element('#controller').scope().displayonpanel(rowid, cellname, value);
},
onSelectRow: function(rowid, status, e) {
  var selection = [];
  if ($(this).jqGrid('getGridParam').multiselect === true) {
    selection = $(this).jqGrid('getGridParam','selarrrow').slice();
  } else {
    selection = [$(this).jqGrid('getGridParam','selrow').slice()];
  }
  grid.markSelectedRow(selection.length);

  var selectiondata = [];
  var rowdata={};
  var colname = "";
  var editedval = "";
  jQuery.each(selection , function(index,item) {
    rowdata = jQuery("#grid").getRowData(item);
    var elem = $(document.getElementById(item)).find("input");
    editedval = elem.attr('cm','[Object Object]').not('.cbox').val();
    if ( typeof elem.attr('cm','[Object Object]').not('.cbox').val() !== 'undefined' ) {
      if (typeof elem.attr('cm','[Object Object]').not('.cbox').attr("id") !== 'undefined') {
        colname=elem.attr('cm','[Object Object]').not('.cbox').attr("id").split("_")[1];
        if (typeof colname !== 'undefined') {
          rowdata[colname] = elem.attr('cm','[Object Object]').not('.cbox').val();
        }
      }
    }
    selectiondata.push(rowdata);
  });

  if (selectiondata.length > 1) {
    angular.element('#controller').scope().processAggregatedInfo(selectiondata, jQuery("#grid").jqGrid ('getGridParam', 'colModel'));
  } else if (selectiondata.length === 1) {
    angular.element('#controller').scope().displayInfo(selectiondata[0]);
  } else {
    angular.element('#controller').scope().displayInfo(undefined);
  }
},
multiboxonly: false,
loadComplete: function(data) {
      $('#curerror').html("");
      if (upload.selectedRows.length === 1) {
        angular.element('#controller').scope().displayInfo(
          jQuery("#grid").getRowData(upload.selectedRows[0])
        );
      }
      else if (upload.selectedRows.length > 1) {
        var selectiondata = [];
        for (var x of upload.selectedRows)
          selectiondata.push(jQuery("#grid").getRowData(x));
        angular.element('#controller').scope().processAggregatedInfo(selectiondata, jQuery("#grid").jqGrid ('getGridParam', 'colModel'));
      }
      else {
        var s = angular.element('#controller').scope();
        if (s) s.processAggregatedInfo([], jQuery("#grid").jqGrid ('getGridParam', 'colModel'));
      }
      upload.restoreSelection();
    },
{% endblock %}

{% block table %}
<div data-ng-controller="operationplandetailCtrl" id="controller">

<div class="row text-center">
<div id="content-main" class="col-md-12" style="min-height: 150px; margin-top: 0.7em">
  <div data-ng-hide="mode == 'kanban' || mode == 'gantt' || mode.startsWith('calendar')">
    <table id="grid" class="table table-striped" style="background-color: white"></table>
    <div id="gridpager"></div>
  </div>
  <div id="calendar" data-ng-hide="!mode.startsWith('calendar')" class="col-md-12">
    <calendar
      data-range-changed="calendarRangeChanged(startdate, enddate)"
      data-event-selected="displayInfo(event)"
      data-event-source="calendarevents"
      data-editable="{% if reportclass.editable and haschangeperm %}true{% else %}false{% endif %}"
      data-mode="mode"></calendar>
  </div>
  <div id="kanban" data-ng-hide="mode != 'kanban'"
    show-kanban-drv class="row"
    data-editable="{% if reportclass.editable and haschangeperm %}true{% else %}false{% endif %}"
    data-kanbanoperationplans="kanbanoperationplans"
    data-operationplan="operationplan"
    data-kanbancolumns="kanbancolumns">
  </div>
  <div id="gantt" data-ng-hide="mode != 'gantt'"
    show-gantt-drv class="row"
    data-ganttoperationplans="ganttoperationplans"
    data-editable="{% if reportclass.editable and haschangeperm %}true{% else %}false{% endif %}">
  </div>
</div>
<span id="resize-handle" class="fa fa-bars handle" style="display: inline-block"></span>
</div>

<div data-ng-include="'/static/operationplandetail/operationplandetail.html'"></div>

</div>

<svg width="0" height="0"><defs id="gradients"></defs></svg>
{% endblock %}
