{% extends "data_grid.html" %}
{% load i18n iclock_tags %}
{% block main_body %}
{% block extend_js %}
  <link rel="stylesheet" type="text/css" href="{% static "css/fullcalendar.min.css" %}"/>
{% endblock %}
<input type="hidden" id="id_{{ model_name }}SelectedShift" value=""/>
<div class="layui-row layui-col-space15" style="margin-top: 0px; margin-bottom: 0px">
  <div class="layui-col-md7">
      <table id="id_grid_{{ model_name }}" class="layui-hide" lay-filter="{{ model_name }}"></table>
      <script type="text/html" id="{{ model_name|safe }}_toolbar">
        <div class="layui-btn-container grid-toolbar" style="">
          <ul class="layui-nav" ></ul>
        </div>
      </script>
  </div>
  <div class="layui-col-md5">
    <style>
      h2 {
        line-height: 1.5;
      }
      .fc-day-header {
        height: 35px;
      }
    </style>
    <div id="id_shift_detail_{{ model_name }}" class="layui-card">
      <div class="layui-card-header" style="background-color: #e6e6e6; font-size: 25px;">
        {% trans 'shiftDetail_grid_detailLabel' %}
      </div>
      <div class="layui-card-body">
        <div id="fullcalendar_emp_schedule" style="height: 450px;"></div>
      </div>
    </div>
  </div>
</div>
{% endblock %}
{% block valid_form %}
  var week=[
    "{% trans 'weekday_option_sunday' %}",
    "{% trans 'weekday_option_monday' %}",
    "{% trans 'weekday_option_tuesday' %}",
    "{% trans 'weekday_option_wednesday' %}",
    "{% trans 'weekday_option_thursday' %}",
    "{% trans 'weekday_option_friday' %}",
    "{% trans 'weekday_option_saturday' %}"
  ];
  var nowDate = new Date();
  var cur = moment(new Date());
  var fullStartOfMonth = cur.startOf('month').format('YYYY-MM-DD');
  var fullEndOfMonth = cur.endOf('month').format('YYYY-MM-DD');
  function getTimeStr(t){
    return t<10? '0'+t: t;
  }
  function getDuringTimeStr(t){
    var sec=1/24/60/60;
    var t_hour=parseInt((t+sec)*24*60/60);
    var t_minute=Math.round((t+sec)*24*60%60);
    return getTimeStr(t_hour)+":"+getTimeStr(t_minute);
  }
  function showTimetable(t1,t2, cross_day){
    if(cross_day > 0){
      return getDuringTimeStr(t1)+"-"+getDuringTimeStr(t2)+"<sup style='color:#7ac143;'>+"+cross_day+"</sup>";
    }
    return getDuringTimeStr(t1)+"-"+getDuringTimeStr(t2);
  }
  function getTZDateAlt(index, sdate){
    if(sdate == undefined)
        return "";
    var tmp = moment(sdate).add(index, 'days');
    return tmp.format('YYYY-MM-DD');
  }
  function getDayLabel(day, st, weekend, holidays, weekend_shift, unit, cal_weekend_start, cal_weekend_end){
    var v = moment(st).add(day, 'days');
    var vStr = v.format('YYYYMMDD');
    var holiday = holidays[vStr];
    var sup = '<sup style="color:white;">'+v.format('ddd')+'</sup>';
    var day_in_month = v.toObject().date;
    if(holiday){
      var alias = [];
      holiday.forEach(function(item){
        alias.push(item['alias'])
      })
      var holiday = alias.join(',');
      var tmps = holiday.split(' ');
      if(tmps.length <= 1){
         var reg = /(\w{3})/;
         alias = holiday.split(reg);
      }
      sup = '<sup style="color:yellow;">'+alias.join('')+'</sup>';
    }else if(weekend[(parseInt(v.format('d')) + 6) % 7]){
      sup = '<sup style="color:greenyellow;">'+v.format('ddd')+'</sup>';
    }else if((!v.isBefore(cal_weekend_start)) && (!v.isAfter(cal_weekend_end))){
        if(unit===1){
          if(weekend_shift[(parseInt(v.format('d')) + 6) % 7]){
            sup = '<sup style="color:greenyellow;">'+v.format('ddd')+'</sup>';
          }
        }else if(unit===2){
          if(weekend_shift[day_in_month-1]){
            sup = '<sup style="color:greenyellow;">'+v.format('ddd')+'</sup>';
          }
        }else if(unit===0){
          if(weekend_shift[0]){
            sup = '<sup style="color:greenyellow;">'+v.format('ddd')+'</sup>';
          }
        }
    }
    return v.format('MM.DD')+sup;
  }

  var scheduleDetail = function(payload){
    var start_date = $("#{{ model_name }}_start_date").val();
    var end_date = $("#{{ model_name }}_end_date").val();
    var start_date = payload.start_date;
    var end_date = payload.end_date;
    $.ajax({
      url: "/att/showShiftDetail/"
      ,type: "GET"
      ,data: {shift: payload.shift_no, st: start_date, ed: end_date, emp: payload.emp_code, schedule:payload.id}
      ,dataType: "json"
      ,success: function(response){}
      ,error: function(XMLHttpRequest, textStatus, errorThrown){

      }
    });
  };

  layui.use('laydate', function(){
    var laydate=layui.laydate;
    var startDate = laydate.render({
      elem: '#{{ model_name }}_start_date',
      type: 'date',
      value: fullStartOfMonth
    });
    var endDate = laydate.render({
      elem: '#{{ model_name }}_end_date',
      type: 'date',
      value: fullEndOfMonth
    });
  });
{% endblock %}

{% block dimension_info %}
  {{ block.super }}
  dimension.width = '1000px'
  dimension.height = '600px'
{% endblock dimension_info  %}

{% block grid_opt_update %}

function update_side_ztree() {
      $('#{{ model_name }}_show_all').trigger('click');
    }
    $.extend(true, dimension, {
        actions: {
          Import: [900, 500],
        }
    });

    $.extend(true, callback, {
      load: {
        done: $.fn.resize_side_ztree_if_any
      },
      actions: {
        GeneralActionNew: {
          done: update_side_ztree
        },
        GeneralActionDelete: {
          done: update_side_ztree
        },
        Import: {
          done: update_side_ztree
        }
      }
    });

  function convert(str) {
    var date = new Date(str),
      month = ("0" + (date.getMonth() + 1)).slice(-2),
      day = ("0" + date.getDate()).slice(-2);
    return [date.getFullYear(), month, day].join("-");
  }

  function get_index(tag, date){
    parent_tr = $(tag).parent().children();
    index = 0
    for (i=0; i < parent_tr.length; i++) {
      element = $(parent_tr[i]).attr('data-date');
      if (element == date) {
        return index
      } else {
        index += 1
      }
    }
  }

  function get_weekend_holiday_element(time_table_data, date, date_index){
      weekend_day_indexes = Object.keys(time_table_data.weekend_total);
      var weekend = weekend_day_indexes.includes(date_index);

      holiday_indexes = Object.keys(time_table_data.holidays);
      var date_str = date.toString().replaceAll('-', '');
      var holiday = holiday_indexes.includes(date_str);

      var element = ""

      if (weekend) {
          time_table = "<p style='background-color:green'>Week off</p>"
          var element = '<td class="fc-event-container"><a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end"><div class="fc-content"><p>' + time_table + '</p></div></a></td>'
      }

      else if (holiday) {
          var holiday_name = time_table_data.holidays[date_str][0].alias
          holiday_name = "<p style='background-color:green'>" + holiday_name + "</p>"
          element = "<a class='fc-day-grid-event fc-h-event fc-event fc-start fc-end'>" + holiday_name + "</a>"
      }

      return element;
  }

  function set_time_table_data(date, time_table_data) {
      var date_tag = $('td[data-date="' + date + '"]');
      var date_index = get_index(date_tag, date);

      var time_table_length = time_table_data.data.length/7;
      var cycle_unit = time_table_data.cycle_unit;
      var time_table = "";
      var element = '<td class="fc-event-container"><a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end"><div class="fc-content"><p>' + time_table + '</p></div></a></td>'

      if (date_index !== undefined) {
          if (cycle_unit === 1) {
              if (time_table_length === 1) {
                  var start_time;
                  var end_time;
                  var cross_day;
                  for (i=0; i < time_table_data.data.length; i++) {
                      if (time_table_data.data[i].day_index == date_index) {
                          start_time = time_table_data.data[i].start_time
                          end_time = time_table_data.data[i].end_time
                          cross_day = time_table_data.data[i].cross_day
                      }
                  }

                  time_table = start_time + "-" + end_time
                  time_table = "<p>" + time_table + "</p>"

                  if (cross_day) {
                    cross_day_suffix = '<sup style="color:yellow;">+' + cross_day + '</sup>'
                    time_table = "<p>" + time_table + cross_day_suffix + "</p>"
                  }
                  element = '<td class="fc-event-container"><a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end"><div class="fc-content"><p>' + time_table + '</p></div></a></td>'

                  element_ = get_weekend_holiday_element(time_table_data, date, date_index.toString());
                  element = (element_ === "") ? element : element_
              }
              else {
                  for (i=0; i < time_table_data.data.length; i++) {
                      if (date_index == time_table_data.data[i].day_index + 1){
                          start_time = time_table_data.data[i].start_time
                          end_time = time_table_data.data[i].end_time

                          time_data = start_time + "-" + end_time
                          time_table_p_tag = "<p>" + time_data + "</p>"
                          time_table = time_table + time_table_p_tag;

                          cross_day = time_table_data.data[i].cross_day
                          if (cross_day) {
                              cross_day_suffix = '<sup style="color:yellow;">+' + cross_day + '</sup>'
                              time_table = "<p>" + time_table + cross_day_suffix + "</p>"
                          }

                          element = '<td class="fc-event-container"><a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end"><div class="fc-content"><p>' + time_table + '</p></div></a></td>'
                      }
                      element_ = get_weekend_holiday_element(time_table_data, date, date_index.toString());
                      element = (element_ === "") ? element : element_
                  }
              }
          }
          else {
              date_ = date.split("-")[2];
              for (i=0; i < time_table_data.data.length; i++) {
                  if (date_ == time_table_data.data[i].day_index + 1){
                      start_time = time_table_data.data[i].start_time
                      end_time = time_table_data.data[i].end_time

                      time_data = start_time + "-" + end_time
                      time_table_p_tag = "<p>" + time_data + "</p>"
                      time_table = time_table + time_table_p_tag;

                      cross_day = time_table_data.data[i].cross_day

                      if (cross_day) {
                        cross_day_suffix = '<sup style="color:yellow;">+' + cross_day + '</sup>'
                        var time_table = "<p>" + time_table + cross_day_suffix + "</p>"
                      }

                      var element = '<td class="fc-event-container"><a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end"><div class="fc-content"><p>' + time_table + '</p></div></a></td>'
                  }
                  element_ = get_weekend_holiday_element(time_table_data, date, date_);
                  element = (element_ === "") ? element : element_
              }
          }
      }

      var data = date_tag.parent().parent().next().children().children();
      $(data).eq(date_index).html(element);
  }

  let schedule_data;

  function get_schedule_data() {
    var schedule = $("#id_{{ model_name }}SelectedShift").val();
    if(schedule){
      var payload = JSON.parse(schedule);
      var start_date = $("#{{ model_name }}_start_date").val();
      var end_date = $("#{{ model_name }}_end_date").val();
      var start_date = payload.start_date;
      var end_date = payload.end_date;
      $.ajax({
        url: "/att/showShiftDetail/"
        ,type: "GET"
        ,data: {shift: payload.shift_no, st: start_date, ed: end_date, emp: payload.emp_code, schedule:payload.id}
        ,dataType: "json"
        ,async: false
        ,success: function(response){
          schedule_data = response;
        }
        ,error: function(XMLHttpRequest, textStatus, errorThrown){
        }
      });
    }
  }

  function show_calendar_view(obj, time_table_data) {
    start_date_ = obj.start_date
    end_date_ = obj.end_date

    start_date_D = new Date(start_date_);
    end_date_D = new Date(end_date_);


    $('#fullcalendar_emp_schedule').fullCalendar({
        height: "auto"
        , header: {
          center: '',
          right: 'today prev,next'
        }
        , isRTL:false
        , monthNames : [
          gettext('fullcal_January'), gettext('fullcal_February'), gettext('fullcal_March'), gettext('fullcal_April')
          , gettext('fullcal_May'), gettext('fullcal_June'), gettext('fullcal_July'), gettext('fullcal_August')
          , gettext('fullcal_September'), gettext('fullcal_October'), gettext('fullcal_November'), gettext('fullcal_December')
        ]
        , monthNamesShort : [
          gettext('fullcal_Jan'), gettext('fullcal_Feb'), gettext('fullcal_Mar'), gettext('fullcal_Apr')
          , gettext('fullcal_May'), gettext('fullcal_Jun'), gettext('fullcal_Jul'), gettext('fullcal_Aug')
          , gettext('fullcal_Sep'), gettext('fullcal_Oct'), gettext('fullcal_Nov'), gettext('fullcal_Dec')
        ]
        , dayNames : [
          gettext('fullcal_Sunday'), gettext('fullcal_Monday'), gettext('fullcal_Tuesday'), gettext('fullcal_Wednesday')
          , gettext('fullcal_Thursday'), gettext('fullcal_Friday'), gettext('fullcal_Saturday')
        ]
        , dayNamesShort : [
          gettext('fullcal_Sun'), gettext('fullcal_Mon'), gettext('fullcal_Tue'), gettext('fullcal_Wed')
          , gettext('fullcal_Thur'), gettext('fullcal_Fri'), gettext('fullcal_Sat')
        ]
        , editable: false
        , fixedWeekCount: false
        , selectable: true
        , select: function (start, end) {
          var daytype = $("input[name=day-type]:checked").val() ? $("input[name=day-type]:checked").val() : 0;
          var events = () => {};
        },
        eventClick: function (event) {}
      });

    function update_weekend(){
        weekend_total = time_table_data.weekend_total
        updated_weekend_total = {}
        for (var key of Object.keys(weekend_total)) {
            new_key = String(Number(key) + 1)
            new_key = (new_key.length == 1) ? "0" + new_key : new_key
            updated_weekend_total[new_key] = weekend_total[key]
        }
        time_table_data.weekend_total = updated_weekend_total
    }

    var cycle_unit = time_table_data.cycle_unit;
    if (cycle_unit != 1){
        update_weekend();
    }

    function loop_dates(start_date_D) {
      let loop = new Date(start_date_D);
      while (loop <= end_date_D) {
        var date = convert(loop);
        set_time_table_data(date, time_table_data);
        let newDate = loop.setDate(loop.getDate() + 1);
        loop = new Date(newDate);
      }
    }
    $('#fullcalendar_emp_schedule').fullCalendar('gotoDate', start_date_D);
    loop_dates(start_date_D);

    $(".fc-next-button").click(
      function() {
        loop_dates(start_date_D);
      }
    );

    $(".fc-prev-button").click(
      function() {
        loop_dates(start_date_D);
      }
    );

    $(".fc-today-button").click(
      function() {
        loop_dates(start_date_D);
      }
    );

  }

  data_grid_opts["rowClick"] = function(obj){
    $("#id_{{ model_name }}SelectedShift").val(JSON.stringify(obj.data));
    $("#id_shift_detail_{{ model_name }} .layui-card-header").text(obj.data.shift_alias);

    var td_tag = $(".fc-content-skeleton").find("tbody").find("tr").find("td");
    for (i=0; i< td_tag.length; i++){
      $(td_tag[i]).text('');
    }

    var schedule = $("#id_{{ model_name }}SelectedShift").val();
    if(schedule){
      var payload = JSON.parse(schedule);
      get_schedule_data();
    }
    show_calendar_view(obj.data, schedule_data);
  }
{% endblock %}
