{% load i18n static %}
{% load common %}
{#{% autoescape off %}#}
{% block extend_js %}
  <link rel="stylesheet" type="text/css" href="{% static "css/fullcalendar.min.css" %}"/>
{% endblock %}

<div style="padding: 10px;min-height: 350px;max-height: 550px;width: 1000px">
   <form action="" method="post" id="leave_apply_save_form" class="layui-form" lay-filter="staff_leave_add">
    <input type="hidden" name="employee" class="layui-hide" value="{{ user.pk }}">
      <input type="hidden" name="leave_schedule" class="layui-hide" value="{{ leave_schedule_data }}">
    {% csrf_token %}
    <div class="layui-row">
      <div class="layui-col-md7" style="width:69%">
        <div class="layui-card">
          <div class="layui-card-body" style="padding: 0 5px;">
            <div id="fullcalendar" style="height: 520px"></div>
          </div>
        </div>
      </div>
      <div class="layui-col-md2" style="width:31%">
          <div class="layui-form-item">
             <div class="layui-inline">
                <input type="radio"  name="day-type" value="1"  title="{% trans 'att_aleave_full_day' %}">
             </div>
             <div class="layui-inline">
                 <p class="fulldata" style="font-size: 15px;"></p>
             </div>
          </div>
          <div class="layui-form-item">
              <div class="layui-inline">
                <input type="radio"   name="day-type" value="2"  title="{% trans 'att_aleave_first_half' %}"><span class="layui-inline "></span>
             </div>
              <div class="layui-inline">
                 <p class="firstdata" style="font-size: 15px;"></p>
             </div>
          </div>
          <div class="layui-form-item">
              <div class="layui-inline">
                <input type="radio"   name="day-type" value="3"  title="{% trans 'att_aleave_second_half' %}"><span class="layui-inline "></span>
             </div>
              <div class="layui-inline">
                 <p class="seconddata" style="font-size: 15px;"></p>
             </div>
          </div>
        <div class="layui-form-item" style="padding-top: 25px;">
        <label class="layui-form-label">{% trans 'staff_leave_leaveType' %}<span class="required">*</span></label>
        <div class="layui-input-block">
            <select id="id_leavetype" name="leave_payment_type" lay-search="" lay-verify="leave_type" autocomplete="off"
                placeholder="" class="layui-input">
                <option value=0>{% trans 'staff_module_pl' %}</option>
                <option value=1>{% trans 'staff_module_upl' %}</option>
            </select>
        </div>
    </div>
        <div class="layui-form-item">
      <label class="layui-form-label">{% trans 'staff_leave_leaveCategory' %}<span class="required">*</span></label>
      <div class="layui-input-block">
        <select id="id_category" name="category" lay-search="" lay-verify="leave_category" autocomplete="off"
                placeholder="" class="layui-input"></select>
      </div>
    <div class="layui-form-item">
      <label class="layui-form-label">{% trans 'staff_leave_dailyquantity' %}<span class="required">*</span></label>
      <div class="layui-input-block">
        <input id="id_daily_quantity" type="text" name="days" autocomplete="off" placeholder="" class="layui-input" readonly>
      </div>
    </div>
          <div class="layui-form-item">
      <label class="layui-form-label">{% trans 'staff_leave_applyReason' %}</label>
      <div class="layui-input-block">
        <input type="textarea" id="id_apply_reason" name="apply_reason" lay-verify="apply_reason" autocomplete="off"
               placeholder="" class="layui-textarea">

      </div>
    </div>
      </div>
    </div>
      <input id="leave_applied_data" type="hidden" name="leave_applied_data" value="">
    </div>
  </form>
</div>
<script>
  $(function () {
    layui.use(['form',], function () {
      form = layui.form;
      $.ajax({
      url: "/att/api/leavecategorys/?page_size=1000"
      , type: "GET"
      , async: false
      , dataType: "json"
      , success: function (response) {
        var data = response.data;
        var html = "";
        for (var i = 0; i < data.length; i++) {
          html += '<option value="' + data[i]['id'] + '">' + data[i]['category_name'] + '</option>';
        }
        $("#id_category").append(html);
        form.render();
      }
      , error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.trace(arguments);
        form.render();
      }
    });

      function getEvents(start) {
        var daytype = $("input[name=day-type]:checked").val() ? $("input[name=day-type]:checked").val() : 0;
        var events = [];
        var leave_applied_data = $('#leave_applied_data').val();
        var count = eval($('#id_daily_quantity').val());
          if (eval(daytype) == 1) {
              if(leave_applied_data){
                  var existing_leave_data = JSON.parse(leave_applied_data);
                  var key = start.toISOString().substring(0, 10);
                  if(key in existing_leave_data){
                      var events = [];
                  }else{
                    $('#id_daily_quantity').val(count+1);
                    existing_leave_data[key] = 1;
                     $('#leave_applied_data').val(JSON.stringify(existing_leave_data));
                    var event = {item: 1, title: 'Full Day'};
                    events.push(event);
                  }
              }else{
                  var new_leave_applied_data = {};
                  var ldate = start.toISOString().substring(0, 10);
                  new_leave_applied_data[ldate] = 1;
                  $('#leave_applied_data').val(JSON.stringify(new_leave_applied_data));
                  var event = {item: 1, title: 'Full Day'};
                  events.push(event);
              }

          } else if (eval(daytype) == 2) {
               if(leave_applied_data){
                  var existing_leave_data = JSON.parse(leave_applied_data);
                  var key = start.toISOString().substring(0, 10);
                  if(key in existing_leave_data){
                      var events = [];
                  }else{
                    $('#id_daily_quantity').val(count+0.5);
                    existing_leave_data[key] = 2;
                     $('#leave_applied_data').val(JSON.stringify(existing_leave_data));
                    var event = {item: 2, title: 'First Half'};
                    events.push(event);
                  }
              }else{
                  var new_leave_applied_data = {};
                  var ldate = start.toISOString().substring(0, 10);
                  new_leave_applied_data[ldate] = 2;
                  $('#leave_applied_data').val(JSON.stringify(new_leave_applied_data));
                  var event = {item: 2, title: 'First Half'};
                  events.push(event);
              }
          } else if (eval(daytype) == 3) {
               if(leave_applied_data){
                  var existing_leave_data = JSON.parse(leave_applied_data);
                  var key = start.toISOString().substring(0, 10);
                  if(key in existing_leave_data){
                      var events = [];
                  }else{
                    $('#id_daily_quantity').val(count+0.5);
                    existing_leave_data[key] = 3;
                     $('#leave_applied_data').val(JSON.stringify(existing_leave_data));
                    var event = {item: 3, title: 'Second Half'};
                    events.push(event);
                  }
              }else{
                  var new_leave_applied_data = {};
                  var ldate = start.toISOString().substring(0, 10);
                  new_leave_applied_data[ldate] = 3;
                  $('#leave_applied_data').val(JSON.stringify(new_leave_applied_data));
                  var event = {item: 3, title: 'Second Half'};
                  events.push(event);
              }
          } else {
              layer.alert(gettext('Please_select_leave_day_type'),
                                            {title: gettext('system_exception')
                                            , icon: 5
                                            , btn: gettext('btn_confirm')}
                                        );

          }
          if(leave_applied_data){

          }else{
              if(eval(daytype) == 1){
                $('#id_daily_quantity').val(1);
              }else if(eval(daytype) == 2){
                $('#id_daily_quantity').val(0.5);
              }else if(eval(daytype) == 3){
                $('#id_daily_quantity').val(0.5);
              }
          }


            return events;
      }

      $('#fullcalendar').fullCalendar({
        height: 520
        , 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
        , selectable: true
        , select: function (start, end) {
          var daytype = $("input[name=day-type]:checked").val() ? $("input[name=day-type]:checked").val() : 0;
          if(daytype > 0){

            getInOutTime(start,daytype,event._id)
          }
          function getWeekendDetails(start,ts){
              var cdate = start.toISOString().substring(0, 10);
              $.ajax({
                    url: "att/api/empScheduleReport/?employees={{ user.pk }}&start_date="+cdate+ "&end_date="+cdate
                    , type: "GET"
                    , dataType: "json"
                    , success: function (response) {
                        data = response["data"][0];
                        console.log(data);
                        var cdatekey = cdate.replace("-", '');
                        var cdatekey = cdatekey.replace("-", '');
                      if(data[cdatekey]=='Weekend'){
                            layer.alert(gettext("Sorry_you_cannot_apply_leave_on_week_off"),
                                            {title: gettext('system_exception')
                                            , icon: 5
                                            , btn: gettext('btn_confirm')}
                                        );
                            $('#fullcalendar').fullCalendar('removeEvents', ts);
                             var leave_applied_data = $('#leave_applied_data').val();
                            $('#leave_applied_data').val('');
                            $('#id_daily_quantity').val(0);
                      }else if(!(cdatekey in data)){
                            layer.alert(gettext("Sorry_you_cannot_apply_leave_on_week_off"),
                                            {title: gettext('system_exception')
                                            , icon: 5
                                            , btn: gettext('btn_confirm')}
                                        );
                            $('#fullcalendar').fullCalendar('removeEvents', ts);
                             var leave_applied_data = $('#leave_applied_data').val();
                            $('#leave_applied_data').val('');
                            $('#id_daily_quantity').val(0);
                      }
                    }
                });

          }
          function getInOutTime(start, daytype, ts){
            return new Promise(function(resolve, reject) {
                var cdate = start.toISOString().substring(0, 10);
                $.ajax({
                    url: "/att/getInOutTimes/?date="+cdate+ "&day_type="+daytype
                    , type: "GET"
                    , dataType: "json"
                    , success: function (response) {
                       if(daytype==1){
                           $('.fulldata').html("In : "+response['in_time']+" Out : "+response['out_time']);
                       }else if(daytype==2){
                            $('.firstdata').html("In : "+response['in_time']+" Out : "+response['firsthalf_out_time']);
                       }else{
                            $('.seconddata').html("In : "+response['secondhalf_in_time']+" Out : "+response['out_time']);
                       }
                       getWeekendDetails(start,event._id);
                    }, error: function(err) {
                        layer.alert(err.responseText,
                                            {title: gettext('system_exception')
                                            , icon: 5
                                            , btn: gettext('btn_confirm')}
                                        );
                        $('#fullcalendar').fullCalendar('removeEvents', ts);
                        var leave_applied_data = $('#leave_applied_data').val();
                        $('#leave_applied_data').val('');
                        $('#id_daily_quantity').val(0);
                    }
                });

            });
          }

          var events = getEvents(start);
          if (events.length > 0) {
            events.forEach(function (item, index) {
              var event = $.extend({start: start, end: end}, item);
              $('#fullcalendar').fullCalendar('renderEvent', event, true); // stick? = true
            });
          } else {
            $('#fullcalendar').fullCalendar('unselect');
          }

        },
        eventClick: function (event) {
          $('#fullcalendar').fullCalendar('removeEvents', event._id);
          var leave_applied_data = $('#leave_applied_data').val();
          var ldate = event.start;
          var key = ldate.toISOString().substring(0, 10);
          var existing_leave_data = JSON.parse(leave_applied_data);
          delete existing_leave_data[key];
          $('#leave_applied_data').val(JSON.stringify(existing_leave_data));
          var count = 0;
          for(var x in existing_leave_data){
            if(x) {
                if (existing_leave_data[x] == 1) {
                    count += 1;
                } else {
                    count += 0.5;
                }
            }
          }
          $('#id_daily_quantity').val(count);
        }
      });

    });
  });
</script>
{#{% endautoescape %}#}

