<?php
/**
 * The calendar view file of todo module of ZenTaoPMS.
 *
 * @copyright   Copyright 2009-2018 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
 * @license     ZPL (http://zpl.pub/page/zplv12.html)
 * @author      chujilu <chujilu@cnezsoft.com>
 * @package     todo
 * @version     $Id$
 * @link        http://www.zdoo.com
 */
?>
<?php include '../../../sys/my/view/header.html.php';?>
<?php include '../../../sys/common/view/datepicker.html.php';?>
<?php include '../../../sys/common/view/calendar.html.php';?>
<?php js::set('account', $this->app->user->account);?>
<?php js::set('settings', new stdclass());?>
<?php js::set('settings.startDate', $date == 'future' ? date('Y-m-d') : date('Y-m-d', strtotime($date)));?>
<?php js::set('settings.data', $data);?>
<?php js::set('users', $users);?>
<?php js::set('zentaoEntryList', array_keys($zentaoEntryList));?>
<?php js::set('mainPaddingRight', $lang->todo->mainPaddingRight);?>

<div class="main-row fade<?php if($this->cookie->todoCalendarSide == 'hide') echo ' hide-side';?>" id='mainRow'>
  <div class="main-col">
    <div class="cell">
      <div id="todoCalendar" class="calendar">
        <header class="calender-header table-row">
          <div class="btn-toolbar col-4 table-col text-middle">
            <button type="button" class="btn btn-primary btn-sm btn-today"><?php echo $lang->today;?></button>
            <div class='btn-group'>
              <button type="button" class="btn btn-sm btn-prev"><i class="icon-angle-left"></i></button>
              <button type="button" class="btn btn-sm btn-next"><i class="icon-angle-right"></i></button>
            </div>
            <span class="calendar-caption"></span>
          </div>
          <div class="col-4 table-col"></div>
          <div class="col-4 table-col text-right">
            <div class='day trash' data-date='1970-01-01' title='<?php echo $lang->delete?>'>
              <span class="tip"><?php echo $lang->todo->deleteTip;?></span>
              <span class='btn'><i class="icon icon-delete"></i></span>
            </div>
            <div class='side-handle'>
              <?php $class = $this->cookie->todoCalendarSide == 'hide' ? 'icon-collapse-full' : 'icon-expand-full'?>
              <?php echo html::a('###', "<i class='icon $class'></i>", "class='btn' id='sidebarToggleBtn'")?>
            </div>
          </div>
        </header>
      </div>
    </div>
  </div>
  <div class="side-col">
    <div class="cell" id='sidebar'>
      <ul id='myTab' class='nav nav-secondary nav-justified'>
        <li class='active'><a href='#tab_undone' data-toggle='tab'><?php echo $lang->todo->periods['before']?></a></li>
        <li><a href='#tab_custom' data-toggle='tab'><?php echo $lang->todo->periods['future']?></a></li>
        <li><a href='#tab_task' data-toggle='tab'><?php echo $lang->task->common;?></a></li>
        <li><a href='#tab_order' data-toggle='tab'><?php echo $lang->order->common;?></a></li>
        <li><a href='#tab_customer' data-toggle='tab'><?php echo $lang->customer->common;?></a></li>
        <?php if(!empty($zentaoEntryList)):?>
        <li class='dropdown'>
          <a data-toggle='dropdown' class='dropdown-toggle' href='#'><?php echo $lang->entry->common;?><b class='caret'></b></a>
          <ul aria-labelledby='myTabDrop1' role='menu' class='dropdown-menu pull-right'>
            <?php foreach($zentaoEntryList as $code => $name):?>
            <li><a data-toggle='tab' tabindex='-1' href="<?php echo "#tab_{$code}";?>"><?php echo $name;?></a></li>
            <?php endforeach;?>
          </ul>
        </li>
        <?php endif;?>
      </ul>
      <div class='tab-content' id="todoLists">
        <?php if(!empty($todoList)):?>
        <?php foreach($todoList as $type => $todoSides):?>
        <div class='tab-pane fade <?php if($type == 'undone') echo 'active in';?>' id='tab_<?php echo $type;?>'>
          <?php if(!empty($todoSides)):?>
          <ul class='todo-list'>
          <?php $i = 1;?>
          <?php foreach($todoSides as $id => $todo):?>
            <?php if($type == 'custom' or $type == 'undone'):?>
            <li data-index='<?php echo $i++;?>'>
              <?php
              $viewLink = $this->createLink('todo', 'view', "id=$todo->id");
              echo html::a("javascript:void(0)", $todo->name, "class='iframe todo-item' data-id='$id' data-type='$todo->type' data-remote='$viewLink' data-todo-name='$todo->name' data-begin='$todo->begin' data-end='$todo->end' data-action='edit' data-target='.day' data-toggle='droppable' data-width='1060px'");
              ?>
            </li>
            <?php endif;?>
          <?php endforeach;?>
          </ul>
          <?php endif;?>
        </div>
        <?php endforeach;?>
        <?php endif;?>
      </div>
    </div>
  </div>
</div>
<script>
function updateCalendar(todoID)
{
    var $calendar = $('#todoCalendar');

    if(todoID)
    {
        $('#todoLists .todo-item[data-id="' + todoID + '"]').remove();
        if(!$calendar.find('.event[data-id="' + todoID + '"]').length) return;
    }

    var calendar = $calendar.data('zui.calendar');

    $calendar.find('.label-rest').remove();

    var date = calendar.date.format('yyyyMMdd');
    $.get(createLink('todo', 'calendar', 'date=' + date, 'json'), function(response)
    {
        if(response.status == 'success')
        {
            var data = JSON.parse(response.data);
            for(e in data.data.events)
            {
                data.data.events[e]['start'] = new Date(data.data.events[e]['start']);
                data.data.events[e]['end']   = new Date(data.data.events[e]['end']);
            }
            calendar.events = data.data.events;
            calendar.sortEvents();
            v.settings.data.events = data.data.events;
            calendar.display();
        }
    }, 'json');
}

/* Finish a todo. */
function finishTodo(id)
{
    $.get(createLink('todo', 'finish', 'todoId=' + id, 'json'),function(response)
    {
        if(response.result == 'success')
        {
            if(response.confirm)
            {
                if(confirm(response.confirm.note))
                {
                    $.openEntry(response.confirm.entry, response.confirm.url);
                }
            }
        }
        else
        {
            if(response.message) $.zui.messager.show(response.message);
        }
        updateCalendar();
        return false;
    }, 'json');
}

/* Add calendar event handler. */
v.date = new Date();
v.d    = v.date.getDate();
v.m    = v.date.getMonth();
v.y    = v.date.getFullYear();

if(typeof(v.settings) == 'undefined') v.settings = {};
if(typeof(v.settings.data) == 'undefined') v.settings.data = {};
var handleClickCell = function(event)
{
    if(event.view == 'month')
    {
        var date  = event.date;
        var year  = date.getFullYear();
        var month = date.getMonth();
        var day   = date.getDate();
        if(year > v.y || (year == v.y && month > v.m) || (year == v.y && month == v.m && day >= v.d))
        {
            month = month + 1;
            if(day <= 9)   day   = '0' + day;
            if(month <= 9) month = '0' + month;
            var todourl = createLink('todo', 'batchCreate', "date=" + year + '' + month + '' + day, '', true);

            $.zui.modalTrigger.show({width: '85%', url: todourl, backdrop: 'static'});
        }
    }
};

var handleBeforeChange = function(event)
{
    if(event.change == 'start')
    {
        var data = {
            'date': event.to.format('yyyy-MM-dd'),
            'name': event.event.title,
            'type': event.event.calendar
        }
        if(!event.event.allDay)
        {
            data.begin = event.event.start.format('hh:mm');
            data.end = event.event.end.format('hh:mm');
        }
        if(data.date == '1970-01-01')
        {
            /* Delete. */
            var link = createLink('todo', 'delete', 'id=' + event.event.id);
        }
        else
        {
            /* Edit. */
            var link = createLink('todo', 'edit', 'id=' + event.event.id);
        }

        $.post(link, data, function(response)
        {
            updateCalendar();
        }, 'json');
    }
};

var handleEventCreator = function(event, $cell, calendar)
{
    var finish = event.data.status == 'done' || event.data.status == 'closed';
    var canFinish = (event.data.status != 'done' && event.data.status != 'closed') && (event.data.assignedTo == '' || event.data.assignedTo == v.account) && (event.calendar != 'trip' && event.calendar != 'leave' );
    var $event = $('<div title="' + event.title + '" data-id="' + (event.id || '') + '" class="event"><span class="title">' + event.title + '</span>' + (event.allDay ? '' : '<span class="time">' + event.start.format('hh:mm') + '</span>') + (canFinish ? '<span class="todo-finish event-btn"><?php echo $lang->todo->finish?></span>' : '') + '</div>');
    $event.toggleClass('wait', !finish).toggleClass('can-finish', !!canFinish).toggleClass('finish', !!finish).toggleClass('has-time', !event.allDay).toggleClass('expired', !finish && !$cell.hasClass('future'));

    var $assignTo;
    if(typeof(event.data.assignedBy) != 'undefined' && event.data.assignedBy != '' && event.data.assignedBy != v.account && event.data.assignedTo == v.account)
    {
        $assignTo = $("<span title='<?php echo $lang->todo->assignedBy;?>' class='assign'>" + v.users[event.data.assignedBy] + "<\/span>");
    }
    if(event.data.assignedTo != '' && event.data.assignedTo != v.account)
    {
        $assignTo = $("<span title='<?php echo $lang->todo->assignedTo;?>' class='assign'>" + v.users[event.data.assignedTo] + "<\/span>");
    }
    if($assignTo)
    {
        $assignTo.prependTo($event.children('.title'));
        $event.addClass('assigned').removeClass('wait');
    }
    return $event;
};

var handleFormatDay = function($cell, date, events, calendar)
{
    $cell.toggleClass('with-plus-sign', $cell.hasClass('future'));
};

var sortTodoEvents = function(a, b)
{
    var result = ((a.data.status == 'done' || a.data.status == 'closed') ? 1 : 0) - ((b.data.status == 'done' || b.data.status == 'closed') ? 1 : 0);
    if (result === 0) result = (a.allDay ? 1 : 0) - (b.allDay ? 1 : 0);
    if (result === 0) result = a.start > b.start ? 1 : (a.start < b.start ? (-1) : 0);
    if (result === 0) result = a.id < b.id ? (-1) : 1;
    return result;
};

$.extend(v.settings,
{
    clickCell: handleClickCell,
    beforeChange: handleBeforeChange,
    eventCreator: handleEventCreator,
    dayFormater: handleFormatDay,
    clickNextBtn: updateCalendar,
    clickPrevBtn: updateCalendar,
    clickTodayBtn: updateCalendar,
    hideEmptyWeekends: true,
    eventSorter: sortTodoEvents
});

$(function()
{
    $('#todoCalendar').on('click', '.event .todo-finish', function()
    {
          var id = $(this).closest('.event').data('id');
          finishTodo(id);
    });
});
</script>
<?php include '../../common/view/footer.html.php';?>
