{% load i18n static common %}
<style>
  #{{ model_name }}_edit_form .layui-form-switch {
    margin-top: 0px;
  }

</style>
{% autoescape off %}
<div id="{{ model_name }}_edit_form" style="padding: 10px;height: 390px">
  <form class="layui-form data-form shift-add-form" action="" method="post" lay-filter="shiftForm">
    <input type="hidden" id="id_model_pk" name="pk" value="{{ object_id }}">
    <input type="hidden" id="id_days" name="days" class="layui-hide">
    {% csrf_token %}
    <div class="layui-row">
      <div class="layui-col-md12">
        <div class="layui-card">
          <div class="layui-card-body">
            <div class="layui-form-item">
                {% layui_inline adminform.form.alias %}
                {% layui_switch adminform.form.auto_shift %}
                <div class="layui-inline" title>
                  <label for="" class="layui-form-label">Week off</label>
                  <div class="layui-input-inline">
                    <input type="checkbox" name="weekend" id="weekend-flag" lay-skin="primary">
                  </div>
                </div>
            </div>
          </div>
        </div>
      </div>
      <div class="layui-col-md5">
        <div class="layui-card">
          <div class="layui-card-header" style="padding: 0 0 0 3px;background-color: #f2f2f2;">
            <div class="layui-form">
              <div class="layui-form-item">
                <div class="layui-inline">
                  <div class="layui-input-inline">
                    <input id="id_frameTimetableSearch" type="text"
                           placeholder="{% trans 'schedule_timetableFrameSearch_placeholder_timetable' %}"
                           name="frame-timetabel-search" autocomplete="off"
                           class="layui-input">
                  </div>
                </div>
                <div class="layui-inline">
                  <div class="button-3d" lay-submit="" lay-filter="timetableSearch"
                       style="background-color: #f2f2f2;padding: 0 10px;">
                    <i class="fa fa-fw fa-search"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="layui-card-body">
            <table id="schedule_timetable" class="layui-hide" lay-filter="scheduleTimetable"></table>
          </div>
        </div>
      </div>
      <div class="layui-col-md7" style="padding: 0 0 0 10px">
        <div class="layui-card">
          <div class="daily-shift-attr layui-card-header" style="background-color: #f2f2f2;"><div class="layui-form">
            <div class="layui-form-item">
              {% layui_inline adminform.form.cycle_unit %}
              {% layui_inline adminform.form.shift_cycle %}
            </div>
            <div class="layui-form-item layui-hide">
              {% layui_inline adminform.form.daily_shift %}
              {% layui_inline adminform.form.daily_shift_display %}
            </div>
          </div></div>
          <div class="layui-card-body">
            <table id="id_dailyShift" class="layui-hide" lay-filter="dailyShift"></table>
          </div>
        </div>
      </div>
      <div class="layui-col-md12">
        <div class="layui-card"><div class="layui-card-body">
          <div><span style="color: red">*</span><span>{% trans 'shift_helpText_title' %}</span></div>
          <div style="padding: 0 20px;">
            <p>{% trans 'shift_helpText_tip1' %}</p>
            <p>{% trans 'shift_helpText_tip2' %}{% trans 'shift_helpText_tip3' %}{% trans 'shift_helpText_tip4' %}</p>
          </div>
        </div></div>
      </div>
    </div>
  </form>
</div>
<script>
  $(function () {
    layui.use(['form', 'laydate', 'table', 'tablePlug', 'layer'], function () {
      var table = layui.table, tablePlug = layui.tablePlug, form = layui.form, layer = layui.layer;
      tablePlug.smartReload.enable(true);
			$("#id_cycle_unit").attr('lay-filter','cycleUnit');
      var timetableOpts = {
        id: 'schedule_timetable'
        , elem: "#schedule_timetable"
        , height: 275
        , text: {none: gettext('none_data')}
        , request: {
          pageName: 'page',
          limitName: 'page_size'
        }
        , page: {
          layout: ['count', 'prev', 'page', 'next', 'limit']
          , limit: 50
          , limits: [20, 50, 80, 100, 200]
          , groups: 1
        }
        , cols: [[
          {field: 'id', type: 'checkbox'},
          {field: 'alias', title: "{% trans 'timeInterval_field_alias' %}"},
          {field: 'in_time', title: "{% trans 'timeInterval_field_checkIn' %}"},
          {field: 'out_time', title: "{% trans 'timeInterval_field_checkOut' %}", templet: function (data) {
            if(data.cross_day > 0){
                return data.out_time + '<sup>+'+data.cross_day + '</sup>';
            }else{
                return data.out_time;
            }
          }},
          {field: 'break_time_duration', title: "{% trans 'timeInterval_field_breakTime' %}"}
        ]]
        , url: '/att/api/timeintervals/'
      };
      var timeTable = table.render(timetableOpts);
      var week = [
        gettext('weekday_shortWrite_sunday'), gettext('weekday_shortWrite_monday'),
        gettext('weekday_shortWrite_tuesday'), gettext('weekday_shortWrite_wednesday'),
        gettext('weekday_shortWrite_thursday'), gettext('weekday_shortWrite_friday'),
        gettext('weekday_shortWrite_saturday')
      ];
      var week_cols = [[{field: 'cycle', title: '', fixed: true, type: 'numbers'}]];
      for(var i=0; i < week.length; i ++){
        week_cols[0].push({field: i.toString(), title: week[i], event:'assignTimeTable'+i});
      }
      var dailyShiftOpts = {
        id: 'id_dailyShift'
        , elem: "#id_dailyShift"
        , height: 275
        , text: {none: gettext('none_data')}
        , request: {
          pageName: 'page',
          limitName: 'page_size'
        }
        , page: false
        , limit: 366
        , cols: week_cols
        , data: []
      };
      {#var dailyShiftTable = table.render(dailyShiftOpts);#}
      var shift_days = {
        0: 1,
        1: 7,
        2: 31
      };
      {#var check_unit = $("#id_cycle_unit").val();#}
      table.on('tool(dailyShift)', function(obj){
        var cycle_unit = $("#id_cycle_unit").val();
        var event = obj.event.replace('assignTimeTable', '');
        var checkStatus = table.checkStatus('schedule_timetable');
        var weekend_flag = $("#weekend-flag").is(":checked");
        var days = shift_days[cycle_unit];
        var daily_shift_string = $("#id_daily_shift").val();
        var daily_shift = {};
        var item = {};
        if(checkStatus.data != ''){
            var tbs = [], tbIDs = [];
            if(weekend_flag){
                tbs[0] = 'Week off';
                tbIDs[0] = 'w';
            }
            checkStatus.data.forEach(function (item, index) {
                tbs.push(item.alias);
                tbIDs.push(item.id);
            });
            item[event] = tbs.join(',');
            if (obj.data[event] === item[event]){
              item[event] = ""
            }
            obj.update(item);
            if (daily_shift_string !== "") {
                daily_shift = JSON.parse(daily_shift_string);
            }
            var shift_index = ((parseInt(obj.data.cycle) - 1) * days) + parseInt(event);
            if (daily_shift[shift_index] === tbIDs.join(',')){
              daily_shift[shift_index] = ""
            }else{
              daily_shift[shift_index] = tbIDs.join(',');
            }
            $("#id_daily_shift").val(JSON.stringify(daily_shift));
        }else {
          layer.alert(gettext('Please_select_the_time_table'), {
            title: gettext('system_exception')
            , icon: 5
            , btn: gettext('btn_confirm')
          })
        }
      });
      form.render();
      var old_data;
      function cycleUnitChange(cycle, unit) {
        old_data = JSON.parse($("#id_daily_shift_display").val());
        var len = JSON.parse($("#id_daily_shift_display").val()).length;

           if (dailyShiftOpts.data.length){
              old_data = dailyShiftOpts.data;
          }
          else {
              old_data = JSON.parse($("#id_daily_shift_display").val())
           }
        var len = old_data.length;
        switch (unit) {
          case 0:
            $("#id_shiftCycle").attr("max", '366');
            if (cycle > 366) {
              layer.msg(gettext('shift_cycleError_dayCycleExceed366'), {icon: 5});
              $("#id_shift_cycle").val('');
              return;
            }
            var _cols = [[{field: 'cycle', title: '', fixed: true, type: 'numbers'}]];
            _cols[0].push({field: '0', title: "{% trans 'att_model_timeInterval' %}", event: 'assignTimeTable0'});

            var _data = old_data;
            {#if (check_unit  != unit){#}
            {#    _data = [];#}
            {#    len = 0;#}
            {#    $("#id_daily_shift").val("");#}

            for (var c = len; c < cycle; c++) {
              _data.push({cycle: c+1, 0: ''});
            }
            if(_data.length != cycle){
                var diff = Math.abs(_data.length - cycle);
                for (var c = 0; c < diff; c++) {
                    _data.pop();
                }
            }
            dailyShiftOpts['cols'] = _cols;
            dailyShiftOpts['data'] = _data;
            table.render(dailyShiftOpts);
            break;
          case 1:
            $("#id_shift_cycle").attr("max", '52');
            if (cycle > 52) {
              layer.msg(gettext('shift_cycleError_weekCycleExceed52'), {icon: 5});
              $("#id_shift_cycle").val('');
              return;
            }
            var _data = old_data;
            {#if (check_unit  != unit){#}
            {#    _data = [];#}
            {#    len = 0;#}
            {#    $("#id_daily_shift").val("");#}

            for (var c = len; c < cycle; c++) {
              _data.push({cycle: c+1, 0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: ''});
            }
            if(_data.length != cycle){
                var diff = Math.abs(_data.length - cycle);
                for (var c = 0; c < diff; c++) {
                    _data.pop();
                }
            }
            dailyShiftOpts['cols'] = week_cols;
            dailyShiftOpts['data'] = _data;
            table.render(dailyShiftOpts);
            break;
          case 2:
            $("#id_shift_cycle").attr("max", '12');
            if (cycle > 12) {
              layer.msg(gettext('shift_cycleError_monthCycleExceed12'), {icon: 5});
              $("#id_shift_cycle").val('');
              return;
            }
            var _cols = [[{field: 'cycle', title: '', fixed: true, type: 'numbers'}]];
            var _data = old_data;
            {#if (check_unit  != unit){#}
            {#    _data = [];#}
            {#    len = 0;#}
            {#    $("#id_daily_shift").val("");#}

            for (var j = 0; j < 31; j++) {
              _cols[0].push({field: j.toString(), title: (j + 1), event: 'assignTimeTable'+j})
            }
            for (var c = len; c < cycle; c++) {
              var item = {cycle: (c + 1)};
              for (i = 0; i < 31; i++) {
                item[i] = '';
              }
              _data.push(item);
            }
            if(_data.length != cycle){
                var diff = Math.abs(_data.length - cycle);
                for (var c = 0; c < diff; c++) {
                    _data.pop();
                }
            }
            dailyShiftOpts['cols'] = _cols;
            dailyShiftOpts['data'] = _data;
            table.render(dailyShiftOpts);
            break;
          default:
            break;
        }
        form.render();
      };
      var _cycle = $("#id_shift_cycle").val();
      var _unit = $("#id_cycle_unit").val();
      cycleUnitChange(parseInt(_cycle), parseInt(_unit));
      dailyShiftOpts['data'] = JSON.parse($("#id_daily_shift_display").val());
      table.render(dailyShiftOpts);
      form.on('select(cycleUnit)', function (data) {
        var unit = data.value;
        var cycle = $("#id_shift_cycle").val();
        dailyShiftOpts.data = [];
        $("#id_daily_shift").val("");
        $("#id_daily_shift_display").val("[]");
        cycleUnitChange(parseInt(cycle), parseInt(unit));
        {#$("#id_daily_shift").val("");#}
      });
      $("#id_shift_cycle").change(function () {
        var unit = $("#id_cycle_unit").val();
        var cycle = $(this).val();
        var weekend_flag = $("#weekend-flag");
        //if(cycle > 1){
        //  weekend_flag.attr('checked', false);
        //  weekend_flag.attr('disabled', 'disabled');
        //}else if(cycle == 1){
        //  weekend_flag.removeAttr('disabled');
        //}
        cycleUnitChange(parseInt(cycle), parseInt(unit));
        {#$("#id_daily_shift").val("");#}
      });
      form.on('submit(timetableSearch)', function () {
        var alias = $("#id_frameTimetableSearch").val();
        table.reload(timeTable.config.id, {where: {alias__icontains: alias}});
      });
      $("#id_frameTimetableSearch").keypress(function (event) {
        if (event.keyCode == "13") {
          var alias = $(this).val();
          table.reload(timeTable.config.id, {where: {alias__icontains: alias}});
        }
      });
    });
  });
</script>
{% endautoescape %}
