var angular = require('angular');
var _ = require('jsUtil');
require('../modules');
var module = angular.module('flow.services');

module.factory('CommonNotionService', function($http, $q) {
  var currentCommonNotions = [];
  
  function CommonNotionService() {}
  
  
  function replaceCommonNotions(commonNotions) {
    currentCommonNotions.splice(0, currentCommonNotions.length);
    if (commonNotions) {
      currentCommonNotions.push.apply(currentCommonNotions, commonNotions);
    }
  }

  function validExistCommonNotion(content) {
    if (!currentCommonNotions) { return false; }
    return _.some(currentCommonNotions, function(commonNotion) {
      return content === commonNotion.content;
    });
  }

  /**
  * 获取指定用户的常用意见
  *
  * @param {String} userId 用户ID
  */
  CommonNotionService.getCommonNotions = function(userId) {
    return $http({
      method: 'GET',
      url: '/workflow/commonNotion',
      params: {
        userId: userId
      },
      timeout: 15000
    }).then(function(response) {
      replaceCommonNotions(response.data);
      return currentCommonNotions;
    });
  };

  CommonNotionService.saveCommonNotion = function(userId, content) {
    if (validExistCommonNotion(content)) {
      return $q.when();
    }
    return $http({
      method: 'POST',
      url: '/workflow/commonNotion',
      data: {
        userId: userId,
        content: content,
        creTime: _.DateUtil.format(new Date(), 'Y-m-d H:i:s') 
      },
      timeout: 15000
    }).then(function(response) {
      if (currentCommonNotions) {
        currentCommonNotions.push(response.data);
      }
      return response.data;
    });
  };

  CommonNotionService.deleteCommonNotion = function(commonNotionId) {
    return $http({
      method: 'POST',
      url: '/workflow/commonNotion/' + commonNotionId + '?_method=delete',
      timeout: 15000
    }).then(function(response) {
      return response;
    });
  };

  return CommonNotionService;
});
