var angular = require('angular');
require('jsUtil');
require('../modules');
require('./TaskRepository');
require('./taskMessages');
require('./taskList');
require('./taskDrafts');
require('./delaySaveTasks');
require('./delaySaveDiscussions');
require('./CurrentTaskService');
require('../../login/services/LoginService');

'use strict';

var module = angular.module('task.services');

module.run(function(TaskRepository, $rootScope, taskMessages, taskList, taskDrafts,
  delaySaveTasks, delaySaveDiscussions, CurrentTaskService) {
  function generateEventHandler(obj, fn) {
    return function(event, data) {
      obj[fn](_.isArray(data.content) ? data.content : data);
    };
  }

  $rootScope.$on('task.add', generateEventHandler(TaskRepository, 'addOrUpdateTasks'));
  $rootScope.$on('task.update', generateEventHandler(TaskRepository, 'addOrUpdateTasks'));
  //$rootScope.$on('task.discussion.add', generateEventHandler(TaskRepository, 'addDiscussion'));

  var callbackWithIdEventHandler = function(obj, fn) {
    return function(event, taskId) {
      TaskRepository.getTaskById(taskId).then(function(task) {
        obj[fn](task);
      });
    };
  };

  //消息列表数据同步
  $rootScope.$on('task.add', generateEventHandler(taskMessages, 'insert'));
  $rootScope.$on('task.update', generateEventHandler(taskMessages, 'insert'));
  $rootScope.$on('task.remove', callbackWithIdEventHandler(taskMessages, 'remove'));
  $rootScope.$on('task.complete', callbackWithIdEventHandler(taskMessages, 'insert'));

  var setLatestMessageOfTask = function(event, data) {
    var addDiscussion = function(discussion) {
      TaskRepository.getTaskById(discussion.recordId).then(function(task) {
        task.latestMessage = discussion;
        taskMessages.insert(task);
      });
    };
    if (jsUtil.isArray(data)) {
      jsUtil.each(data, addDiscussion);
    } else {
      addDiscussion(data);
    }

  };
  $rootScope.$on('discussion.sended', setLatestMessageOfTask);
  $rootScope.$on('discussion.sending', setLatestMessageOfTask);
  $rootScope.$on('discussion.loadAfter', setLatestMessageOfTask);

  //任务列表数据同步
  $rootScope.$on('task.add', generateEventHandler(taskList, 'insert'));
  $rootScope.$on('task.update', generateEventHandler(taskList, 'insert'));
  $rootScope.$on('task.remove', callbackWithIdEventHandler(taskList, 'remove'));
  $rootScope.$on('task.complete', callbackWithIdEventHandler(taskList, 'insert'));

  //草稿列表数据同步
  var insertDraftFn = function(event, data) {
    if (data.status === '0') {
      taskDrafts.insert(data);
    }
  };
  $rootScope.$on('task.add', insertDraftFn);
  $rootScope.$on('task.update', insertDraftFn);
  $rootScope.$on('task.remove', callbackWithIdEventHandler(taskDrafts, 'remove'));

  //重置任务的消息未读数目。
  $rootScope.$on('task.noticeNum.reset', function(event, taskId) {
    TaskRepository.getTaskById(taskId).then(function(task) {
      task.noticeNum = 0;
      var index = taskMessages.indexOf(task);
      if (index !== -1) {
        taskMessages.items[index].noticeNum = 0;
      }
      return TaskRepository.addOrUpdateTasks(task);
    });
  });
  /**
   * 任务保存草稿或者发送失败时，在消息列表最顶端展示，且缓存到本地。
   */
  $rootScope.$on('task.saving', function(event, task, cacheTaskId) {
    var clonedTask = jsUtil.clone(task);
    clonedTask.id = cacheTaskId;
    clonedTask.createDate = jsUtil.formatDate(new Date(), 'Y-m-dTH:i:s.uZ');
    delaySaveTasks.insert(clonedTask);
  });
  /**
   * 任务保存成功后，将其从待处理队列中移除，且从缓存中移除
   */
  $rootScope.$on('task.saved', function(event, task, cacheId, draftInServer) {
    var cacheTask = jsUtil.clone(task);
    cacheTask.id = cacheId;
    delaySaveTasks.remove(cacheTask, cacheId, draftInServer);
  });
  /**
   * 聊天消息发送中监听处理。
   */
  $rootScope.$on('discussion.sending', function(event, discussion, cacheId) {
    discussion.id = discussion.id ? discussion.id : cacheId;
    delaySaveDiscussions.insert(discussion);
  });
  /**
   * 聊天信息发送成功的处理。
   */
  $rootScope.$on('discussion.sended', function(event, discussion, cacheId) {
    var cacheDiscussion = jsUtil.clone(discussion);
    cacheDiscussion.id = cacheId;
    delaySaveDiscussions.remove(cacheDiscussion, cacheId);
  });
  /**
   * 聊天信息发送失败的处理。
   */
  $rootScope.$on('discussion.sendfail', function(event, discussion, cacheId) {
    discussion.id = cacheId;
    delaySaveDiscussions.change(discussion, cacheId);
  });

  $rootScope.$on('discussions.loaded', function(event, taskId) {
    delaySaveDiscussions.loadCacheItemsInToRelatedList(taskId);
  });

  $rootScope.$on('messages.refreshComplete', function() {
    delaySaveTasks.loadCacheItemsInToRelatedList();
  });
  /**
   * 捕获事件：服务器地址更改。
   */
  $rootScope.$on('serverUrl.changed', function() {
    taskMessages.clear();
    taskList.clear();
    taskDrafts.clear();
    delaySaveDiscussions.clear();
    delaySaveTasks.clear();
    CurrentTaskService.clearCurrentTask();
  });
});