{% extends "data_grid.html" %}
{% load i18n iclock_tags %}
{% block main_body %}
<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-md9">
      <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-md3">
    <div id="id_shift_detail_{{ model_name }}" class="layui-card">
      <div class="layui-card-header" style="background-color: #e6e6e6">
        {% trans 'shiftDetail_grid_detailLabel' %}
      </div>
      <div class="layui-card-body">
        <form class="layui-form" id="{{ model_name }}SearchForm">
          <div class="layui-form-item">
              <div class="layui-input-inline" style="width: 100px !important;">
                <input class="layui-input"  autocomplete="off" style="width: 100px !important;" data-date-format="yyyy-mm-dd" id="{{ model_name }}_start_date">
              </div>
            <div class="layui-form-mid">-</div>
              <div class="layui-input-inline" style="width: 100px !important;">
                <input class="layui-input"  autocomplete="off" style="width: 100px !important;" data-date-format="yyyy-mm-dd" id="{{ model_name }}_end_date">
            </div>
            <div class="layui-inline">
              <div id="id_{{ model_name }}_search" class="button-3d">
                <i class="fa fa-fw fa-search"></i>
              </div>
            </div>
          </div>
        </form>
        <div id="id_{{ model_name }}ShiftDetail" style="overflow-y: scroll"></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){
    if(t1 == t2){
      return "";
    }
    else{
      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){
    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>';
    if(holiday){
      var alias = [];
      holiday.forEach(function(item){
        alias.push(item['alias'])
      })
      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>';
    }
    return v.format('MM.DD')+sup;
  }
  var createTZTable = function(response, start_date, end_date, payload){
    var cycle = parseInt(response.shift[2]);
    var unit = parseInt(response.shift[3]);
    var holidays = response.holidays;
    var weekend = response.weekend;
    var shift_start = Date.parse(payload.start_date), shift_end = Date.parse(payload.end_date);
    var search_start = Date.parse(start_date), search_end = Date.parse(end_date);
    var start = 0, end = 0;
    if(shift_start > search_end || shift_end < search_start){
      //_start_date = new Date(start_date.replace(/-/g,'/'));
    }else if(shift_start >= search_start && shift_end <= search_end){
      start = Math.floor((shift_start - search_start)/(24 * 60 * 60 * 1000));
      end = Math.floor((shift_end - search_start)/(24 * 60 * 60 * 1000));
    }else if(shift_start >= search_start && shift_end >= search_end){
      start = Math.floor((shift_start - search_start)/(24 * 60 * 60 * 1000));
      end = Math.floor((search_end - search_start)/(24 * 60 * 60 * 1000));
    }else if(shift_start <= search_start && shift_end <= search_end){
      start = 0;
      end = Math.floor((shift_end - search_start)/(24 * 60 * 60 * 1000));
    }else if(shift_start <= search_start && shift_end >= search_end){
      start = 0;
      end = Math.floor((search_end - search_start)/(24 * 60 * 60 * 1000));
    }
    //_start_date = new Date(start_date.replace(/-/g,'/'));
    _start_date = moment(start_date, "YYYY-MM-DD");
    _shift_start = moment(shift_start).format("YYYY-MM-DD");
    console.log(_start_date.diff(_shift_start, 'day'))
    var time_detal = _start_date.diff(_shift_start, 'day');
    var total_days = 0, begin=0;
    begin = 0
    unit_days = 1
    if(unit == 0){
      begin = 0
      unit_days = 1
    }else if(unit == 1){
      unit_days = 7
      begin = _start_date.format('d');
    }else if(unit == 2){
      unit_days = 31;
      begin = _start_date.format('D') - 1;
    }
    total_days = cycle * unit_days;
    begin = parseInt(begin) + parseInt(time_detal / unit_days) % cycle * unit_days
    var detail = response.data;
    var days = Math.floor((search_end - search_start)/(24 * 60 * 60 * 1000)) + 1;
    var data = response.data;
    var r = 0, tbs = [];
    for(var i=0; i<total_days; i++){
      if(data.length < r || data.length == 0){
        break;
      }
      if(data.length == r && i==total_days){
        break;
      }else if(data.length == r && i !=total_days){
        var left_days = total_days - i;
        for (var t=0; t<left_days; t++){
            tbs.push("");
        }
        break;
      }
      var day = Math.floor(data[r].start_time);
      if(day == i){
        var sub = [];
        while(r < data.length){
          var day = Math.floor(data[r].start_time);
          if(day == i){
            sub.push(data[r]);
          }else{
            break;
          }
          r += 1;
        }
        tbs.push(sub);
      }else{
        tbs.push("");
      }
    }
    var html='<div style="display:block"><div id="id_timezone_header"></div><table class="timezone-table">';
    if(days > 0){
      var this_day = 0;
      var pos = begin;
      while(this_day < days){
        if(pos >= tbs.length){
          pos = 0;
        }
        if(end >= 0 && start <= this_day && this_day <= end){
          var _days = (this_day - start), _tbs=tbs[pos];
          if(_tbs == ""){
            html+='<tr><td class="timezones-week">'+getDayLabel(this_day, _start_date, weekend, holidays)+'</td><td class="timezones-container" ></td></tr>';
          }else{
            html+='<tr><td class="timezones-week">'+getDayLabel(this_day, _start_date, weekend, holidays)+'</td><td class="timezones-container" >';
            if(_tbs){
              _tbs.forEach(function(tb){
                var color = tb['Color']==undefined?' ':' background-color: #'+(tb['Color']).toString(16);
                var display = showTimetable(tb.start_time-Math.floor(tb.start_time), tb.end_time-Math.floor(tb.end_time));
                html+='<div alt0="'+tb.start_time+'" alt1="'+tb.end_time+'" alt2="'+getTZDateAlt(this_day, _start_date)+'" alt4="'+tb.id+'" style="text-align: center; width: 100%;" class="tzbar"><span title="'+tb.alias+'" style="color:red;font-size:10px;vertical-align:top;">'+display+'</span></div>';
              })
            }
            html+='</td></tr>';
          }
          pos += 1;
        }else{
          html+='<tr><td class="timezones-week">'+getDayLabel(this_day, _start_date, weekend, holidays)+'</td><td class="timezones-container" ></td></tr>';
        }
        this_day += 1;
      }
    }
    html+='<tr style="background: #ccc;display:none;"><td colspan="2" style="height:2px;"></td></tr></table></div>'
    return html;
  };
  var scheduleDetail = function(payload){
    var start_date = $("#{{ model_name }}_start_date").val();
    var end_date = $("#{{ model_name }}_end_date").val();
    console.log(payload)
    $.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){
        var panel = createTZTable(response, start_date, end_date, payload);
        $("#id_{{ model_name }}ShiftDetail").html(panel)
        var height = $("#{{ model_name }}_fluid .layui-table-view").height() - 85;
        $("#id_{{ model_name }}ShiftDetail").css('height', height+"px");
      }
      ,error: function(XMLHttpRequest, textStatus, errorThrown){

      }
    });
  };
  $("#id_{{ model_name }}_search").click(function(){
    var schedule = $("#id_{{ model_name }}SelectedShift").val();
    if(schedule){
      var payload = JSON.parse(schedule);
      scheduleDetail(payload);
    }
  })
  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 %}
  $.extend(true, dimension, {
    actions: {
      AddAttSchedule: [undefined, Math.ceil(window.innerHeight * 0.8)]
    }
  });

  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);
    scheduleDetail(obj.data);
  }
{% endblock %}
